1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-07-02 22:55:26 +02:00

[179102] Re-aligned plugin and package names to confirm with Eclipse policy.

This commit is contained in:
Pawel Piech 2008-02-13 20:57:46 +00:00
parent faddc5dbcf
commit fdea880631
66 changed files with 12795 additions and 0 deletions

View file

@ -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/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1 @@
bin

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.eclipse.dd.tests.dsf</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>

View file

@ -0,0 +1,65 @@
#Thu Jun 07 11:08:23 PDT 2007
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning
org.eclipse.jdt.core.compiler.problem.nullReference=ignore
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
org.eclipse.jdt.core.compiler.problem.unusedImport=error
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.5

View file

@ -0,0 +1,3 @@
#Thu Oct 12 11:27:35 PDT 2006
eclipse.preferences.version=1
internal.default.compliance=default

View file

@ -0,0 +1,17 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Debug Services Framework Unit Tests
Bundle-Vendor: Eclipse.org
Bundle-SymbolicName: org.eclipse.dd.tests.dsf;singleton:=true
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: org.eclipse.dd.tests.dsf.DsfTestPlugin
Bundle-Localization: plugin
Bundle-ActivationPolicy: lazy
Require-Bundle: org.eclipse.core.runtime,
org.eclipse.debug.core,
org.eclipse.debug.ui,
org.eclipse.dd.dsf,
org.junit4,
org.eclipse.ui,
org.eclipse.dd.dsf.ui
Bundle-RequiredExecutionEnvironment: J2SE-1.5

View file

@ -0,0 +1,24 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>About</title></head><body lang="EN-US">
<h2>About This Content</h2>
<p>June 5, 2007</p>
<h3>License</h3>
<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
indicated below, the Content is provided to you under the terms and conditions of the
Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available
at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
For purposes of the EPL, "Program" will mean the Content.</p>
<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
being redistributed by another party ("Redistributor") and different terms and conditions may
apply to your use of any object code in the Content. Check the Redistributor's license that was
provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
indicated below, the terms and conditions of the EPL still apply to any source code in the Content
and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
</body></html>

View file

@ -0,0 +1,6 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
plugin.xml,\
about.html

View file

@ -0,0 +1,13 @@
###############################################################################
# Copyright (c) 2006 Wind River Systems 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:
# Wind River Systems - initial API and implementation
###############################################################################
pluginName=DSDP/DD Debugger Services Framework (DSF) Test Plugin
providerName=Eclipse.org

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
<extension
point="org.eclipse.ui.views">
<category
name="DSF Tests"
id="org.eclipse.dd.dsf.tests.model">
</category>
<view
name="Model Test View"
category="org.eclipse.dd.dsf.tests.model"
class="org.eclipse.dd.dsf.tests.model.ModelTestsView"
id="org.eclipse.dd.dsf.tests.model.ModelTestView">
</view>
</extension>
</plugin>

View file

@ -0,0 +1,59 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.dsf.tests.service;
import java.util.Hashtable;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.service.AbstractDsfService;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.osgi.framework.BundleContext;
public class MultiInstanceTestService extends AbstractDsfService {
public static String PROP_INSTANCE_ID = "org.eclipse.dd.dsf.tests.service.MultiInstanceTestService.id"; //$NON-NLS-1$
String fInstanceId;
public MultiInstanceTestService(DsfSession session, String instanceId) {
super(session);
fInstanceId = instanceId;
}
@Override
protected BundleContext getBundleContext() {
return DsfTestPlugin.getBundleContext();
}
@Override
public void initialize(final RequestMonitor requestMonitor) {
super.initialize(
new RequestMonitor(getExecutor(), requestMonitor) {
@Override
public void handleOK() {
doInitialize(requestMonitor);
}
});
}
private void doInitialize(RequestMonitor requestMonitor) {
Hashtable<String,String> properties = new Hashtable<String,String>();
properties.put(PROP_INSTANCE_ID, fInstanceId);
register(new String[]{MultiInstanceTestService.class.getName()}, properties);
requestMonitor.done();
}
@Override
public void shutdown(RequestMonitor requestMonitor) {
unregister();
super.shutdown(requestMonitor);
}
}

View file

@ -0,0 +1,277 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.dsf.tests.service;
import java.lang.reflect.Constructor;
import java.util.concurrent.ExecutionException;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.concurrent.DsfRunnable;
import org.eclipse.dd.dsf.concurrent.Sequence;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.dsf.service.IDsfService;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.eclipse.dd.tests.dsf.TestDsfExecutor;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
public class ServiceTests {
TestDsfExecutor fExecutor;
@Before public void startExecutor() throws ExecutionException, InterruptedException {
fExecutor = new TestDsfExecutor();
}
@After public void shutdownExecutor() throws ExecutionException, InterruptedException {
fExecutor.submit(new DsfRunnable() { public void run() {
fExecutor.shutdown();
}}).get();
if (fExecutor.exceptionsCaught()) {
Throwable[] exceptions = fExecutor.getExceptions();
throw new ExecutionException(exceptions[0]);
}
fExecutor = null;
}
private class CreateSessionStep extends Sequence.Step {
private DsfSession fSession;
@Override public void execute(RequestMonitor requestMonitor) {
fSession = DsfSession.startSession(fExecutor, "org.eclipse.dd.dsf.tests"); //$NON-NLS-1$
requestMonitor.done();
}
DsfSession getSession() { return fSession; }
}
private class ShutdownSessionStep extends Sequence.Step {
private CreateSessionStep fCreateSessionStep;
ShutdownSessionStep(CreateSessionStep createSessionStep) {
fCreateSessionStep = createSessionStep;
}
@Override
public void execute(RequestMonitor requestMonitor) {
DsfSession.endSession(fCreateSessionStep.getSession());
requestMonitor.done();
}
}
private class InitializeServiceStep extends Sequence.Step {
CreateSessionStep fCreateSessionStep;
Class<? extends IDsfService> fServiceClass;
IDsfService fService;
InitializeServiceStep(CreateSessionStep createSessionStep, Class<? extends IDsfService> serviceClass) {
fCreateSessionStep = createSessionStep;
fServiceClass = serviceClass;
}
IDsfService getService() { return fService; }
@Override
public void execute(RequestMonitor requestMonitor) {
try {
Constructor<? extends IDsfService> c = fServiceClass.getConstructor(new Class[] {DsfSession.class});
fService = c.newInstance(new Object[] {fCreateSessionStep.getSession()});
} catch (Exception e) {
Assert.fail("Unexpected exception"); //$NON-NLS-1$
}
fService.initialize(requestMonitor);
}
}
private class InitializeMultiInstanceServiceStep extends InitializeServiceStep {
String fServiceId;
InitializeMultiInstanceServiceStep(CreateSessionStep createSessionStep, Class<? extends IDsfService> serviceClass, String serviceId) {
super(createSessionStep, serviceClass);
fServiceId = serviceId;
}
@Override
IDsfService getService() { return fService; }
@Override
public void execute(RequestMonitor requestMonitor) {
try {
Constructor<? extends IDsfService> c =
fServiceClass.getConstructor(new Class[] {DsfSession.class, String.class});
fService = c.newInstance(new Object[] {fCreateSessionStep.getSession(), fServiceId});
} catch (Exception e) {
Assert.fail("Unexpected exception"); //$NON-NLS-1$
}
fService.initialize(requestMonitor);
}
}
private class ShutdownServiceStep extends Sequence.Step {
InitializeServiceStep fInitializeServiceStep;
ShutdownServiceStep(InitializeServiceStep initStep) {
fInitializeServiceStep = initStep;
}
@Override
public void execute(RequestMonitor requestMonitor) {
fInitializeServiceStep.getService().shutdown(requestMonitor);
}
}
abstract private class TestRetrievingReferenceStep extends Sequence.Step {
String fClass;
boolean fShouldSucceed;
TestRetrievingReferenceStep(Class<?> clazz, boolean shouldSucceed) {
fClass = clazz.getName();
fShouldSucceed = shouldSucceed;
}
abstract String getFilter();
@Override
public void execute(RequestMonitor requestMonitor) {
ServiceReference[] refs = null;
try {
refs = DsfTestPlugin.getBundleContext().getServiceReferences(fClass, getFilter());
} catch (InvalidSyntaxException e) {
Assert.fail("Unexpected exception"); //$NON-NLS-1$
}
if (fShouldSucceed) {
Assert.assertTrue(refs != null);
Assert.assertTrue(refs.length == 1);
IDsfService service = (IDsfService)DsfTestPlugin.getBundleContext().getService(refs[0]);
Assert.assertTrue(service != null);
DsfTestPlugin.getBundleContext().ungetService(refs[0]);
} else {
Assert.assertTrue(refs == null);
}
requestMonitor.done();
}
}
private class TestRetrievingSimpleServiceReferenceStep extends TestRetrievingReferenceStep {
CreateSessionStep fCreateSessionStep;
TestRetrievingSimpleServiceReferenceStep(Class<?> clazz, boolean shouldSucceed, CreateSessionStep createSessionStep) {
super(clazz, shouldSucceed);
fCreateSessionStep = createSessionStep;
}
@Override
String getFilter() {
return "(" + IDsfService.PROP_SESSION_ID + "=" + fCreateSessionStep.getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
private class TestRetrievingMultiSessionServiceReferenceStep extends TestRetrievingSimpleServiceReferenceStep {
String fServiceId;
TestRetrievingMultiSessionServiceReferenceStep(Class<?> clazz, boolean shouldSucceed, CreateSessionStep createSessionStep,
String serviceId) {
super(clazz, shouldSucceed, createSessionStep);
fServiceId = serviceId;
}
@Override
String getFilter() {
return "(&" + //$NON-NLS-1$
"(" + IDsfService.PROP_SESSION_ID + "=" + fCreateSessionStep.getSession().getId() + ")" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"(" + MultiInstanceTestService.PROP_INSTANCE_ID + "=" + fServiceId + ")" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
")"; //$NON-NLS-1$
}
}
@Test
public void singleServiceTest() throws InterruptedException, ExecutionException {
Sequence seq = new Sequence(fExecutor) {
CreateSessionStep fSessionStep;
InitializeServiceStep fServiceStep;
@Override
public Step[] getSteps() { return fSteps; }
final private Step[] fSteps = new Step[]
{
fSessionStep = new CreateSessionStep(),
fServiceStep = new InitializeServiceStep(fSessionStep, SimpleTestService.class),
new TestRetrievingSimpleServiceReferenceStep(SimpleTestService.class, true, fSessionStep),
new ShutdownServiceStep(fServiceStep),
new TestRetrievingSimpleServiceReferenceStep(SimpleTestService.class, false, fSessionStep),
new ShutdownSessionStep(fSessionStep)
};
};
fExecutor.execute(seq);
seq.get();
}
/**
* Creates two sessions and starts a single service within each session.
* Then it tests retrieving the reference to the service.
*/
@Test
public void singleServiceMultiSessionTest() throws InterruptedException, ExecutionException {
Sequence seq = new Sequence(fExecutor) {
CreateSessionStep fSession1Step;
CreateSessionStep fSession2Step;
InitializeServiceStep fSession1ServiceStep;
InitializeServiceStep fSession2ServiceStep;
@Override
public Step[] getSteps() { return fSteps; }
final private Step[] fSteps = new Step[]
{
fSession1Step = new CreateSessionStep(),
fSession2Step = new CreateSessionStep(),
fSession1ServiceStep = new InitializeServiceStep(fSession1Step, SimpleTestService.class),
fSession2ServiceStep = new InitializeServiceStep(fSession2Step, SimpleTestService.class),
new TestRetrievingSimpleServiceReferenceStep(SimpleTestService.class, true, fSession1Step),
new TestRetrievingSimpleServiceReferenceStep(SimpleTestService.class, true, fSession2Step),
new ShutdownServiceStep(fSession1ServiceStep),
new ShutdownServiceStep(fSession2ServiceStep),
new TestRetrievingSimpleServiceReferenceStep(SimpleTestService.class, false, fSession1Step),
new TestRetrievingSimpleServiceReferenceStep(SimpleTestService.class, false, fSession2Step),
new ShutdownSessionStep(fSession1Step),
new ShutdownSessionStep(fSession2Step)
};
};
fExecutor.execute(seq);
seq.get();
}
@Test
public void multiServiceServiceTest() throws InterruptedException, ExecutionException {
Sequence seq = new Sequence(fExecutor) {
CreateSessionStep fSessionStep;
InitializeServiceStep fService1Step;
InitializeServiceStep fService2Step;
@Override
public Step[] getSteps() { return fSteps; }
final private Step[] fSteps = new Step[]
{
fSessionStep = new CreateSessionStep(),
fService1Step = new InitializeMultiInstanceServiceStep(fSessionStep, MultiInstanceTestService.class, "1"), //$NON-NLS-1$
fService2Step = new InitializeMultiInstanceServiceStep(fSessionStep, MultiInstanceTestService.class, "2"), //$NON-NLS-1$
new TestRetrievingMultiSessionServiceReferenceStep(MultiInstanceTestService.class, true, fSessionStep, "1"), //$NON-NLS-1$
new TestRetrievingMultiSessionServiceReferenceStep(MultiInstanceTestService.class, true, fSessionStep, "2"), //$NON-NLS-1$
new ShutdownServiceStep(fService1Step),
new ShutdownServiceStep(fService2Step),
new TestRetrievingMultiSessionServiceReferenceStep(MultiInstanceTestService.class, false, fSessionStep, "1"), //$NON-NLS-1$
new TestRetrievingMultiSessionServiceReferenceStep(MultiInstanceTestService.class, false, fSessionStep, "2"), //$NON-NLS-1$
new ShutdownSessionStep(fSessionStep)
};
};
fExecutor.execute(seq);
seq.get();
}
}

View file

@ -0,0 +1,53 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.dsf.tests.service;
import java.util.Hashtable;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.service.AbstractDsfService;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.osgi.framework.BundleContext;
public class SimpleTestService extends AbstractDsfService {
public SimpleTestService(DsfSession session) {
super(session);
}
@Override
protected BundleContext getBundleContext() {
return DsfTestPlugin.getBundleContext();
}
@Override
public void initialize(final RequestMonitor requestMonitor) {
super.initialize(
new RequestMonitor(getExecutor(), requestMonitor) {
@Override
public void handleOK() {
doInitialize(requestMonitor);
}
});
}
private void doInitialize(RequestMonitor requestMonitor) {
register(new String[]{SimpleTestService.class.getName()}, new Hashtable<String,String>());
requestMonitor.done();
}
@Override
public void shutdown(RequestMonitor requestMonitor) {
unregister();
super.shutdown(requestMonitor);
}
}

View file

@ -0,0 +1,69 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class DsfTestPlugin extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.eclipse.dd.tests.dsf"; //$NON-NLS-1$
// The shared instance
private static DsfTestPlugin fgPlugin;
private static BundleContext fgBundleContext;
/**
* The constructor
*/
public DsfTestPlugin() {
fgPlugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(BundleContext context) throws Exception {
fgBundleContext = context;
super.start(context);
}
/*
* (non-Javadoc)
* @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception {
super.stop(context);
fgBundleContext = null;
fgPlugin = null;
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static DsfTestPlugin getDefault() {
return fgPlugin;
}
public static BundleContext getBundleContext() {
return fgBundleContext;
}
}

View file

@ -0,0 +1,50 @@
package org.eclipse.dd.tests.dsf;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.eclipse.dd.dsf.concurrent.DefaultDsfExecutor;
/**
* DsfExecutor for use with unit tests. It records the exceptions that were
* thrown in the executor thread so that they can be re-thrown by the test.
*
*/
public class TestDsfExecutor extends DefaultDsfExecutor {
private List<Throwable> fExceptions = Collections.synchronizedList(new ArrayList<Throwable>());
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (r instanceof Future<?>) {
Future<?> future = (Future<?>)r;
try {
if (future.isDone()) {
future.get();
}
future.get();
} catch (InterruptedException e) { // Ignore
} catch (CancellationException e) { // Ignore also
} catch (ExecutionException e) {
if (e.getCause() != null) {
fExceptions.add(e.getCause());
}
}
}
}
public boolean exceptionsCaught() {
return fExceptions.size() != 0;
}
public Throwable[] getExceptions() {
synchronized (fExceptions) {
return fExceptions.toArray(new Throwable[fExceptions.size()]);
}
}
}

View file

@ -0,0 +1,28 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf;
/**
* Utility class to hold a value retrieved in a runnable.
* Usage in a test is as follows:
* <pre>
* final ValueHolder<Integer> value = new ValueHolder<Integer>();
* fExecutor.execute(new Runnable() {
* public void run() {
* value.fValue = 1;
* }
* });
* Assert.assertTrue(value.fValue == 1);
* </pre>
*/
public class ValueHolder<V> {
public V fValue;
}

View file

@ -0,0 +1,216 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.concurrent;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import junit.framework.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.concurrent.DsfRunnable;
import org.eclipse.dd.dsf.concurrent.Query;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.eclipse.dd.tests.dsf.TestDsfExecutor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests that excercise the Query object.
*/
public class DsfQueryTests {
TestDsfExecutor fExecutor;
@Before
public void startServices() throws ExecutionException, InterruptedException {
fExecutor = new TestDsfExecutor();
}
@After
public void shutdownServices() throws ExecutionException, InterruptedException {
fExecutor.submit(new DsfRunnable() { public void run() {
fExecutor.shutdown();
}}).get();
if (fExecutor.exceptionsCaught()) {
Throwable[] exceptions = fExecutor.getExceptions();
throw new ExecutionException(exceptions[0]);
}
fExecutor = null;
}
@Test
public void simpleGetTest() throws InterruptedException, ExecutionException {
Query<Integer> q = new Query<Integer>() {
@Override
protected void execute(DataRequestMonitor<Integer> rm) {
rm.setData(1);
rm.done();
}
};
// Check initial state
Assert.assertTrue(!q.isDone());
Assert.assertTrue(!q.isCancelled());
fExecutor.execute(q);
Assert.assertEquals(1, (int)q.get());
// Check final state
Assert.assertTrue(q.isDone());
Assert.assertTrue(!q.isCancelled());
}
@Test
public void getWithMultipleDispatchesTest() throws InterruptedException, ExecutionException {
Query<Integer> q = new Query<Integer>() {
@Override
protected void execute(final DataRequestMonitor<Integer> rm) {
fExecutor.execute(new DsfRunnable() {
public void run() {
rm.setData(1);
rm.done();
}
@Override
public String toString() { return super.toString() + "\n getWithMultipleDispatchesTest() second runnable"; } //$NON-NLS-1$
});
}
@Override
public String toString() { return super.toString() + "\n getWithMultipleDispatchesTest() first runnable (query)"; } //$NON-NLS-1$
};
fExecutor.execute(q);
Assert.assertEquals(1, (int)q.get());
}
@Test (expected = ExecutionException.class)
public void exceptionOnGetTest() throws InterruptedException, ExecutionException {
Query<Integer> q = new Query<Integer>() {
@Override
protected void execute(final DataRequestMonitor<Integer> rm) {
rm.setStatus(new Status(IStatus.ERROR, DsfTestPlugin.PLUGIN_ID, -1, "", null)); //$NON-NLS-1$
rm.done();
}
};
fExecutor.execute(q);
try {
q.get();
} finally {
Assert.assertTrue(q.isDone());
Assert.assertTrue(!q.isCancelled());
}
}
@Test
public void cancelWhileWaitingTest() throws InterruptedException, ExecutionException {
final Query<Integer> q = new Query<Integer>() {
@Override
protected void execute(final DataRequestMonitor<Integer> rm) {
// Call done with a delay of 1 second, to avoid stalling the tests.
fExecutor.schedule(
new DsfRunnable() {
public void run() { rm.done(); }
},
1, TimeUnit.SECONDS);
}
};
fExecutor.execute(q);
// Note: no point in checking isDone() and isCancelled() here, because
// the value could change on timing.
// This does not really guarantee that the cancel will be called after
// the call to Fugure.get(), but the 1ms delay in call to schedule should
// help.
new Job("DsfQueryTests cancel job") { @Override public IStatus run(IProgressMonitor monitor) { //$NON-NLS-1$
q.cancel(false);
return Status.OK_STATUS;
}}.schedule(1);
try {
q.get();
} catch (CancellationException e) {
return; // Success
} finally {
Assert.assertTrue(q.isDone());
Assert.assertTrue(q.isCancelled());
}
Assert.assertTrue("CancellationException should have been thrown", false); //$NON-NLS-1$
}
@Test
public void cancelBeforeWaitingTest() throws InterruptedException, ExecutionException {
final Query<Integer> q = new Query<Integer>() {
@Override protected void execute(final DataRequestMonitor<Integer> rm) {
Assert.fail("Query was cancelled, it should not be called."); //$NON-NLS-1$
rm.done();
}
};
// Cancel before invoking the query.
q.cancel(false);
Assert.assertTrue(q.isDone());
Assert.assertTrue(q.isCancelled());
// Start the query.
fExecutor.execute(q);
// Block to retrieve data
try {
q.get();
} catch (CancellationException e) {
return; // Success
} finally {
Assert.assertTrue(q.isDone());
Assert.assertTrue(q.isCancelled());
}
Assert.assertTrue("CancellationException should have been thrown", false); //$NON-NLS-1$
}
@Test
public void getTimeoutTest() throws InterruptedException, ExecutionException {
final Query<Integer> q = new Query<Integer>() {
@Override
protected void execute(final DataRequestMonitor<Integer> rm) {
// Call done with a delay of 1 second, to avoid stalling the tests.
fExecutor.schedule(
new DsfRunnable() {
public void run() { rm.done(); }
},
1, TimeUnit.SECONDS);
}
};
fExecutor.execute(q);
// Note: no point in checking isDone() and isCancelled() here, because
// the value could change on timing.
try {
q.get(1, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
return; // Success
} finally {
Assert.assertFalse("Query should not be done yet, it should have timed out first.", q.isDone()); //$NON-NLS-1$
}
Assert.assertTrue("TimeoutException should have been thrown", false); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,315 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.concurrent;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.concurrent.DsfRunnable;
import org.eclipse.dd.dsf.concurrent.Sequence;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.eclipse.dd.tests.dsf.TestDsfExecutor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests that excercise the Sequence object.
*/
public class DsfSequenceTests {
TestDsfExecutor fExecutor;
@Before
public void startExecutor() throws ExecutionException, InterruptedException {
fExecutor = new TestDsfExecutor();
}
@After
public void shutdownExecutor() throws ExecutionException, InterruptedException {
fExecutor.submit(new DsfRunnable() { public void run() {
fExecutor.shutdown();
}}).get();
if (fExecutor.exceptionsCaught()) {
Throwable[] exceptions = fExecutor.getExceptions();
throw new ExecutionException(exceptions[0]);
}
fExecutor = null;
}
@Test
public void simpleTest() throws InterruptedException, ExecutionException {
// Create a counter for tracking number of steps performed.
class IntegerHolder { int fInteger; }
final IntegerHolder stepCounter = new IntegerHolder();
// Create the steps of the sequence
final Sequence.Step[] steps = new Sequence.Step[] {
new Sequence.Step() {
@Override
public void execute(RequestMonitor requestMonitor) {
stepCounter.fInteger++;
requestMonitor.done();
}
},
new Sequence.Step() {
@Override
public void execute(RequestMonitor requestMonitor) {
stepCounter.fInteger++;
requestMonitor.done();
}
}
};
// Create, start, and wait for the sequence.
Sequence sequence = new Sequence(fExecutor) {
@Override public Step[] getSteps() { return steps; }
};
Assert.assertTrue(!sequence.isDone());
Assert.assertTrue(!sequence.isCancelled());
fExecutor.execute(sequence);
sequence.get();
// Check the count
Assert.assertTrue(stepCounter.fInteger == 2);
// Check post conditions
Assert.assertTrue(sequence.isDone());
Assert.assertTrue(!sequence.isCancelled());
}
@Test (expected = ExecutionException.class)
public void rollbackTest() throws InterruptedException, ExecutionException {
// Create a counter for tracking number of steps performed and steps
// rolled back.
class IntegerHolder { int fInteger; }
final IntegerHolder stepCounter = new IntegerHolder();
final IntegerHolder rollBackCounter = new IntegerHolder();
// Create the steps of the sequence
final Sequence.Step[] steps = new Sequence.Step[] {
new Sequence.Step() {
@Override public void execute(RequestMonitor requestMonitor) {
stepCounter.fInteger++;
requestMonitor.done();
}
@Override public void rollBack(RequestMonitor requestMonitor) {
rollBackCounter.fInteger++;
requestMonitor.done();
}
},
new Sequence.Step() {
@Override public void execute(RequestMonitor requestMonitor) {
stepCounter.fInteger++;
requestMonitor.setStatus(new Status(IStatus.ERROR, DsfTestPlugin.PLUGIN_ID, -1, "", null)); //$NON-NLS-1$
requestMonitor.done();
}
@Override public void rollBack(RequestMonitor requestMonitor) {
rollBackCounter.fInteger++;
requestMonitor.done();
}
}
};
// Create and start.
Sequence sequence = new Sequence(fExecutor) {
@Override public Step[] getSteps() { return steps; }
};
fExecutor.execute(sequence);
// Block and wait for sequence to bomplete.
try {
sequence.get();
} finally {
// Both steps should be performed
Assert.assertTrue(stepCounter.fInteger == 2);
// Only one step is rolled back, the first one.
Assert.assertTrue(rollBackCounter.fInteger == 1);
// Check state from Future interface
Assert.assertTrue(sequence.isDone());
Assert.assertTrue(!sequence.isCancelled());
}
Assert.assertTrue("Exception should have been thrown", false); //$NON-NLS-1$
}
/**
* The goal of this test it to check that if an exception is thrown within
* the Step.execute(), the step will return from the Future.get() method.
*/
@Test (expected = ExecutionException.class)
public void exceptionTest() throws InterruptedException, ExecutionException {
final Sequence.Step[] steps = new Sequence.Step[] {
new Sequence.Step() {
@Override public void execute(RequestMonitor requestMonitor) {
throw new Error("Exception part of unit test."); //$NON-NLS-1$
}
}
};
// Create and start.
Sequence sequence = new Sequence(fExecutor) {
@Override public Step[] getSteps() { return steps; }
};
fExecutor.execute(sequence);
// Block and wait for sequence to bomplete.
try {
sequence.get();
} finally {
// Check state from Future interface
Assert.assertTrue(sequence.isDone());
Assert.assertTrue(!sequence.isCancelled());
}
Assert.assertTrue("Exception should have been thrown", false); //$NON-NLS-1$
}
@Test (expected = CancellationException.class)
public void cancelBeforeWaitingTest() throws InterruptedException, ExecutionException {
// Create the sequence
final Sequence.Step[] steps = new Sequence.Step[] {
new Sequence.Step() {
@Override public void execute(RequestMonitor requestMonitor) {
Assert.assertTrue("Sequence was cancelled, it should not be called.", false); //$NON-NLS-1$
}
}
};
Sequence sequence = new Sequence(fExecutor) {
@Override public Step[] getSteps() { return steps; }
};
// Cancel before invoking the sequence.
sequence.cancel(false);
Assert.assertTrue(!sequence.isDone());
Assert.assertTrue(sequence.isCancelled());
// Start the sequence
fExecutor.execute(sequence);
// Block and wait for sequence to bomplete.
try {
sequence.get();
} finally {
Assert.assertTrue(sequence.isDone());
Assert.assertTrue(sequence.isCancelled());
}
Assert.assertTrue("CancellationException should have been thrown", false); //$NON-NLS-1$
}
@Test (expected = CancellationException.class)
public void cancelFromStepTest() throws InterruptedException, ExecutionException {
// Create a counter for tracking number of steps performed and steps
// rolled back.
class IntegerHolder { int fInteger; }
final IntegerHolder stepCounter = new IntegerHolder();
final IntegerHolder rollBackCounter = new IntegerHolder();
// Create the steps of the sequence
final Sequence.Step[] steps = new Sequence.Step[] {
new Sequence.Step() {
@Override public void execute(RequestMonitor requestMonitor) {
stepCounter.fInteger++;
requestMonitor.done();
}
@Override public void rollBack(RequestMonitor requestMonitor) {
rollBackCounter.fInteger++;
requestMonitor.done();
}
},
new Sequence.Step() {
@Override public void execute(RequestMonitor requestMonitor) {
stepCounter.fInteger++;
// Perform the cancel!
getSequence().cancel(false);
requestMonitor.done();
}
@Override public void rollBack(RequestMonitor requestMonitor) {
rollBackCounter.fInteger++;
requestMonitor.done();
}
}
};
// Create and start sequence with a delay. Delay so that we call get() before
// cancel is called.
final Sequence sequence = new Sequence(fExecutor) {
@Override public Step[] getSteps() { return steps; }
};
fExecutor.schedule(sequence, 1, TimeUnit.MILLISECONDS);
// Block to retrieve data
try {
sequence.get();
} finally {
// Both steps should be performed
Assert.assertTrue(stepCounter.fInteger == 2);
// Both roll-backs should be performed since cancel does not take effect until
// after the step is completed.
Assert.assertTrue(rollBackCounter.fInteger == 2);
Assert.assertTrue(sequence.isDone());
Assert.assertTrue(sequence.isCancelled());
}
Assert.assertTrue("CancellationException should have been thrown", false); //$NON-NLS-1$
}
@Test (expected = CancellationException.class)
public void cancelBeforeWithProgressManagerTest() throws InterruptedException, ExecutionException {
// Create the sequence
final Sequence.Step[] steps = new Sequence.Step[] {
new Sequence.Step() {
@Override public void execute(RequestMonitor requestMonitor) {
Assert.assertTrue("Sequence was cancelled, it should not be called.", false); //$NON-NLS-1$
}
}
};
// Create the progress monitor that we will cancel.
IProgressMonitor pm = new NullProgressMonitor();
// Create the seqeunce with our steps.
Sequence sequence = new Sequence(fExecutor, pm, "", "", null) { //$NON-NLS-1$ //$NON-NLS-2$
@Override public Step[] getSteps() { return steps; }
};
// Cancel the progress monitor before invoking the sequence. Note
// that the state of the sequence doesn't change yet, because the
// sequence does not check the progress monitor until it is executed.
pm.setCanceled(true);
// Start the sequence
fExecutor.execute(sequence);
// Block and wait for sequence to bomplete. Exception is thrown,
// which is expected.
try {
sequence.get();
} finally {
Assert.assertTrue(sequence.isDone());
Assert.assertTrue(sequence.isCancelled());
}
}
}

View file

@ -0,0 +1,110 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.concurrent.ThreadSafe;
import org.eclipse.dd.dsf.service.AbstractDsfService;
import org.eclipse.dd.dsf.service.DsfServiceEventHandler;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.osgi.framework.BundleContext;
/**
* Test service class used to test event behavior. It has three types of events
* and three methods to receive the events.
*
*/
abstract public class AbstractService extends AbstractDsfService
{
AbstractService(DsfSession session) {
super(session);
}
@Override protected BundleContext getBundleContext() {
return DsfTestPlugin.getBundleContext();
}
@Override public void initialize(final RequestMonitor requestMonitor) {
super.initialize(
new RequestMonitor(getExecutor(), requestMonitor) {
@Override
public void handleOK() {
doInitialize(requestMonitor);
}
});
}
private void doInitialize(RequestMonitor requestMonitor) {
getSession().addServiceEventListener(this, null);
requestMonitor.done();
}
@Override public void shutdown(RequestMonitor requestMonitor) {
getSession().removeServiceEventListener(this);
super.shutdown(requestMonitor);
}
///////////////////////////////////////////////////////////////////////////
// Test API
/** Records the number in the event 1 object when this service received the event. */
int fEvent1RecipientNumber;
/** Records the number in the event 2 object when this service received the event. */
int fEvent2RecipientNumber;
/** Records the number in the event 3 object when this service received the event. */
int fEvent3RecipientNumber;
/** Simple event class 1 */
public class Event1 {
// 1-based counter for the recipient of the event.
int fRecipientNumberCounter = 1;
}
/** Simple event class 2. Note it doesn't have any relation to event 1 */
public class Event2 {
int fRecipientNumberCounter = 1;
}
/** Simple event class 3. Note it does sub-class event 1 */
public class Event3 extends Event1 {}
@ThreadSafe
public void dispatchEvent1() {
getSession().dispatchEvent(new Event1(), getProperties());
}
@ThreadSafe
public void dispatchEvent2() {
getSession().dispatchEvent(new Event2(), getProperties());
}
@ThreadSafe
public void dispatchEvent3() {
getSession().dispatchEvent(new Event3(), getProperties());
}
/** Handles event 1 (and event 3 which derives from event 1) */
@DsfServiceEventHandler public void eventDispatched(Event1 e) {
fEvent1RecipientNumber = e.fRecipientNumberCounter++;
}
/** Handles event 2 only */
@DsfServiceEventHandler public void eventDispatched(Event2 e) {
fEvent2RecipientNumber = e.fRecipientNumberCounter++;
}
/** Handles event 3 only */
@DsfServiceEventHandler public void eventDispatched(Event3 e) {
fEvent3RecipientNumber = e.fRecipientNumberCounter++;
}
}

View file

@ -0,0 +1,16 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
public class Event1 {
}

View file

@ -0,0 +1,15 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
public class Event2 extends Event1 {
}

View file

@ -0,0 +1,147 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
import java.util.concurrent.ExecutionException;
import org.eclipse.dd.dsf.concurrent.DsfRunnable;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.eclipse.dd.tests.dsf.TestDsfExecutor;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class EventTest {
DsfSession fSession;
TestDsfExecutor fExecutor;
DsfServicesTracker fTracker;
Service1 fService1;
Service2 fService2;
Service3 fService3;
@Before public void startServices() throws ExecutionException, InterruptedException {
fExecutor = new TestDsfExecutor();
fExecutor.submit(new DsfRunnable() { public void run() {
fSession = DsfSession.startSession(fExecutor, "org.eclipse.dd.dsf.tests"); //$NON-NLS-1$
}}).get();
StartupSequence startupSeq = new StartupSequence(fSession);
fExecutor.execute(startupSeq);
startupSeq.get();
fExecutor.submit(new DsfRunnable() { public void run() {
fTracker = new DsfServicesTracker(DsfTestPlugin.getBundleContext(), fSession.getId());
fService1 = fTracker.getService(Service1.class);
fService2 = fTracker.getService(Service2.class);
fService3 = fTracker.getService(Service3.class);
}}).get();
Assert.assertNotNull(fService1);
Assert.assertNotNull(fService2);
Assert.assertNotNull(fService3);
}
@After public void shutdownServices() throws ExecutionException, InterruptedException {
ShutdownSequence shutdownSeq = new ShutdownSequence(fSession);
fExecutor.execute(shutdownSeq);
shutdownSeq.get();
fExecutor.submit(new DsfRunnable() { public void run() {
fService1 = null;
fService2 = null;
fService3 = null;
fTracker.dispose();
fTracker = null;
DsfSession.endSession(fSession);
fSession = null;
fExecutor.shutdown();
}}).get();
if (fExecutor.exceptionsCaught()) {
Throwable[] exceptions = fExecutor.getExceptions();
throw new ExecutionException(exceptions[0]);
}
fExecutor = null;
}
/**
* Test only the startup and shutdown sequences.
*/
@Test public void startStopTest() {
}
/**
* Tests dispatching event 1. The goal of the test is to make sure that
* recipients are called in the correct order.
*/
@Test public void event1Test() throws ExecutionException, InterruptedException {
fService1.dispatchEvent1();
fExecutor.submit(new DsfRunnable() { public void run() {
Assert.assertTrue(1 == fService1.fEvent1RecipientNumber);
Assert.assertTrue(2 == fService2.fEvent1RecipientNumber);
Assert.assertTrue(3 == fService3.fEvent1RecipientNumber);
Assert.assertTrue(0 == fService1.fEvent2RecipientNumber);
Assert.assertTrue(0 == fService2.fEvent2RecipientNumber);
Assert.assertTrue(0 == fService3.fEvent2RecipientNumber);
Assert.assertTrue(0 == fService1.fEvent3RecipientNumber);
Assert.assertTrue(0 == fService2.fEvent3RecipientNumber);
Assert.assertTrue(0 == fService3.fEvent3RecipientNumber);
}}).get();
}
/**
* Tests dispatching event 2. The goal of the test is to make sure that
* recipients are called in the correct order, and that the other events
* are not registered.
*/
@Test public void event2Test() throws ExecutionException, InterruptedException {
fService1.dispatchEvent2();
fExecutor.submit(new DsfRunnable() { public void run() {
Assert.assertTrue(0 == fService1.fEvent1RecipientNumber);
Assert.assertTrue(0 == fService2.fEvent1RecipientNumber);
Assert.assertTrue(0 == fService3.fEvent1RecipientNumber);
Assert.assertTrue(1 == fService1.fEvent2RecipientNumber);
Assert.assertTrue(2 == fService2.fEvent2RecipientNumber);
Assert.assertTrue(3 == fService3.fEvent2RecipientNumber);
Assert.assertTrue(0 == fService1.fEvent3RecipientNumber);
Assert.assertTrue(0 == fService2.fEvent3RecipientNumber);
Assert.assertTrue(0 == fService3.fEvent3RecipientNumber);
}}).get();
}
/**
* Tests dispatching event 2. The goal of the test is to make sure that
* both event 2 and even 3 recipients are called for this event.
* <br>
* Note: When a single listener object has more than one method that that
* matches the event, both methods will be called. But there is currently
* no guaranteed order in which they should be called.
*/
@Test public void event3Test() throws ExecutionException, InterruptedException {
fService1.dispatchEvent3();
fExecutor.submit(new DsfRunnable() { public void run() {
Assert.assertTrue(1 == fService1.fEvent1RecipientNumber || 2 == fService1.fEvent1RecipientNumber);
Assert.assertTrue(3 == fService2.fEvent1RecipientNumber || 4 == fService2.fEvent1RecipientNumber);
Assert.assertTrue(5 == fService3.fEvent1RecipientNumber || 6 == fService3.fEvent1RecipientNumber);
Assert.assertTrue(0 == fService1.fEvent2RecipientNumber);
Assert.assertTrue(0 == fService2.fEvent2RecipientNumber);
Assert.assertTrue(0 == fService3.fEvent2RecipientNumber);
Assert.assertTrue(1 == fService1.fEvent3RecipientNumber || 2 == fService1.fEvent3RecipientNumber);
Assert.assertTrue(3 == fService2.fEvent3RecipientNumber || 4 == fService2.fEvent3RecipientNumber);
Assert.assertTrue(5 == fService3.fEvent3RecipientNumber || 6 == fService3.fEvent3RecipientNumber);
}}).get();
}
}

View file

@ -0,0 +1,42 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
import java.util.Hashtable;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.service.DsfSession;
public class Service1 extends AbstractService {
Service1(DsfSession session) {
super(session);
}
@Override public void initialize(final RequestMonitor requestMonitor) {
super.initialize(
new RequestMonitor(getExecutor(), requestMonitor) {
@Override
public void handleOK() {
doInitialize(requestMonitor);
}
});
}
private void doInitialize(RequestMonitor requestMonitor) {
register(new String[]{Service1.class.getName()}, new Hashtable<String,String>());
requestMonitor.done();
}
@Override public void shutdown(RequestMonitor requestMonitor) {
unregister();
super.shutdown(requestMonitor);
}
}

View file

@ -0,0 +1,43 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
import java.util.Hashtable;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.service.DsfSession;
public class Service2 extends AbstractService {
Service2(DsfSession session) {
super(session);
}
@Override public void initialize(final RequestMonitor requestMonitor) {
super.initialize(
new RequestMonitor(getExecutor(), requestMonitor) {
@Override
public void handleOK() {
doInitialize(requestMonitor);
}
});
}
private void doInitialize(RequestMonitor requestMonitor) {
getServicesTracker().getService(Service1.class);
register(new String[]{Service2.class.getName()}, new Hashtable<String,String>());
requestMonitor.done();
}
@Override public void shutdown(RequestMonitor requestMonitor) {
unregister();
super.shutdown(requestMonitor);
}
}

View file

@ -0,0 +1,50 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
import java.util.Hashtable;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
import org.osgi.framework.BundleContext;
public class Service3 extends AbstractService {
Service3(DsfSession session) {
super(session);
}
@Override protected BundleContext getBundleContext() {
return DsfTestPlugin.getBundleContext();
}
@Override public void initialize(final RequestMonitor requestMonitor) {
super.initialize(
new RequestMonitor(getExecutor(), requestMonitor) {
@Override
public void handleOK() {
doInitialize(requestMonitor);
}
});
}
private void doInitialize(RequestMonitor requestMonitor) {
getServicesTracker().getService(Service1.class);
getServicesTracker().getService(Service2.class);
register(new String[]{Service3.class.getName()}, new Hashtable<String,String>());
requestMonitor.done();
}
@Override public void shutdown(RequestMonitor requestMonitor) {
unregister();
super.shutdown(requestMonitor);
}
}

View file

@ -0,0 +1,75 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.concurrent.Sequence;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.dsf.service.IDsfService;
import org.eclipse.dd.tests.dsf.DsfTestPlugin;
class ShutdownSequence extends Sequence {
DsfSession fSession;
DsfServicesTracker fTracker;
ShutdownSequence(DsfSession session) {
super(session.getExecutor());
fSession = session;
}
@Override
public Step[] getSteps() { return fSteps; }
final Step[] fSteps = new Step[] {
new Step() {
@Override public void execute(RequestMonitor requestMonitor) {
fTracker = new DsfServicesTracker(DsfTestPlugin.getBundleContext(), fSession.getId());
requestMonitor.done();
}
@Override public void rollBack(RequestMonitor requestMonitor) {
fTracker.dispose();
fTracker = null;
requestMonitor.done();
}
},
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
shutdownService(Service3.class, requestMonitor);
}},
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
shutdownService(Service2.class, requestMonitor);
}},
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
shutdownService(Service1.class, requestMonitor);
}},
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
fTracker.dispose();
fTracker = null;
requestMonitor.done();
}}
};
private void shutdownService(Class<? extends IDsfService> clazz, RequestMonitor requestMonitor) {
IDsfService service = fTracker.getService(clazz);
if (service != null) {
service.shutdown(requestMonitor);
}
else {
requestMonitor.setStatus(new Status(IStatus.ERROR, DsfTestPlugin.PLUGIN_ID, -1, "Service '" + clazz.getName() + "' not found.", null)); //$NON-NLS-1$//$NON-NLS-2$
requestMonitor.done();
}
}
}

View file

@ -0,0 +1,39 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.dsf.events;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.concurrent.Sequence;
import org.eclipse.dd.dsf.service.DsfSession;
class StartupSequence extends Sequence {
DsfSession fSession;
StartupSequence(DsfSession session) {
super(session.getExecutor());
fSession = session;
}
@Override
public Step[] getSteps() { return fSteps; }
final Step[] fSteps = new Step[] {
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
new Service1(fSession).initialize(requestMonitor);
}},
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
new Service2(fSession).initialize(requestMonitor);
}},
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
new Service3(fSession).initialize(requestMonitor);
}}
};
}

View file

@ -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/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_CLEAN_TARGETS" value="clean,"/>
<booleanAttribute key="org.eclipse.ant.ui.ATTR_TARGETS_UPDATED" value="true"/>
<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/>
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;launchConfigurationWorkingSet editPageId=&quot;org.eclipse.ui.resourceWorkingSetPage&quot; factoryID=&quot;org.eclipse.ui.internal.WorkingSetFactory&quot; label=&quot;working set&quot; name=&quot;working set&quot;&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/org.eclipse.dd.tests.gdb/data&quot; type=&quot;2&quot;/&gt;&#10;&lt;/launchConfigurationWorkingSet&gt;}"/>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/org.eclipse.dd.tests.gdb"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="4"/>
</listAttribute>
<booleanAttribute key="org.eclipse.debug.core.appendEnvironmentVariables" value="true"/>
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="org.eclipse.dd.tests.gdb"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/org.eclipse.dd.tests.gdb/TestAppBuilder.xml}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,clean"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

View file

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.eclipse.dd.tests.gdb</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/TestAppBuilder.launch</value>
</dictionary>
</arguments>
</buildCommand>
<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>

View file

@ -0,0 +1,65 @@
#Thu Jun 07 11:08:01 PDT 2007
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
org.eclipse.jdt.core.compiler.problem.nullReference=ignore
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
org.eclipse.jdt.core.compiler.problem.unusedImport=error
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.5

View file

@ -0,0 +1,23 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: GDB/MI reference application tests
Bundle-SymbolicName: org.eclipse.dd.tests.gdb;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: org.eclipse.dd.tests.gdb.launching.TestsPlugin
Bundle-Vendor: Ericsson
Bundle-Localization: plugin
Require-Bundle: org.eclipse.core.runtime,
org.eclipse.dd.dsf,
org.eclipse.dd.dsf.debug,
org.eclipse.cdt.core,
org.eclipse.cdt.launch,
org.eclipse.cdt.debug.core,
org.eclipse.dd.mi,
org.junit4,
org.eclipse.debug.core,
org.eclipse.cdt.debug.mi.core,
org.eclipse.swt,
org.eclipse.dd.gdb
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: J2SE-1.5
Bundle-ClassPath: .

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project default="makeTestApps">
<!-- properties -->
<property name="bin_dir" location="./data/launch/bin"/>
<property name="src_dir" location="./data/launch/src"/>
<!-- targets -->
<target name="makeTestApps" description="Create the binaries for the test applications">
<exec executable="make" dir="${src_dir}" />
</target>
<target name="clean" description="Delete Test Applications">
<delete>
<fileset dir="${bin_dir}" includes="*"/>
</delete>
</target>
</project>

View file

@ -0,0 +1,5 @@
output.tests.jar = bin/
bin.includes = plugin.xml,\
META-INF/,\
.
source.. = src/

View file

@ -0,0 +1,47 @@
//============================================================================
// Name : BreakpointTestApp.cpp
// Author : Francois Chouinard
// Version : 1.0
// Copyright : Ericsson AB
// Description : Breakpoint test application
//============================================================================
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 256;
char charBlock[ARRAY_SIZE];
int integerBlock[ARRAY_SIZE];
void zeroBlocks(int abc)
{
for (int i = 0; i < ARRAY_SIZE; i++) {
charBlock[i] = '\0';
integerBlock[i] = 0;
}
}
void setBlocks()
{
for (int i = 0; i < ARRAY_SIZE; i++) {
charBlock[i] = (char) i;
integerBlock[i] = i;
}
}
void loop()
{
int j;
for (int i = 0; i < ARRAY_SIZE; i++)
j = i;
}
int main()
{
zeroBlocks(1);
loop();
setBlocks();
return 0;
}

View file

@ -0,0 +1,298 @@
#include <stdio.h>
int gIntVar = 543;
double gDoubleVar = 543.543;
char gCharVar = 'g';
bool gBoolVar = false;
int gIntArray[2] = {987, 654};
double gDoubleArray[2] = {987.654, 654.321};
char gCharArray[2] = {'g', 'd'};
bool gBoolArray[2] = {true, false};
int *gIntPtr = &gIntVar;
double *gDoublePtr = &gDoubleVar;
char *gCharPtr = &gCharVar;
bool *gBoolPtr = &gBoolVar;
int *gIntPtr2 = (int*)0x8;
double *gDoublePtr2 = (double*)0x5432;
char *gCharPtr2 = (char*)0x4321;
bool *gBoolPtr2 = (bool*)0x12ABCDEF;
class bar {
public:
int d;
private:
int e[2];
};
class bar2 {
public:
int f;
private:
int g[2];
};
class foo: public bar, bar2 {
public:
int a[2];
bar b;
private:
int c;
};
struct Z {
public:
int x;
int y;
};
struct childStruct {
public:
Z z;
};
void locals2() {
// Check that we get the content of local variables with
// the same name as the calling method
int lIntVar = 6789;
double lDoubleArray[2] = {123.456, 6789.6789};
char lCharVar = 'i';
char *lCharPtr = &lCharVar;
bool *lBoolPtr2 = (bool*)0xABCDE123;
return;
}
void testLocals() {
int lIntVar = 12345;
double lDoubleVar = 12345.12345;
char lCharVar = 'm';
bool lBoolVar = false;
int lIntArray[2] = {6789, 12345};
double lDoubleArray[2] = {456.789, 12345.12345};
char lCharArray[2] = {'i', 'm'};
bool lBoolArray[2] = {true, false};
int *lIntPtr = &lIntVar;
double *lDoublePtr = &lDoubleVar;
char *lCharPtr = &lCharVar;
bool *lBoolPtr = &gBoolVar;
int *lIntPtr2 = (int*)0x1;
double *lDoublePtr2 = (double*)0x2345;
char *lCharPtr2 = (char*)0x1234;
bool *lBoolPtr2 = (bool*)0x123ABCDE;
locals2();
return;
}
int testChildren() {
foo f;
f.d = 1;
return 0;
}
int testWrite() {
int a[2] = {3, 456};
return 0;
}
int testName1(int newVal) {
int a = newVal;
return a;
}
int testName2(int newVal) {
int a = newVal;
return a;
}
int testSameName1(int newVal) {
int a = newVal;
Z z;
z.x = newVal;
return a;
}
int testSameName1(int newVal, int ignore) {
int a = newVal;
Z z;
z.x = newVal;
return a;
}
int testSameName() {
testSameName1(1);
testSameName1(2, 0);
testSameName1(3);
return 0;
}
int testConcurrent() {
int a[2] = {28, 32};
return a[0];
}
int testSubblock() {
int a = 8;
int b = 1;
if (a) {
int a = 12;
b = a;
}
return b;
}
int testAddress() {
int a = 8;
int* a_ptr = &a;
return a;
}
int testUpdateChildren(int val) {
childStruct a;
a.z.x = val + 10;
a.z.y = val + 11;
a.z.x = val + 20;
a.z.y = val + 21;
return a.z.x;
}
int testUpdateChildren2(int val) {
childStruct a;
a.z.x = val + 10;
a.z.y = val + 11;
a.z.x = val + 20;
a.z.y = val + 21;
return a.z.x;
}
int testDeleteChildren() {
foo f;
int a[1111];
return 1;
}
int testUpdateGDBBug() {
// GDB 6.7 has a bug which will cause var-update not to show
// the new value of 'a' if we switch the format to binary,
// since binary of 3 is 11 which is the same as the old value
// in natural format
int a = 11;
a = 3;
return 0;
}
int testUpdateIssue() {
double a = 1.99;
a = 1.22;
}
int testUpdateIssue2() {
struct {
double d;
} z;
z.d = 1.0;
z.d = 1.22;
}
int testConcurrentReadAndUpdateChild() {
struct {
int d;
}z;
z.d = 1;
z.d = 2;
}
int testConcurrentUpdateOutOfScopeChildThenParent1() {
struct {
int d;
}z;
z.d = 1;
}
int testConcurrentUpdateOutOfScopeChildThenParent2() {
struct {
int d;
}z;
z.d = 2;
}
int testConcurrentUpdateOutOfScopeChildThenParent() {
testConcurrentUpdateOutOfScopeChildThenParent1();
testConcurrentUpdateOutOfScopeChildThenParent2();
}
int testUpdateOfPointer() {
struct {
int a;
int* b;
}z;
int c = 3;
z.b = &(z.a);
z.a = 1;
z.b = &c;
z.a = 2;
}
int testCanWrite() {
int a;
int* b;
struct {
int in;
} c;
int d[2];
return 1;
}
int main() {
printf("Running ExpressionTest App\n");
testLocals();
testChildren();
testWrite();
testName1(1);
testName2(2);
testName1(3);
testSameName();
testConcurrent();
testSubblock();
testAddress();
testUpdateChildren(0);
testUpdateChildren(100);
testUpdateChildren2(200);
testDeleteChildren();
testUpdateGDBBug();
testUpdateIssue();
testUpdateIssue2();
testConcurrentReadAndUpdateChild();
testConcurrentUpdateOutOfScopeChildThenParent();
testUpdateOfPointer();
testCanWrite();
return 0;
}

View file

@ -0,0 +1,15 @@
#include <stdio.h>
int main() {
printf("Running Generic App\n");
const char *path = "/tmp/dsftest.txt";
const char *mode = "a";
FILE* fd = fopen(path, mode);
fprintf(fd, "Running Generic App\n");
fclose(fd);
return 0;
}

View file

@ -0,0 +1,14 @@
src = $(wildcard *.cc *.c)
destDir = ../bin
GCCFLAGS = -g -pthread
all:
@mkdir -p $(destDir)
# Name the target with an .exe extension so that CVS does not
# include it when making a patch
@for file in $(src) ; \
do \
target=`basename $$file .c` ; \
target=`basename $$target .cc` ; \
g++ $(GCCFLAGS) $$file -o $(destDir)/$$target.exe ; \
done

View file

@ -0,0 +1,38 @@
//============================================================================
// Name : MemoryTestApp.cpp
// Author : Francois Chouinard
// Version : 1.0
// Copyright : Ericsson AB
// Description : Memory test application
//============================================================================
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 256;
char charBlock[ARRAY_SIZE];
int integerBlock[ARRAY_SIZE];
void zeroBlocks()
{
for (int i = 0; i < ARRAY_SIZE; i++) {
charBlock[i] = '\0';
integerBlock[i] = 0;
}
}
void setBlocks()
{
for (int i = 0; i < ARRAY_SIZE; i++) {
charBlock[i] = (char) i;
integerBlock[i] = i;
}
}
int main()
{
zeroBlocks();
setBlocks();
return 0;
}

View file

@ -0,0 +1,29 @@
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
int tid;
tid = (int)threadid;
printf("Hello World! It's me, thread #%d!\n", tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc, t;
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %d\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}

View file

@ -0,0 +1,15 @@
#include <stdio.h>
int main() {
printf("Running SpecialTestApp\n");
const char *path = "/tmp/dsftest.txt";
const char *mode = "a";
FILE* fd = fopen(path, mode);
fprintf(fd, "Running SpecialTestApp\n");
fclose(fd);
return 0;
}

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
<extension point="org.eclipse.debug.core.launchConfigurationTypes">
<launchConfigurationType
sourceLocatorId="org.eclipse.cdt.debug.core.sourceLocator"
delegate="org.eclipse.dd.tests.gdb.launching.TestLaunchDelegate"
public="true"
sourcePathComputerId="org.eclipse.cdt.debug.core.sourcePathComputer"
name="DSF JUnit Test Application"
id="org.eclipse.dd.tests.gdb.TestLaunch"
modes="debug">
</launchConfigurationType>
</extension>
</plugin>

View file

@ -0,0 +1,38 @@
package org.eclipse.dd.mi.service;
import org.eclipse.dd.dsf.debug.service.IExpressions.IExpressionDMContext;
import org.eclipse.dd.mi.service.ExpressionService.MIExpressionDMC;
public class ClassAccessor {
public static class MIExpressionDMCAccessor {
private MIExpressionDMC miExprDmc;
public MIExpressionDMCAccessor(IExpressionDMContext dmc) {
miExprDmc = (MIExpressionDMC) dmc;
}
@Override
public boolean equals(Object other) {
return miExprDmc.equals(other);
}
@Override
public int hashCode() {
return miExprDmc.hashCode();
}
@Override
public String toString() {
return miExprDmc.toString();
}
public String getExpression() {
return miExprDmc.getExpression();
}
public String getRelativeExpression() {
return miExprDmc.getRelativeExpression();
}
}
}

View file

@ -0,0 +1,34 @@
/*******************************************************************************
* Copyright (c) 2007 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 Implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/*
* This class is meant to be empty. It enables us to define
* the annotations which list all the different JUnit class we
* want to run. When creating a new test class, it should be
* added to the list below.
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
MIRegistersTest.class,
MIRunControlTest.class,
ExpressionServiceTest.class,
MIMemoryTest.class,
MIBreakpointsTest.class,
/* Add your test class here */
})
public class AllTests {}

View file

@ -0,0 +1,117 @@
/*******************************************************************************
* Copyright (c) 2007 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 Implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb;
import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.dd.tests.gdb.framework.BackgroundRunner;
import org.eclipse.dd.tests.gdb.framework.BaseTestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* This is an example of how to write new JUnit test cases
* for services of DSF.
*
* Each test class should extend BaseTestCase
* so as to automatically launch the application before
* each testcase and tear it down after.
*
* Also, each new test class must be added to the list within AllTest.
*
* Finally, each testcase should be @RunWith(BackgroundRunner.class)
* so as to release the UI thread and allow things such as
* timeouts to work in JUnit
*/
// Each test must run with the BackgroundRunner so as
// to release the UI thread
@RunWith(BackgroundRunner.class)
public class ExampleTest extends BaseTestCase {
@BeforeClass
public static void beforeClassMethod() {
// Things to run once specifically for this class,
// before starting this set of tests.
// Any method name can be used
// To choose your own test application, use the following form
// You must make sure the compiled binary is available in the
// specified location.
// If this method call is not made, the default GDBMIGenericTestApp
// will be used
setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
"data/launch/bin/SpecialTestApp.exe");
// Other attributes can be changed here
}
@AfterClass
public static void afterClassMethod() {
// Things to run once specifically for this class,
// after the launch has been performed
// Any method name can be used
}
@Before
public void beforeMethod() {
// Things to run specifically for this class,
// before each test but after the launch has been performed
// The Launched used is for the default test application
// Any method name can be used
}
@After
public void afterMethod() {
// Things to run specifically for this class
// after each test but before the launch has been torn down
// Any method name can be used
}
// @Override
// public void baseBeforeMethod() {
// // Can be used to override and prevent the baseSetup from being run
// // The name baseBeforeMethod must be used
// }
// @Override
// public void baseAfterMethod() {
// // Can be used to override and prevent the baseTeardown from being run
// // The name baseAfterMethod must be used
// }
@Test
public void basicTest() {
// First test to run
assertTrue("", true);
}
@Test(timeout=5000)
public void timeoutTest() {
// Second test to run, which will timeout if not finished on time
assertTrue("", true);
}
@Test(expected=FileNotFoundException.class)
public void exceptionTest() throws FileNotFoundException {
// Third test to run which expects an exception
throw new FileNotFoundException("Just testing");
}
}

View file

@ -0,0 +1,183 @@
/*******************************************************************************
* Copyright (c) 2007 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 AB - Initial implementation of Test cases
*******************************************************************************/
package org.eclipse.dd.tests.gdb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.gdb.service.GDBRunControl;
import org.eclipse.dd.gdb.service.GDBRunControl.GDBProcessData;
import org.eclipse.dd.gdb.service.GDBRunControl.GDBThreadData;
import org.eclipse.dd.gdb.service.command.GDBControl;
import org.eclipse.dd.mi.service.IMIExecutionDMContext;
import org.eclipse.dd.tests.gdb.framework.AsyncCompletionWaitor;
import org.eclipse.dd.tests.gdb.framework.BaseTestCase;
import org.eclipse.dd.tests.gdb.launching.TestsPlugin;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class GDBProcessesTest extends BaseTestCase {
/*
* Path to executable
*/
private static final String EXEC_PATH = "data/launch/bin/";
/*
* Name of the executable
*/
private static final String EXEC_NAME = "MultiThread.exe";
private DsfSession fSession;
private DsfServicesTracker fServicesTracker;
private GDBControl fGdbCtrl;
private GDBRunControl fRunCtrl;
/*
* Create a waiter and a generic completion object. They will be used to
* wait for asynchronous call completion.
*/
private final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
@Before
public void init() throws Exception {
fSession = getGDBLaunch().getSession();
fServicesTracker = new DsfServicesTracker(TestsPlugin.getBundleContext(), fSession.getId());
/*
* Get the GDBProcesses & MIRunControl service.
*/
fRunCtrl = fServicesTracker.getService(GDBRunControl.class);
fGdbCtrl = fServicesTracker.getService(GDBControl.class);
}
@After
public void tearDown() {
fRunCtrl = null;
fServicesTracker.dispose();
}
@BeforeClass
public static void beforeClassMethod() {
setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
EXEC_PATH + EXEC_NAME);
}
@Test
/*
* Get the process data for the current program. Process is executable name in case of GDB back end
*/
public void getProcessData() throws InterruptedException{
/*
* Create a request monitor
*/
final DataRequestMonitor<GDBProcessData> rm =
new DataRequestMonitor<GDBProcessData>(fSession.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
/*
* Ask the service to get model data for the process.
* There is only one process in case of GDB back end.
*/
fSession.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getProcessData(fGdbCtrl.getGDBDMContext(), rm);
}
});
/*
* Wait for the operation to get over
*/
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
/*
* Assert false if status is not OK
*/
Assert.assertTrue(fWait.getMessage(), fWait.isOK());
/*
* Get process data
*/
GDBProcessData processData = rm.getData();
if(processData == null)
Assert.fail("No process data is returned for Process DMC");
else{
/*
* Name of the process is the executable name in case of GDB back-end.
*/
assertEquals("Process data should be executable name " + EXEC_NAME, EXEC_NAME, processData.getName());
}
}
/*
* getThreadData() for multiple threads
*/
@Test
public void getThreadData() throws InterruptedException{
final DataRequestMonitor<GDBThreadData> rm =
new DataRequestMonitor<GDBThreadData>(fSession.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
/*
* Create an execution DMC
*/
final IMIExecutionDMContext dmc = fRunCtrl.createMIExecutionContext(fGdbCtrl.getGDBDMContext(), 1);
/*
* getModelData for Execution DMC
*/
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getThreadData(dmc, rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
assertTrue(fWait.getMessage(), fWait.isOK());
GDBThreadData threadData = rm.getData();
if(threadData == null)
fail("Thread data not returned for thread id = " + dmc.getThreadId());
else{
// Thread id is only a series of numbers
Pattern pattern = Pattern.compile("\\d*", Pattern.MULTILINE); //$NON-NLS-1$
Matcher matcher = pattern.matcher(threadData.getId());
assertTrue("Thread ID is a series of number", matcher.find());
// Name is blank in case of GDB back end
assertEquals("Thread name is blank for GDB Back end", "", threadData.getName());
}
fWait.waitReset();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,428 @@
package org.eclipse.dd.tests.gdb;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.debug.service.IFormattedValues;
import org.eclipse.dd.dsf.debug.service.IRegisters;
import org.eclipse.dd.dsf.debug.service.IFormattedValues.FormattedValueDMContext;
import org.eclipse.dd.dsf.debug.service.IFormattedValues.FormattedValueDMData;
import org.eclipse.dd.dsf.debug.service.IRegisters.IRegisterDMContext;
import org.eclipse.dd.dsf.debug.service.IRegisters.IRegisterGroupDMContext;
import org.eclipse.dd.dsf.debug.service.IStack.IFrameDMContext;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.gdb.service.command.GDBControl;
import org.eclipse.dd.gdb.service.command.GDBControlDMContext;
import org.eclipse.dd.mi.service.IMIExecutionDMContext;
import org.eclipse.dd.mi.service.MIRunControl;
import org.eclipse.dd.mi.service.MIStack;
import org.eclipse.dd.mi.service.command.events.MIStoppedEvent;
import org.eclipse.dd.tests.gdb.framework.AsyncCompletionWaitor;
import org.eclipse.dd.tests.gdb.framework.BackgroundRunner;
import org.eclipse.dd.tests.gdb.framework.BaseTestCase;
import org.eclipse.dd.tests.gdb.framework.SyncUtil;
import org.eclipse.dd.tests.gdb.launching.TestsPlugin;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(BackgroundRunner.class)
public class MIRegistersTest extends BaseTestCase {
final int NUMBER_OF_REGISTERS = 50;
/*
* Path to executable
*/
private static final String EXEC_PATH = "data/launch/bin/";
/*
* Name of the executable
*/
private static final String EXEC_NAME = "MultiThread.exe";
// Will be used to wait for asynchronous call to complete
//private final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
private DsfSession fSession;
private DsfServicesTracker fServicesTracker;
private GDBControlDMContext fGdbControlDmc;
private IRegisters fRegService;
private MIRunControl fRunControl;
private MIStack fStack;
@Before
public void init() throws Exception {
fSession = getGDBLaunch().getSession();
// We obtain the services we need after the new
// launch has been performed
fServicesTracker = new DsfServicesTracker(TestsPlugin.getBundleContext(), fSession.getId());
GDBControl gdbControl = fServicesTracker.getService(GDBControl.class);
fGdbControlDmc = gdbControl.getGDBDMContext();
fRegService = fServicesTracker.getService(IRegisters.class);
fRunControl = fServicesTracker.getService(MIRunControl.class);
fStack = fServicesTracker.getService(MIStack.class);
// This is the way to have the entire application run
// final IDMContext<IExecutionDMData> execDMContext = ((MIRunControl)fRunControl).getExecutionDMC();
// fRunControl.getExecutor().submit(new Runnable() {
// public void run() {
// fRunControl.resume(execDMContext, null);
// }
// });
}
@BeforeClass
public static void beforeClassMethod() {
setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
EXEC_PATH + EXEC_NAME);
}
@After
public void tearDown() {
fRegService = null;
fRunControl = null;
fStack = null;
}
/*
* This is a common support method which gets the Register Group Information
* and verifies it.
*/
private IRegisterGroupDMContext getRegisterGroup() throws Throwable {
final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
final DataRequestMonitor<IRegisterGroupDMContext[]> regGroupDone =
new DataRequestMonitor<IRegisterGroupDMContext[]>(fRegService.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
fRegService.getExecutor().submit(new Runnable() {
public void run() {
fRegService.getRegisterGroups(fGdbControlDmc, regGroupDone);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
assertTrue(fWait.getMessage(), fWait.isOK());
IRegisterGroupDMContext[] regGroupsDMCs = (IRegisterGroupDMContext[])fWait.getReturnInfo();
assertTrue("There was more than one register group (" + regGroupsDMCs.length + ")", //$NON-NLS-1$
regGroupsDMCs.length == 1 );
fWait.waitReset();
return(regGroupsDMCs[0]);
}
/*
* This is a common support method which gets the Registers names.
*/
private IRegisterDMContext[] getRegisters(final IFrameDMContext frameDmc) throws Throwable {
final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
final IRegisterGroupDMContext regGroupsDMC = getRegisterGroup();
final DataRequestMonitor<IRegisterDMContext[]> regDone =
new DataRequestMonitor<IRegisterDMContext[]>(fRegService.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
fRegService.getExecutor().submit(new Runnable() {
public void run() {
// fRegService.getRegisters(regGroupsDMC, frameDmc, regDone);
fWait.waitFinished(
new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID,
"Commented out some code until it can compile", null));
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
assertTrue(fWait.getMessage(), fWait.isOK());
IRegisterDMContext[] regContexts = (IRegisterDMContext[]) fWait.getReturnInfo();
fWait.waitReset();
assertTrue("The number of registers should have been " + NUMBER_OF_REGISTERS +
" instead of " + regContexts.length,
regContexts.length == NUMBER_OF_REGISTERS);
return(regContexts);
}
/*************************************************************************
*
* The tests for the register service.
*
*************************************************************************/
@Test
public void getRegisterGroups() throws Throwable {
final IRegisterGroupDMContext regGroupsDMC = getRegisterGroup();
assertTrue("The name of the main group should be: General Registers instead of: " +
regGroupsDMC.getName(),
regGroupsDMC.getName().equals("General Registers"));
}
@Test
public void getRegistersLength() throws Throwable {
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
final IRegisterDMContext[] regDMCs = getRegisters(frameDmc);
assertTrue("The number of registers should have been " + NUMBER_OF_REGISTERS +
" instead of " + regDMCs.length,
regDMCs.length == NUMBER_OF_REGISTERS);
}
@Test
public void getRegisters() throws Throwable {
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
final IRegisterDMContext[] regDMCs = getRegisters(frameDmc);
List<String> regNames = Arrays.asList("eax","ecx","edx","ebx","esp","ebp","esi","edi","eip","eflags","cs","ss","ds","es","fs","gs","st0","st1","st2","st3","st4","st5","st6","st7","fctrl","fstat","ftag","fiseg","fioff","foseg","fooff","fop","xmm0","xmm1","xmm2","xmm3","xmm4","xmm5","xmm6","xmm7","mxcsr","orig_eax","mm0","mm1","mm2","mm3","mm4","mm5","mm6","mm7");
for(IRegisterDMContext reg: regDMCs){
String regName = reg.getName();
Assert.assertFalse("GDB does not support register name: " + regName, !regNames.contains(regName));
}
}
//private static String REGISTER_VALUE = "16";
private String getModelDataForRegisterDataValue(IFrameDMContext frameDmc, String format, int regNo) throws Throwable {
final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
final IRegisterDMContext[] regDMCs = getRegisters(frameDmc);
final FormattedValueDMContext valueDmc = fRegService.getFormattedValueContext(regDMCs[regNo], format);
final DataRequestMonitor<FormattedValueDMData> regRm =
new DataRequestMonitor<FormattedValueDMData>(fRegService.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
fRegService.getExecutor().submit(new Runnable() {
public void run() {
fRegService.getFormattedExpressionValue(valueDmc, regRm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
assertTrue(fWait.getMessage(), fWait.isOK());
FormattedValueDMData data = (FormattedValueDMData)fWait.getReturnInfo();
String val = data.getFormattedValue();
fWait.waitReset();
return val;
}
private static String REGISTER_VALUE = "";
@Test
public void getModelDataForRegisterDataValueNatural() throws Throwable {
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 0);
REGISTER_VALUE = val;
assertTrue("Register Value is not in NATURAL format " , Integer.parseInt(val)== Integer.parseInt(REGISTER_VALUE));
}
@Test
public void getModelDataForRegisterDataValueHex() throws Throwable {
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.HEX_FORMAT, 0);
assertTrue("Register Value is not in HEX_FORMAT " ,val.startsWith("0x"));
}
@Test
public void getModelDataForRegisterDataValueBinary() throws Throwable {
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.BINARY_FORMAT, 0);
assertTrue("Register Value is not in BINARY_FORMAT " , val.equals(Integer.toBinaryString(Integer.parseInt(REGISTER_VALUE))));
}
@Test
public void getModelDataForRegisterDataValueDecimal() throws Throwable {
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.DECIMAL_FORMAT , 0);
assertTrue("Register Value is not in DECIMAL_FORMAT" ,Integer.parseInt(val) == Integer.parseInt(REGISTER_VALUE));
}
@Test
public void getModelDataForRegisterDataValueOctal() throws Throwable {
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.OCTAL_FORMAT, 0);
assertTrue("Register Value is not in OCTAL_FORMAT " ,val.startsWith("0"));
}
@Test
public void compareRegisterForMultipleExecutionContexts() throws Throwable {
final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String regVal0 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 0);
String regVal1 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 1);
String regVal2 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 2);
String regVal3 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 3);
String regVal4 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 4);
String regVal5 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 5);
MIStoppedEvent stoppedEvent = SyncUtil.SyncRunToLine(EXEC_NAME + ".cc", "22");
execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 2);
frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String thread2RegVal0 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 0);
String thread2RegVal1 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 1);
String thread2RegVal2 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 2);
String thread2RegVal3 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 3);
String thread2RegVal4 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 4);
String thread2RegVal5 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 5);
// Set execution context to 1
execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 0);
// Re-set the execution context to 2 and Fetch from the Cache
execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 2);
frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String dupliThread2RegVal0 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 0);
String dupliThread2RegVal1 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 1);
String dupliThread2RegVal2 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 2);
String dupliThread2RegVal3 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 3);
String dupliThread2RegVal4 = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 4);
String dupliThread2RegVal5= getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, 5);
// If Values not equal , then context haven't been re-set properly
assertTrue("Multiple context not working. Execution Context is not reset to 2", thread2RegVal0.equals(dupliThread2RegVal0));
assertTrue("Multiple context not working. Execution Context is not reset to 2", thread2RegVal1.equals(dupliThread2RegVal1));
assertTrue("Multiple context not working. Execution Context is not reset to 2", thread2RegVal2.equals(dupliThread2RegVal2));
assertTrue("Multiple context not working. Execution Context is not reset to 2", thread2RegVal3.equals(dupliThread2RegVal3));
assertTrue("Multiple context not working. Execution Context is not reset to 2", thread2RegVal4.equals(dupliThread2RegVal4));
assertTrue("Multiple context not working. Execution Context is not reset to 2", thread2RegVal5.equals(dupliThread2RegVal5));
}
private void writeRegister(IFrameDMContext frameDmc, final int regIndex, final String regValue, final String formatId) throws Throwable {
final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
// final MIRegisterGroupDMC grpDmc = new MIRegisterGroupDMC( (MIRegisters)fRegService , 0 , "General Registers" ) ;
final IRegisterDMContext[] regDMCs = getRegisters(frameDmc);
final RequestMonitor writeDone =
new RequestMonitor(fRegService.getExecutor(), null) {
@Override
protected void handleCompleted() {
fWait.waitFinished(getStatus());
}
};
fRegService.getExecutor().submit(new Runnable() {
public void run() {
// fRegService.writeRegister(grpDmc, regDMCs[regIndex], regValue,
// formatId, writeDone);
fWait.waitFinished(
new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID,
"Commented out some code until it can compile", null));
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
fWait.waitReset();
}
@Test
public void writeRegisterNaturalFormat() throws Throwable{
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String regValue = "10";
int regIndex = 3;
writeRegister(frameDmc, 3, regValue, IFormattedValues.NATURAL_FORMAT);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.NATURAL_FORMAT, regIndex);
assertTrue("Failed writing register. New value should have been " + regValue, regValue.equals(val));
}
@Test
public void writeRegisterHEXFormat() throws Throwable{
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
String regValue = "0x10";
int regIndex = 3;
writeRegister(frameDmc, 3, regValue, IFormattedValues.HEX_FORMAT);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.HEX_FORMAT, regIndex);
assertTrue("Failed writing register. New value should have been " + regValue, regValue.equals(val));
}
@Test
@Ignore
public void writeRegisterBinaryFormat() throws Throwable{
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
//String regValue = "0100101001";
String regValue = "10";
int regIndex = 3;
writeRegister(frameDmc, 3, regValue, IFormattedValues.BINARY_FORMAT);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.BINARY_FORMAT, regIndex);
assertTrue("Failed writing register. New value should have been " + regValue + " instead of " + val, regValue.equals(val));
}
@Test
public void writeRegisterOctalFormat() throws Throwable{
IMIExecutionDMContext execDmc = fRunControl.createMIExecutionContext(fGdbControlDmc, 1);
IFrameDMContext frameDmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
//String regValue = "10";
String regValue = "012";
int regIndex = 3;
writeRegister(frameDmc, 3, regValue, IFormattedValues.OCTAL_FORMAT);
String val = getModelDataForRegisterDataValue(frameDmc, IFormattedValues.OCTAL_FORMAT, regIndex);
assertTrue("Failed writing register. New value should have been " + regValue + "instead of " + val, regValue.equals(val));
}
}

View file

@ -0,0 +1,654 @@
/*******************************************************************************
* Copyright (c) 2007 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 AB - Initial implementation of Test cases
*******************************************************************************/
package org.eclipse.dd.tests.gdb;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.debug.service.IRunControl;
import org.eclipse.dd.dsf.debug.service.IRunControl.IContainerDMContext;
import org.eclipse.dd.dsf.debug.service.IRunControl.IExecutionDMContext;
import org.eclipse.dd.dsf.debug.service.IRunControl.IExecutionDMData;
import org.eclipse.dd.dsf.debug.service.IRunControl.IResumedDMEvent;
import org.eclipse.dd.dsf.debug.service.IRunControl.IStartedDMEvent;
import org.eclipse.dd.dsf.debug.service.IRunControl.StateChangeReason;
import org.eclipse.dd.dsf.debug.service.IRunControl.StepType;
import org.eclipse.dd.dsf.service.DsfServiceEventHandler;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.gdb.service.command.GDBControl;
import org.eclipse.dd.gdb.service.command.GDBControlDMContext;
import org.eclipse.dd.mi.service.IMIExecutionDMContext;
import org.eclipse.dd.mi.service.MIRunControl;
import org.eclipse.dd.mi.service.MIStack;
import org.eclipse.dd.mi.service.command.events.MIStoppedEvent;
import org.eclipse.dd.mi.service.command.output.MIInfo;
import org.eclipse.dd.tests.gdb.framework.AsyncCompletionWaitor;
import org.eclipse.dd.tests.gdb.framework.BaseTestCase;
import org.eclipse.dd.tests.gdb.framework.ServiceEventWaitor;
import org.eclipse.dd.tests.gdb.framework.SyncUtil;
import org.eclipse.dd.tests.gdb.launching.TestsPlugin;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
/*
* Tests MIRunControl class for Multi-threaded application.
*/
public class MIRunControlTest extends BaseTestCase {
private DsfServicesTracker fServicesTracker;
private GDBControl fGDBCtrl;
private MIRunControl fRunCtrl;
private MIStack fStack;
/*
* Boolean variables for testing events. Test thread create event only when this is set to true
*/
private boolean fIsTestingThreadCreateEvent = false;
/*
* Boolean variables for error from events. Set to true only if there is an error in the event being tested.
*/
private boolean fIsEventError = false;
/*
* Path to executable
*/
private static final String EXEC_PATH = "data/launch/bin/";
/*
* Name of the executable
*/
private static final String EXEC_NAME = "MultiThread.exe";
private static final String SOURCE_NAME = "MultiThread.cc";
/*
* Variable to wait for asynchronous call to complete
*/
private final AsyncCompletionWaitor fWait = new AsyncCompletionWaitor();
@Before
public void init() throws Exception {
fServicesTracker =
new DsfServicesTracker(TestsPlugin.getBundleContext(),
getGDBLaunch().getSession().getId());
/*
* Get the MIRunControl & MIStack service.
*/
fGDBCtrl = fServicesTracker.getService(GDBControl.class);
fRunCtrl = fServicesTracker.getService(MIRunControl.class);
fStack = fServicesTracker.getService(MIStack.class);
/*
* Add to the Listeners list
*/
getGDBLaunch().getSession().addServiceEventListener(this, null);
}
@After
public void tearDown() {
fRunCtrl = null;
fStack = null;
fServicesTracker.dispose();
}
@BeforeClass
public static void beforeClassMethod() {
setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
EXEC_PATH + EXEC_NAME);
}
/*
* For Multi-threaded application - In case of one thread, Thread id should start with 1.
*/
@Test
public void getExecutionContext() throws InterruptedException{
//TestsPlugin.debugMethod("getExecutionContext()");
/*
* Create a request monitor
*/
final DataRequestMonitor<IExecutionDMContext[]> rm =
new DataRequestMonitor<IExecutionDMContext[]>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
/*
* Test getExecutionContexts() when only one thread exist.
*/
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getExecutionContexts(fGDBCtrl.getGDBDMContext(), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
Assert.assertTrue(fWait.getMessage(), fWait.isOK());
/*
* Get data from the Request Monitor
*/
IRunControl.IExecutionDMContext[] ctxts = rm.getData();
// Context can not be null
if(ctxts == null)
Assert.fail("Context returned is null. Atleast one context should have been returned");
else{
// Only one Context in this case
if(ctxts.length > 1)
Assert.fail("Context returned canot be more than 1. This test case is for single context application.");
IMIExecutionDMContext dmc = (IMIExecutionDMContext)ctxts[0];
// Thread id for the main thread should be one
Assert.assertEquals(1, dmc.getThreadId());
}
fWait.waitReset();
}
/*
* Get Execution DMCs for a valid container DMC
* Testing for two execution DMC with id 1 & 2
*/
@Test
public void getExecutionContexts() throws InterruptedException{
//TestsPlugin.debugMethod("getExecutionContexts()");
/*
* Create a request monitor
*/
final DataRequestMonitor<IExecutionDMContext[]> rmExecutionCtxts =
new DataRequestMonitor<IExecutionDMContext[]>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
/*
* Also Testing Thread create event. Set boolean variable to true
*/
fIsTestingThreadCreateEvent = true;
try{
/*
* Run till line for 2 threads to be created
*/
SyncUtil.SyncRunToLine(fGDBCtrl.getGDBDMContext(), SOURCE_NAME, "22", true);
}
catch(Throwable t){
Assert.fail("Exception in SyncUtil.SyncRunToLine: " + t.getMessage());
}
/*
* Re-set the boolean variable for testing thread create event.
*/
fIsTestingThreadCreateEvent = false;
/*
* Check if error in thread create event
*/
if(fIsEventError){
Assert.fail("Thread create event has failed.");
}
/*
* Test getExecutionContexts for a valid container DMC
*/
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getExecutionContexts(fGDBCtrl.getGDBDMContext(), rmExecutionCtxts);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
Assert.assertTrue(fWait.getMessage(), fWait.isOK());
fWait.waitReset();
/*
* Get data
*/
IRunControl.IExecutionDMContext[] data = rmExecutionCtxts.getData();
/*
* Contexts returned can not be null
*/
if(data == null)
Assert.fail("No context returned. 2 Contexts with id 1 & 2 should have been returned");
else{
// 2 Contexts shd be returned
Assert.assertTrue(data.length==2);
IMIExecutionDMContext dmc1 = (IMIExecutionDMContext)data[0];
IMIExecutionDMContext dmc2 = (IMIExecutionDMContext)data[1];
// Context ids should be 1 & 2
Assert.assertTrue(dmc1.getThreadId()==2 && dmc2.getThreadId() == 1);
}
}
/*
* Testing getModelData() for ExecutionDMC
*/
@Test
public void getModelDataForThread() throws InterruptedException{
//TestsPlugin.debugMethod("getModelDataForThread(");
/*
* Create a request monitor
*/
final DataRequestMonitor<IExecutionDMData> rm =
new DataRequestMonitor<IExecutionDMData>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
/*
* Call getModelData for Execution DMC
*/
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getExecutionData(fRunCtrl.createMIExecutionContext(fGDBCtrl.getGDBDMContext(), 1), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
Assert.assertTrue(fWait.getMessage(), fWait.isOK());
IRunControl.IExecutionDMData data = rm.getData();
if(data == null)
Assert.fail("No data returned.");
else{
/*
* getModelData should return StateChangeReason.
*/
Assert.assertTrue(" State change reason for a normal execution should be CONTAINER." ,
StateChangeReason.CONTAINER == data.getStateChangeReason());
}
}
@Test
public void getModelDataForThreadWhenStep() throws Throwable {
//TestsPlugin.debugMethod("getModelDataForThread()");
/*
* Run till step returns
*/
final MIStoppedEvent stoppedEvent = SyncUtil.SyncStep(StepType.STEP_OVER);
final DataRequestMonitor<IExecutionDMData> rm =
new DataRequestMonitor<IExecutionDMData>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
/*
* getModelData for Execution DMC
*/
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getExecutionData(stoppedEvent.getDMContext(), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
Assert.assertTrue(fWait.getMessage(), fWait.isOK());
IRunControl.IExecutionDMData data = rm.getData();
if(data == null)
Assert.fail("No data Returned.");
else{
/*
* getModelData for Execution DMC in case Step has been performed.
*/
Assert.assertTrue("getModelData for ExecutionDMC in case of step should be STEP." ,
StateChangeReason.STEP == data.getStateChangeReason());
}
}
/*
* getModelData() for ExecutionDMC when a breakpoint is hit
*/
@Test
public void getModelDataForThreadWhenBreakpoint() throws Throwable {
//TestsPlugin.debugMethod("getModelDataForThreadWhenBreakpoint()");
/*
* Add a breakpoint
*/
SyncUtil.SyncAddBreakpoint(SOURCE_NAME + ":21", false);
/*
* Resume till the breakpoint is hit
*/
final MIStoppedEvent stoppedEvent = SyncUtil.SyncResumeUntilStopped();
final DataRequestMonitor<IExecutionDMData> rm =
new DataRequestMonitor<IExecutionDMData>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getExecutionData(stoppedEvent.getDMContext(), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
Assert.assertTrue(fWait.getMessage(), fWait.isOK());
IRunControl.IExecutionDMData data = rm.getData();
if(data == null)
Assert.fail("No data Returned.");
else{
/*
* getModelData for ExecutionDMC in case a breakpoint is hit
*/
Assert.assertTrue("getModelData for an Execution DMC when a breakpoint is hit is not BREAKPOINT and is " + data.getStateChangeReason(),
StateChangeReason.BREAKPOINT == data.getStateChangeReason());
}
}
/*
* getModelData() for Container DMC
*/
@Test
public void getModelDataForContainer() throws InterruptedException{
//TestsPlugin.debugMethod("getModelDataForContainer()");
final DataRequestMonitor<IExecutionDMData> rm =
new DataRequestMonitor<IExecutionDMData>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.getExecutionData(fGDBCtrl.getGDBDMContext(), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
Assert.assertTrue(fWait.getMessage(), fWait.isOK());
IRunControl.IExecutionDMData data = rm.getData();
if(data == null)
Assert.fail("No data returned.");
else{
/*
* StateChangeReason in getModelData for Container DMC is null.
*/
Assert.assertNull(data.getStateChangeReason());
}
}
/*
* getExecutionContexts for an invalid container DMC
*/
@Ignore
@Test
public void getExecutionContextsForInvalidContainerDMC() throws InterruptedException{
//TestsPlugin.debug("getExecutionContextsForInvalidContainerDMC()");
final DataRequestMonitor<IExecutionDMContext[]> rm =
new DataRequestMonitor<IExecutionDMContext[]>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
fWait.setReturnInfo(getData());
}
fWait.waitFinished(getStatus());
}
};
final IContainerDMContext ctxt = new GDBControlDMContext("-1", getClass().getName() + ":" + 1);
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
// Pass an invalid dmc
fRunCtrl.getExecutionContexts(fGDBCtrl.getGDBDMContext(), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
Assert.assertTrue(fWait.getMessage(), !fWait.isOK());
IStatus status = rm.getStatus();
Assert.assertEquals("Error message for invalid container", IStatus.ERROR, status.getSeverity());
}
/*
* Test Thread Create event for thread ID. Thread IDs should be GDB generated thread ids.
*/
@DsfServiceEventHandler
public void eventDispatched(IStartedDMEvent e) {
if(fIsTestingThreadCreateEvent){
if(((IMIExecutionDMContext)e.getExecutionContext()).getThreadId() != 2)
/*
* Set variable if thread create event is unsuccesful
*/
fIsEventError = true;
}
}
/*
* Cache after ContainerSuspendEvent should be re-set
*/
@Test
public void cacheAfterContainerSuspendEvent() throws InterruptedException{
//TestsPlugin.debugMethod("cacheAfterContainerSuspendEvent()");
final IExecutionDMContext dmc = fRunCtrl.createMIExecutionContext(fGDBCtrl.getGDBDMContext(), 1);
/*
* Step to fire ContainerSuspendEvent
*/
try {
SyncUtil.SyncStep(dmc, StepType.STEP_OVER);
} catch (Throwable e) {
Assert.fail("Exception in SyncUtil.SyncStep: " + e.getMessage());
}
/*
* Cache should be re-set
*/
//TODO TRy going to back end and fetching values instead
//Assert.assertEquals(fRunCtrl.getCache().getCachedContext().size(), 0);
}
//Also test Cache after ContainerResumeEvent
@Test
public void resume() throws InterruptedException{
//TestsPlugin.debugMethod("resume()");
final DataRequestMonitor<MIInfo> rm =
new DataRequestMonitor<MIInfo>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
fWait.waitFinished(getStatus());
//TestsPlugin.debug("handleCompleted over");
}
};
final ServiceEventWaitor<IResumedDMEvent> eventWaitor =
new ServiceEventWaitor<IResumedDMEvent>(
getGDBLaunch().getSession(),
IResumedDMEvent.class);
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.resume(fGDBCtrl.getGDBDMContext(), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
try {
eventWaitor.waitForEvent(ServiceEventWaitor.WAIT_FOREVER);
} catch (Exception e) {
Assert.fail("Exception raised:: " + e.getMessage());
e.printStackTrace();
return;
}
if (fWait.isOK() == false)
Assert.assertTrue(fWait.getMessage(), false);
Assert.assertFalse("Target is suspended. It should have been running", fRunCtrl.isSuspended(fGDBCtrl.getGDBDMContext()));
fWait.waitReset();
}
@Test
public void resumeContainerContext() throws InterruptedException{
//TestsPlugin.debugMethod("resumeContainerContext()");
final DataRequestMonitor<MIInfo> rm =
new DataRequestMonitor<MIInfo>(fRunCtrl.getExecutor(), null) {
@Override
protected void handleCompleted() {
fWait.waitFinished(getStatus());
}
};
final ServiceEventWaitor<IResumedDMEvent> eventWaitor =
new ServiceEventWaitor<IResumedDMEvent>(
getGDBLaunch().getSession(),
IResumedDMEvent.class);
fRunCtrl.getExecutor().submit(new Runnable() {
public void run() {
fRunCtrl.resume(fGDBCtrl.getGDBDMContext(), rm);
}
});
fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
try {
eventWaitor.waitForEvent(ServiceEventWaitor.WAIT_FOREVER);
//TestsPlugin.debug("DsfMIRunningEvent received");
} catch (Exception e) {
Assert.fail("Exception raised:: " + e.getMessage());
e.printStackTrace();
return;
}
if (fWait.isOK() == false)
Assert.assertTrue(fWait.getMessage(), false);
Assert.assertFalse("Target is suspended. It should have been running", fRunCtrl.isSuspended(fGDBCtrl.getGDBDMContext()));
fWait.waitReset();
}
// PP: test no longer applies, the resume command now takes a strongly-typed execution context as an argument.
//
// @Test
// public void resumeFrameContext() throws Throwable {
// //TestsPlugin.debugMethod("resumeFrameContext()");
// final DataRequestMonitor<DsfMIInfo> rm =
// new DataRequestMonitor<DsfMIInfo>(fRunCtrl.getExecutor(), null) {
// @Override
// protected void handleCompleted() {
// fWait.waitFinished(getStatus());
// }
// };
// final ServiceEventWaitor<IResumedDMEvent> eventWaitor =
// new ServiceEventWaitor<IResumedDMEvent>(
// getGDBLaunch().getSession(),
// IResumedDMEvent.class);
//
// IExecutionDMContext execDmc = fRunCtrl.createMIExecutionContext(fGDBCtrl.getGDBDMContext(), 1);
// final IFrameDMContext dmc = SyncUtil.SyncGetStackFrame(execDmc, 0);
// fRunCtrl.getExecutor().submit(new Runnable() {
// public void run() {
// fRunCtrl.resume(dmc, rm);
// }
// });
// fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
//
// try {
// eventWaitor.waitForEvent(ServiceEventWaitor.WAIT_FOREVER);
// } catch (Exception e) {
// Assert.fail("Exception raised:: " + e.getMessage());
// e.printStackTrace();
// return;
// }
//
// if (fWait.isOK() == false)
// Assert.assertTrue(fWait.getMessage(), false);
// Assert.assertFalse("Target is suspended. It should have been running", fRunCtrl.isSuspended(fGDBCtrl.getGDBDMContext()));
// fWait.waitReset();
// }
// @Test
// public void resumeAndSuspend() throws InterruptedException{
// final DataRequestMonitor<DsfMIInfo> rm =
// new DataRequestMonitor<DsfMIInfo>(fRunCtrl.getExecutor(), null) {
// @Override
// protected void handleCompleted() {
// if (getStatus().isOK()) {
// assert true;
// fWait.setReturnInfo(getData());
// }
// System.out.println("Wait Finished called on getTHreads rm with status " + getStatus().getMessage());
// fWait.waitFinished(getStatus());
// }
// };
// final MIExecutionDMC dmc = new MIExecutionDMC(fRunCtrl, 1);
// fRunCtrl.getExecutor().submit(new Runnable() {
// public void run() {
// fRunCtrl.resume(dmc, rm);
// }
// });
// fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
// if (fWait.isOK() == false)
// Assert.assertTrue(fWait.getMessage(), false);
// System.out.println("Message from isSuspended " +fRunCtrl.isSuspended(dmc));
// Assert.assertFalse("Target is suspended. It should have been running", fRunCtrl.isSuspended(dmc));
// fWait.waitReset();
//
// final DataRequestMonitor<DsfMIInfo> rmSuspend =
// new DataRequestMonitor<DsfMIInfo>(fRunCtrl.getExecutor(), null) {
// @Override
// protected void handleCompleted() {
// if (getStatus().isOK()) {
// assert true;
// fWait.setReturnInfo(getData());
// }
// System.out.println("Wait Finished called on getTHreads rm with status " + getStatus().getMessage());
// fWait.waitFinished(getStatus());
// }
// };
//
// final ServiceEventWaitor eventWaitor =
// new ServiceEventWaitor(
// getGDBLaunch().getSession(),
// DsfMIStoppedEvent.class);
//
// fRunCtrl.getExecutor().submit(new Runnable() {
// public void run() {
// fRunCtrl.suspend(dmc, rmSuspend);
// }
// });
// fWait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
// try {
// eventWaitor.waitForEvent(ServiceEventWaitor.WAIT_FOREVER);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// if (fWait.isOK() == false)
// Assert.assertTrue(fWait.getMessage(), false);
// System.out.println("Message from isSuspended !!! " +fRunCtrl.isSuspended(dmc));
// Assert.assertTrue("Target is running. It should have been suspended.", fRunCtrl.isSuspended(dmc));
// fWait.waitReset();
// }
}

View file

@ -0,0 +1,125 @@
/*******************************************************************************
* Copyright (c) 2007 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 Implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.framework;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.tests.gdb.launching.TestsPlugin;
public class AsyncCompletionWaitor {
/*
* Indicates we will wait forever. Otherwise the time specified
* is in milliseconds.
*/
public final static int WAIT_FOREVER = 0;
/*
* Private control space.
*/
private IStatus fStatus;
private Object fReturnInfo;
private boolean fWaitFinished;
private int fNumWaiting;
/*
* Main constructor.
*/
public AsyncCompletionWaitor() {
waitReset();
}
/*
* A timeout of WAIT_FOREVER indicates we wait until the operation is
* completed by a call to waitFinished. Or if we are interrupted
* with an exception.
*/
public synchronized void waitUntilDone(int timeout) throws InterruptedException {
if (fWaitFinished) return;
wait(timeout);
}
/*
* Indicates that we are done with the operation and the code
* waiting ( waitUntilDone ) will be allowed to continue.
*/
public void waitFinished() {
waitFinished(new Status(IStatus.OK, TestsPlugin.PLUGIN_ID, ""));
}
public synchronized void waitFinished(IStatus status) {
if (fWaitFinished) {
((MultiStatus)fStatus).merge(
new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID,
"waitFinished called too many times!", null));
}
((MultiStatus)fStatus).merge(status);
if (fNumWaiting == 0 || --fNumWaiting == 0) {
fWaitFinished = true;
notifyAll();
}
}
/*
* Resets the state so we allow ourselves to be reused instead
* of having to create a new wait object each time.
*/
public synchronized void waitReset() {
fWaitFinished = false;
fStatus = new MultiStatus(TestsPlugin.PLUGIN_ID, 0, "", null); //$NON-NLS-1$
fReturnInfo = null;
fNumWaiting = 0;
}
public boolean isOK() {
if ( fStatus == null ) {
// We timed out
return false;
}
return fStatus.isOK();
}
public String getMessage() {
if ( fStatus == null ) {
return "Timed out"; //$NON-NLS-1$
}
// Build a concatenation of all messages
String fullMessage = "";
IStatus[] children = fStatus.getChildren();
for (int i=0; i<children.length; i++) {
if (children[i].getMessage().length() > 0) {
fullMessage += "\"" + children[i].getMessage() + "\", ";//$NON-NLS-1$//$NON-NLS-2$
}
}
// Remove the trailing comma and space before returning (as long as they are there)
return fullMessage.length() <= 2 ? fullMessage : fullMessage.substring(0, fullMessage.length() - 2);
}
public void setReturnInfo(Object info) {
fReturnInfo = info ;
}
public Object getReturnInfo() {
return fReturnInfo;
}
public void increment() {
fNumWaiting++;
}
}

View file

@ -0,0 +1,135 @@
/*******************************************************************************
* Copyright (c) 2007 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 Implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.framework;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.dd.tests.gdb.launching.TestsPlugin;
import org.eclipse.swt.widgets.Display;
import org.junit.internal.runners.InitializationError;
import org.junit.internal.runners.TestClassRunner;
import org.junit.runner.notification.RunNotifier;
/**
* This runner starts an eclipse job ro run the tests, so as
* to release the UI thread.
*/
@SuppressWarnings("restriction")
public class BackgroundRunner extends TestClassRunner {
public BackgroundRunner(Class<?> klass) throws InitializationError {
super(klass);
}
final static QualifiedName BACKGROUND_TEST_EXECUTION_FINISHED = new QualifiedName(TestsPlugin.getDefault().getBundle().getSymbolicName(), "background_test_execution_finished"); //$NON-NLS-1$
void invokeSuperRunImpl(RunNotifier notifier) {
super.run(notifier);
}
/*
* This method overrides the one from TestClassRunner.
* What we do here is start a background job which will call
* TestClassRunner.run; this enables us to release
* the main UI thread.
*
* This has been adapted from the JUnits tests of TargetManagement
* (RSECoreTestCase and RSEWaitAndDispatchUtil)
*/
@Override
public void run(final RunNotifier notifier) {
// Start the test in a background thread
Job job = new Job("GDB/MI JUnit Test Case Execution Job") {
@Override
protected IStatus run(IProgressMonitor monitor) {
invokeSuperRunImpl(notifier);
monitor.done();
setProperty(BACKGROUND_TEST_EXECUTION_FINISHED, Boolean.TRUE);
// The job never fails. The test result is the real result.
return Status.OK_STATUS;
}
};
// The job is not complete yet
job.setProperty(BACKGROUND_TEST_EXECUTION_FINISHED, Boolean.FALSE);
// schedule the job to run immediatelly
job.schedule();
// wait till the job finishes executing
waitAndDispatch(0, new BackgroundTestExecutionJobWaiter(job));
}
public interface IInterruptCondition {
public boolean isTrue();
public void dispose();
}
private final static class BackgroundTestExecutionJobWaiter implements IInterruptCondition {
private final Job job;
public BackgroundTestExecutionJobWaiter(Job job) {
assert job != null;
this.job = job;
}
public boolean isTrue() {
// Interrupt the wait method if the job signaled that it has finished.
return ((Boolean)job.getProperty(BACKGROUND_TEST_EXECUTION_FINISHED)).booleanValue();
}
public void dispose() {
// nothing to do
}
}
public static boolean waitAndDispatch(long timeout, IInterruptCondition condition) {
assert timeout >= 0 && condition != null;
boolean isTimedOut= false;
if (timeout >= 0 && condition != null) {
long start = System.currentTimeMillis();
Display display = Display.findDisplay(Thread.currentThread());
if (display != null) {
// ok, we are running within a display thread --> keep the
// display event dispatching running.
long current = System.currentTimeMillis();
while (timeout == 0 || (current - start) < timeout) {
if (condition.isTrue()) break;
if (!display.readAndDispatch()) display.sleep();
current = System.currentTimeMillis();
}
isTimedOut = (current - start) >= timeout && timeout > 0;
} else {
// ok, we are not running within a display thread --> we can
// just block the thread here
long current = System.currentTimeMillis();
while (timeout == 0 || (current - start) < timeout) {
if (condition.isTrue()) break;
try { Thread.sleep(50); } catch (InterruptedException e) { /* ignored on purpose */ }
current = System.currentTimeMillis();
}
isTimedOut = (current - start) >= timeout && timeout > 0;
}
}
// Signal the interrupt condition that we are done here
// and it can cleanup whatever necessary.
condition.dispose();
return isTimedOut;
}
}

View file

@ -0,0 +1,100 @@
/*******************************************************************************
* Copyright (c) 2007 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 Implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.framework;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.dd.gdb.launching.GdbLaunch;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
/**
* This is the base class for the GDB/MI Unit tests.
* It provides the @Before and @After methods which setup
* and teardown the launch, for each test.
* If these methods are overwridden by a subclass, the new method
* must call super.baseSetup or super.baseTeardown itself, if this
* code is to be run.
*/
public class BaseTestCase {
private static final String DEFAULT_TEST_APP = "data/launch/bin/GDBMIGenericTestApp";
private static GdbLaunch fLaunch;
private static Map<String, Object> attrs = new HashMap<String, Object>();
public GdbLaunch getGDBLaunch() { return fLaunch; }
public static void setLaunchAttribute(String key, Object value) {
attrs.put(key, value);
}
@BeforeClass
public static void baseBeforeClassMethod() {
// Setup information for the launcher
attrs.put(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, DEFAULT_TEST_APP);
attrs.put(ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL, true);
attrs.put(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN, true);
attrs.put(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN_SYMBOL, ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT);
}
@Before
public void baseBeforeMethod() throws Exception {
System.out.println("====================================================================");
System.out.println("Launching test application: " + attrs.get(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME));
System.out.println("====================================================================");
ILaunchManager launchMgr = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType lcType = launchMgr.getLaunchConfigurationType("org.eclipse.dd.tests.gdb.TestLaunch");
assert lcType != null;
ILaunchConfigurationWorkingCopy lcWorkingCopy = lcType.newInstance(
null,
launchMgr.generateUniqueLaunchConfigurationNameFrom("Test Launch")); //$NON-NLS-1$
assert lcWorkingCopy != null;
lcWorkingCopy.setAttributes(attrs);
final ILaunchConfiguration lc = lcWorkingCopy.doSave();
assert lc != null;
fLaunch = (GdbLaunch)lc.launch(ILaunchManager.DEBUG_MODE, new NullProgressMonitor());
assert fLaunch != null;
// Now initialize our SyncUtility, since we have the launcher
SyncUtil.initialize(fLaunch.getSession());
}
@After
public void baseAfterMethod() throws Exception {
System.out.println("====================================================================");
System.out.println("Tearing down test application: " + attrs.get(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME));
System.out.println("====================================================================");
if (fLaunch != null) {
fLaunch.terminate();
fLaunch = null;
}
}
@AfterClass
public static void baseAfterClassMehod() throws Exception {
}
}

View file

@ -0,0 +1,104 @@
/*******************************************************************************
* Copyright (c) 2007 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 Implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.framework;
import org.eclipse.dd.dsf.service.DsfServiceEventHandler;
import org.eclipse.dd.dsf.service.DsfSession;
/*
* This class provides a way to wait for an asynchronous ServerEvent
* to occur. The user of this class specifies which event is of
* interest using the proper constructor or the registerForEvent() method.
* waitForEvent() can then be called to block until the event occurs or
* the timeout elapses.
*
* Note that if the event occurs after regsiterForEvent() is called but
* before waitForEvent() is called, waitForEvent() will return immediatly
* since it will know the event has already occured.
*/
public class ServiceEventWaitor<V> {
/*
* Indicates we will wait forever. Otherwise the time specified
* is in milliseconds.
*/
public final static int WAIT_FOREVER = 0 ;
/* The type of event to wait for */
private Class<V> fEventTypeClass;
private DsfSession fSession;
private V fEvent;
/* Empty contructor. registerForEvent() should be called when
* this constructor is used.
*/
public ServiceEventWaitor(DsfSession session) {
fSession = session;
}
/* Contructor that takes the eventClass as parameter. This is a shortcut
* that avoids calling registerForEvent()
*/
public ServiceEventWaitor(DsfSession session, Class<V> eventClass) {
this(session);
registerForEvent(eventClass);
}
/* Specify which event to wait for, and add ourselves as
* a listener with the session
*/
public void registerForEvent(Class<V> eventClass) {
fEventTypeClass = eventClass;
fEvent = null;
fSession.addServiceEventListener(this, null);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if (fEventTypeClass != null) fSession.removeServiceEventListener(this);
}
/* Block until 'timeout' or the previously specified event has been
* received. The reason we don's specify the event as a parameter
* is that we must be ready for the event to occur event before
* this method is called.
*/
public synchronized V waitForEvent(int timeout) throws Exception {
if (fEventTypeClass == null) {
throw new Exception("Event to wait for has not been specified!");
}
// The event might have already been received
if (fEvent != null) return fEvent;
wait(timeout);
if (fEvent == null) {
throw new Exception("Timed out waiting for ServiceEvent: " + fEventTypeClass.getName());
}
return fEvent;
}
/*
* Listen to all possible events by having the base class be the parameter.
* and then igure out if that event is the one we were waiting for.
*/
@DsfServiceEventHandler
public void eventDispatched(V event) {
if (fEventTypeClass.isAssignableFrom(event.getClass())) {
synchronized(this) {
fEvent = event;
notifyAll();
}
}
}
}

View file

@ -0,0 +1,314 @@
/*******************************************************************************
* Copyright (c) 2007 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 AB - Initial implementation of Test cases
*******************************************************************************/
package org.eclipse.dd.tests.gdb.framework;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.Callable;
import junit.framework.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.concurrent.Query;
import org.eclipse.dd.dsf.datamodel.IDMContext;
import org.eclipse.dd.dsf.debug.service.IExpressions;
import org.eclipse.dd.dsf.debug.service.IFormattedValues;
import org.eclipse.dd.dsf.debug.service.IExpressions.IExpressionDMContext;
import org.eclipse.dd.dsf.debug.service.IFormattedValues.FormattedValueDMContext;
import org.eclipse.dd.dsf.debug.service.IFormattedValues.IFormattedDataDMContext;
import org.eclipse.dd.dsf.debug.service.IRunControl.IExecutionDMContext;
import org.eclipse.dd.dsf.debug.service.IRunControl.StepType;
import org.eclipse.dd.dsf.debug.service.IStack.IFrameDMContext;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.gdb.service.command.GDBControl;
import org.eclipse.dd.mi.service.MIRunControl;
import org.eclipse.dd.mi.service.MIStack;
import org.eclipse.dd.mi.service.command.commands.MIBreakDelete;
import org.eclipse.dd.mi.service.command.commands.MIBreakInsert;
import org.eclipse.dd.mi.service.command.commands.MIBreakList;
import org.eclipse.dd.mi.service.command.commands.MIExecContinue;
import org.eclipse.dd.mi.service.command.commands.MIExecFinish;
import org.eclipse.dd.mi.service.command.commands.MIExecNext;
import org.eclipse.dd.mi.service.command.commands.MIExecStep;
import org.eclipse.dd.mi.service.command.commands.MIExecUntil;
import org.eclipse.dd.mi.service.command.events.MIStoppedEvent;
import org.eclipse.dd.mi.service.command.output.MIBreakInsertInfo;
import org.eclipse.dd.mi.service.command.output.MIBreakListInfo;
import org.eclipse.dd.mi.service.command.output.MIBreakpoint;
import org.eclipse.dd.mi.service.command.output.MIInfo;
import org.eclipse.dd.tests.gdb.launching.TestsPlugin;
public class SyncUtil {
private static GDBControl fGDBControl;
private static MIRunControl fRunControl;
private static MIStack fStack;
private static IExpressions fExpressions;
private static DsfSession fSession;
// Initialize some common things, once the session has been established
public static void initialize(DsfSession session) {
fSession = session;
DsfServicesTracker tracker =
new DsfServicesTracker(TestsPlugin.getBundleContext(),
fSession.getId());
fGDBControl = tracker.getService(GDBControl.class);
fRunControl = tracker.getService(MIRunControl.class);
fStack = tracker.getService(MIStack.class);
fExpressions = tracker.getService(IExpressions.class);
}
public static MIStoppedEvent SyncStep(final StepType stepType, int numSteps) throws Throwable {
MIStoppedEvent retVal = null;
for (int i=0; i<numSteps; i++) {
retVal = SyncStep(stepType);
}
return retVal;
}
public static MIStoppedEvent SyncStep(final StepType stepType) throws Throwable {
return SyncStep(fGDBControl.getGDBDMContext(), stepType);
}
public static MIStoppedEvent SyncStep(final IExecutionDMContext dmc, final StepType stepType) throws Throwable {
final ServiceEventWaitor<MIStoppedEvent> eventWaitor =
new ServiceEventWaitor<MIStoppedEvent>(
fSession,
MIStoppedEvent.class);
fRunControl.getExecutor().submit(new Runnable() {
public void run() {
// No need for a RequestMonitor since we will wait for the
// ServiceEvent telling us the program has been suspended again
switch(stepType) {
case STEP_INTO:
fGDBControl.queueCommand(new MIExecStep(dmc), null);
break;
case STEP_OVER:
fGDBControl.queueCommand(new MIExecNext(dmc), null);
break;
case STEP_RETURN:
fGDBControl.queueCommand(new MIExecFinish(fStack.createFrameDMContext(dmc, 0)), null);
break;
default:
Assert.assertTrue("Unsupported step type; " + stepType.toString(), false);
}
}
});
// Wait for the execution to suspend after the step
return eventWaitor.waitForEvent(ServiceEventWaitor.WAIT_FOREVER);
}
public static MIStoppedEvent SyncRunToLine(final IExecutionDMContext dmc, final String fileName, final String lineNo,
final boolean skipBreakpoints) throws Throwable {
final ServiceEventWaitor<MIStoppedEvent> eventWaitor =
new ServiceEventWaitor<MIStoppedEvent>(
fSession,
MIStoppedEvent.class);
fRunControl.getExecutor().submit(new Runnable() {
public void run() {
// No need for a RequestMonitor since we will wait for the
// ServiceEvent telling us the program has been suspended again
fGDBControl.queueCommand(
new MIExecUntil(dmc, fileName + ":" + lineNo), //$NON-NLS-1$
null);
}
});
// Wait for the execution to suspend after the step
return eventWaitor.waitForEvent(ServiceEventWaitor.WAIT_FOREVER);
}
public static MIStoppedEvent SyncRunToLine(final String fileName, final String lineNo,
final boolean skipBreakpoints) throws Throwable {
return SyncRunToLine(fGDBControl.getGDBDMContext(), fileName, lineNo, skipBreakpoints);
}
public static MIStoppedEvent SyncRunToLine(final String fileName, final String lineNo) throws Throwable {
return SyncRunToLine(fGDBControl.getGDBDMContext(), fileName, lineNo, false);
}
public static int SyncAddBreakpoint(final String location) throws Throwable {
return SyncAddBreakpoint(location, true);
}
public static int SyncAddBreakpoint(final String location, boolean temporary)
throws Throwable {
final AsyncCompletionWaitor wait = new AsyncCompletionWaitor();
DataRequestMonitor<MIBreakInsertInfo> addBreakDone =
new DataRequestMonitor<MIBreakInsertInfo>(fRunControl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
wait.setReturnInfo(getData());
}
wait.waitFinished(getStatus());
}
};
fGDBControl.queueCommand(
new MIBreakInsert(fGDBControl.getGDBDMContext(), temporary, false, null, 0, location, 0),
addBreakDone);
wait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
assertTrue(wait.getMessage(), wait.isOK());
MIBreakInsertInfo info = (MIBreakInsertInfo) wait.getReturnInfo();
return info.getMIBreakpoints()[0].getNumber();
}
public static int[] SyncGetBreakpointList() throws Throwable {
final AsyncCompletionWaitor wait = new AsyncCompletionWaitor();
DataRequestMonitor<MIBreakListInfo> listDRM =
new DataRequestMonitor<MIBreakListInfo>(fRunControl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
wait.setReturnInfo(getData());
}
wait.waitFinished(getStatus());
}
};
fGDBControl.queueCommand(new MIBreakList(fGDBControl.getGDBDMContext()), listDRM);
wait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
assertTrue(wait.getMessage(), wait.isOK());
MIBreakpoint[] breakpoints = listDRM.getData().getMIBreakpoints();
int[] result = new int[breakpoints.length];
for (int i = 0; i < breakpoints.length; i++) {
result[i] = breakpoints[i].getNumber();
}
return result;
}
public static void SyncDeleteBreakpoint(int breakpointIndex) throws Throwable {
SyncDeleteBreakpoint(new int[] {breakpointIndex});
}
public static void SyncDeleteBreakpoint(int[] breakpointIndices) throws Throwable {
final AsyncCompletionWaitor wait = new AsyncCompletionWaitor();
DataRequestMonitor<MIInfo> deleteBreakDone =
new DataRequestMonitor<MIInfo>(fRunControl.getExecutor(), null) {
@Override
protected void handleCompleted() {
if (getStatus().isOK()) {
wait.setReturnInfo(getData());
}
wait.waitFinished(getStatus());
}
};
fGDBControl.queueCommand(
new MIBreakDelete(fGDBControl.getGDBDMContext(), breakpointIndices), //$NON-NLS-1$
deleteBreakDone);
wait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER);
assertTrue(wait.getMessage(), wait.isOK());
}
public static MIStoppedEvent SyncResumeUntilStopped(final IExecutionDMContext dmc) throws Throwable {
final ServiceEventWaitor<MIStoppedEvent> eventWaitor =
new ServiceEventWaitor<MIStoppedEvent>(
fSession,
MIStoppedEvent.class);
fRunControl.getExecutor().submit(new Runnable() {
public void run() {
// No need for a RequestMonitor since we will wait for the
// ServiceEvent telling us the program has been suspended again
fGDBControl.queueCommand(
new MIExecContinue(dmc),
null);
}
});
// Wait for the execution to suspend after the step
return eventWaitor.waitForEvent(ServiceEventWaitor.WAIT_FOREVER);
}
public static MIStoppedEvent SyncResumeUntilStopped() throws Throwable {
return SyncResumeUntilStopped(fGDBControl.getGDBDMContext());
}
public static MIStoppedEvent SyncRunToLocation(final String location) throws Throwable {
// Set a temporary breakpoint and run to it.
// Note that if there were other breakpoints set ahead of this one,
// they will stop execution earlier than planned
SyncAddBreakpoint(location, true);
return SyncResumeUntilStopped();
}
public static IFrameDMContext SyncGetStackFrame(final IExecutionDMContext execCtx, final int level) throws Throwable {
class StackFrameQuery extends Query<IFrameDMContext> {
@Override
protected void execute(final DataRequestMonitor<IFrameDMContext> rm) {
fStack.getFrames(execCtx, new DataRequestMonitor<IFrameDMContext[]>(fSession.getExecutor(), rm) {
@Override
protected void handleOK() {
if (getData().length > level) {
rm.setData(getData()[level]);
} else {
rm.setStatus(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, "Frame not available"));
}
rm.done();
}
});
}
}
StackFrameQuery sfQuery = new StackFrameQuery();
fSession.getExecutor().execute(sfQuery);
return sfQuery.get();
}
public static IExpressionDMContext SyncCreateExpression(final IDMContext parentCtx, final String expression)
throws Throwable {
Callable<IExpressionDMContext> callable = new Callable<IExpressionDMContext>() {
public IExpressionDMContext call() throws Exception {
return fExpressions.createExpression(parentCtx, expression);
}
};
return fSession.getExecutor().submit(callable).get();
}
public static FormattedValueDMContext SyncGetFormattedValue(
final IFormattedValues service, final IFormattedDataDMContext dmc, final String formatId) throws Throwable
{
Callable<FormattedValueDMContext> callable = new Callable<FormattedValueDMContext>() {
public FormattedValueDMContext call() throws Exception {
return service.getFormattedValueContext(dmc, formatId);
}
};
return fSession.getExecutor().submit(callable).get();
}
}

View file

@ -0,0 +1,262 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.launching;
import java.util.concurrent.TimeUnit;
import org.eclipse.cdt.debug.core.CDebugCorePlugin;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.cdt.debug.internal.core.sourcelookup.CSourceLookupDirector;
import org.eclipse.cdt.debug.mi.core.IMILaunchConfigurationConstants;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.concurrent.Sequence;
import org.eclipse.dd.dsf.debug.service.StepQueueManager;
import org.eclipse.dd.dsf.service.DsfServiceEventHandler;
import org.eclipse.dd.dsf.service.DsfSession;
import org.eclipse.dd.gdb.launching.GdbLaunch;
import org.eclipse.dd.gdb.service.GDBRunControl;
import org.eclipse.dd.gdb.service.command.GDBControl;
import org.eclipse.dd.mi.service.CSourceLookup;
import org.eclipse.dd.mi.service.ExpressionService;
import org.eclipse.dd.mi.service.MIBreakpoints;
import org.eclipse.dd.mi.service.MIBreakpointsManager;
import org.eclipse.dd.mi.service.MIMemory;
import org.eclipse.dd.mi.service.MIRegisters;
import org.eclipse.dd.mi.service.MIStack;
import org.eclipse.dd.mi.service.command.commands.MIBreakInsert;
import org.eclipse.dd.mi.service.command.commands.MIExecRun;
import org.eclipse.dd.mi.service.command.events.MIStoppedEvent;
import org.eclipse.dd.mi.service.command.output.MIBreakInsertInfo;
import org.eclipse.dd.mi.service.command.output.MIInfo;
import org.eclipse.debug.core.DebugException;
public class LaunchSequence extends Sequence {
public class EntryPointHitEventListener {
boolean fAborted = false;
boolean fFinished = false;
final RequestMonitor fRequestMonitor;
EntryPointHitEventListener(RequestMonitor requestMonitor) {
fRequestMonitor = requestMonitor;
}
@DsfServiceEventHandler
public void eventDispatched(@SuppressWarnings("unused")
MIStoppedEvent e) {
fFinished = true;
if (!fAborted) {
fSession.removeServiceEventListener(this);
fRequestMonitor.done();
}
}
}
Step[] fSteps = new Step[] {
// Create and initialize the Connection service.
new Step() {
@Override
public void execute(RequestMonitor requestMonitor) {
//
// Create the connection.
//
fCommandControl = new GDBControl(
fSession, getGDBPath(), fExecPath, GDBControl.SessionType.RUN, 30);
fCommandControl.initialize(requestMonitor);
}
},
/*
* If needed, insert breakpoint at main and run to it.
*/
new Step() {
private boolean fStopInMain = false;
private String fStopSymbol = null;
/**
* @return The return value actually indicates whether the get operation succeeded,
* not whether to stop.
*/
private boolean readStopAtMain(RequestMonitor requestMonitor) {
try {
fStopInMain = fLaunch.getLaunchConfiguration().getAttribute( ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN, false );
} catch (CoreException e) {
requestMonitor.setStatus(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, -1, "Cannot retrieve the entry point symbol", e)); //$NON-NLS-1$
requestMonitor.done();
return false;
}
return true;
}
private boolean readStopSymbol(RequestMonitor requestMonitor) {
try {
fStopSymbol = fLaunch.getLaunchConfiguration().getAttribute( ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN_SYMBOL, ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT );
} catch (CoreException e) {
requestMonitor.setStatus(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, DebugException.CONFIGURATION_INVALID, "Cannot retrieve the entry point symbol", e)); //$NON-NLS-1$
requestMonitor.done();
return false;
}
return true;
}
@Override
public void execute(final RequestMonitor requestMonitor) {
if (!readStopAtMain(requestMonitor)) return;
if (!fStopInMain) {
requestMonitor.done();
return;
}
if (!readStopSymbol(requestMonitor)) return;
// Create a listener to wait for the stopped event, and register as even handler.
// This handler will execute the requestMonitor.
final EntryPointHitEventListener entryPointHitListener = new EntryPointHitEventListener(requestMonitor);
fSession.addServiceEventListener(entryPointHitListener, null);
// Create a time-out, to abort if breakpoint not hit.
fSession.getExecutor().schedule(
new Runnable() { public void run() {
// Only process the event if we have not finished yet (hit the breakpoint).
if (!entryPointHitListener.fFinished) {
// Mark the listener as aborted, and unregister it as event listener.
entryPointHitListener.fAborted = true;
fSession.removeServiceEventListener(entryPointHitListener);
// Submit the error result for the step.
requestMonitor.setStatus(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, DebugException.TARGET_REQUEST_FAILED, "Timed out running to entry point.", null)); //$NON-NLS-1$
requestMonitor.done();
}
}},
60, TimeUnit.SECONDS);
// Insert a breakpoint at the requested stop symbol.
fCommandControl.queueCommand(
new MIBreakInsert(fCommandControl.getGDBDMContext(), true, false, null, 0, fStopSymbol, 0),
new DataRequestMonitor<MIBreakInsertInfo>(getExecutor(), requestMonitor) {
@Override
protected void handleOK() {
// After the break-insert is done, execute the -exec-run command.
fCommandControl.queueCommand(
new MIExecRun(fCommandControl.getGDBDMContext(), new String[0]),
new DataRequestMonitor<MIInfo>(getExecutor(), requestMonitor) {
@Override
protected void handleOK() {
// Note : Do we not need to do something with the original requestMonitor?
// Do nothing. Execution was resumed and the EntryPointHitEventListener
// will resume execution
}
}
);
}
});
}
},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
new GDBRunControl(fSession).initialize(requestMonitor);
}},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
new StepQueueManager(fSession).initialize(requestMonitor);
}},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
new MIMemory(fSession).initialize(requestMonitor);
}},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
new MIStack(fSession).initialize(requestMonitor);
}},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
new ExpressionService(fSession).initialize(requestMonitor);
}},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
fSourceLookup = new CSourceLookup(fSession);
fSourceLookup.initialize(requestMonitor);
}},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
fSourceLookup.setSourceLookupDirector(
fCommandControl.getGDBDMContext(),
((CSourceLookupDirector)fLaunch.getSourceLocator()));
requestMonitor.done();
}},
new Step() { @Override
public void execute(final RequestMonitor requestMonitor) {
// Create the low-level breakpoint service
final MIBreakpoints bpService = new MIBreakpoints(fSession);
bpService.initialize(new RequestMonitor(getExecutor(), requestMonitor) {
@Override
protected void handleOK() {
requestMonitor.done();
}
});
}},
new Step() { @Override
public void execute(final RequestMonitor requestMonitor) {
// Create high-level breakpoint service and install breakpoints
// for the GDB debug context.
final MIBreakpointsManager bpmService = new MIBreakpointsManager(fSession, CDebugCorePlugin.PLUGIN_ID);
bpmService.initialize(new RequestMonitor(getExecutor(), requestMonitor) {
@Override
protected void handleOK() {
bpmService.startTrackingBreakpoints(fCommandControl.getGDBDMContext(), requestMonitor);
}
});
}},
new Step() { @Override
public void execute(RequestMonitor requestMonitor) {
new MIRegisters(fSession).initialize(requestMonitor);
}},
/*new Step() { public void execute(RequestMonitor requestMonitor) {
new GDBVariables(fSession).initialize(requestMonitor);
}},*/
};
final DsfSession fSession;
final GdbLaunch fLaunch;
final IPath fExecPath;
GDBControl fCommandControl;
CSourceLookup fSourceLookup;
public LaunchSequence(DsfSession session, GdbLaunch launch, IPath execPath) {
super(session.getExecutor());
fSession = session;
fLaunch = launch;
fExecPath = execPath;
}
@Override
public Step[] getSteps() {
return fSteps;
}
private IPath getGDBPath() {
IPath retVal = new Path("gdb.exe"); //$NON-NLS-1$
try {
retVal = new Path( fLaunch.getLaunchConfiguration().getAttribute( IMILaunchConfigurationConstants.ATTR_DEBUG_NAME, IMILaunchConfigurationConstants.DEBUGGER_DEBUG_NAME_DEFAULT ) );
} catch (CoreException e) {
}
return retVal;
}
}

View file

@ -0,0 +1,105 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.launching;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.dsf.concurrent.DsfExecutor;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
import org.eclipse.dd.dsf.concurrent.Sequence;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.dsf.service.IDsfService;
import org.eclipse.dd.gdb.service.GDBRunControl;
import org.eclipse.dd.gdb.service.command.GDBControl;
import org.eclipse.dd.mi.service.CSourceLookup;
import org.eclipse.dd.mi.service.ExpressionService;
import org.eclipse.dd.mi.service.MIBreakpoints;
import org.eclipse.dd.mi.service.MIBreakpointsManager;
import org.eclipse.dd.mi.service.MIMemory;
import org.eclipse.dd.mi.service.MIRegisters;
import org.eclipse.dd.mi.service.MIStack;
public class ShutdownSequence extends Sequence {
String fSessionId;
String fApplicationName;
String fDebugModelId;
DsfServicesTracker fTracker;
public ShutdownSequence(DsfExecutor executor, String sessionId, RequestMonitor requestMonitor) {
super(executor, requestMonitor);
fSessionId = sessionId;
}
@Override
public Step[] getSteps() { return fSteps; }
private final Step[] fSteps = new Step[] {
new Step() {
@Override
public void execute(RequestMonitor requestMonitor) {
fTracker = new DsfServicesTracker(TestsPlugin.getBundleContext(), fSessionId);
requestMonitor.done();
}
@Override
public void rollBack(RequestMonitor requestMonitor) {
fTracker.dispose();
fTracker = null;
requestMonitor.done();
}
},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(MIRegisters.class, requestMonitor); }},
new Step() {
// Uninstall the breakpoints before the service is shut down.
@Override
public void execute(RequestMonitor requestMonitor) {
MIBreakpointsManager bpm = fTracker.getService(MIBreakpointsManager.class);
GDBControl commandControl = fTracker.getService(GDBControl.class);
if (bpm != null && commandControl != null) {
bpm.stopTrackingBreakpoints(commandControl.getGDBDMContext(), requestMonitor);
} else {
requestMonitor.setStatus(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, IDsfService.INTERNAL_ERROR,
"Needed services not found.", null)); //$NON-NLS-1$
requestMonitor.done();
}
}
},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(MIBreakpointsManager.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(MIBreakpoints.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(CSourceLookup.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(ExpressionService.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(MIStack.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(MIMemory.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(GDBRunControl.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) { shutdownService(GDBControl.class, requestMonitor); }},
new Step() { @Override public void execute(RequestMonitor requestMonitor) {
fTracker.dispose();
fTracker = null;
requestMonitor.done();
}}
};
@SuppressWarnings("unchecked")
private void shutdownService(Class clazz, RequestMonitor requestMonitor) {
IDsfService service = fTracker.getService(clazz);
if (service != null) {
service.shutdown(requestMonitor);
}
else {
requestMonitor.setStatus(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, IDsfService.INTERNAL_ERROR,
"Service '" + clazz.getName() + "' not found.", null)); //$NON-NLS-1$//$NON-NLS-2$
requestMonitor.done();
}
}
}

View file

@ -0,0 +1,302 @@
/*******************************************************************************
* Copyright (c) 2004, 2006 QNX Software Systems 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:
* QNX Software Systems - Initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.launching;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.cdt.launch.AbstractCLaunchDelegate;
import org.eclipse.cdt.launch.internal.ui.LaunchMessages;
import org.eclipse.cdt.launch.internal.ui.LaunchUIPlugin;
import org.eclipse.cdt.utils.pty.PTY;
import org.eclipse.cdt.utils.spawner.ProcessFactory;
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.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.dd.dsf.concurrent.ThreadSafe;
import org.eclipse.dd.dsf.debug.model.DsfMemoryBlockRetrieval;
import org.eclipse.dd.dsf.service.DsfServicesTracker;
import org.eclipse.dd.gdb.launching.GdbLaunch;
import org.eclipse.dd.gdb.service.command.GDBControl;
import org.eclipse.dd.mi.service.command.AbstractCLIProcess;
import org.eclipse.dd.mi.service.command.MIInferiorProcess;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.IStatusHandler;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate2;
import org.eclipse.debug.core.model.IMemoryBlockRetrieval;
import org.eclipse.debug.core.model.IPersistableSourceLocator;
import org.eclipse.debug.core.model.ISourceLocator;
import org.eclipse.debug.core.sourcelookup.IPersistableSourceLocator2;
/**
* The launch configuration delegate for the CDI debugger session types.
*/
@ThreadSafe
public class TestLaunchDelegate extends AbstractCLaunchDelegate
implements ILaunchConfigurationDelegate2
{
public final static String GDB_DEBUG_MODEL_ID = "org.eclipse.dd.tests.gdb"; //$NON-NLS-1$
/* (non-Javadoc)
* @see org.eclipse.cdt.launch.AbstractCLaunchDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void launch( ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException {
if ( monitor == null ) {
monitor = new NullProgressMonitor();
}
if ( mode.equals( ILaunchManager.DEBUG_MODE ) ) {
launchDebugger( config, launch, monitor );
}
}
private void launchDebugger( ILaunchConfiguration config, ILaunch launch, IProgressMonitor monitor ) throws CoreException {
monitor.beginTask("Launching debugger session", 10); //$NON-NLS-1$
if ( monitor.isCanceled() ) {
return;
}
try {
String debugMode = config.getAttribute( ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_START_MODE, ICDTLaunchConfigurationConstants.DEBUGGER_MODE_RUN );
if ( debugMode.equals( ICDTLaunchConfigurationConstants.DEBUGGER_MODE_RUN ) ) {
launchLocalDebugSession( config, launch, monitor );
}
}
finally {
monitor.done();
}
}
private void launchLocalDebugSession( ILaunchConfiguration config, ILaunch l, IProgressMonitor monitor ) throws CoreException {
if ( monitor.isCanceled() ) {
return;
}
final GdbLaunch launch = (GdbLaunch)l;
monitor.subTask("Debugging using GDB/MI reference for DSF"); //$NON-NLS-1$
IPath exePath = new Path(getProgramName(config));
verifyBinary(exePath);
setDefaultSourceLocator(launch, config);
monitor.worked( 1 );
// Create and invoke the launch sequence to create the debug control and services
final LaunchSequence launchSequence =
new LaunchSequence(launch.getSession(), launch, exePath);
launch.getSession().getExecutor().execute(launchSequence);
try {
launchSequence.get();
} catch (InterruptedException e1) {
throw new DebugException(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, DebugException.INTERNAL_ERROR, "Interrupted Exception in dispatch thread", e1)); //$NON-NLS-1$
} catch (ExecutionException e1) {
throw new DebugException(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Error in launch sequence", e1.getCause())); //$NON-NLS-1$
}
launch.initializeControl();
// Add the CLI and "inferior" process objects to the launch.
final AtomicReference<AbstractCLIProcess> cliProcessRef = new AtomicReference<AbstractCLIProcess>();
final AtomicReference<MIInferiorProcess> inferiorProcessRef = new AtomicReference<MIInferiorProcess>();
try {
launch.getDsfExecutor().submit( new Callable<Object>() {
public Object call() throws CoreException {
DsfServicesTracker tracker = new DsfServicesTracker(TestsPlugin.getBundleContext(), launch.getSession().getId());
GDBControl gdb = tracker.getService(GDBControl.class);
if (gdb != null) {
cliProcessRef.set(gdb.getCLIProcess());
inferiorProcessRef.set(gdb.getInferiorProcess());
}
tracker.dispose();
return null;
}
}).get();
launch.addProcess(DebugPlugin.newProcess(launch, cliProcessRef.get(), "gdb")); //$NON-NLS-1$
launch.addProcess(DebugPlugin.newProcess(launch, inferiorProcessRef.get(), exePath.lastSegment()));
} catch (InterruptedException e) {
throw new CoreException(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, 0, "Interrupted while waiting for get process callable.", e)); //$NON-NLS-1$
} catch (ExecutionException e) {
throw (CoreException)e.getCause();
} catch (RejectedExecutionException e) {
throw new CoreException(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, 0, "Debugger shut down before launch was completed.", e)); //$NON-NLS-1$
}
// Create a memory retrieval and register it with session
try {
launch.getDsfExecutor().submit( new Callable<Object>() {
public Object call() throws CoreException {
DsfServicesTracker tracker = new DsfServicesTracker(TestsPlugin.getBundleContext(), launch.getSession().getId());
GDBControl gdbControl = tracker.getService(GDBControl.class);
if (gdbControl != null) {
IMemoryBlockRetrieval memRetrieval = new DsfMemoryBlockRetrieval(
GDB_DEBUG_MODEL_ID, gdbControl.getGDBDMContext());
launch.getSession().registerModelAdapter(IMemoryBlockRetrieval.class, memRetrieval);
}
tracker.dispose();
return null;
}
}).get();
} catch (InterruptedException e) {
throw new CoreException(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, 0, "Interrupted while waiting for get process callable.", e)); //$NON-NLS-1$
} catch (ExecutionException e) {
throw (CoreException)e.getCause();
} catch (RejectedExecutionException e) {
throw new CoreException(new Status(IStatus.ERROR, TestsPlugin.PLUGIN_ID, 0, "Debugger shut down before launch was completed.", e)); //$NON-NLS-1$
}
}
/*
* Verify that the specified file exists on the file system.
*/
private void verifyBinary(IPath exePath) throws CoreException {
try {
new FileReader(exePath.toFile());
} catch (Exception e) {
Throwable exception = new FileNotFoundException(exePath.toOSString() + " does not exist"); //$NON-NLS-1$
int code = ICDTLaunchConfigurationConstants.ERR_PROGRAM_NOT_BINARY;
throw new CoreException(new Status(IStatus.ERROR, getPluginID(), code, exception == null ? "" : exception.getLocalizedMessage(), //$NON-NLS-1$
exception));
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.launch.AbstractCLaunchDelegate#getPluginID()
*/
@Override
protected String getPluginID() {
return LaunchUIPlugin.getUniqueIdentifier();
}
/**
* Performs a runtime exec on the given command line in the context of the
* specified working directory, and returns the resulting process. If the
* current runtime does not support the specification of a working
* directory, the status handler for error code
* <code>ERR_WORKING_DIRECTORY_NOT_SUPPORTED</code> is queried to see if
* the exec should be re-executed without specifying a working directory.
*
* @param cmdLine
* the command line
* @param workingDirectory
* the working directory, or <code>null</code>
* @return the resulting process or <code>null</code> if the exec is
* cancelled
* @see Runtime
*/
protected Process exec( String[] cmdLine, String[] environ, File workingDirectory, boolean usePty ) throws CoreException {
Process p = null;
try {
if ( workingDirectory == null ) {
p = ProcessFactory.getFactory().exec( cmdLine, environ );
}
else {
if ( usePty && PTY.isSupported() ) {
p = ProcessFactory.getFactory().exec( cmdLine, environ, workingDirectory, new PTY() );
}
else {
p = ProcessFactory.getFactory().exec( cmdLine, environ, workingDirectory );
}
}
}
catch( IOException e ) {
if ( p != null ) {
p.destroy();
}
abort( "Error starting process.", e, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR ); //$NON-NLS-1$
}
catch( NoSuchMethodError e ) {
// attempting launches on 1.2.* - no ability to set working
// directory
IStatus status = new Status( IStatus.ERROR, LaunchUIPlugin.getUniqueIdentifier(), ICDTLaunchConfigurationConstants.ERR_WORKING_DIRECTORY_NOT_SUPPORTED, LaunchMessages.getString( "LocalDsfLaunchDelegate.9" ), e ); //$NON-NLS-1$
IStatusHandler handler = DebugPlugin.getDefault().getStatusHandler( status );
if ( handler != null ) {
Object result = handler.handleStatus( status, this );
if ( result instanceof Boolean && ((Boolean)result).booleanValue() ) {
p = exec( cmdLine, environ, null, usePty );
}
}
}
return p;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.launch.AbstractCLaunchDelegate#preLaunchCheck(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public boolean preLaunchCheck( ILaunchConfiguration config, String mode, IProgressMonitor monitor ) throws CoreException {
// no pre launch check for core file
if ( mode.equals( ILaunchManager.DEBUG_MODE ) ) {
if ( ICDTLaunchConfigurationConstants.DEBUGGER_MODE_CORE.equals( config.getAttribute( ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_START_MODE, ICDTLaunchConfigurationConstants.DEBUGGER_MODE_RUN ) ) )
return true;
}
return super.preLaunchCheck( config, mode, monitor );
// return true;
}
///////////////////////////////////////////////////////////////////////////
// ILaunchConfigurationDelegate2
@Override
public boolean buildForLaunch(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException {
return false;
}
@Override
public boolean finalLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException {
return true;
}
@Override
public ILaunch getLaunch(ILaunchConfiguration configuration, String mode) throws CoreException {
// Need to configure the source locator before creating the launch
// because once the launch is created and added to launch manager,
// the adapters will be created for the whole session, including
// the source lookup adapter.
ISourceLocator locator = getSourceLocator(configuration);
return new GdbLaunch(configuration, mode, locator);
}
private ISourceLocator getSourceLocator(ILaunchConfiguration configuration) throws CoreException {
String type = configuration.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, (String)null);
if (type == null) {
type = configuration.getType().getSourceLocatorId();
}
if (type != null) {
IPersistableSourceLocator locator = DebugPlugin.getDefault().getLaunchManager().newSourceLocator(type);
String memento = configuration.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_MEMENTO, (String)null);
if (memento == null) {
locator.initializeDefaults(configuration);
} else {
if(locator instanceof IPersistableSourceLocator2)
((IPersistableSourceLocator2)locator).initializeFromMemento(memento, configuration);
else
locator.initializeFromMemento(memento);
}
return locator;
}
return null;
}
}

View file

@ -0,0 +1,97 @@
/*******************************************************************************
* Copyright (c) 2007 Wind River Systems 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.tests.gdb.launching;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*/
public class TestsPlugin extends Plugin {
//The shared instance.
private static TestsPlugin plugin;
//Resource bundle.
private ResourceBundle resourceBundle;
private static BundleContext bundleContext;
public static final String PLUGIN_ID = "org.eclipse.dd.tests.gdb"; //$NON-NLS-1$
/**
* The constructor.
*/
public TestsPlugin() {
super();
plugin = this;
try {
resourceBundle = ResourceBundle.getBundle("org.eclipse.dd.tests.gdb.TestsPluginResources"); //$NON-NLS-1$
}
catch (MissingResourceException x) {
resourceBundle = null;
}
}
/**
* This method is called upon plug-in activation
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
bundleContext = context;
}
/**
* This method is called when the plug-in is stopped
*/
@Override
public void stop(BundleContext context) throws Exception {
super.stop(context);
}
/**
* Returns the shared instance.
*/
public static TestsPlugin getDefault() {
return plugin;
}
/**
* Returns the string from the plugin's resource bundle,
* or 'key' if not found.
*/
public static String getResourceString(String key) {
ResourceBundle bundle = TestsPlugin.getDefault().getResourceBundle();
try {
return (bundle != null) ? bundle.getString(key) : key;
}
catch (MissingResourceException e) {
return key;
}
}
/**
* Returns the plugin's resource bundle,
*/
public ResourceBundle getResourceBundle() {
return resourceBundle;
}
/**
* Returns the plugin's bundle context,
*/
public static BundleContext getBundleContext() {
return bundleContext;
}
/**
* Convenience method which returns the unique identifier of this plugin.
*/
public static String getUniqueIdentifier() {
return getDefault().getBundle().getSymbolicName();
}
}