feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,67 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
public class AccessWatchpointSpec extends WatchpointSpec {
AccessWatchpointSpec(EventRequestSpecList specs,
ReferenceTypeSpec refSpec, String fieldId) {
super(specs, refSpec, fieldId);
}
/**
* The 'refType' is known to match.
*/
@Override
void resolve(ReferenceType refType) throws InvalidTypeException,
NoSuchFieldException {
if (!(refType instanceof ClassType)) {
throw new InvalidTypeException();
}
Field field = refType.fieldByName(fieldId);
if (field == null) {
throw new NoSuchFieldException(fieldId);
}
setRequest(refType.virtualMachine().eventRequestManager()
.createAccessWatchpointRequest(field));
}
@Override
public boolean equals(Object obj) {
return (obj instanceof AccessWatchpointSpec) && super.equals(obj);
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class AmbiguousMethodException extends Exception
{
private static final long serialVersionUID = 7793370943251707514L;
public AmbiguousMethodException()
{
super();
}
public AmbiguousMethodException(String s)
{
super(s);
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public abstract class BreakpointSpec extends EventRequestSpec {
BreakpointSpec(EventRequestSpecList specs, ReferenceTypeSpec refSpec) {
super(specs, refSpec);
}
@Override
void notifySet(SpecListener listener, SpecEvent evt) {
listener.breakpointSet(evt);
}
@Override
void notifyDeferred(SpecListener listener, SpecEvent evt) {
listener.breakpointDeferred(evt);
}
@Override
void notifyResolved(SpecListener listener, SpecEvent evt) {
listener.breakpointResolved(evt);
}
@Override
void notifyDeleted(SpecListener listener, SpecEvent evt) {
listener.breakpointDeleted(evt);
}
@Override
void notifyError(SpecListener listener, SpecErrorEvent evt) {
listener.breakpointError(evt);
}
}

View File

@@ -0,0 +1,309 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import com.sun.jdi.connect.LaunchingConnector;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.VMStartException;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import java.io.*;
import java.util.Map;
import javax.swing.SwingUtilities;
class ChildSession extends Session {
private Process process;
private PrintWriter in;
private BufferedReader out;
private BufferedReader err;
private InputListener input;
private OutputListener output;
private OutputListener error;
public ChildSession(ExecutionManager runtime,
String userVMArgs, String cmdLine,
InputListener input,
OutputListener output,
OutputListener error,
OutputListener diagnostics) {
this(runtime, getVM(diagnostics, userVMArgs, cmdLine),
input, output, error, diagnostics);
}
public ChildSession(ExecutionManager runtime,
LaunchingConnector connector,
Map<String, Connector.Argument> arguments,
InputListener input,
OutputListener output,
OutputListener error,
OutputListener diagnostics) {
this(runtime, generalGetVM(diagnostics, connector, arguments),
input, output, error, diagnostics);
}
private ChildSession(ExecutionManager runtime,
VirtualMachine vm,
InputListener input,
OutputListener output,
OutputListener error,
OutputListener diagnostics) {
super(vm, runtime, diagnostics);
this.input = input;
this.output = output;
this.error = error;
}
@Override
public boolean attach() {
if (!connectToVMProcess()) {
diagnostics.putString("Could not launch VM");
return false;
}
/*
* Create a Thread that will retrieve and display any output.
* Needs to be high priority, else debugger may exit before
* it can be displayed.
*/
//### Rename InputWriter and OutputReader classes
//### Thread priorities cribbed from ttydebug. Think about them.
OutputReader outputReader =
new OutputReader("output reader", "output",
out, output, diagnostics);
outputReader.setPriority(Thread.MAX_PRIORITY-1);
outputReader.start();
OutputReader errorReader =
new OutputReader("error reader", "error",
err, error, diagnostics);
errorReader.setPriority(Thread.MAX_PRIORITY-1);
errorReader.start();
InputWriter inputWriter =
new InputWriter("input writer", in, input);
inputWriter.setPriority(Thread.MAX_PRIORITY-1);
inputWriter.start();
if (!super.attach()) {
if (process != null) {
process.destroy();
process = null;
}
return false;
}
//### debug
//System.out.println("IO after attach: "+ inputWriter + " " + outputReader + " "+ errorReader);
return true;
}
@Override
public void detach() {
//### debug
//System.out.println("IO before detach: "+ inputWriter + " " + outputReader + " "+ errorReader);
super.detach();
/*
inputWriter.quit();
outputReader.quit();
errorReader.quit();
*/
if (process != null) {
process.destroy();
process = null;
}
}
/**
* Launch child java interpreter, return host:port
*/
static private void dumpStream(OutputListener diagnostics,
InputStream stream) throws IOException {
BufferedReader in =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = in.readLine()) != null) {
diagnostics.putString(line);
}
}
static private void dumpFailedLaunchInfo(OutputListener diagnostics,
Process process) {
try {
dumpStream(diagnostics, process.getErrorStream());
dumpStream(diagnostics, process.getInputStream());
} catch (IOException e) {
diagnostics.putString("Unable to display process output: " +
e.getMessage());
}
}
static private VirtualMachine getVM(OutputListener diagnostics,
String userVMArgs,
String cmdLine) {
VirtualMachineManager manager = Bootstrap.virtualMachineManager();
LaunchingConnector connector = manager.defaultConnector();
Map<String, Connector.Argument> arguments = connector.defaultArguments();
arguments.get("options").setValue(userVMArgs);
arguments.get("main").setValue(cmdLine);
return generalGetVM(diagnostics, connector, arguments);
}
static private VirtualMachine generalGetVM(OutputListener diagnostics,
LaunchingConnector connector,
Map<String, Connector.Argument> arguments) {
VirtualMachine vm = null;
try {
diagnostics.putString("Starting child.");
vm = connector.launch(arguments);
} catch (IOException ioe) {
diagnostics.putString("Unable to start child: " + ioe.getMessage());
} catch (IllegalConnectorArgumentsException icae) {
diagnostics.putString("Unable to start child: " + icae.getMessage());
} catch (VMStartException vmse) {
diagnostics.putString("Unable to start child: " + vmse.getMessage() + '\n');
dumpFailedLaunchInfo(diagnostics, vmse.process());
}
return vm;
}
private boolean connectToVMProcess() {
if (vm == null) {
return false;
}
process = vm.process();
in = new PrintWriter(new OutputStreamWriter(process.getOutputStream()));
//### Note small buffer sizes!
out = new BufferedReader(new InputStreamReader(process.getInputStream()), 1);
err = new BufferedReader(new InputStreamReader(process.getErrorStream()), 1);
return true;
}
/**
* Threads to handle application input/output.
*/
private static class OutputReader extends Thread {
private String streamName;
private BufferedReader stream;
private OutputListener output;
private OutputListener diagnostics;
private boolean running = true;
private char[] buffer = new char[512];
OutputReader(String threadName,
String streamName,
BufferedReader stream,
OutputListener output,
OutputListener diagnostics) {
super(threadName);
this.streamName = streamName;
this.stream = stream;
this.output = output;
this.diagnostics = diagnostics;
}
@Override
public void run() {
try {
int count;
while (running && (count = stream.read(buffer, 0, 512)) != -1) {
if (count > 0) {
// Run in Swing event dispatcher thread.
final String chars = new String(buffer, 0, count);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
output.putString(chars);
}
});
}
//### Should we sleep briefly here?
}
} catch (IOException e) {
// Run in Swing event dispatcher thread.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
diagnostics.putString("IO error reading " +
streamName +
" stream of child java interpreter");
}
});
}
}
}
private static class InputWriter extends Thread {
private PrintWriter stream;
private InputListener input;
private boolean running = true;
InputWriter(String threadName,
PrintWriter stream,
InputListener input) {
super(threadName);
this.stream = stream;
this.input = input;
}
@Override
public void run() {
String line;
while (running) {
line = input.getLine();
stream.println(line);
// Should not be needed for println above!
stream.flush();
}
}
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class EvaluationException extends Exception {
private static final long serialVersionUID = 4947109680354951694L;
}

View File

@@ -0,0 +1,168 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import com.sun.jdi.request.EventRequest;
abstract public class EventRequestSpec {
static final int STATUS_UNRESOLVED = 1;
static final int STATUS_RESOLVED = 2;
static final int STATUS_ERROR = 3;
static final Object specPropertyKey = "spec";
final EventRequestSpecList specs;
final ReferenceTypeSpec refSpec;
EventRequest request = null;
int status = STATUS_UNRESOLVED;
EventRequestSpec(EventRequestSpecList specs, ReferenceTypeSpec refSpec) {
this.specs = specs;
this.refSpec = refSpec;
}
void setRequest(EventRequest request) {
this.request = request;
request.putProperty(specPropertyKey, this);
request.enable();
}
/**
* The 'refType' is known to match.
*/
abstract void resolve(ReferenceType refType) throws Exception;
abstract void notifySet(SpecListener listener, SpecEvent evt);
abstract void notifyDeferred(SpecListener listener, SpecEvent evt);
abstract void notifyResolved(SpecListener listener, SpecEvent evt);
abstract void notifyDeleted(SpecListener listener, SpecEvent evt);
abstract void notifyError(SpecListener listener, SpecErrorEvent evt);
/**
* The 'refType' is known to match.
*/
void resolveNotify(ReferenceType refType) {
try {
resolve(refType);
status = STATUS_RESOLVED;
specs.notifyResolved(this);
} catch(Exception exc) {
status = STATUS_ERROR;
specs.notifyError(this, exc);
}
}
/**
* See if 'refType' matches and resolve.
*/
void attemptResolve(ReferenceType refType) {
if (!isResolved() && refSpec.matches(refType)) {
resolveNotify(refType);
}
}
void attemptImmediateResolve(VirtualMachine vm) {
// try to resolve immediately
for (ReferenceType refType : vm.allClasses()) {
if (refSpec.matches(refType)) {
try {
resolve(refType);
status = STATUS_RESOLVED;
specs.notifySet(this);
} catch(Exception exc) {
status = STATUS_ERROR;
specs.notifyError(this, exc);
}
return;
}
}
specs.notifyDeferred(this);
}
public EventRequest getEventRequest() {
return request;
}
/**
* @return true if this spec has been resolved.
*/
public boolean isResolved() {
return status == STATUS_RESOLVED;
}
/**
* @return true if this spec has not yet been resolved.
*/
public boolean isUnresolved() {
return status == STATUS_UNRESOLVED;
}
/**
* @return true if this spec is unresolvable due to error.
*/
public boolean isErroneous() {
return status == STATUS_ERROR;
}
public String getStatusString() {
switch (status) {
case STATUS_RESOLVED:
return "resolved";
case STATUS_UNRESOLVED:
return "deferred";
case STATUS_ERROR:
return "erroneous";
}
return "unknown";
}
boolean isJavaIdentifier(String s) {
return Utils.isJavaIdentifier(s);
}
public String errorMessageFor(Exception e) {
if (e instanceof IllegalArgumentException) {
return ("Invalid command syntax");
} else if (e instanceof RuntimeException) {
// A runtime exception that we were not expecting
throw (RuntimeException)e;
} else {
return ("Internal error; unable to set" + this);
}
}
}

View File

@@ -0,0 +1,187 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
import java.util.*;
class EventRequestSpecList {
// all specs
private List<EventRequestSpec> eventRequestSpecs = Collections.synchronizedList(
new ArrayList<EventRequestSpec>());
final ExecutionManager runtime;
EventRequestSpecList(ExecutionManager runtime) {
this.runtime = runtime;
}
/**
* Resolve all deferred eventRequests waiting for 'refType'.
*/
void resolve(ReferenceType refType) {
synchronized(eventRequestSpecs) {
for (EventRequestSpec spec : eventRequestSpecs) {
spec.attemptResolve(refType);
}
}
}
void install(EventRequestSpec ers, VirtualMachine vm) {
synchronized (eventRequestSpecs) {
eventRequestSpecs.add(ers);
}
if (vm != null) {
ers.attemptImmediateResolve(vm);
}
}
BreakpointSpec
createClassLineBreakpoint(String classPattern, int line) {
ReferenceTypeSpec refSpec =
new PatternReferenceTypeSpec(classPattern);
return new LineBreakpointSpec(this, refSpec, line);
}
BreakpointSpec
createSourceLineBreakpoint(String sourceName, int line) {
ReferenceTypeSpec refSpec =
new SourceNameReferenceTypeSpec(sourceName, line);
return new LineBreakpointSpec(this, refSpec, line);
}
BreakpointSpec
createMethodBreakpoint(String classPattern,
String methodId, List<String> methodArgs) {
ReferenceTypeSpec refSpec =
new PatternReferenceTypeSpec(classPattern);
return new MethodBreakpointSpec(this, refSpec,
methodId, methodArgs);
}
ExceptionSpec
createExceptionIntercept(String classPattern,
boolean notifyCaught,
boolean notifyUncaught) {
ReferenceTypeSpec refSpec =
new PatternReferenceTypeSpec(classPattern);
return new ExceptionSpec(this, refSpec,
notifyCaught, notifyUncaught);
}
AccessWatchpointSpec
createAccessWatchpoint(String classPattern, String fieldId) {
ReferenceTypeSpec refSpec =
new PatternReferenceTypeSpec(classPattern);
return new AccessWatchpointSpec(this, refSpec, fieldId);
}
ModificationWatchpointSpec
createModificationWatchpoint(String classPattern, String fieldId) {
ReferenceTypeSpec refSpec =
new PatternReferenceTypeSpec(classPattern);
return new ModificationWatchpointSpec(this, refSpec, fieldId);
}
void delete(EventRequestSpec ers) {
EventRequest request = ers.getEventRequest();
synchronized (eventRequestSpecs) {
eventRequestSpecs.remove(ers);
}
if (request != null) {
request.virtualMachine().eventRequestManager()
.deleteEventRequest(request);
}
notifyDeleted(ers);
//### notify delete - here?
}
List<EventRequestSpec> eventRequestSpecs() {
// We need to make a copy to avoid synchronization problems
synchronized (eventRequestSpecs) {
return new ArrayList<EventRequestSpec>(eventRequestSpecs);
}
}
// -------- notify routines --------------------
@SuppressWarnings("unchecked")
private Vector<SpecListener> specListeners() {
return (Vector<SpecListener>)runtime.specListeners.clone();
}
void notifySet(EventRequestSpec spec) {
Vector<SpecListener> l = specListeners();
SpecEvent evt = new SpecEvent(spec);
for (int i = 0; i < l.size(); i++) {
spec.notifySet(l.elementAt(i), evt);
}
}
void notifyDeferred(EventRequestSpec spec) {
Vector<SpecListener> l = specListeners();
SpecEvent evt = new SpecEvent(spec);
for (int i = 0; i < l.size(); i++) {
spec.notifyDeferred(l.elementAt(i), evt);
}
}
void notifyDeleted(EventRequestSpec spec) {
Vector<SpecListener> l = specListeners();
SpecEvent evt = new SpecEvent(spec);
for (int i = 0; i < l.size(); i++) {
spec.notifyDeleted(l.elementAt(i), evt);
}
}
void notifyResolved(EventRequestSpec spec) {
Vector<SpecListener> l = specListeners();
SpecEvent evt = new SpecEvent(spec);
for (int i = 0; i < l.size(); i++) {
spec.notifyResolved(l.elementAt(i), evt);
}
}
void notifyError(EventRequestSpec spec, Exception exc) {
Vector<SpecListener> l = specListeners();
SpecErrorEvent evt = new SpecErrorEvent(spec, exc);
for (int i = 0; i < l.size(); i++) {
spec.notifyError(l.elementAt(i), evt);
}
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.ReferenceType;
public class ExceptionSpec extends EventRequestSpec {
boolean notifyCaught;
boolean notifyUncaught;
ExceptionSpec(EventRequestSpecList specs, ReferenceTypeSpec refSpec,
boolean notifyCaught, boolean notifyUncaught)
{
super(specs, refSpec);
this.notifyCaught = notifyCaught;
this.notifyUncaught = notifyUncaught;
}
@Override
void notifySet(SpecListener listener, SpecEvent evt) {
listener.exceptionInterceptSet(evt);
}
@Override
void notifyDeferred(SpecListener listener, SpecEvent evt) {
listener.exceptionInterceptDeferred(evt);
}
@Override
void notifyResolved(SpecListener listener, SpecEvent evt) {
listener.exceptionInterceptResolved(evt);
}
@Override
void notifyDeleted(SpecListener listener, SpecEvent evt) {
listener.exceptionInterceptDeleted(evt);
}
@Override
void notifyError(SpecListener listener, SpecErrorEvent evt) {
listener.exceptionInterceptError(evt);
}
/**
* The 'refType' is known to match.
*/
@Override
void resolve(ReferenceType refType) {
setRequest(refType.virtualMachine().eventRequestManager()
.createExceptionRequest(refType,
notifyCaught, notifyUncaught));
}
@Override
public int hashCode() {
return refSpec.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ExceptionSpec) {
ExceptionSpec es = (ExceptionSpec)obj;
return refSpec.equals(es.refSpec);
} else {
return false;
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer("exception catch ");
buffer.append(refSpec.toString());
return buffer.toString();
}
}

View File

@@ -0,0 +1,824 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
import com.sun.jdi.connect.*;
import com.sun.tools.example.debug.expr.ExpressionParser;
import com.sun.tools.example.debug.expr.ParseException;
import java.io.*;
import java.util.*;
import com.sun.tools.example.debug.event.*;
import javax.swing.SwingUtilities;
/**
* Move this towards being only state and functionality
* that spans across Sessions (and thus VMs).
*/
public class ExecutionManager {
private Session session;
/**
* Get/set JDI trace mode.
*/
int traceMode = VirtualMachine.TRACE_NONE;
////////////////// Listener registration //////////////////
// Session Listeners
ArrayList<SessionListener> sessionListeners = new ArrayList<SessionListener>();
public void addSessionListener(SessionListener listener) {
sessionListeners.add(listener);
}
public void removeSessionListener(SessionListener listener) {
sessionListeners.remove(listener);
}
// Spec Listeners
ArrayList<SpecListener> specListeners = new ArrayList<SpecListener>();
public void addSpecListener(SpecListener cl) {
specListeners.add(cl);
}
public void removeSpecListener(SpecListener cl) {
specListeners.remove(cl);
}
// JDI Listeners
ArrayList<JDIListener> jdiListeners = new ArrayList<JDIListener>();
/**
* Adds a JDIListener
*/
public void addJDIListener(JDIListener jl) {
jdiListeners.add(jl);
}
/**
* Adds a JDIListener - at the specified position
*/
public void addJDIListener(int index, JDIListener jl) {
jdiListeners.add(index, jl);
}
/**
* Removes a JDIListener
*/
public void removeJDIListener(JDIListener jl) {
jdiListeners.remove(jl);
}
// App Echo Listeners
private ArrayList<OutputListener> appEchoListeners = new ArrayList<OutputListener>();
public void addApplicationEchoListener(OutputListener l) {
appEchoListeners.add(l);
}
public void removeApplicationEchoListener(OutputListener l) {
appEchoListeners.remove(l);
}
// App Output Listeners
private ArrayList<OutputListener> appOutputListeners = new ArrayList<OutputListener>();
public void addApplicationOutputListener(OutputListener l) {
appOutputListeners.add(l);
}
public void removeApplicationOutputListener(OutputListener l) {
appOutputListeners.remove(l);
}
// App Error Listeners
private ArrayList<OutputListener> appErrorListeners = new ArrayList<OutputListener>();
public void addApplicationErrorListener(OutputListener l) {
appErrorListeners.add(l);
}
public void removeApplicationErrorListener(OutputListener l) {
appErrorListeners.remove(l);
}
// Diagnostic Listeners
private ArrayList<OutputListener> diagnosticsListeners = new ArrayList<OutputListener>();
public void addDiagnosticsListener(OutputListener l) {
diagnosticsListeners.add(l);
}
public void removeDiagnosticsListener(OutputListener l) {
diagnosticsListeners.remove(l);
}
/////////// End Listener Registration //////////////
//### We probably don't want this public
public VirtualMachine vm() {
return session == null ? null : session.vm;
}
void ensureActiveSession() throws NoSessionException {
if (session == null) {
throw new NoSessionException();
}
}
public EventRequestManager eventRequestManager() {
return vm() == null ? null : vm().eventRequestManager();
}
/**
* Get JDI trace mode.
*/
public int getTraceMode(int mode) {
return traceMode;
}
/**
* Set JDI trace mode.
*/
public void setTraceMode(int mode) {
traceMode = mode;
if (session != null) {
session.setTraceMode(mode);
}
}
/**
* Determine if VM is interrupted, i.e, present and not running.
*/
public boolean isInterrupted() /* should: throws NoSessionException */ {
// ensureActiveSession();
return session.interrupted;
}
/**
* Return a list of ReferenceType objects for all
* currently loaded classes and interfaces.
* Array types are not returned.
*/
public List<ReferenceType> allClasses() throws NoSessionException {
ensureActiveSession();
return vm().allClasses();
}
/**
* Return a ReferenceType object for the currently
* loaded class or interface whose fully-qualified
* class name is specified, else return null if there
* is none.
*
* In general, we must return a list of types, because
* multiple class loaders could have loaded a class
* with the same fully-qualified name.
*/
public List<ReferenceType> findClassesByName(String name) throws NoSessionException {
ensureActiveSession();
return vm().classesByName(name);
}
/**
* Return a list of ReferenceType objects for all
* currently loaded classes and interfaces whose name
* matches the given pattern. The pattern syntax is
* open to some future revision, but currently consists
* of a fully-qualified class name in which the first
* component may optionally be a "*" character, designating
* an arbitrary prefix.
*/
public List<ReferenceType> findClassesMatchingPattern(String pattern)
throws NoSessionException {
ensureActiveSession();
List<ReferenceType> result = new ArrayList<ReferenceType>(); //### Is default size OK?
if (pattern.startsWith("*.")) {
// Wildcard matches any leading package name.
pattern = pattern.substring(1);
for (ReferenceType type : vm().allClasses()) {
if (type.name().endsWith(pattern)) {
result.add(type);
}
}
return result;
} else {
// It's a class name.
return vm().classesByName(pattern);
}
}
/*
* Return a list of ThreadReference objects corresponding
* to the threads that are currently active in the VM.
* A thread is removed from the list just before the
* thread terminates.
*/
public List<ThreadReference> allThreads() throws NoSessionException {
ensureActiveSession();
return vm().allThreads();
}
/*
* Return a list of ThreadGroupReference objects corresponding
* to the top-level threadgroups that are currently active in the VM.
* Note that a thread group may be empty, or contain no threads as
* descendents.
*/
public List<ThreadGroupReference> topLevelThreadGroups() throws NoSessionException {
ensureActiveSession();
return vm().topLevelThreadGroups();
}
/*
* Return the system threadgroup.
*/
public ThreadGroupReference systemThreadGroup()
throws NoSessionException {
ensureActiveSession();
return vm().topLevelThreadGroups().get(0);
}
/*
* Evaluate an expression.
*/
public Value evaluate(final StackFrame f, String expr)
throws ParseException,
InvocationException,
InvalidTypeException,
ClassNotLoadedException,
NoSessionException,
IncompatibleThreadStateException {
ExpressionParser.GetFrame frameGetter = null;
ensureActiveSession();
if (f != null) {
frameGetter = new ExpressionParser.GetFrame() {
@Override
public StackFrame get() /* throws IncompatibleThreadStateException */ {
return f;
}
};
}
return ExpressionParser.evaluate(expr, vm(), frameGetter);
}
/*
* Start a new VM.
*/
public void run(boolean suspended,
String vmArgs,
String className,
String args) throws VMLaunchFailureException {
endSession();
//### Set a breakpoint on 'main' method.
//### Would be cleaner if we could just bring up VM already suspended.
if (suspended) {
//### Set breakpoint at 'main(java.lang.String[])'.
List<String> argList = new ArrayList<String>(1);
argList.add("java.lang.String[]");
createMethodBreakpoint(className, "main", argList);
}
String cmdLine = className + " " + args;
startSession(new ChildSession(this, vmArgs, cmdLine,
appInput, appOutput, appError,
diagnostics));
}
/*
* Attach to an existing VM.
*/
public void attach(String portName) throws VMLaunchFailureException {
endSession();
//### Changes made here for connectors have broken the
//### the 'Session' abstraction. The 'Session.attach()'
//### method is intended to encapsulate all of the various
//### ways in which session start-up can fail. (maddox 12/18/98)
/*
* Now that attaches and launches both go through Connectors,
* it may be worth creating a new subclass of Session for
* attach sessions.
*/
VirtualMachineManager mgr = Bootstrap.virtualMachineManager();
AttachingConnector connector = mgr.attachingConnectors().get(0);
Map<String, Connector.Argument> arguments = connector.defaultArguments();
arguments.get("port").setValue(portName);
Session newSession = internalAttach(connector, arguments);
if (newSession != null) {
startSession(newSession);
}
}
private Session internalAttach(AttachingConnector connector,
Map<String, Connector.Argument> arguments) {
try {
VirtualMachine vm = connector.attach(arguments);
return new Session(vm, this, diagnostics);
} catch (IOException ioe) {
diagnostics.putString("\n Unable to attach to target VM: " +
ioe.getMessage());
} catch (IllegalConnectorArgumentsException icae) {
diagnostics.putString("\n Invalid connector arguments: " +
icae.getMessage());
}
return null;
}
private Session internalListen(ListeningConnector connector,
Map<String, Connector.Argument> arguments) {
try {
VirtualMachine vm = connector.accept(arguments);
return new Session(vm, this, diagnostics);
} catch (IOException ioe) {
diagnostics.putString(
"\n Unable to accept connection to target VM: " +
ioe.getMessage());
} catch (IllegalConnectorArgumentsException icae) {
diagnostics.putString("\n Invalid connector arguments: " +
icae.getMessage());
}
return null;
}
/*
* Connect via user specified arguments
* @return true on success
*/
public boolean explictStart(Connector connector, Map<String, Connector.Argument> arguments)
throws VMLaunchFailureException {
Session newSession = null;
endSession();
if (connector instanceof LaunchingConnector) {
// we were launched, use ChildSession
newSession = new ChildSession(this, (LaunchingConnector)connector,
arguments,
appInput, appOutput, appError,
diagnostics);
} else if (connector instanceof AttachingConnector) {
newSession = internalAttach((AttachingConnector)connector,
arguments);
} else if (connector instanceof ListeningConnector) {
newSession = internalListen((ListeningConnector)connector,
arguments);
} else {
diagnostics.putString("\n Unknown connector: " + connector);
}
if (newSession != null) {
startSession(newSession);
}
return newSession != null;
}
/*
* Detach from VM. If VM was started by debugger, terminate it.
*/
public void detach() throws NoSessionException {
ensureActiveSession();
endSession();
}
private void startSession(Session s) throws VMLaunchFailureException {
if (!s.attach()) {
throw new VMLaunchFailureException();
}
session = s;
EventRequestManager em = vm().eventRequestManager();
ClassPrepareRequest classPrepareRequest = em.createClassPrepareRequest();
//### We must allow the deferred breakpoints to be resolved before
//### we continue executing the class. We could optimize if there
//### were no deferred breakpoints outstanding for a particular class.
//### Can we do this with JDI?
classPrepareRequest.setSuspendPolicy(EventRequest.SUSPEND_ALL);
classPrepareRequest.enable();
ClassUnloadRequest classUnloadRequest = em.createClassUnloadRequest();
classUnloadRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE);
classUnloadRequest.enable();
ThreadStartRequest threadStartRequest = em.createThreadStartRequest();
threadStartRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE);
threadStartRequest.enable();
ThreadDeathRequest threadDeathRequest = em.createThreadDeathRequest();
threadDeathRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE);
threadDeathRequest.enable();
ExceptionRequest exceptionRequest =
em.createExceptionRequest(null, false, true);
exceptionRequest.setSuspendPolicy(EventRequest.SUSPEND_ALL);
exceptionRequest.enable();
validateThreadInfo();
session.interrupted = true;
notifySessionStart();
}
void endSession() {
if (session != null) {
session.detach();
session = null;
invalidateThreadInfo();
notifySessionDeath();
}
}
/*
* Suspend all VM activity.
*/
public void interrupt() throws NoSessionException {
ensureActiveSession();
vm().suspend();
//### Is it guaranteed that the interrupt has happened?
validateThreadInfo();
session.interrupted = true;
notifyInterrupted();
}
/*
* Resume interrupted VM.
*/
public void go() throws NoSessionException, VMNotInterruptedException {
ensureActiveSession();
invalidateThreadInfo();
session.interrupted = false;
notifyContinued();
vm().resume();
}
/*
* Stepping.
*/
void clearPreviousStep(ThreadReference thread) {
/*
* A previous step may not have completed on this thread;
* if so, it gets removed here.
*/
EventRequestManager mgr = vm().eventRequestManager();
for (StepRequest request : mgr.stepRequests()) {
if (request.thread().equals(thread)) {
mgr.deleteEventRequest(request);
break;
}
}
}
private void generalStep(ThreadReference thread, int size, int depth)
throws NoSessionException {
ensureActiveSession();
invalidateThreadInfo();
session.interrupted = false;
notifyContinued();
clearPreviousStep(thread);
EventRequestManager reqMgr = vm().eventRequestManager();
StepRequest request = reqMgr.createStepRequest(thread,
size, depth);
// We want just the next step event and no others
request.addCountFilter(1);
request.enable();
vm().resume();
}
public void stepIntoInstruction(ThreadReference thread)
throws NoSessionException {
generalStep(thread, StepRequest.STEP_MIN, StepRequest.STEP_INTO);
}
public void stepOverInstruction(ThreadReference thread)
throws NoSessionException {
generalStep(thread, StepRequest.STEP_MIN, StepRequest.STEP_OVER);
}
public void stepIntoLine(ThreadReference thread)
throws NoSessionException,
AbsentInformationException {
generalStep(thread, StepRequest.STEP_LINE, StepRequest.STEP_INTO);
}
public void stepOverLine(ThreadReference thread)
throws NoSessionException,
AbsentInformationException {
generalStep(thread, StepRequest.STEP_LINE, StepRequest.STEP_OVER);
}
public void stepOut(ThreadReference thread)
throws NoSessionException {
generalStep(thread, StepRequest.STEP_MIN, StepRequest.STEP_OUT);
}
/*
* Thread control.
*/
public void suspendThread(ThreadReference thread) throws NoSessionException {
ensureActiveSession();
thread.suspend();
}
public void resumeThread(ThreadReference thread) throws NoSessionException {
ensureActiveSession();
thread.resume();
}
public void stopThread(ThreadReference thread) throws NoSessionException {
ensureActiveSession();
//### Need an exception now. Which one to use?
//thread.stop();
}
/*
* ThreadInfo objects -- Allow query of thread status and stack.
*/
private List<ThreadInfo> threadInfoList = new LinkedList<ThreadInfo>();
//### Should be weak! (in the value, not the key)
private HashMap<ThreadReference, ThreadInfo> threadInfoMap = new HashMap<ThreadReference, ThreadInfo>();
public ThreadInfo threadInfo(ThreadReference thread) {
if (session == null || thread == null) {
return null;
}
ThreadInfo info = threadInfoMap.get(thread);
if (info == null) {
//### Should not hardcode initial frame count and prefetch here!
//info = new ThreadInfo(thread, 10, 10);
info = new ThreadInfo(thread);
if (session.interrupted) {
info.validate();
}
threadInfoList.add(info);
threadInfoMap.put(thread, info);
}
return info;
}
void validateThreadInfo() {
session.interrupted = true;
for (ThreadInfo threadInfo : threadInfoList) {
threadInfo.validate();
}
}
private void invalidateThreadInfo() {
if (session != null) {
session.interrupted = false;
for (ThreadInfo threadInfo : threadInfoList) {
threadInfo.invalidate();
}
}
}
void removeThreadInfo(ThreadReference thread) {
ThreadInfo info = threadInfoMap.get(thread);
if (info != null) {
info.invalidate();
threadInfoMap.remove(thread);
threadInfoList.remove(info);
}
}
/*
* Listen for Session control events.
*/
private void notifyInterrupted() {
ArrayList<SessionListener> l = new ArrayList<SessionListener>(sessionListeners);
EventObject evt = new EventObject(this);
for (int i = 0; i < l.size(); i++) {
l.get(i).sessionInterrupt(evt);
}
}
private void notifyContinued() {
ArrayList<SessionListener> l = new ArrayList<SessionListener>(sessionListeners);
EventObject evt = new EventObject(this);
for (int i = 0; i < l.size(); i++) {
l.get(i).sessionContinue(evt);
}
}
private void notifySessionStart() {
ArrayList<SessionListener> l = new ArrayList<SessionListener>(sessionListeners);
EventObject evt = new EventObject(this);
for (int i = 0; i < l.size(); i++) {
l.get(i).sessionStart(evt);
}
}
private void notifySessionDeath() {
/*** noop for now
ArrayList<SessionListener> l = new ArrayList<SessionListener>(sessionListeners);
EventObject evt = new EventObject(this);
for (int i = 0; i < l.size(); i++) {
((SessionListener)l.get(i)).sessionDeath(evt);
}
****/
}
/*
* Listen for input and output requests from the application
* being debugged. These are generated only when the debuggee
* is spawned as a child of the debugger.
*/
private Object inputLock = new Object();
private LinkedList<String> inputBuffer = new LinkedList<String>();
private void resetInputBuffer() {
synchronized (inputLock) {
inputBuffer = new LinkedList<String>();
}
}
public void sendLineToApplication(String line) {
synchronized (inputLock) {
inputBuffer.addFirst(line);
inputLock.notifyAll();
}
}
private InputListener appInput = new InputListener() {
@Override
public String getLine() {
// Don't allow reader to be interrupted -- catch and retry.
String line = null;
while (line == null) {
synchronized (inputLock) {
try {
while (inputBuffer.size() < 1) {
inputLock.wait();
}
line = inputBuffer.removeLast();
} catch (InterruptedException e) {}
}
}
// We must not be holding inputLock here, as the listener
// that we call to echo a line might call us re-entrantly
// to provide another line of input.
// Run in Swing event dispatcher thread.
final String input = line;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
echoInputLine(input);
}
});
return line;
}
};
private static String newline = System.getProperty("line.separator");
private void echoInputLine(String line) {
ArrayList<OutputListener> l = new ArrayList<OutputListener>(appEchoListeners);
for (int i = 0; i < l.size(); i++) {
OutputListener ol = l.get(i);
ol.putString(line);
ol.putString(newline);
}
}
private OutputListener appOutput = new OutputListener() {
@Override
public void putString(String string) {
ArrayList<OutputListener> l = new ArrayList<OutputListener>(appEchoListeners);
for (int i = 0; i < l.size(); i++) {
l.get(i).putString(string);
}
}
};
private OutputListener appError = new OutputListener() {
@Override
public void putString(String string) {
ArrayList<OutputListener> l = new ArrayList<OutputListener>(appEchoListeners);
for (int i = 0; i < l.size(); i++) {
l.get(i).putString(string);
}
}
};
private OutputListener diagnostics = new OutputListener() {
@Override
public void putString(String string) {
ArrayList<OutputListener> l = new ArrayList<OutputListener>(diagnosticsListeners);
for (int i = 0; i < l.size(); i++) {
l.get(i).putString(string);
}
}
};
///////////// Spec Request Creation/Deletion/Query ///////////
private EventRequestSpecList specList = new EventRequestSpecList(this);
public BreakpointSpec
createSourceLineBreakpoint(String sourceName, int line) {
return specList.createSourceLineBreakpoint(sourceName, line);
}
public BreakpointSpec
createClassLineBreakpoint(String classPattern, int line) {
return specList.createClassLineBreakpoint(classPattern, line);
}
public BreakpointSpec
createMethodBreakpoint(String classPattern,
String methodId, List<String> methodArgs) {
return specList.createMethodBreakpoint(classPattern,
methodId, methodArgs);
}
public ExceptionSpec
createExceptionIntercept(String classPattern,
boolean notifyCaught,
boolean notifyUncaught) {
return specList.createExceptionIntercept(classPattern,
notifyCaught,
notifyUncaught);
}
public AccessWatchpointSpec
createAccessWatchpoint(String classPattern, String fieldId) {
return specList.createAccessWatchpoint(classPattern, fieldId);
}
public ModificationWatchpointSpec
createModificationWatchpoint(String classPattern, String fieldId) {
return specList.createModificationWatchpoint(classPattern,
fieldId);
}
public void delete(EventRequestSpec spec) {
specList.delete(spec);
}
void resolve(ReferenceType refType) {
specList.resolve(refType);
}
public void install(EventRequestSpec spec) {
specList.install(spec, vm());
}
public List<EventRequestSpec> eventRequestSpecs() {
return specList.eventRequestSpecs();
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class FrameIndexOutOfBoundsException extends IndexOutOfBoundsException {
private static final long serialVersionUID = -4870148107027371437L;
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public interface InputListener {
String getLine();
}

View File

@@ -0,0 +1,193 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.tools.example.debug.event.*;
import javax.swing.SwingUtilities;
/**
*/
class JDIEventSource extends Thread {
private /*final*/ EventQueue queue;
private /*final*/ Session session;
private /*final*/ ExecutionManager runtime;
private final JDIListener firstListener = new FirstListener();
private boolean wantInterrupt; //### Hack
/**
* Create event source.
*/
JDIEventSource(Session session) {
super("JDI Event Set Dispatcher");
this.session = session;
this.runtime = session.runtime;
this.queue = session.vm.eventQueue();
}
@Override
public void run() {
try {
runLoop();
} catch (Exception exc) {
//### Do something different for InterruptedException???
// just exit
}
session.running = false;
}
private void runLoop() throws InterruptedException {
AbstractEventSet es;
do {
EventSet jdiEventSet = queue.remove();
es = AbstractEventSet.toSpecificEventSet(jdiEventSet);
session.interrupted = es.suspendedAll();
dispatchEventSet(es);
} while(!(es instanceof VMDisconnectEventSet));
}
//### Gross foul hackery!
private void dispatchEventSet(final AbstractEventSet es) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
boolean interrupted = es.suspendedAll();
es.notify(firstListener);
boolean wantInterrupt = JDIEventSource.this.wantInterrupt;
for (JDIListener jl : session.runtime.jdiListeners) {
es.notify(jl);
}
if (interrupted && !wantInterrupt) {
session.interrupted = false;
//### Catch here is a hack
try {
session.vm.resume();
} catch (VMDisconnectedException ee) {}
}
if (es instanceof ThreadDeathEventSet) {
ThreadReference t = ((ThreadDeathEventSet)es).getThread();
session.runtime.removeThreadInfo(t);
}
}
});
}
private void finalizeEventSet(AbstractEventSet es) {
if (session.interrupted && !wantInterrupt) {
session.interrupted = false;
//### Catch here is a hack
try {
session.vm.resume();
} catch (VMDisconnectedException ee) {}
}
if (es instanceof ThreadDeathEventSet) {
ThreadReference t = ((ThreadDeathEventSet)es).getThread();
session.runtime.removeThreadInfo(t);
}
}
//### This is a Hack, deal with it
private class FirstListener implements JDIListener {
@Override
public void accessWatchpoint(AccessWatchpointEventSet e) {
session.runtime.validateThreadInfo();
wantInterrupt = true;
}
@Override
public void classPrepare(ClassPrepareEventSet e) {
wantInterrupt = false;
runtime.resolve(e.getReferenceType());
}
@Override
public void classUnload(ClassUnloadEventSet e) {
wantInterrupt = false;
}
@Override
public void exception(ExceptionEventSet e) {
wantInterrupt = true;
}
@Override
public void locationTrigger(LocationTriggerEventSet e) {
session.runtime.validateThreadInfo();
wantInterrupt = true;
}
@Override
public void modificationWatchpoint(ModificationWatchpointEventSet e) {
session.runtime.validateThreadInfo();
wantInterrupt = true;
}
@Override
public void threadDeath(ThreadDeathEventSet e) {
wantInterrupt = false;
}
@Override
public void threadStart(ThreadStartEventSet e) {
wantInterrupt = false;
}
@Override
public void vmDeath(VMDeathEventSet e) {
//### Should have some way to notify user
//### that VM died before the session ended.
wantInterrupt = false;
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
//### Notify user?
wantInterrupt = false;
session.runtime.endSession();
}
@Override
public void vmStart(VMStartEventSet e) {
//### Do we need to do anything with it?
wantInterrupt = false;
}
}
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import java.util.List;
public class LineBreakpointSpec extends BreakpointSpec {
int lineNumber;
LineBreakpointSpec(EventRequestSpecList specs,
ReferenceTypeSpec refSpec, int lineNumber) {
super(specs, refSpec);
this.lineNumber = lineNumber;
}
/**
* The 'refType' is known to match.
*/
@Override
void resolve(ReferenceType refType) throws InvalidTypeException,
LineNotFoundException {
if (!(refType instanceof ClassType)) {
throw new InvalidTypeException();
}
Location location = location((ClassType)refType);
setRequest(refType.virtualMachine().eventRequestManager()
.createBreakpointRequest(location));
}
private Location location(ClassType clazz) throws
LineNotFoundException {
Location location = null;
try {
List<Location> locs = clazz.locationsOfLine(lineNumber());
if (locs.size() == 0) {
throw new LineNotFoundException();
}
// TODO handle multiple locations
location = locs.get(0);
if (location.method() == null) {
throw new LineNotFoundException();
}
} catch (AbsentInformationException e) {
/*
* TO DO: throw something more specific, or allow
* AbsentInfo exception to pass through.
*/
throw new LineNotFoundException();
}
return location;
}
public int lineNumber() {
return lineNumber;
}
@Override
public int hashCode() {
return refSpec.hashCode() + lineNumber;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof LineBreakpointSpec) {
LineBreakpointSpec breakpoint = (LineBreakpointSpec)obj;
return refSpec.equals(breakpoint.refSpec) &&
(lineNumber == breakpoint.lineNumber);
} else {
return false;
}
}
@Override
public String errorMessageFor(Exception e) {
if (e instanceof LineNotFoundException) {
return ("No code at line " + lineNumber() + " in " + refSpec);
} else if (e instanceof InvalidTypeException) {
return ("Breakpoints can be located only in classes. " +
refSpec + " is an interface or array");
} else {
return super.errorMessageFor( e);
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer("breakpoint ");
buffer.append(refSpec.toString());
buffer.append(':');
buffer.append(lineNumber);
buffer.append(" (");
buffer.append(getStatusString());
buffer.append(')');
return buffer.toString();
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class LineNotFoundException extends Exception
{
private static final long serialVersionUID = -5630418117861587582L;
public LineNotFoundException()
{
super();
}
public LineNotFoundException(String s)
{
super(s);
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
class MalformedMemberNameException extends Exception {
private static final long serialVersionUID = -7726664097374844485L;
public MalformedMemberNameException() {
super();
}
public MalformedMemberNameException(String s) {
super(s);
}
}

View File

@@ -0,0 +1,346 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import java.util.ArrayList;
import java.util.List;
public class MethodBreakpointSpec extends BreakpointSpec {
String methodId;
List<String> methodArgs;
MethodBreakpointSpec(EventRequestSpecList specs,
ReferenceTypeSpec refSpec,
String methodId, List<String> methodArgs) {
super(specs, refSpec);
this.methodId = methodId;
this.methodArgs = methodArgs;
}
/**
* The 'refType' is known to match.
*/
@Override
void resolve(ReferenceType refType) throws MalformedMemberNameException,
AmbiguousMethodException,
InvalidTypeException,
NoSuchMethodException,
NoSessionException {
if (!isValidMethodName(methodId)) {
throw new MalformedMemberNameException(methodId);
}
if (!(refType instanceof ClassType)) {
throw new InvalidTypeException();
}
Location location = location((ClassType)refType);
setRequest(refType.virtualMachine().eventRequestManager()
.createBreakpointRequest(location));
}
private Location location(ClassType clazz) throws
AmbiguousMethodException,
NoSuchMethodException,
NoSessionException {
Method method = findMatchingMethod(clazz);
Location location = method.location();
return location;
}
public String methodName() {
return methodId;
}
public List<String> methodArgs() {
return methodArgs;
}
@Override
public int hashCode() {
return refSpec.hashCode() +
((methodId != null) ? methodId.hashCode() : 0) +
((methodArgs != null) ? methodArgs.hashCode() : 0);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MethodBreakpointSpec) {
MethodBreakpointSpec breakpoint = (MethodBreakpointSpec)obj;
return methodId.equals(breakpoint.methodId) &&
methodArgs.equals(breakpoint.methodArgs) &&
refSpec.equals(breakpoint.refSpec);
} else {
return false;
}
}
@Override
public String errorMessageFor(Exception e) {
if (e instanceof AmbiguousMethodException) {
return ("Method " + methodName() + " is overloaded; specify arguments");
/*
* TO DO: list the methods here
*/
} else if (e instanceof NoSuchMethodException) {
return ("No method " + methodName() + " in " + refSpec);
} else if (e instanceof InvalidTypeException) {
return ("Breakpoints can be located only in classes. " +
refSpec + " is an interface or array");
} else {
return super.errorMessageFor( e);
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer("breakpoint ");
buffer.append(refSpec.toString());
buffer.append('.');
buffer.append(methodId);
if (methodArgs != null) {
boolean first = true;
buffer.append('(');
for (String name : methodArgs) {
if (!first) {
buffer.append(',');
}
buffer.append(name);
first = false;
}
buffer.append(")");
}
buffer.append(" (");
buffer.append(getStatusString());
buffer.append(')');
return buffer.toString();
}
private boolean isValidMethodName(String s) {
return isJavaIdentifier(s) ||
s.equals("<init>") ||
s.equals("<clinit>");
}
/*
* Compare a method's argument types with a Vector of type names.
* Return true if each argument type has a name identical to the
* corresponding string in the vector (allowing for varargs)
* and if the number of arguments in the method matches the
* number of names passed
*/
private boolean compareArgTypes(Method method, List<String> nameList) {
List<String> argTypeNames = method.argumentTypeNames();
// If argument counts differ, we can stop here
if (argTypeNames.size() != nameList.size()) {
return false;
}
// Compare each argument type's name
int nTypes = argTypeNames.size();
for (int i = 0; i < nTypes; ++i) {
String comp1 = argTypeNames.get(i);
String comp2 = nameList.get(i);
if (! comp1.equals(comp2)) {
/*
* We have to handle varargs. EG, the
* method's last arg type is xxx[]
* while the nameList contains xxx...
* Note that the nameList can also contain
* xxx[] in which case we don't get here.
*/
if (i != nTypes - 1 ||
!method.isVarArgs() ||
!comp2.endsWith("...")) {
return false;
}
/*
* The last types differ, it is a varargs
* method and the nameList item is varargs.
* We just have to compare the type names, eg,
* make sure we don't have xxx[] for the method
* arg type and yyy... for the nameList item.
*/
int comp1Length = comp1.length();
if (comp1Length + 1 != comp2.length()) {
// The type names are different lengths
return false;
}
// We know the two type names are the same length
if (!comp1.regionMatches(0, comp2, 0, comp1Length - 2)) {
return false;
}
// We do have xxx[] and xxx... as the last param type
return true;
}
}
return true;
}
private VirtualMachine vm() {
return request.virtualMachine();
}
/**
* Remove unneeded spaces and expand class names to fully
* qualified names, if necessary and possible.
*/
private String normalizeArgTypeName(String name) throws NoSessionException {
/*
* Separate the type name from any array modifiers,
* stripping whitespace after the name ends.
*/
int i = 0;
StringBuffer typePart = new StringBuffer();
StringBuffer arrayPart = new StringBuffer();
name = name.trim();
int nameLength = name.length();
/*
* For varargs, there can be spaces before the ... but not
* within the ... So, we will just ignore the ...
* while stripping blanks.
*/
boolean isVarArgs = name.endsWith("...");
if (isVarArgs) {
nameLength -= 3;
}
while (i < nameLength) {
char c = name.charAt(i);
if (Character.isWhitespace(c) || c == '[') {
break; // name is complete
}
typePart.append(c);
i++;
}
while (i < nameLength) {
char c = name.charAt(i);
if ( (c == '[') || (c == ']')) {
arrayPart.append(c);
} else if (!Character.isWhitespace(c)) {
throw new IllegalArgumentException(
"Invalid argument type name");
}
i++;
}
name = typePart.toString();
/*
* When there's no sign of a package name already,
* try to expand the
* the name to a fully qualified class name
*/
if ((name.indexOf('.') == -1) || name.startsWith("*.")) {
try {
List<?> refs = specs.runtime.findClassesMatchingPattern(name);
if (refs.size() > 0) { //### ambiguity???
name = ((ReferenceType)(refs.get(0))).name();
}
} catch (IllegalArgumentException e) {
// We'll try the name as is
}
}
name += arrayPart.toString();
if (isVarArgs) {
name += "...";
}
return name;
}
/*
* Attempt an unambiguous match of the method name and
* argument specification to a method. If no arguments
* are specified, the method must not be overloaded.
* Otherwise, the argument types much match exactly
*/
private Method findMatchingMethod(ClassType clazz)
throws AmbiguousMethodException,
NoSuchMethodException,
NoSessionException {
// Normalize the argument string once before looping below.
List<String> argTypeNames = null;
if (methodArgs() != null) {
argTypeNames = new ArrayList<String>(methodArgs().size());
for (String name : methodArgs()) {
name = normalizeArgTypeName(name);
argTypeNames.add(name);
}
}
// Check each method in the class for matches
Method firstMatch = null; // first method with matching name
Method exactMatch = null; // (only) method with same name & sig
int matchCount = 0; // > 1 implies overload
for (Method candidate : clazz.methods()) {
if (candidate.name().equals(methodName())) {
matchCount++;
// Remember the first match in case it is the only one
if (matchCount == 1) {
firstMatch = candidate;
}
// If argument types were specified, check against candidate
if ((argTypeNames != null)
&& compareArgTypes(candidate, argTypeNames) == true) {
exactMatch = candidate;
break;
}
}
}
// Determine method for breakpoint
Method method = null;
if (exactMatch != null) {
// Name and signature match
method = exactMatch;
} else if ((argTypeNames == null) && (matchCount > 0)) {
// At least one name matched and no arg types were specified
if (matchCount == 1) {
method = firstMatch; // Only one match; safe to use it
} else {
throw new AmbiguousMethodException();
}
} else {
throw new NoSuchMethodException(methodName());
}
return method;
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class MethodNotFoundException extends Exception
{
private static final long serialVersionUID = -2064968107599632609L;
public MethodNotFoundException()
{
super();
}
public MethodNotFoundException(String s)
{
super(s);
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
public class ModificationWatchpointSpec extends WatchpointSpec {
ModificationWatchpointSpec(EventRequestSpecList specs,
ReferenceTypeSpec refSpec, String fieldId) {
super(specs, refSpec, fieldId);
}
/**
* The 'refType' is known to match.
*/
@Override
void resolve(ReferenceType refType) throws InvalidTypeException,
NoSuchFieldException {
if (!(refType instanceof ClassType)) {
throw new InvalidTypeException();
}
Field field = refType.fieldByName(fieldId);
if (field == null) {
throw new NoSuchFieldException(fieldId);
}
setRequest(refType.virtualMachine().eventRequestManager()
.createModificationWatchpointRequest(field));
}
@Override
public boolean equals(Object obj) {
return (obj instanceof ModificationWatchpointSpec) &&
super.equals(obj);
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class NoSessionException extends Exception {
private static final long serialVersionUID = -7324357828115128603L;
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class NoThreadException extends Exception {
private static final long serialVersionUID = 1846613539928921998L;
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public interface OutputListener {
void putString(String str);
//void putLine(String line);
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
// dummy placeholder for javaCC-generated code.
public class ParseException extends Exception {}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
import java.util.StringTokenizer;
class PatternReferenceTypeSpec implements ReferenceTypeSpec {
final boolean isWild;
final String classId;
PatternReferenceTypeSpec(String classId)
// throws ClassNotFoundException
{
// checkClassName(classId);
isWild = classId.startsWith("*.");
if (isWild) {
this.classId = classId.substring(1);
} else {
this.classId = classId;
}
}
/**
* Does the specified ReferenceType match this spec.
*/
@Override
public boolean matches(ReferenceType refType) {
if (isWild) {
return refType.name().endsWith(classId);
} else {
return refType.name().equals(classId);
}
}
@Override
public int hashCode() {
return classId.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PatternReferenceTypeSpec) {
PatternReferenceTypeSpec spec = (PatternReferenceTypeSpec)obj;
return classId.equals(spec.classId) && (isWild == spec.isWild);
} else {
return false;
}
}
private void checkClassName(String className) throws ClassNotFoundException {
// Do stricter checking of class name validity on deferred
// because if the name is invalid, it will
// never match a future loaded class, and we'll be silent
// about it.
StringTokenizer tokenizer = new StringTokenizer(className, ".");
boolean first = true;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
// Each dot-separated piece must be a valid identifier
// and the first token can also be "*". (Note that
// numeric class ids are not permitted. They must
// match a loaded class.)
if (!Utils.isJavaIdentifier(token) && !(first && token.equals("*"))) {
throw new ClassNotFoundException();
}
first = false;
}
}
@Override
public String toString() {
return isWild? "*" + classId : classId;
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
interface ReferenceTypeSpec {
/**
* Does the specified ReferenceType match this spec.
*/
boolean matches(ReferenceType refType);
@Override
int hashCode();
@Override
boolean equals(Object obj);
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.VMDisconnectedException;
/**
* Our repository of what we know about the state of one
* running VM.
*/
class Session {
final VirtualMachine vm;
final ExecutionManager runtime;
final OutputListener diagnostics;
boolean running = true; // Set false by JDIEventSource
boolean interrupted = false; // Set false by JDIEventSource
private JDIEventSource eventSourceThread = null;
private int traceFlags;
private boolean dead = false;
public Session(VirtualMachine vm, ExecutionManager runtime,
OutputListener diagnostics) {
this.vm = vm;
this.runtime = runtime;
this.diagnostics = diagnostics;
this.traceFlags = VirtualMachine.TRACE_NONE;
}
/**
* Determine if VM is interrupted, i.e, present and not running.
*/
public boolean isInterrupted() {
return interrupted;
}
public void setTraceMode(int traceFlags) {
this.traceFlags = traceFlags;
if (!dead) {
vm.setDebugTraceMode(traceFlags);
}
}
public boolean attach() {
vm.setDebugTraceMode(traceFlags);
diagnostics.putString("Connected to VM");
eventSourceThread = new JDIEventSource(this);
eventSourceThread.start();
return true;
}
public void detach() {
if (!dead) {
eventSourceThread.interrupt();
eventSourceThread = null;
//### The VM may already be disconnected
//### if the debuggee did a System.exit().
//### Exception handler here is a kludge,
//### Rather, there are many other places
//### where we need to handle this exception,
//### and initiate a detach due to an error
//### condition, e.g., connection failure.
try {
vm.dispose();
} catch (VMDisconnectedException ee) {}
dead = true;
diagnostics.putString("Disconnected from VM");
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import java.util.EventObject;
import java.util.EventListener;
public interface SessionListener extends EventListener {
void sessionStart(EventObject e);
void sessionInterrupt(EventObject e);
void sessionContinue(EventObject e);
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
class SourceNameReferenceTypeSpec implements ReferenceTypeSpec {
final String sourceName;
final int linenumber;
SourceNameReferenceTypeSpec(String sourceName, int linenumber) {
this.sourceName = sourceName;
this.linenumber = linenumber;
}
/**
* Does the specified ReferenceType match this spec.
*/
@Override
public boolean matches(ReferenceType refType) {
try {
if (refType.sourceName().equals(sourceName)) {
try {
refType.locationsOfLine(linenumber);
// if we don't throw an exception then it was found
return true;
} catch(AbsentInformationException exc) {
} catch(ObjectCollectedException exc) {
}
}
} catch(AbsentInformationException exc) {
// for sourceName(), fall through
}
return false;
}
@Override
public int hashCode() {
return sourceName.hashCode() + linenumber;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SourceNameReferenceTypeSpec) {
SourceNameReferenceTypeSpec spec = (SourceNameReferenceTypeSpec)obj;
return sourceName.equals(spec.sourceName) &&
(linenumber == spec.linenumber);
} else {
return false;
}
}
@Override
public String toString() {
return sourceName + "@" + linenumber;
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class SpecErrorEvent extends SpecEvent {
private static final long serialVersionUID = 8162634387866409578L;
private Exception reason;
public SpecErrorEvent(EventRequestSpec eventRequestSpec,
Exception reason) {
super(eventRequestSpec);
this.reason = reason;
}
public Exception getReason() {
return reason;
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import java.util.EventObject;
import com.sun.jdi.request.EventRequest;
public class SpecEvent extends EventObject {
private static final long serialVersionUID = 4820735456787276230L;
private EventRequestSpec eventRequestSpec;
public SpecEvent(EventRequestSpec eventRequestSpec) {
super(eventRequestSpec.specs);
this.eventRequestSpec = eventRequestSpec;
}
public EventRequestSpec getEventRequestSpec() {
return eventRequestSpec;
}
public EventRequest getEventRequest() {
return eventRequestSpec.getEventRequest();
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import java.util.EventListener;
public interface SpecListener extends EventListener {
void breakpointSet(SpecEvent e);
void breakpointDeferred(SpecEvent e);
void breakpointDeleted(SpecEvent e);
void breakpointResolved(SpecEvent e);
void breakpointError(SpecErrorEvent e);
void watchpointSet(SpecEvent e);
void watchpointDeferred(SpecEvent e);
void watchpointDeleted(SpecEvent e);
void watchpointResolved(SpecEvent e);
void watchpointError(SpecErrorEvent e);
void exceptionInterceptSet(SpecEvent e);
void exceptionInterceptDeferred(SpecEvent e);
void exceptionInterceptDeleted(SpecEvent e);
void exceptionInterceptResolved(SpecEvent e);
void exceptionInterceptError(SpecErrorEvent e);
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.ThreadGroupReference;
import java.util.List;
import java.util.Stack;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Descend the tree of thread groups.
* @author Robert G. Field
*/
public class ThreadGroupIterator implements Iterator<ThreadGroupReference> {
private final Stack<Iterator<ThreadGroupReference>> stack
= new Stack<Iterator<ThreadGroupReference>>();
public ThreadGroupIterator(List<ThreadGroupReference> tgl) {
push(tgl);
}
public ThreadGroupIterator(ThreadGroupReference tg) {
List<ThreadGroupReference> tgl = new ArrayList<ThreadGroupReference>();
tgl.add(tg);
push(tgl);
}
/*
ThreadGroupIterator() {
this(Env.vm().topLevelThreadGroups());
}
*/
private Iterator<ThreadGroupReference> top() {
return stack.peek();
}
/**
* The invariant in this class is that the top iterator
* on the stack has more elements. If the stack is
* empty, there is no top. This method assures
* this invariant.
*/
private void push(List<ThreadGroupReference> tgl) {
stack.push(tgl.iterator());
while (!stack.isEmpty() && !top().hasNext()) {
stack.pop();
}
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public ThreadGroupReference next() {
return nextThreadGroup();
}
public ThreadGroupReference nextThreadGroup() {
ThreadGroupReference tg = top().next();
push(tg.threadGroups());
return tg;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/*
static ThreadGroupReference find(String name) {
ThreadGroupIterator tgi = new ThreadGroupIterator();
while (tgi.hasNext()) {
ThreadGroupReference tg = tgi.nextThreadGroup();
if (tg.name().equals(name)) {
return tg;
}
}
return null;
}
*/
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.*;
//### Should handle target VM death or connection failure cleanly.
public class ThreadInfo {
private ThreadReference thread;
private int status;
private int frameCount;
Object userObject; // User-supplied annotation.
private boolean interrupted = false;
private void assureInterrupted() throws VMNotInterruptedException {
if (!interrupted) {
throw new VMNotInterruptedException();
}
}
ThreadInfo (ThreadReference thread) {
this.thread = thread;
this.frameCount = -1;
}
public ThreadReference thread() {
return thread;
}
public int getStatus() throws VMNotInterruptedException {
assureInterrupted();
update();
return status;
}
public int getFrameCount() throws VMNotInterruptedException {
assureInterrupted();
update();
return frameCount;
}
public StackFrame getFrame(int index) throws VMNotInterruptedException {
assureInterrupted();
update();
try {
return thread.frame(index);
} catch (IncompatibleThreadStateException e) {
// Should not happen
interrupted = false;
throw new VMNotInterruptedException();
}
}
public Object getUserObject() {
return userObject;
}
public void setUserObject(Object obj) {
userObject = obj;
}
// Refresh upon first access after cache is cleared.
void update() throws VMNotInterruptedException {
if (frameCount == -1) {
try {
status = thread.status();
frameCount = thread.frameCount();
} catch (IncompatibleThreadStateException e) {
// Should not happen
interrupted = false;
throw new VMNotInterruptedException();
}
}
}
// Called from 'ExecutionManager'.
void validate() {
interrupted = true;
}
void invalidate() {
interrupted = false;
frameCount = -1;
status = ThreadReference.THREAD_STATUS_UNKNOWN;
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
import com.sun.jdi.ThreadGroupReference;
import com.sun.jdi.ThreadReference;
import java.util.List;
import java.util.Iterator;
public class ThreadIterator implements Iterator<ThreadReference> {
Iterator<ThreadReference> it = null;
ThreadGroupIterator tgi;
public ThreadIterator(ThreadGroupReference tg) {
tgi = new ThreadGroupIterator(tg);
}
//### make this package access only?
public ThreadIterator(List<ThreadGroupReference> tgl) {
tgi = new ThreadGroupIterator(tgl);
}
@Override
public boolean hasNext() {
while (it == null || !it.hasNext()) {
if (!tgi.hasNext()) {
return false; // no more
}
it = tgi.nextThreadGroup().threads().iterator();
}
return true;
}
@Override
public ThreadReference next() {
return it.next();
}
public ThreadReference nextThread() {
return next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}

View File

@@ -0,0 +1,190 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi; //### does it belong here?
import com.sun.jdi.*;
public class Utils {
/**
* Return the thread status description.
*/
public static String getStatus(ThreadReference thr) {
int status = thr.status();
String result;
switch (status) {
case ThreadReference.THREAD_STATUS_UNKNOWN:
result = "unknown status";
break;
case ThreadReference.THREAD_STATUS_ZOMBIE:
result = "zombie";
break;
case ThreadReference.THREAD_STATUS_RUNNING:
result = "running";
break;
case ThreadReference.THREAD_STATUS_SLEEPING:
result = "sleeping";
break;
case ThreadReference.THREAD_STATUS_MONITOR:
result = "waiting to acquire a monitor lock";
break;
case ThreadReference.THREAD_STATUS_WAIT:
result = "waiting on a condition";
break;
default:
result = "<invalid thread status>";
}
if (thr.isSuspended()) {
result += " (suspended)";
}
return result;
}
/**
* Return a description of an object.
*/
public static String description(ObjectReference ref) {
ReferenceType clazz = ref.referenceType();
long id = ref.uniqueID(); //### TODO use real id
if (clazz == null) {
return toHex(id);
} else {
return "(" + clazz.name() + ")" + toHex(id);
}
}
/**
* Convert a long to a hexadecimal string.
*/
public static String toHex(long n) {
char s1[] = new char[16];
char s2[] = new char[18];
// Store digits in reverse order.
int i = 0;
do {
long d = n & 0xf;
s1[i++] = (char)((d < 10) ? ('0' + d) : ('a' + d - 10));
} while ((n >>>= 4) > 0);
// Now reverse the array.
s2[0] = '0';
s2[1] = 'x';
int j = 2;
while (--i >= 0) {
s2[j++] = s1[i];
}
return new String(s2, 0, j);
}
/**
* Convert hexadecimal strings to longs.
*/
public static long fromHex(String hexStr) {
String str = hexStr.startsWith("0x") ?
hexStr.substring(2).toLowerCase() : hexStr.toLowerCase();
if (hexStr.length() == 0) {
throw new NumberFormatException();
}
long ret = 0;
for (int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (c >= '0' && c <= '9') {
ret = (ret * 16) + (c - '0');
} else if (c >= 'a' && c <= 'f') {
ret = (ret * 16) + (c - 'a' + 10);
} else {
throw new NumberFormatException();
}
}
return ret;
}
/*
* The next two methods are used by this class and by EventHandler
* to print consistent locations and error messages.
*/
public static String locationString(Location loc) {
return loc.declaringType().name() +
"." + loc.method().name() + "(), line=" +
loc.lineNumber();
}
//### UNUSED.
/************************
private String typedName(Method method) {
// TO DO: Use method.signature() instead of method.arguments() so that
// we get sensible results for classes without debugging info
StringBuffer buf = new StringBuffer();
buf.append(method.name());
buf.append("(");
Iterator it = method.arguments().iterator();
while (it.hasNext()) {
buf.append(((LocalVariable)it.next()).typeName());
if (it.hasNext()) {
buf.append(",");
}
}
buf.append(")");
return buf.toString();
}
************************/
public static boolean isValidMethodName(String s) {
return isJavaIdentifier(s) ||
s.equals("<init>") ||
s.equals("<clinit>");
}
public static boolean isJavaIdentifier(String s) {
if (s.length() == 0) {
return false;
}
int cp = s.codePointAt(0);
if (! Character.isJavaIdentifierStart(cp)) {
return false;
}
for (int i = Character.charCount(cp); i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
if (! Character.isJavaIdentifierPart(cp)) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class VMLaunchFailureException extends Exception {
private static final long serialVersionUID = -2439646729274310108L;
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public class VMNotInterruptedException extends Exception {
private static final long serialVersionUID = 8111074582188765600L;
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.bdi;
public abstract class WatchpointSpec extends EventRequestSpec {
final String fieldId;
WatchpointSpec(EventRequestSpecList specs,
ReferenceTypeSpec refSpec, String fieldId) {
super(specs, refSpec);
this.fieldId = fieldId;
// if (!isJavaIdentifier(fieldId)) {
// throw new MalformedMemberNameException(fieldId);
// }
}
@Override
void notifySet(SpecListener listener, SpecEvent evt) {
listener.watchpointSet(evt);
}
@Override
void notifyDeferred(SpecListener listener, SpecEvent evt) {
listener.watchpointDeferred(evt);
}
@Override
void notifyResolved(SpecListener listener, SpecEvent evt) {
listener.watchpointResolved(evt);
}
@Override
void notifyDeleted(SpecListener listener, SpecEvent evt) {
listener.watchpointDeleted(evt);
}
@Override
void notifyError(SpecListener listener, SpecErrorEvent evt) {
listener.watchpointError(evt);
}
@Override
public int hashCode() {
return refSpec.hashCode() + fieldId.hashCode() +
getClass().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof WatchpointSpec) {
WatchpointSpec watchpoint = (WatchpointSpec)obj;
return fieldId.equals(watchpoint.fieldId) &&
refSpec.equals(watchpoint.refSpec) &&
getClass().equals(watchpoint.getClass());
} else {
return false;
}
}
@Override
public String errorMessageFor(Exception e) {
if (e instanceof NoSuchFieldException) {
return ("No field " + fieldId + " in " + refSpec);
} else {
return super.errorMessageFor(e);
}
}
}

View File

@@ -0,0 +1,272 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
import java.util.*;
public abstract class AbstractEventSet extends EventObject implements EventSet {
private static final long serialVersionUID = 2772717574222076977L;
private final EventSet jdiEventSet;
final Event oneEvent;
/**
*/
AbstractEventSet(EventSet jdiEventSet) {
super(jdiEventSet.virtualMachine());
this.jdiEventSet = jdiEventSet;
this.oneEvent = eventIterator().nextEvent();
}
public static AbstractEventSet toSpecificEventSet(EventSet jdiEventSet) {
Event evt = jdiEventSet.eventIterator().nextEvent();
if (evt instanceof LocatableEvent) {
if (evt instanceof ExceptionEvent) {
return new ExceptionEventSet(jdiEventSet);
} else if (evt instanceof WatchpointEvent) {
if (evt instanceof AccessWatchpointEvent) {
return new AccessWatchpointEventSet(jdiEventSet);
} else {
return new ModificationWatchpointEventSet(jdiEventSet);
}
} else {
return new LocationTriggerEventSet(jdiEventSet);
}
} else if (evt instanceof ClassPrepareEvent) {
return new ClassPrepareEventSet(jdiEventSet);
} else if (evt instanceof ClassUnloadEvent) {
return new ClassUnloadEventSet(jdiEventSet);
} else if (evt instanceof ThreadDeathEvent) {
return new ThreadDeathEventSet(jdiEventSet);
} else if (evt instanceof ThreadStartEvent) {
return new ThreadStartEventSet(jdiEventSet);
} else if (evt instanceof VMDeathEvent) {
return new VMDeathEventSet(jdiEventSet);
} else if (evt instanceof VMDisconnectEvent) {
return new VMDisconnectEventSet(jdiEventSet);
} else if (evt instanceof VMStartEvent) {
return new VMStartEventSet(jdiEventSet);
} else {
throw new IllegalArgumentException("Unknown event " + evt);
}
}
public abstract void notify(JDIListener listener);
// Implement Mirror
@Override
public VirtualMachine virtualMachine() {
return jdiEventSet.virtualMachine();
}
public VirtualMachine getVirtualMachine() {
return jdiEventSet.virtualMachine();
}
// Implement EventSet
/**
* Returns the policy used to suspend threads in the target VM
* for this event set. This policy is selected from the suspend
* policies for each event's request. The one that suspends the
* most threads is chosen when the event occurs in the target VM
* and that policy is returned here. See
* com.sun.jdi.request.EventRequest for the possible policy values.
*
* @return the integer suspendPolicy
*/
public int getSuspendPolicy() {
return jdiEventSet.suspendPolicy();
}
@Override
public void resume() {
jdiEventSet.resume();
}
@Override
public int suspendPolicy() {
return jdiEventSet.suspendPolicy();
}
public boolean suspendedAll() {
return jdiEventSet.suspendPolicy() == EventRequest.SUSPEND_ALL;
}
public boolean suspendedEventThread() {
return jdiEventSet.suspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD;
}
public boolean suspendedNone() {
return jdiEventSet.suspendPolicy() == EventRequest.SUSPEND_NONE;
}
/**
* Return an iterator specific to {@link Event} objects.
*/
@Override
public EventIterator eventIterator() {
return jdiEventSet.eventIterator();
}
// Implement java.util.Set (by pass through)
/**
* Returns the number of elements in this set (its cardinality). If this
* set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this set (its cardinality).
*/
@Override
public int size() {
return jdiEventSet.size();
}
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements.
*/
@Override
public boolean isEmpty() {
return jdiEventSet.isEmpty();
}
/**
* Returns <tt>true</tt> if this set contains the specified element. More
* formally, returns <tt>true</tt> if and only if this set contains an
* element <code>e</code> such that <code>(o==null ? e==null :
* o.equals(e))</code>.
*
* @return <tt>true</tt> if this set contains the specified element.
*/
@Override
public boolean contains(Object o) {
return jdiEventSet.contains(o);
}
/**
* Returns an iterator over the elements in this set. The elements are
* returned in no particular order (unless this set is an instance of some
* class that provides a guarantee).
*
* @return an iterator over the elements in this set.
*/
@Override
public Iterator<Event> iterator() {
return jdiEventSet.iterator();
}
/**
* Returns an array containing all of the elements in this set.
* Obeys the general contract of the <tt>Collection.toArray</tt> method.
*
* @return an array containing all of the elements in this set.
*/
@Override
public Object[] toArray() {
return jdiEventSet.toArray();
}
/**
* Returns an array containing all of the elements in this set whose
* runtime type is that of the specified array. Obeys the general
* contract of the <tt>Collection.toArray(Object[])</tt> method.
*
* @param a the array into which the elements of this set are to
* be stored, if it is big enough {
return jdiEventSet.XXX();
} otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of this set.
* @throws ArrayStoreException the runtime type of a is not a supertype
* of the runtime type of every element in this set.
*/
@Override
public <T> T[] toArray(T a[]) {
return jdiEventSet.toArray(a);
}
// Bulk Operations
/**
* Returns <tt>true</tt> if this set contains all of the elements of the
* specified collection. If the specified collection is also a set, this
* method returns <tt>true</tt> if it is a <i>subset</i> of this set.
*
* @param c collection to be checked for containment in this set.
* @return <tt>true</tt> if this set contains all of the elements of the
* specified collection.
*/
@Override
public boolean containsAll(Collection<?> c) {
return jdiEventSet.containsAll(c);
}
// Make the rest of Set unmodifiable
@Override
public boolean add(Event e){
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends Event> coll) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.event.*;
public class AccessWatchpointEventSet extends WatchpointEventSet {
private static final long serialVersionUID = -2620394219156607673L;
AccessWatchpointEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
@Override
public void notify(JDIListener listener) {
listener.accessWatchpoint(this);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
public class ClassPrepareEventSet extends AbstractEventSet {
private static final long serialVersionUID = 5958493423581010491L;
ClassPrepareEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Returns the thread in which this event has occurred.
*
* @return a {@link ThreadReference} which mirrors the event's thread in
* the target VM.
*/
public ThreadReference getThread() {
return ((ClassPrepareEvent)oneEvent).thread();
}
/**
* Returns the reference type for which this event was generated.
*
* @return a {@link ReferenceType} which mirrors the class, interface, or
* array which has been linked.
*/
public ReferenceType getReferenceType() {
return ((ClassPrepareEvent)oneEvent).referenceType();
}
@Override
public void notify(JDIListener listener) {
listener.classPrepare(this);
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.event.*;
public class ClassUnloadEventSet extends AbstractEventSet {
private static final long serialVersionUID = 8370341450345835866L;
ClassUnloadEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Returns the name of the class that has been unloaded.
*/
public String getClassName() {
return ((ClassUnloadEvent)oneEvent).className();
}
/**
* Returns the JNI-style signature of the class that has been unloaded.
*/
public String getClassSignature() {
return ((ClassUnloadEvent)oneEvent).classSignature();
}
@Override
public void notify(JDIListener listener) {
listener.classUnload(this);
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
public class ExceptionEventSet extends LocatableEventSet {
private static final long serialVersionUID = 5328140167954640711L;
ExceptionEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Gets the thrown exception object. The exception object is
* an instance of java.lang.Throwable or a subclass in the
* target VM.
*
* @return an {@link ObjectReference} which mirrors the thrown object in
* the target VM.
*/
public ObjectReference getException() {
return ((ExceptionEvent)oneEvent).exception();
}
/**
* Gets the location where the exception will be caught. An exception
* is considered to be caught if, at the point of the throw, the
* current location is dynamically enclosed in a try statement that
* handles the exception. (See the JVM specification for details).
* If there is such a try statement, the catch location is the
* first code index of the appropriate catch clause.
* <p>
* If there are native methods in the call stack at the time of the
* exception, there are important restrictions to note about the
* returned catch location. In such cases,
* it is not possible to predict whether an exception will be handled
* by some native method on the call stack.
* Thus, it is possible that exceptions considered uncaught
* here will, in fact, be handled by a native method and not cause
* termination of the target VM. Also, it cannot be assumed that the
* catch location returned here will ever be reached by the throwing
* thread. If there is
* a native frame between the current location and the catch location,
* the exception might be handled and cleared in that native method
* instead.
*
* @return the {@link Location} where the exception will be caught or null if
* the exception is uncaught.
*/
public Location getCatchLocation() {
return ((ExceptionEvent)oneEvent).catchLocation();
}
@Override
public void notify(JDIListener listener) {
listener.exception(this);
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
/**
* The adapter which receives JDI event sets. The methods in this
* class are empty; this class is provided as a convenience for
* easily creating listeners by extending this class and overriding
* only the methods of interest.
*/
public class JDIAdapter implements JDIListener {
@Override
public void accessWatchpoint(AccessWatchpointEventSet e) {
}
@Override
public void classPrepare(ClassPrepareEventSet e) {
}
@Override
public void classUnload(ClassUnloadEventSet e) {
}
@Override
public void exception(ExceptionEventSet e) {
}
@Override
public void locationTrigger(LocationTriggerEventSet e) {
}
@Override
public void modificationWatchpoint(ModificationWatchpointEventSet e) {
}
@Override
public void threadDeath(ThreadDeathEventSet e) {
}
@Override
public void threadStart(ThreadStartEventSet e) {
}
@Override
public void vmDeath(VMDeathEventSet e) {
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
}
@Override
public void vmStart(VMStartEventSet e) {
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import java.util.EventListener;
public interface JDIListener extends EventListener {
void accessWatchpoint(AccessWatchpointEventSet e);
void classPrepare(ClassPrepareEventSet e);
void classUnload(ClassUnloadEventSet e);
void exception(ExceptionEventSet e);
void locationTrigger(LocationTriggerEventSet e);
void modificationWatchpoint(ModificationWatchpointEventSet e);
void threadDeath(ThreadDeathEventSet e);
void threadStart(ThreadStartEventSet e);
void vmDeath(VMDeathEventSet e);
void vmDisconnect(VMDisconnectEventSet e);
void vmStart(VMStartEventSet e);
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
/**
* Abstract event set for events with location and thread.
*/
public abstract class LocatableEventSet extends AbstractEventSet {
private static final long serialVersionUID = 1027131209997915620L;
LocatableEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Returns the {@link Location} of this mirror. Depending on context
* and on available debug information, this location will have
* varying precision.
*
* @return the {@link Location} of this mirror.
*/
public Location getLocation() {
return ((LocatableEvent)oneEvent).location();
}
/**
* Returns the thread in which this event has occurred.
*
* @return a {@link ThreadReference} which mirrors the event's thread in
* the target VM.
*/
public ThreadReference getThread() {
return ((LocatableEvent)oneEvent).thread();
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.event.*;
public class LocationTriggerEventSet extends LocatableEventSet {
private static final long serialVersionUID = -3674631710485872487L;
LocationTriggerEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
@Override
public void notify(JDIListener listener) {
listener.locationTrigger(this);
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
public class ModificationWatchpointEventSet extends WatchpointEventSet {
private static final long serialVersionUID = -680889300856154719L;
ModificationWatchpointEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Value that will be assigned to the field when the instruction
* completes.
*/
public Value getValueToBe() {
return ((ModificationWatchpointEvent)oneEvent).valueToBe();
}
@Override
public void notify(JDIListener listener) {
listener.modificationWatchpoint(this);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
public class ThreadDeathEventSet extends AbstractEventSet {
private static final long serialVersionUID = -8801604712308151331L;
ThreadDeathEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Returns the thread which is terminating.
*
* @return a {@link ThreadReference} which mirrors the event's thread in
* the target VM.
*/
public ThreadReference getThread() {
return ((ThreadDeathEvent)oneEvent).thread();
}
@Override
public void notify(JDIListener listener) {
listener.threadDeath(this);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
public class ThreadStartEventSet extends AbstractEventSet {
private static final long serialVersionUID = -3802096132294933502L;
ThreadStartEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Returns the thread which has started.
*
* @return a {@link ThreadReference} which mirrors the event's thread in
* the target VM.
*/
public ThreadReference getThread() {
return ((ThreadStartEvent)oneEvent).thread();
}
@Override
public void notify(JDIListener listener) {
listener.threadStart(this);
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.event.*;
public class VMDeathEventSet extends AbstractEventSet {
private static final long serialVersionUID = 1163097303940092229L;
VMDeathEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
@Override
public void notify(JDIListener listener) {
listener.vmDeath(this);
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.event.*;
public class VMDisconnectEventSet extends AbstractEventSet {
private static final long serialVersionUID = 7968123152344675342L;
VMDisconnectEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
@Override
public void notify(JDIListener listener) {
listener.vmDisconnect(this);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
public class VMStartEventSet extends AbstractEventSet {
private static final long serialVersionUID = -3384957227835478191L;
VMStartEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Returns the initial thread of the VM which has started.
*
* @return a {@link ThreadReference} which mirrors the event's
* thread in the target VM.
*/
public ThreadReference getThread() {
return ((VMStartEvent)oneEvent).thread();
}
@Override
public void notify(JDIListener listener) {
listener.vmStart(this);
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.event;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
public abstract class WatchpointEventSet extends LocatableEventSet {
private static final long serialVersionUID = 5606285209703845409L;
WatchpointEventSet(EventSet jdiEventSet) {
super(jdiEventSet);
}
/**
* Returns the field that is about to be accessed/modified.
*
* @return a {@link Field} which mirrors the field
* in the target VM.
*/
public Field getField() {
return ((WatchpointEvent)oneEvent).field();
}
/**
* Returns the object whose field is about to be accessed/modified.
* Return null is the access is to a static field.
*
* @return a {@link ObjectReference} which mirrors the event's
* object in the target VM.
*/
public ObjectReference getObject() {
return ((WatchpointEvent)oneEvent).object();
}
/**
* Current value of the field.
*/
public Value getValueCurrent() {
return ((WatchpointEvent)oneEvent).valueCurrent();
}
}

View File

@@ -0,0 +1,533 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
/* Generated By:JavaCC: Do not edit this line. ASCII_UCodeESC_CharStream.java Version 0.7pre6 */
package com.sun.tools.example.debug.expr;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (with java-like unicode escape processing).
*/
public final class ASCII_UCodeESC_CharStream
{
public static final boolean staticFlag = false;
static final int hexval(char c) throws java.io.IOException {
switch(c)
{
case '0' :
return 0;
case '1' :
return 1;
case '2' :
return 2;
case '3' :
return 3;
case '4' :
return 4;
case '5' :
return 5;
case '6' :
return 6;
case '7' :
return 7;
case '8' :
return 8;
case '9' :
return 9;
case 'a' :
case 'A' :
return 10;
case 'b' :
case 'B' :
return 11;
case 'c' :
case 'C' :
return 12;
case 'd' :
case 'D' :
return 13;
case 'e' :
case 'E' :
return 14;
case 'f' :
case 'F' :
return 15;
}
throw new java.io.IOException(); // Should never come here
}
public int bufpos = -1;
int bufsize;
int available;
int tokenBegin;
private int bufline[];
private int bufcolumn[];
private int column = 0;
private int line = 1;
private java.io.InputStream inputStream;
private boolean prevCharIsCR = false;
private boolean prevCharIsLF = false;
private byte[] nextCharBuf;
private char[] buffer;
private int maxNextCharInd = 0;
private int nextCharInd = -1;
private int inBuf = 0;
private final void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer,
bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
bufpos += (bufsize - tokenBegin);
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
bufpos -= tokenBegin;
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
available = (bufsize += 2048);
tokenBegin = 0;
}
private final void FillBuff() throws java.io.IOException
{
int i;
if (maxNextCharInd == 4096)
maxNextCharInd = nextCharInd = 0;
try {
if ((i = inputStream.read(nextCharBuf, maxNextCharInd,
4096 - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
if (bufpos != 0)
{
--bufpos;
backup(0);
}
else
{
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
throw e;
}
}
private final byte ReadByte() throws java.io.IOException
{
if (++nextCharInd >= maxNextCharInd)
FillBuff();
return nextCharBuf[nextCharInd];
}
public final char BeginToken() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
return buffer[tokenBegin = (bufpos == bufsize - 1) ? (bufpos = 0)
: ++bufpos];
}
tokenBegin = 0;
bufpos = -1;
return readChar();
}
private final void AdjustBuffSize()
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = 0;
available = tokenBegin;
}
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
private final void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (8 - (column & 07));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
public final char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
return buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos];
}
char c;
if (++bufpos == available)
AdjustBuffSize();
if (((buffer[bufpos] = c = (char)((char)0xff & ReadByte())) == '\\'))
{
UpdateLineColumn(c);
int backSlashCnt = 1;
for (;;) // Read all the backslashes
{
if (++bufpos == available)
AdjustBuffSize();
try
{
if ((buffer[bufpos] = c = (char)((char)0xff & ReadByte())) != '\\')
{
UpdateLineColumn(c);
// found a non-backslash char.
if ((c == 'u') && ((backSlashCnt & 1) == 1))
{
if (--bufpos < 0)
bufpos = bufsize - 1;
break;
}
backup(backSlashCnt);
return '\\';
}
}
catch(java.io.IOException e)
{
if (backSlashCnt > 1)
backup(backSlashCnt);
return '\\';
}
UpdateLineColumn(c);
backSlashCnt++;
}
// Here, we have seen an odd number of backslash's followed by a 'u'
try
{
while ((c = (char)((char)0xff & ReadByte())) == 'u')
++column;
buffer[bufpos] = c = (char)(hexval(c) << 12 |
hexval((char)((char)0xff & ReadByte())) << 8 |
hexval((char)((char)0xff & ReadByte())) << 4 |
hexval((char)((char)0xff & ReadByte())));
column += 4;
}
catch(java.io.IOException e)
{
throw new Error("Invalid escape character at line " + line +
" column " + column + ".");
}
if (backSlashCnt == 1)
return c;
else
{
backup(backSlashCnt - 1);
return '\\';
}
}
else
{
UpdateLineColumn(c);
return (c);
}
}
/**
* @deprecated
* @see #getEndColumn
*/
@Deprecated
public final int getColumn() {
return bufcolumn[bufpos];
}
/**
* @deprecated
* @see #getEndLine
*/
@Deprecated
public final int getLine() {
return bufline[bufpos];
}
public final int getEndColumn() {
return bufcolumn[bufpos];
}
public final int getEndLine() {
return bufline[bufpos];
}
public final int getBeginColumn() {
return bufcolumn[tokenBegin];
}
public final int getBeginLine() {
return bufline[tokenBegin];
}
public final void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
public ASCII_UCodeESC_CharStream(java.io.InputStream dstream,
int startline, int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
nextCharBuf = new byte[4096];
}
public ASCII_UCodeESC_CharStream(java.io.InputStream dstream,
int startline, int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
public void ReInit(java.io.InputStream dstream,
int startline, int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
nextCharBuf = new byte[4096];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
nextCharInd = bufpos = -1;
}
public void ReInit(java.io.InputStream dstream,
int startline, int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
public final String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
public final char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
public void Done()
{
nextCharBuf = null;
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.<BR>
*/
public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len &&
bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,382 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* Generated By:JavaCC: Do not edit this line. ExpressionParserConstants.java */
package com.sun.tools.example.debug.expr;
/**
* Token literal values and constants.
* Generated by org.javacc.parser.OtherFilesGen#start()
*/
public interface ExpressionParserConstants {
/** End of File. */
int EOF = 0;
/** RegularExpression Id. */
int SINGLE_LINE_COMMENT = 6;
/** RegularExpression Id. */
int FORMAL_COMMENT = 7;
/** RegularExpression Id. */
int MULTI_LINE_COMMENT = 8;
/** RegularExpression Id. */
int ABSTRACT = 9;
/** RegularExpression Id. */
int BOOLEAN = 10;
/** RegularExpression Id. */
int BREAK = 11;
/** RegularExpression Id. */
int BYTE = 12;
/** RegularExpression Id. */
int CASE = 13;
/** RegularExpression Id. */
int CATCH = 14;
/** RegularExpression Id. */
int CHAR = 15;
/** RegularExpression Id. */
int CLASS = 16;
/** RegularExpression Id. */
int CONST = 17;
/** RegularExpression Id. */
int CONTINUE = 18;
/** RegularExpression Id. */
int _DEFAULT = 19;
/** RegularExpression Id. */
int DO = 20;
/** RegularExpression Id. */
int DOUBLE = 21;
/** RegularExpression Id. */
int ELSE = 22;
/** RegularExpression Id. */
int EXTENDS = 23;
/** RegularExpression Id. */
int FALSE = 24;
/** RegularExpression Id. */
int FINAL = 25;
/** RegularExpression Id. */
int FINALLY = 26;
/** RegularExpression Id. */
int FLOAT = 27;
/** RegularExpression Id. */
int FOR = 28;
/** RegularExpression Id. */
int GOTO = 29;
/** RegularExpression Id. */
int IF = 30;
/** RegularExpression Id. */
int IMPLEMENTS = 31;
/** RegularExpression Id. */
int IMPORT = 32;
/** RegularExpression Id. */
int INSTANCEOF = 33;
/** RegularExpression Id. */
int INT = 34;
/** RegularExpression Id. */
int INTERFACE = 35;
/** RegularExpression Id. */
int LONG = 36;
/** RegularExpression Id. */
int NATIVE = 37;
/** RegularExpression Id. */
int NEW = 38;
/** RegularExpression Id. */
int NULL = 39;
/** RegularExpression Id. */
int PACKAGE = 40;
/** RegularExpression Id. */
int PRIVATE = 41;
/** RegularExpression Id. */
int PROTECTED = 42;
/** RegularExpression Id. */
int PUBLIC = 43;
/** RegularExpression Id. */
int RETURN = 44;
/** RegularExpression Id. */
int SHORT = 45;
/** RegularExpression Id. */
int STATIC = 46;
/** RegularExpression Id. */
int SUPER = 47;
/** RegularExpression Id. */
int SWITCH = 48;
/** RegularExpression Id. */
int SYNCHRONIZED = 49;
/** RegularExpression Id. */
int THIS = 50;
/** RegularExpression Id. */
int THROW = 51;
/** RegularExpression Id. */
int THROWS = 52;
/** RegularExpression Id. */
int TRANSIENT = 53;
/** RegularExpression Id. */
int TRUE = 54;
/** RegularExpression Id. */
int TRY = 55;
/** RegularExpression Id. */
int VOID = 56;
/** RegularExpression Id. */
int VOLATILE = 57;
/** RegularExpression Id. */
int WHILE = 58;
/** RegularExpression Id. */
int INTEGER_LITERAL = 59;
/** RegularExpression Id. */
int DECIMAL_LITERAL = 60;
/** RegularExpression Id. */
int HEX_LITERAL = 61;
/** RegularExpression Id. */
int OCTAL_LITERAL = 62;
/** RegularExpression Id. */
int FLOATING_POINT_LITERAL = 63;
/** RegularExpression Id. */
int EXPONENT = 64;
/** RegularExpression Id. */
int CHARACTER_LITERAL = 65;
/** RegularExpression Id. */
int STRING_LITERAL = 66;
/** RegularExpression Id. */
int IDENTIFIER = 67;
/** RegularExpression Id. */
int LETTER = 68;
/** RegularExpression Id. */
int DIGIT = 69;
/** RegularExpression Id. */
int LPAREN = 70;
/** RegularExpression Id. */
int RPAREN = 71;
/** RegularExpression Id. */
int LBRACE = 72;
/** RegularExpression Id. */
int RBRACE = 73;
/** RegularExpression Id. */
int LBRACKET = 74;
/** RegularExpression Id. */
int RBRACKET = 75;
/** RegularExpression Id. */
int SEMICOLON = 76;
/** RegularExpression Id. */
int COMMA = 77;
/** RegularExpression Id. */
int DOT = 78;
/** RegularExpression Id. */
int ASSIGN = 79;
/** RegularExpression Id. */
int GT = 80;
/** RegularExpression Id. */
int LT = 81;
/** RegularExpression Id. */
int BANG = 82;
/** RegularExpression Id. */
int TILDE = 83;
/** RegularExpression Id. */
int HOOK = 84;
/** RegularExpression Id. */
int COLON = 85;
/** RegularExpression Id. */
int EQ = 86;
/** RegularExpression Id. */
int LE = 87;
/** RegularExpression Id. */
int GE = 88;
/** RegularExpression Id. */
int NE = 89;
/** RegularExpression Id. */
int SC_OR = 90;
/** RegularExpression Id. */
int SC_AND = 91;
/** RegularExpression Id. */
int INCR = 92;
/** RegularExpression Id. */
int DECR = 93;
/** RegularExpression Id. */
int PLUS = 94;
/** RegularExpression Id. */
int MINUS = 95;
/** RegularExpression Id. */
int STAR = 96;
/** RegularExpression Id. */
int SLASH = 97;
/** RegularExpression Id. */
int BIT_AND = 98;
/** RegularExpression Id. */
int BIT_OR = 99;
/** RegularExpression Id. */
int XOR = 100;
/** RegularExpression Id. */
int REM = 101;
/** RegularExpression Id. */
int LSHIFT = 102;
/** RegularExpression Id. */
int RSIGNEDSHIFT = 103;
/** RegularExpression Id. */
int RUNSIGNEDSHIFT = 104;
/** RegularExpression Id. */
int PLUSASSIGN = 105;
/** RegularExpression Id. */
int MINUSASSIGN = 106;
/** RegularExpression Id. */
int STARASSIGN = 107;
/** RegularExpression Id. */
int SLASHASSIGN = 108;
/** RegularExpression Id. */
int ANDASSIGN = 109;
/** RegularExpression Id. */
int ORASSIGN = 110;
/** RegularExpression Id. */
int XORASSIGN = 111;
/** RegularExpression Id. */
int REMASSIGN = 112;
/** RegularExpression Id. */
int LSHIFTASSIGN = 113;
/** RegularExpression Id. */
int RSIGNEDSHIFTASSIGN = 114;
/** RegularExpression Id. */
int RUNSIGNEDSHIFTASSIGN = 115;
/** Lexical state. */
int DEFAULT = 0;
/** Literal token values. */
String[] tokenImage = {
"<EOF>",
"\" \"",
"\"\\t\"",
"\"\\n\"",
"\"\\r\"",
"\"\\f\"",
"<SINGLE_LINE_COMMENT>",
"<FORMAL_COMMENT>",
"<MULTI_LINE_COMMENT>",
"\"abstract\"",
"\"boolean\"",
"\"break\"",
"\"byte\"",
"\"case\"",
"\"catch\"",
"\"char\"",
"\"class\"",
"\"const\"",
"\"continue\"",
"\"default\"",
"\"do\"",
"\"double\"",
"\"else\"",
"\"extends\"",
"\"false\"",
"\"final\"",
"\"finally\"",
"\"float\"",
"\"for\"",
"\"goto\"",
"\"if\"",
"\"implements\"",
"\"import\"",
"\"instanceof\"",
"\"int\"",
"\"interface\"",
"\"long\"",
"\"native\"",
"\"new\"",
"\"null\"",
"\"package\"",
"\"private\"",
"\"protected\"",
"\"public\"",
"\"return\"",
"\"short\"",
"\"static\"",
"\"super\"",
"\"switch\"",
"\"synchronized\"",
"\"this\"",
"\"throw\"",
"\"throws\"",
"\"transient\"",
"\"true\"",
"\"try\"",
"\"void\"",
"\"volatile\"",
"\"while\"",
"<INTEGER_LITERAL>",
"<DECIMAL_LITERAL>",
"<HEX_LITERAL>",
"<OCTAL_LITERAL>",
"<FLOATING_POINT_LITERAL>",
"<EXPONENT>",
"<CHARACTER_LITERAL>",
"<STRING_LITERAL>",
"<IDENTIFIER>",
"<LETTER>",
"<DIGIT>",
"\"(\"",
"\")\"",
"\"{\"",
"\"}\"",
"\"[\"",
"\"]\"",
"\";\"",
"\",\"",
"\".\"",
"\"=\"",
"\">\"",
"\"<\"",
"\"!\"",
"\"~\"",
"\"?\"",
"\":\"",
"\"==\"",
"\"<=\"",
"\">=\"",
"\"!=\"",
"\"||\"",
"\"&&\"",
"\"++\"",
"\"--\"",
"\"+\"",
"\"-\"",
"\"*\"",
"\"/\"",
"\"&\"",
"\"|\"",
"\"^\"",
"\"%\"",
"\"<<\"",
"\">>\"",
"\">>>\"",
"\"+=\"",
"\"-=\"",
"\"*=\"",
"\"/=\"",
"\"&=\"",
"\"|=\"",
"\"^=\"",
"\"%=\"",
"\"<<=\"",
"\">>=\"",
"\">>>=\"",
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,642 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 5.0 */
/* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.sun.tools.example.debug.expr;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (with java-like unicode escape processing).
*/
public
class JavaCharStream
{
/** Whether parser is static. */
public static final boolean staticFlag = false;
static final int hexval(char c) throws java.io.IOException {
switch(c)
{
case '0' :
return 0;
case '1' :
return 1;
case '2' :
return 2;
case '3' :
return 3;
case '4' :
return 4;
case '5' :
return 5;
case '6' :
return 6;
case '7' :
return 7;
case '8' :
return 8;
case '9' :
return 9;
case 'a' :
case 'A' :
return 10;
case 'b' :
case 'B' :
return 11;
case 'c' :
case 'C' :
return 12;
case 'd' :
case 'D' :
return 13;
case 'e' :
case 'E' :
return 14;
case 'f' :
case 'F' :
return 15;
}
throw new java.io.IOException(); // Should never come here
}
/** Position in buffer. */
public int bufpos = -1;
int bufsize;
int available;
int tokenBegin;
protected int bufline[];
protected int bufcolumn[];
protected int column = 0;
protected int line = 1;
protected boolean prevCharIsCR = false;
protected boolean prevCharIsLF = false;
protected java.io.Reader inputStream;
protected char[] nextCharBuf;
protected char[] buffer;
protected int maxNextCharInd = 0;
protected int nextCharInd = -1;
protected int inBuf = 0;
protected int tabSize = 8;
protected void setTabSize(int i) { tabSize = i; }
protected int getTabSize(int i) { return tabSize; }
protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
bufpos += (bufsize - tokenBegin);
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
bufpos -= tokenBegin;
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
available = (bufsize += 2048);
tokenBegin = 0;
}
protected void FillBuff() throws java.io.IOException
{
int i;
if (maxNextCharInd == 4096)
maxNextCharInd = nextCharInd = 0;
try {
if ((i = inputStream.read(nextCharBuf, maxNextCharInd,
4096 - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
if (bufpos != 0)
{
--bufpos;
backup(0);
}
else
{
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
throw e;
}
}
protected char ReadByte() throws java.io.IOException
{
if (++nextCharInd >= maxNextCharInd)
FillBuff();
return nextCharBuf[nextCharInd];
}
/** @return starting character for token. */
public char BeginToken() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
tokenBegin = bufpos;
return buffer[bufpos];
}
tokenBegin = 0;
bufpos = -1;
return readChar();
}
protected void AdjustBuffSize()
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = 0;
available = tokenBegin;
}
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
/** Read a character. */
public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
char c;
if (++bufpos == available)
AdjustBuffSize();
if ((buffer[bufpos] = c = ReadByte()) == '\\')
{
UpdateLineColumn(c);
int backSlashCnt = 1;
for (;;) // Read all the backslashes
{
if (++bufpos == available)
AdjustBuffSize();
try
{
if ((buffer[bufpos] = c = ReadByte()) != '\\')
{
UpdateLineColumn(c);
// found a non-backslash char.
if ((c == 'u') && ((backSlashCnt & 1) == 1))
{
if (--bufpos < 0)
bufpos = bufsize - 1;
break;
}
backup(backSlashCnt);
return '\\';
}
}
catch(java.io.IOException e)
{
// We are returning one backslash so we should only backup (count-1)
if (backSlashCnt > 1)
backup(backSlashCnt-1);
return '\\';
}
UpdateLineColumn(c);
backSlashCnt++;
}
// Here, we have seen an odd number of backslash's followed by a 'u'
try
{
while ((c = ReadByte()) == 'u')
++column;
buffer[bufpos] = c = (char)(hexval(c) << 12 |
hexval(ReadByte()) << 8 |
hexval(ReadByte()) << 4 |
hexval(ReadByte()));
column += 4;
}
catch(java.io.IOException e)
{
throw new Error("Invalid escape character at line " + line +
" column " + column + ".");
}
if (backSlashCnt == 1)
return c;
else
{
backup(backSlashCnt - 1);
return '\\';
}
}
else
{
UpdateLineColumn(c);
return c;
}
}
@Deprecated
/**
* @deprecated
* @see #getEndColumn
*/
public int getColumn() {
return bufcolumn[bufpos];
}
@Deprecated
/**
* @deprecated
* @see #getEndLine
*/
public int getLine() {
return bufline[bufpos];
}
/** Get end column. */
public int getEndColumn() {
return bufcolumn[bufpos];
}
/** Get end line. */
public int getEndLine() {
return bufline[bufpos];
}
/** @return column of token start */
public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/** @return line number of token start */
public int getBeginLine() {
return bufline[tokenBegin];
}
/** Retreat. */
public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
/** Constructor. */
public JavaCharStream(java.io.Reader dstream,
int startline, int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
nextCharBuf = new char[4096];
}
/** Constructor. */
public JavaCharStream(java.io.Reader dstream,
int startline, int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public JavaCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream,
int startline, int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
nextCharBuf = new char[4096];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
nextCharInd = bufpos = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream,
int startline, int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Constructor. */
public JavaCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Constructor. */
public JavaCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
}
/** Constructor. */
public JavaCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
/** Constructor. */
public JavaCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public JavaCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
/** Constructor. */
public JavaCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** @return token image as String */
public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
/** @return suffix */
public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
/** Set buffers back to null when finished. */
public void Done()
{
nextCharBuf = null;
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
/* JavaCC - OriginalChecksum=17a580b005f6229e8445521923427bab (do not edit this line) */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,212 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */
/* JavaCCOptions:KEEP_LINE_COL=null */
package com.sun.tools.example.debug.expr;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
*
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set.
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
}
/** Constructor with message. */
public ParseException(String message) {
super(message);
}
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* It uses "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser) the correct error message
* gets displayed.
*/
private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
static String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
/* JavaCC - OriginalChecksum=3c9f049ed2bb6ade635c5bf58a386169 (do not edit this line) */

View File

@@ -0,0 +1,156 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */
/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.sun.tools.example.debug.expr;
/**
* Describes the input token stream.
*/
public class Token implements java.io.Serializable {
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/**
* An integer that describes the kind of this token. This numbering
* system is determined by JavaCCParser, and a table of these numbers is
* stored in the file ...Constants.java.
*/
public int kind;
/** The line number of the first character of this Token. */
public int beginLine;
/** The column number of the first character of this Token. */
public int beginColumn;
/** The line number of the last character of this Token. */
public int endLine;
/** The column number of the last character of this Token. */
public int endColumn;
/**
* The string image of the token.
*/
public String image;
/**
* A reference to the next regular (non-special) token from the input
* stream. If this is the last token from the input stream, or if the
* token manager has not read tokens beyond this one, this field is
* set to null. This is true only if this token is also a regular
* token. Otherwise, see below for a description of the contents of
* this field.
*/
public Token next;
/**
* This field is used to access special tokens that occur prior to this
* token, but after the immediately preceding regular (non-special) token.
* If there are no such special tokens, this field is set to null.
* When there are more than one such special token, this field refers
* to the last of these special tokens, which in turn refers to the next
* previous special token through its specialToken field, and so on
* until the first special token (whose specialToken field is null).
* The next fields of special tokens refer to other special tokens that
* immediately follow it (without an intervening regular token). If there
* is no such token, this field is null.
*/
public Token specialToken;
/**
* An optional attribute value of the Token.
* Tokens which are not used as syntactic sugar will often contain
* meaningful values that will be used later on by the compiler or
* interpreter. This attribute value is often different from the image.
* Any subclass of Token that actually wants to return a non-null value can
* override this method as appropriate.
*/
public Object getValue() {
return null;
}
/**
* No-argument constructor
*/
public Token() {}
/**
* Constructs a new token for the specified Image.
*/
public Token(int kind)
{
this(kind, null);
}
/**
* Constructs a new token for the specified Image and Kind.
*/
public Token(int kind, String image)
{
this.kind = kind;
this.image = image;
}
/**
* Returns the image.
*/
public String toString()
{
return image;
}
/**
* Returns a new Token object, by default. However, if you want, you
* can create and return subclass objects based on the value of ofKind.
* Simply add the cases to the switch for all those special cases.
* For example, if you have a subclass of Token called IDToken that
* you want to create if ofKind is ID, simply add something like :
*
* case MyParserConstants.ID : return new IDToken(ofKind, image);
*
* to the following switch statement. Then you can cast matchedToken
* variable to the appropriate type and use sit in your lexical actions.
*/
public static Token newToken(int ofKind, String image)
{
switch(ofKind)
{
default : return new Token(ofKind, image);
}
}
public static Token newToken(int ofKind)
{
return newToken(ofKind, null);
}
}
/* JavaCC - OriginalChecksum=1f1783cae2d4cc94bc225889842dfa8b (do not edit this line) */

View File

@@ -0,0 +1,172 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */
/* JavaCCOptions: */
package com.sun.tools.example.debug.expr;
/** Token Manager Error. */
public class TokenMgrError extends Error
{
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/*
* Ordinals for various reasons why an Error of this type can be thrown.
*/
/**
* Lexical error occurred.
*/
static final int LEXICAL_ERROR = 0;
/**
* An attempt was made to create a second instance of a static token manager.
*/
static final int STATIC_LEXER_ERROR = 1;
/**
* Tried to change to an invalid lexical state.
*/
static final int INVALID_LEXICAL_STATE = 2;
/**
* Detected (and bailed out of) an infinite loop in the token manager.
*/
static final int LOOP_DETECTED = 3;
/**
* Indicates the reason why the exception is thrown. It will have
* one of the above 4 values.
*/
int errorCode;
/**
* Replaces unprintable characters by their escaped (or unicode escaped)
* equivalents in the given string
*/
protected static final String addEscapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
/**
* Returns a detailed message for the Error when it is thrown by the
* token manager to indicate a lexical error.
* Parameters :
* EOFSeen : indicates if EOF caused the lexical error
* curLexState : lexical state in which this error occurred
* errorLine : line number when the error occurred
* errorColumn : column number when the error occurred
* errorAfter : prefix that was seen before this error occurred
* curchar : the offending character
* Note: You can customize the lexical error message by modifying this method.
*/
protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
return("Lexical error at line " +
errorLine + ", column " +
errorColumn + ". Encountered: " +
(EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
"after : \"" + addEscapes(errorAfter) + "\"");
}
/**
* You can also modify the body of this method to customize your error messages.
* For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
* of end-users concern, so you can return something like :
*
* "Internal Error : Please file a bug report .... "
*
* from this method for such cases in the release version of your parser.
*/
public String getMessage() {
return super.getMessage();
}
/*
* Constructors of various flavors follow.
*/
/** No arg constructor. */
public TokenMgrError() {
}
/** Constructor with message and reason. */
public TokenMgrError(String message, int reason) {
super(message);
errorCode = reason;
}
/** Full Constructor. */
public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
}
}
/* JavaCC - OriginalChecksum=9b5d040f247411cad7f77688386c48e7 (do not edit this line) */

View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.tools.example.debug.bdi.*;
public class ApplicationTool extends JPanel {
private static final long serialVersionUID = 310966063293205714L;
private ExecutionManager runtime;
private TypeScript script;
private static final String PROMPT = "Input:";
public ApplicationTool(Environment env) {
super(new BorderLayout());
this.runtime = env.getExecutionManager();
this.script = new TypeScript(PROMPT, false); // No implicit echo.
this.add(script);
script.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runtime.sendLineToApplication(script.readln());
}
});
runtime.addApplicationEchoListener(new TypeScriptOutputListener(script));
runtime.addApplicationOutputListener(new TypeScriptOutputListener(script));
runtime.addApplicationErrorListener(new TypeScriptOutputListener(script));
//### should clean up on exit!
}
/******
public void setFont(Font f) {
script.setFont(f);
}
******/
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
public class ClassManager {
// This class is provided primarily for symmetry with
// SourceManager. Currently, it does very little.
// If we add facilities in the future that require that
// class files be read outside of the VM, for example, to
// provide a disassembled view of a class for bytecode-level
// debugging, the required class file management will be done
// here.
private SearchPath classPath;
public ClassManager(Environment env) {
this.classPath = new SearchPath("");
}
public ClassManager(SearchPath classPath) {
this.classPath = classPath;
}
/*
* Set path for access to class files.
*/
public void setClassPath(SearchPath sp) {
classPath = sp;
}
/*
* Get path for access to class files.
*/
public SearchPath getClassPath() {
return classPath;
}
}

View File

@@ -0,0 +1,287 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
import com.sun.tools.example.debug.bdi.*;
public class ClassTreeTool extends JPanel {
private static final long serialVersionUID = 526178912591739259L;
private Environment env;
private ExecutionManager runtime;
private SourceManager sourceManager;
private ClassManager classManager;
private JTree tree;
private DefaultTreeModel treeModel;
private ClassTreeNode root;
// private SearchPath sourcePath;
private CommandInterpreter interpreter;
private static String HEADING = "CLASSES";
public ClassTreeTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env);
root = createClassTree(HEADING);
treeModel = new DefaultTreeModel(root);
// Create a tree that allows one selection at a time.
tree = new JTree(treeModel);
tree.setSelectionModel(new SingleLeafTreeSelectionModel());
/******
// Listen for when the selection changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
ClassTreeNode node = (ClassTreeNode)
(e.getPath().getLastPathComponent());
if (node != null) {
interpreter.executeCommand("view " + node.getReferenceTypeName());
}
}
});
******/
MouseListener ml = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
ClassTreeNode node =
(ClassTreeNode)selPath.getLastPathComponent();
// If user clicks on leaf, select it, and issue 'view' command.
if (node.isLeaf()) {
tree.setSelectionPath(selPath);
interpreter.executeCommand("view " + node.getReferenceTypeName());
}
}
}
}
};
tree.addMouseListener(ml);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);
// Create listener.
ClassTreeToolListener listener = new ClassTreeToolListener();
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
//### remove listeners on exit!
}
private class ClassTreeToolListener extends JDIAdapter
implements JDIListener, SessionListener {
// SessionListener
@Override
public void sessionStart(EventObject e) {
// Get system classes and any others loaded before attaching.
try {
for (ReferenceType type : runtime.allClasses()) {
root.addClass(type);
}
} catch (VMDisconnectedException ee) {
// VM terminated unexpectedly.
} catch (NoSessionException ee) {
// Ignore. Should not happen.
}
}
@Override
public void sessionInterrupt(EventObject e) {}
@Override
public void sessionContinue(EventObject e) {}
// JDIListener
@Override
public void classPrepare(ClassPrepareEventSet e) {
root.addClass(e.getReferenceType());
}
@Override
public void classUnload(ClassUnloadEventSet e) {
root.removeClass(e.getClassName());
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
// Clear contents of this view.
root = createClassTree(HEADING);
treeModel = new DefaultTreeModel(root);
tree.setModel(treeModel);
}
}
ClassTreeNode createClassTree(String label) {
return new ClassTreeNode(label, null);
}
class ClassTreeNode extends DefaultMutableTreeNode {
private String name;
private ReferenceType refTy; // null for package
ClassTreeNode(String name, ReferenceType refTy) {
this.name = name;
this.refTy = refTy;
}
@Override
public String toString() {
return name;
}
public ReferenceType getReferenceType() {
return refTy;
}
public String getReferenceTypeName() {
return refTy.name();
}
private boolean isPackage() {
return (refTy == null);
}
@Override
public boolean isLeaf() {
return !isPackage();
}
public void addClass(ReferenceType refTy) {
addClass(refTy.name(), refTy);
}
private void addClass(String className, ReferenceType refTy) {
if (className.equals("")) {
return;
}
int pos = className.indexOf('.');
if (pos < 0) {
insertNode(className, refTy);
} else {
String head = className.substring(0, pos);
String tail = className.substring(pos + 1);
ClassTreeNode child = insertNode(head, null);
child.addClass(tail, refTy);
}
}
private ClassTreeNode insertNode(String name, ReferenceType refTy) {
for (int i = 0; i < getChildCount(); i++) {
ClassTreeNode child = (ClassTreeNode)getChildAt(i);
int cmp = name.compareTo(child.toString());
if (cmp == 0) {
// like-named node already exists
return child;
} else if (cmp < 0) {
// insert new node before the child
ClassTreeNode newChild = new ClassTreeNode(name, refTy);
treeModel.insertNodeInto(newChild, this, i);
return newChild;
}
}
// insert new node after last child
ClassTreeNode newChild = new ClassTreeNode(name, refTy);
treeModel.insertNodeInto(newChild, this, getChildCount());
return newChild;
}
public void removeClass(String className) {
if (className.equals("")) {
return;
}
int pos = className.indexOf('.');
if (pos < 0) {
ClassTreeNode child = findNode(className);
if (!isPackage()) {
treeModel.removeNodeFromParent(child);
}
} else {
String head = className.substring(0, pos);
String tail = className.substring(pos + 1);
ClassTreeNode child = findNode(head);
child.removeClass(tail);
if (isPackage() && child.getChildCount() < 1) {
// Prune non-leaf nodes with no children.
treeModel.removeNodeFromParent(child);
}
}
}
private ClassTreeNode findNode(String name) {
for (int i = 0; i < getChildCount(); i++) {
ClassTreeNode child = (ClassTreeNode)getChildAt(i);
int cmp = name.compareTo(child.toString());
if (cmp == 0) {
return child;
} else if (cmp > 0) {
// not found, since children are sorted
return null;
}
}
return null;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,342 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.tools.example.debug.bdi.*;
import com.sun.tools.example.debug.event.*;
public class CommandTool extends JPanel {
private static final long serialVersionUID = 8613516856378346415L;
private Environment env;
private ContextManager context;
private ExecutionManager runtime;
private SourceManager sourceManager;
private TypeScript script;
private static final String DEFAULT_CMD_PROMPT = "Command:";
public CommandTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.context = env.getContextManager();
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
script = new TypeScript(DEFAULT_CMD_PROMPT, false); //no echo
this.add(script);
final CommandInterpreter interpreter =
new CommandInterpreter(env);
// Establish handler for incoming commands.
script.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(script.readln());
}
});
// Establish ourselves as the listener for VM diagnostics.
OutputListener diagnosticsListener =
new TypeScriptOutputListener(script, true);
runtime.addDiagnosticsListener(diagnosticsListener);
// Establish ourselves as the shared debugger typescript.
env.setTypeScript(new PrintWriter(new TypeScriptWriter(script)));
// Handle VM events.
TTYDebugListener listener = new TTYDebugListener(diagnosticsListener);
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
runtime.addSpecListener(listener);
context.addContextListener(listener);
//### remove listeners on exit!
}
private class TTYDebugListener implements
JDIListener, SessionListener, SpecListener, ContextListener {
private OutputListener diagnostics;
TTYDebugListener(OutputListener diagnostics) {
this.diagnostics = diagnostics;
}
// JDIListener
@Override
public void accessWatchpoint(AccessWatchpointEventSet e) {
setThread(e);
for (EventIterator it = e.eventIterator(); it.hasNext(); ) {
it.nextEvent();
diagnostics.putString("Watchpoint hit: " +
locationString(e));
}
}
@Override
public void classPrepare(ClassPrepareEventSet e) {
if (context.getVerboseFlag()) {
String name = e.getReferenceType().name();
diagnostics.putString("Class " + name + " loaded");
}
}
@Override
public void classUnload(ClassUnloadEventSet e) {
if (context.getVerboseFlag()) {
diagnostics.putString("Class " + e.getClassName() +
" unloaded.");
}
}
@Override
public void exception(ExceptionEventSet e) {
setThread(e);
String name = e.getException().referenceType().name();
diagnostics.putString("Exception: " + name);
}
@Override
public void locationTrigger(LocationTriggerEventSet e) {
String locString = locationString(e);
setThread(e);
for (EventIterator it = e.eventIterator(); it.hasNext(); ) {
Event evt = it.nextEvent();
if (evt instanceof BreakpointEvent) {
diagnostics.putString("Breakpoint hit: " + locString);
} else if (evt instanceof StepEvent) {
diagnostics.putString("Step completed: " + locString);
} else if (evt instanceof MethodEntryEvent) {
diagnostics.putString("Method entered: " + locString);
} else if (evt instanceof MethodExitEvent) {
diagnostics.putString("Method exited: " + locString);
} else {
diagnostics.putString("UNKNOWN event: " + e);
}
}
}
@Override
public void modificationWatchpoint(ModificationWatchpointEventSet e) {
setThread(e);
for (EventIterator it = e.eventIterator(); it.hasNext(); ) {
it.nextEvent();
diagnostics.putString("Watchpoint hit: " +
locationString(e));
}
}
@Override
public void threadDeath(ThreadDeathEventSet e) {
if (context.getVerboseFlag()) {
diagnostics.putString("Thread " + e.getThread() +
" ended.");
}
}
@Override
public void threadStart(ThreadStartEventSet e) {
if (context.getVerboseFlag()) {
diagnostics.putString("Thread " + e.getThread() +
" started.");
}
}
@Override
public void vmDeath(VMDeathEventSet e) {
script.setPrompt(DEFAULT_CMD_PROMPT);
diagnostics.putString("VM exited");
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
script.setPrompt(DEFAULT_CMD_PROMPT);
diagnostics.putString("Disconnected from VM");
}
@Override
public void vmStart(VMStartEventSet e) {
script.setPrompt(DEFAULT_CMD_PROMPT);
diagnostics.putString("VM started");
}
// SessionListener
@Override
public void sessionStart(EventObject e) {}
@Override
public void sessionInterrupt(EventObject e) {
Thread.yield(); // fetch output
diagnostics.putString("VM interrupted by user.");
script.setPrompt(DEFAULT_CMD_PROMPT);
}
@Override
public void sessionContinue(EventObject e) {
diagnostics.putString("Execution resumed.");
script.setPrompt(DEFAULT_CMD_PROMPT);
}
// SpecListener
@Override
public void breakpointSet(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint set at " + spec + ".");
}
@Override
public void breakpointDeferred(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint will be set at " +
spec + " when its class is loaded.");
}
@Override
public void breakpointDeleted(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint at " + spec.toString() + " deleted.");
}
@Override
public void breakpointResolved(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint resolved to " + spec.toString() + ".");
}
@Override
public void breakpointError(SpecErrorEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Deferred breakpoint at " +
spec + " could not be resolved:" +
e.getReason());
}
//### Add info for watchpoints and exceptions
@Override
public void watchpointSet(SpecEvent e) {
}
@Override
public void watchpointDeferred(SpecEvent e) {
}
@Override
public void watchpointDeleted(SpecEvent e) {
}
@Override
public void watchpointResolved(SpecEvent e) {
}
@Override
public void watchpointError(SpecErrorEvent e) {
}
@Override
public void exceptionInterceptSet(SpecEvent e) {
}
@Override
public void exceptionInterceptDeferred(SpecEvent e) {
}
@Override
public void exceptionInterceptDeleted(SpecEvent e) {
}
@Override
public void exceptionInterceptResolved(SpecEvent e) {
}
@Override
public void exceptionInterceptError(SpecErrorEvent e) {
}
// ContextListener.
// If the user selects a new current thread or frame, update prompt.
@Override
public void currentFrameChanged(CurrentFrameChangedEvent e) {
// Update prompt only if affect thread is current.
ThreadReference thread = e.getThread();
if (thread == context.getCurrentThread()) {
script.setPrompt(promptString(thread, e.getIndex()));
}
}
}
private String locationString(LocatableEventSet e) {
Location loc = e.getLocation();
return "thread=\"" + e.getThread().name() +
"\", " + Utils.locationString(loc);
}
private void setThread(LocatableEventSet e) {
if (!e.suspendedNone()) {
Thread.yield(); // fetch output
script.setPrompt(promptString(e.getThread(), 0));
//### Current thread should be set elsewhere, e.g.,
//### in ContextManager
//### context.setCurrentThread(thread);
}
}
private String promptString(ThreadReference thread, int frameIndex) {
if (thread == null) {
return DEFAULT_CMD_PROMPT;
} else {
// Frame indices are presented to user as indexed from 1.
return (thread.name() + "[" + (frameIndex + 1) + "]:");
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
public interface ContextListener {
void currentFrameChanged(CurrentFrameChangedEvent e);
}

View File

@@ -0,0 +1,362 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
import com.sun.tools.example.debug.bdi.*;
public class ContextManager {
private ClassManager classManager;
private ExecutionManager runtime;
private String mainClassName;
private String vmArguments;
private String commandArguments;
private String remotePort;
private ThreadReference currentThread;
private boolean verbose;
private ArrayList<ContextListener> contextListeners = new ArrayList<ContextListener>();
public ContextManager(Environment env) {
classManager = env.getClassManager();
runtime = env.getExecutionManager();
mainClassName = "";
vmArguments = "";
commandArguments = "";
currentThread = null;
ContextManagerListener listener = new ContextManagerListener();
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
}
// Program execution defaults.
//### Should there be change listeners for these?
//### They would be needed if we expected a dialog to be
//### synchronized with command input while it was open.
public String getMainClassName() {
return mainClassName;
}
public void setMainClassName(String mainClassName) {
this.mainClassName = mainClassName;
}
public String getVmArguments() {
return processClasspathDefaults(vmArguments);
}
public void setVmArguments(String vmArguments) {
this.vmArguments = vmArguments;
}
public String getProgramArguments() {
return commandArguments;
}
public void setProgramArguments(String commandArguments) {
this.commandArguments = commandArguments;
}
public String getRemotePort() {
return remotePort;
}
public void setRemotePort(String remotePort) {
this.remotePort = remotePort;
}
// Miscellaneous debugger session preferences.
public boolean getVerboseFlag() {
return verbose;
}
public void setVerboseFlag(boolean verbose) {
this.verbose = verbose;
}
// Thread focus.
public ThreadReference getCurrentThread() {
return currentThread;
}
public void setCurrentThread(ThreadReference t) {
if (t != currentThread) {
currentThread = t;
notifyCurrentThreadChanged(t);
}
}
public void setCurrentThreadInvalidate(ThreadReference t) {
currentThread = t;
notifyCurrentFrameChanged(runtime.threadInfo(t),
0, true);
}
public void invalidateCurrentThread() {
notifyCurrentFrameChanged(null, 0, true);
}
// If a view is displaying the current thread, it may
// choose to indicate which frame is current in the
// sense of the command-line UI. It may also "warp" the
// selection to that frame when changed by an 'up' or 'down'
// command. Hence, a notifier is provided.
/******
public int getCurrentFrameIndex() {
return getCurrentFrameIndex(currentThreadInfo);
}
******/
public int getCurrentFrameIndex(ThreadReference t) {
return getCurrentFrameIndex(runtime.threadInfo(t));
}
//### Used in StackTraceTool.
public int getCurrentFrameIndex(ThreadInfo tinfo) {
if (tinfo == null) {
return 0;
}
Integer currentFrame = (Integer)tinfo.getUserObject();
if (currentFrame == null) {
return 0;
} else {
return currentFrame.intValue();
}
}
public int moveCurrentFrameIndex(ThreadReference t, int count) throws VMNotInterruptedException {
return setCurrentFrameIndex(t,count, true);
}
public int setCurrentFrameIndex(ThreadReference t, int newIndex) throws VMNotInterruptedException {
return setCurrentFrameIndex(t, newIndex, false);
}
public int setCurrentFrameIndex(int newIndex) throws VMNotInterruptedException {
if (currentThread == null) {
return 0;
} else {
return setCurrentFrameIndex(currentThread, newIndex, false);
}
}
private int setCurrentFrameIndex(ThreadReference t, int x, boolean relative) throws VMNotInterruptedException {
boolean sameThread = t.equals(currentThread);
ThreadInfo tinfo = runtime.threadInfo(t);
if (tinfo == null) {
return 0;
}
int maxIndex = tinfo.getFrameCount()-1;
int oldIndex = getCurrentFrameIndex(tinfo);
int newIndex = relative? oldIndex + x : x;
if (newIndex > maxIndex) {
newIndex = maxIndex;
} else if (newIndex < 0) {
newIndex = 0;
}
if (!sameThread || newIndex != oldIndex) { // don't recurse
setCurrentFrameIndex(tinfo, newIndex);
}
return newIndex - oldIndex;
}
private void setCurrentFrameIndex(ThreadInfo tinfo, int index) {
tinfo.setUserObject(new Integer(index));
//### In fact, the value may not have changed at this point.
//### We need to signal that the user attempted to change it,
//### however, so that the selection can be "warped" to the
//### current location.
notifyCurrentFrameChanged(tinfo.thread(), index);
}
public StackFrame getCurrentFrame() throws VMNotInterruptedException {
return getCurrentFrame(runtime.threadInfo(currentThread));
}
public StackFrame getCurrentFrame(ThreadReference t) throws VMNotInterruptedException {
return getCurrentFrame(runtime.threadInfo(t));
}
public StackFrame getCurrentFrame(ThreadInfo tinfo) throws VMNotInterruptedException {
int index = getCurrentFrameIndex(tinfo);
try {
// It is possible, though unlikely, that the VM was interrupted
// before the thread created its Java stack.
return tinfo.getFrame(index);
} catch (FrameIndexOutOfBoundsException e) {
return null;
}
}
public void addContextListener(ContextListener cl) {
contextListeners.add(cl);
}
public void removeContextListener(ContextListener cl) {
contextListeners.remove(cl);
}
//### These notifiers are fired only in response to USER-INITIATED changes
//### to the current thread and current frame. When the current thread is set automatically
//### after a breakpoint hit or step completion, no event is generated. Instead,
//### interested parties are expected to listen for the BreakpointHit and StepCompleted
//### events. This convention is unclean, and I believe that it reflects a defect in
//### in the current architecture. Unfortunately, however, we cannot guarantee the
//### order in which various listeners receive a given event, and the handlers for
//### the very same events that cause automatic changes to the current thread may also
//### need to know the current thread.
private void notifyCurrentThreadChanged(ThreadReference t) {
ThreadInfo tinfo = null;
int index = 0;
if (t != null) {
tinfo = runtime.threadInfo(t);
index = getCurrentFrameIndex(tinfo);
}
notifyCurrentFrameChanged(tinfo, index, false);
}
private void notifyCurrentFrameChanged(ThreadReference t, int index) {
notifyCurrentFrameChanged(runtime.threadInfo(t),
index, false);
}
private void notifyCurrentFrameChanged(ThreadInfo tinfo, int index,
boolean invalidate) {
ArrayList<ContextListener> l = new ArrayList<ContextListener>(contextListeners);
CurrentFrameChangedEvent evt =
new CurrentFrameChangedEvent(this, tinfo, index, invalidate);
for (int i = 0; i < l.size(); i++) {
l.get(i).currentFrameChanged(evt);
}
}
private class ContextManagerListener extends JDIAdapter
implements SessionListener, JDIListener {
// SessionListener
@Override
public void sessionStart(EventObject e) {
invalidateCurrentThread();
}
@Override
public void sessionInterrupt(EventObject e) {
setCurrentThreadInvalidate(currentThread);
}
@Override
public void sessionContinue(EventObject e) {
invalidateCurrentThread();
}
// JDIListener
@Override
public void locationTrigger(LocationTriggerEventSet e) {
setCurrentThreadInvalidate(e.getThread());
}
@Override
public void exception(ExceptionEventSet e) {
setCurrentThreadInvalidate(e.getThread());
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
invalidateCurrentThread();
}
}
/**
* Add a -classpath argument to the arguments passed to the exec'ed
* VM with the contents of CLASSPATH environment variable,
* if -classpath was not already specified.
*
* @param javaArgs the arguments to the VM being exec'd that
* potentially has a user specified -classpath argument.
* @return a javaArgs whose -classpath option has been added
*/
private String processClasspathDefaults(String javaArgs) {
if (javaArgs.indexOf("-classpath ") == -1) {
StringBuffer munged = new StringBuffer(javaArgs);
SearchPath classpath = classManager.getClassPath();
if (classpath.isEmpty()) {
String envcp = System.getProperty("env.class.path");
if ((envcp != null) && (envcp.length() > 0)) {
munged.append(" -classpath " + envcp);
}
} else {
munged.append(" -classpath " + classpath.asString());
}
return munged.toString();
} else {
return javaArgs;
}
}
private String appendPath(String path1, String path2) {
if (path1 == null || path1.length() == 0) {
return path2 == null ? "." : path2;
} else if (path2 == null || path2.length() == 0) {
return path1;
} else {
return path1 + File.pathSeparator + path2;
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
import java.util.EventObject;
public class CurrentFrameChangedEvent extends EventObject {
private static final long serialVersionUID = 4214479486546762179L;
private ThreadInfo tinfo;
private int index;
private boolean invalidate;
public CurrentFrameChangedEvent(Object source, ThreadInfo tinfo,
int index, boolean invalidate) {
super(source);
this.tinfo = tinfo;
this.index = index;
this.invalidate = invalidate;
}
public ThreadReference getThread() {
return tinfo == null? null : tinfo.thread();
}
public ThreadInfo getThreadInfo() {
return tinfo;
}
public int getIndex() {
return index;
}
public boolean getInvalidate() {
return invalidate;
}
}

View File

@@ -0,0 +1,165 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
public class Environment {
private SourceManager sourceManager;
private ClassManager classManager;
private ContextManager contextManager;
private MonitorListModel monitorListModel;
private ExecutionManager runtime;
private PrintWriter typeScript;
private boolean verbose;
public Environment() {
this.classManager = new ClassManager(this);
//### Order of the next three lines is important! (FIX THIS)
this.runtime = new ExecutionManager();
this.sourceManager = new SourceManager(this);
this.contextManager = new ContextManager(this);
this.monitorListModel = new MonitorListModel(this);
}
// Services used by debugging tools.
public SourceManager getSourceManager() {
return sourceManager;
}
public ClassManager getClassManager() {
return classManager;
}
public ContextManager getContextManager() {
return contextManager;
}
public MonitorListModel getMonitorListModel() {
return monitorListModel;
}
public ExecutionManager getExecutionManager() {
return runtime;
}
//### TODO:
//### Tools should attach/detach from environment
//### via a property, which should call an 'addTool'
//### method when set to maintain a registry of
//### tools for exit-time cleanup, etc. Tool
//### class constructors should be argument-free, so
//### that they may be instantiated by bean builders.
//### Will also need 'removeTool' in case property
//### value is changed.
//
// public void addTool(Tool t);
// public void removeTool(Tool t);
public void terminate() {
System.exit(0);
}
// public void refresh(); // notify all tools to refresh their views
// public void addStatusListener(StatusListener l);
// public void removeStatusListener(StatusListener l);
// public void addOutputListener(OutputListener l);
// public void removeOutputListener(OutputListener l);
public void setTypeScript(PrintWriter writer) {
typeScript = writer;
}
public void error(String message) {
if (typeScript != null) {
typeScript.println(message);
} else {
System.out.println(message);
}
}
public void failure(String message) {
if (typeScript != null) {
typeScript.println(message);
} else {
System.out.println(message);
}
}
public void notice(String message) {
if (typeScript != null) {
typeScript.println(message);
} else {
System.out.println(message);
}
}
public OutputSink getOutputSink() {
return new OutputSink(typeScript);
}
public void viewSource(String fileName) {
//### HACK ###
//### Should use listener here.
com.sun.tools.example.debug.gui.GUI.srcTool.showSourceFile(fileName);
}
public void viewLocation(Location locn) {
//### HACK ###
//### Should use listener here.
//### Should we use sourceForLocation here?
com.sun.tools.example.debug.gui.GUI.srcTool.showSourceForLocation(locn);
}
//### Also in 'ContextManager'. Do we need both?
public boolean getVerboseFlag() {
return verbose;
}
public void setVerboseFlag(boolean verbose) {
this.verbose = verbose;
}
}

View File

@@ -0,0 +1,265 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
public class GUI extends JPanel {
private static final long serialVersionUID = 3292463234530679091L;
private CommandTool cmdTool;
private ApplicationTool appTool;
//###HACK##
//### There is currently dirty code in Environment that
//### accesses this directly.
//private SourceTool srcTool;
public static SourceTool srcTool;
private SourceTreeTool sourceTreeTool;
private ClassTreeTool classTreeTool;
private ThreadTreeTool threadTreeTool;
private StackTraceTool stackTool;
private MonitorTool monitorTool;
public static final String progname = "javadt";
public static final String version = "1.0Beta"; //### FIX ME.
public static final String windowBanner = "Java(tm) platform Debug Tool";
private Font fixedFont = new Font("monospaced", Font.PLAIN, 10);
private GUI(Environment env) {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(5, 5, 5, 5));
add(new JDBToolBar(env), BorderLayout.NORTH);
srcTool = new SourceTool(env);
srcTool.setPreferredSize(new java.awt.Dimension(500, 300));
srcTool.setTextFont(fixedFont);
stackTool = new StackTraceTool(env);
stackTool.setPreferredSize(new java.awt.Dimension(500, 100));
monitorTool = new MonitorTool(env);
monitorTool.setPreferredSize(new java.awt.Dimension(500, 50));
JSplitPane right = new JSplitPane(JSplitPane.VERTICAL_SPLIT, srcTool,
new JSplitPane(JSplitPane.VERTICAL_SPLIT, stackTool, monitorTool));
sourceTreeTool = new SourceTreeTool(env);
sourceTreeTool.setPreferredSize(new java.awt.Dimension(200, 450));
classTreeTool = new ClassTreeTool(env);
classTreeTool.setPreferredSize(new java.awt.Dimension(200, 450));
threadTreeTool = new ThreadTreeTool(env);
threadTreeTool.setPreferredSize(new java.awt.Dimension(200, 450));
JTabbedPane treePane = new JTabbedPane(SwingConstants.BOTTOM);
treePane.addTab("Source", null, sourceTreeTool);
treePane.addTab("Classes", null, classTreeTool);
treePane.addTab("Threads", null, threadTreeTool);
JSplitPane centerTop = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treePane, right);
cmdTool = new CommandTool(env);
cmdTool.setPreferredSize(new java.awt.Dimension(700, 150));
appTool = new ApplicationTool(env);
appTool.setPreferredSize(new java.awt.Dimension(700, 200));
JSplitPane centerBottom = new JSplitPane(JSplitPane.VERTICAL_SPLIT, cmdTool, appTool);
// centerBottom.setPreferredSize(new java.awt.Dimension(700, 350));
JSplitPane center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, centerTop, centerBottom);
add(center, BorderLayout.CENTER);
}
private static void usage() {
String separator = File.pathSeparator;
System.out.println("Usage: " + progname + " <options> <class> <arguments>");
System.out.println();
System.out.println("where options include:");
System.out.println(" -help print out this message and exit");
System.out.println(" -sourcepath <directories separated by \"" +
separator + "\">");
System.out.println(" list directories in which to look for source files");
System.out.println(" -remote <hostname>:<port-number>");
System.out.println(" host machine and port number of interpreter to attach to");
System.out.println(" -dbgtrace [flags] print info for debugging " + progname);
System.out.println();
System.out.println("options forwarded to debuggee process:");
System.out.println(" -v -verbose[:class|gc|jni]");
System.out.println(" turn on verbose mode");
System.out.println(" -D<name>=<value> set a system property");
System.out.println(" -classpath <directories separated by \"" +
separator + "\">");
System.out.println(" list directories in which to look for classes");
System.out.println(" -X<option> non-standard debuggee VM option");
System.out.println();
System.out.println("<class> is the name of the class to begin debugging");
System.out.println("<arguments> are the arguments passed to the main() method of <class>");
System.out.println();
System.out.println("For command help type 'help' at " + progname + " prompt");
}
public static void main(String argv[]) {
String clsName = "";
String progArgs = "";
String javaArgs = "";
final Environment env = new Environment();
JPanel mainPanel = new GUI(env);
ContextManager context = env.getContextManager();
ExecutionManager runtime = env.getExecutionManager();
for (int i = 0; i < argv.length; i++) {
String token = argv[i];
if (token.equals("-dbgtrace")) {
if ((i == argv.length - 1) ||
! Character.isDigit(argv[i+1].charAt(0))) {
runtime.setTraceMode(VirtualMachine.TRACE_ALL);
} else {
String flagStr = argv[++i];
runtime.setTraceMode(Integer.decode(flagStr).intValue());
}
} else if (token.equals("-X")) {
System.out.println(
"Use 'java -X' to see the available non-standard options");
System.out.println();
usage();
System.exit(1);
} else if (
// Standard VM options passed on
token.equals("-v") || token.startsWith("-v:") || // -v[:...]
token.startsWith("-verbose") || // -verbose[:...]
token.startsWith("-D") ||
// NonStandard options passed on
token.startsWith("-X") ||
// Old-style options
// (These should remain in place as long as the standard VM accepts them)
token.equals("-noasyncgc") || token.equals("-prof") ||
token.equals("-verify") || token.equals("-noverify") ||
token.equals("-verifyremote") ||
token.equals("-verbosegc") ||
token.startsWith("-ms") || token.startsWith("-mx") ||
token.startsWith("-ss") || token.startsWith("-oss") ) {
javaArgs += token + " ";
} else if (token.equals("-sourcepath")) {
if (i == (argv.length - 1)) {
System.out.println("No sourcepath specified.");
usage();
System.exit(1);
}
env.getSourceManager().setSourcePath(new SearchPath(argv[++i]));
} else if (token.equals("-classpath")) {
if (i == (argv.length - 1)) {
System.out.println("No classpath specified.");
usage();
System.exit(1);
}
env.getClassManager().setClassPath(new SearchPath(argv[++i]));
} else if (token.equals("-remote")) {
if (i == (argv.length - 1)) {
System.out.println("No remote specified.");
usage();
System.exit(1);
}
env.getContextManager().setRemotePort(argv[++i]);
} else if (token.equals("-help")) {
usage();
System.exit(0);
} else if (token.equals("-version")) {
System.out.println(progname + " version " + version);
System.exit(0);
} else if (token.startsWith("-")) {
System.out.println("invalid option: " + token);
usage();
System.exit(1);
} else {
// Everything from here is part of the command line
clsName = token;
for (i++; i < argv.length; i++) {
progArgs += argv[i] + " ";
}
break;
}
}
context.setMainClassName(clsName);
context.setProgramArguments(progArgs);
context.setVmArguments(javaArgs);
// Force Cross Platform L&F
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
// If you want the System L&F instead, comment out the above line and
// uncomment the following:
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exc) {
System.err.println("Error loading L&F: " + exc);
}
JFrame frame = new JFrame();
frame.setBackground(Color.lightGray);
frame.setTitle(windowBanner);
frame.setJMenuBar(new JDBMenuBar(env));
frame.setContentPane(mainPanel);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
env.terminate();
}
});
frame.pack();
frame.setVisible(true);
}
}

View File

@@ -0,0 +1,218 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.Icon;
import javax.swing.ImageIcon;
class Icons {
private static int[] exec = {
0xffd8ffe0, 0x00104a46, 0x49460001, 0x01020000
, 0x00000000, 0xffdb0043, 0x00020101, 0x01010102
, 0x01010102, 0x02020202, 0x04030202, 0x02020504
, 0x04030406, 0x05060606, 0x05060606, 0x07090806
, 0x07090706, 0x06080b08, 0x090a0a0a, 0x0a0a0608
, 0x0b0c0b0a, 0x0c090a0a, 0x0affdb00, 0x43010202
, 0x02020202, 0x05030305, 0x0a070607, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0affc0
, 0x00110800, 0x0c000c03, 0x01220002, 0x11010311
, 0x01ffc400, 0x1f000001, 0x05010101, 0x01010100
, 0x00000000, 0x00000001, 0x02030405, 0x06070809
, 0x0a0bffc4, 0x00b51000, 0x02010303, 0x02040305
, 0x05040400, 0x00017d01, 0x02030004, 0x11051221
, 0x31410613, 0x51610722, 0x71143281, 0x91a10823
, 0x42b1c115, 0x52d1f024, 0x33627282, 0x090a1617
, 0x18191a25, 0x26272829, 0x2a343536, 0x3738393a
, 0x43444546, 0x4748494a, 0x53545556, 0x5758595a
, 0x63646566, 0x6768696a, 0x73747576, 0x7778797a
, 0x83848586, 0x8788898a, 0x92939495, 0x96979899
, 0x9aa2a3a4, 0xa5a6a7a8, 0xa9aab2b3, 0xb4b5b6b7
, 0xb8b9bac2, 0xc3c4c5c6, 0xc7c8c9ca, 0xd2d3d4d5
, 0xd6d7d8d9, 0xdae1e2e3, 0xe4e5e6e7, 0xe8e9eaf1
, 0xf2f3f4f5, 0xf6f7f8f9, 0xfaffc400, 0x1f010003
, 0x01010101, 0x01010101, 0x01000000, 0x00000001
, 0x02030405, 0x06070809, 0x0a0bffc4, 0x00b51100
, 0x02010204, 0x04030407, 0x05040400, 0x01027700
, 0x01020311, 0x04052131, 0x06124151, 0x07617113
, 0x22328108, 0x144291a1, 0xb1c10923, 0x3352f015
, 0x6272d10a, 0x162434e1, 0x25f11718, 0x191a2627
, 0x28292a35, 0x36373839, 0x3a434445, 0x46474849
, 0x4a535455, 0x56575859, 0x5a636465, 0x66676869
, 0x6a737475, 0x76777879, 0x7a828384, 0x85868788
, 0x898a9293, 0x94959697, 0x98999aa2, 0xa3a4a5a6
, 0xa7a8a9aa, 0xb2b3b4b5, 0xb6b7b8b9, 0xbac2c3c4
, 0xc5c6c7c8, 0xc9cad2d3, 0xd4d5d6d7, 0xd8d9dae2
, 0xe3e4e5e6, 0xe7e8e9ea, 0xf2f3f4f5, 0xf6f7f8f9
, 0xfaffda00, 0x0c030100, 0x02110311, 0x003f00fd
, 0xbafda27e, 0x35ea1f03, 0x346f0ef8, 0x86cfc2d3
, 0x6b31ea9e, 0x2ab7d2ee, 0xf4fb38cb, 0x5cc91cb0
, 0xce4790a0, 0xfcd2ef44, 0xc29e1f95, 0xf94b065f
, 0x42a86eb4, 0xed3ef67b, 0x7b9bcb18, 0x6692ce63
, 0x35a492c4, 0x19a090a3, 0x465d09fb, 0xadb1dd72
, 0x39daec3a, 0x13535706, 0x1f0f8ca7, 0x8dad56a5
, 0x5e6a72e5, 0xe485be0b, 0x2b49df77, 0xcceda6ca
, 0xda6ece3a, 0x147150c5, 0xd5a93a97, 0x84b97963
, 0x6f86cbde, 0x77ddf33b, 0x69b2b69b, 0xb3ffd900
};
private static int[] blank = {
0xffd8ffe0, 0x00104a46, 0x49460001, 0x01020000
, 0x00000000, 0xffdb0043, 0x00020101, 0x01010102
, 0x01010102, 0x02020202, 0x04030202, 0x02020504
, 0x04030406, 0x05060606, 0x05060606, 0x07090806
, 0x07090706, 0x06080b08, 0x090a0a0a, 0x0a0a0608
, 0x0b0c0b0a, 0x0c090a0a, 0x0affdb00, 0x43010202
, 0x02020202, 0x05030305, 0x0a070607, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0affc0
, 0x00110800, 0x0c000c03, 0x01220002, 0x11010311
, 0x01ffc400, 0x1f000001, 0x05010101, 0x01010100
, 0x00000000, 0x00000001, 0x02030405, 0x06070809
, 0x0a0bffc4, 0x00b51000, 0x02010303, 0x02040305
, 0x05040400, 0x00017d01, 0x02030004, 0x11051221
, 0x31410613, 0x51610722, 0x71143281, 0x91a10823
, 0x42b1c115, 0x52d1f024, 0x33627282, 0x090a1617
, 0x18191a25, 0x26272829, 0x2a343536, 0x3738393a
, 0x43444546, 0x4748494a, 0x53545556, 0x5758595a
, 0x63646566, 0x6768696a, 0x73747576, 0x7778797a
, 0x83848586, 0x8788898a, 0x92939495, 0x96979899
, 0x9aa2a3a4, 0xa5a6a7a8, 0xa9aab2b3, 0xb4b5b6b7
, 0xb8b9bac2, 0xc3c4c5c6, 0xc7c8c9ca, 0xd2d3d4d5
, 0xd6d7d8d9, 0xdae1e2e3, 0xe4e5e6e7, 0xe8e9eaf1
, 0xf2f3f4f5, 0xf6f7f8f9, 0xfaffc400, 0x1f010003
, 0x01010101, 0x01010101, 0x01000000, 0x00000001
, 0x02030405, 0x06070809, 0x0a0bffc4, 0x00b51100
, 0x02010204, 0x04030407, 0x05040400, 0x01027700
, 0x01020311, 0x04052131, 0x06124151, 0x07617113
, 0x22328108, 0x144291a1, 0xb1c10923, 0x3352f015
, 0x6272d10a, 0x162434e1, 0x25f11718, 0x191a2627
, 0x28292a35, 0x36373839, 0x3a434445, 0x46474849
, 0x4a535455, 0x56575859, 0x5a636465, 0x66676869
, 0x6a737475, 0x76777879, 0x7a828384, 0x85868788
, 0x898a9293, 0x94959697, 0x98999aa2, 0xa3a4a5a6
, 0xa7a8a9aa, 0xb2b3b4b5, 0xb6b7b8b9, 0xbac2c3c4
, 0xc5c6c7c8, 0xc9cad2d3, 0xd4d5d6d7, 0xd8d9dae2
, 0xe3e4e5e6, 0xe7e8e9ea, 0xf2f3f4f5, 0xf6f7f8f9
, 0xfaffda00, 0x0c030100, 0x02110311, 0x003f00fd
, 0xfca28a28, 0x03ffd900
};
private static int[] stopSignWords = {
0xffd8ffe0, 0x00104a46, 0x49460001, 0x01020000
, 0x00000000, 0xffdb0043, 0x00020101, 0x01010102
, 0x01010102, 0x02020202, 0x04030202, 0x02020504
, 0x04030406, 0x05060606, 0x05060606, 0x07090806
, 0x07090706, 0x06080b08, 0x090a0a0a, 0x0a0a0608
, 0x0b0c0b0a, 0x0c090a0a, 0x0affdb00, 0x43010202
, 0x02020202, 0x05030305, 0x0a070607, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0affc0
, 0x00110800, 0x0c000c03, 0x01220002, 0x11010311
, 0x01ffc400, 0x1f000001, 0x05010101, 0x01010100
, 0x00000000, 0x00000001, 0x02030405, 0x06070809
, 0x0a0bffc4, 0x00b51000, 0x02010303, 0x02040305
, 0x05040400, 0x00017d01, 0x02030004, 0x11051221
, 0x31410613, 0x51610722, 0x71143281, 0x91a10823
, 0x42b1c115, 0x52d1f024, 0x33627282, 0x090a1617
, 0x18191a25, 0x26272829, 0x2a343536, 0x3738393a
, 0x43444546, 0x4748494a, 0x53545556, 0x5758595a
, 0x63646566, 0x6768696a, 0x73747576, 0x7778797a
, 0x83848586, 0x8788898a, 0x92939495, 0x96979899
, 0x9aa2a3a4, 0xa5a6a7a8, 0xa9aab2b3, 0xb4b5b6b7
, 0xb8b9bac2, 0xc3c4c5c6, 0xc7c8c9ca, 0xd2d3d4d5
, 0xd6d7d8d9, 0xdae1e2e3, 0xe4e5e6e7, 0xe8e9eaf1
, 0xf2f3f4f5, 0xf6f7f8f9, 0xfaffc400, 0x1f010003
, 0x01010101, 0x01010101, 0x01000000, 0x00000001
, 0x02030405, 0x06070809, 0x0a0bffc4, 0x00b51100
, 0x02010204, 0x04030407, 0x05040400, 0x01027700
, 0x01020311, 0x04052131, 0x06124151, 0x07617113
, 0x22328108, 0x144291a1, 0xb1c10923, 0x3352f015
, 0x6272d10a, 0x162434e1, 0x25f11718, 0x191a2627
, 0x28292a35, 0x36373839, 0x3a434445, 0x46474849
, 0x4a535455, 0x56575859, 0x5a636465, 0x66676869
, 0x6a737475, 0x76777879, 0x7a828384, 0x85868788
, 0x898a9293, 0x94959697, 0x98999aa2, 0xa3a4a5a6
, 0xa7a8a9aa, 0xb2b3b4b5, 0xb6b7b8b9, 0xbac2c3c4
, 0xc5c6c7c8, 0xc9cad2d3, 0xd4d5d6d7, 0xd8d9dae2
, 0xe3e4e5e6, 0xe7e8e9ea, 0xf2f3f4f5, 0xf6f7f8f9
, 0xfaffda00, 0x0c030100, 0x02110311, 0x003f00f8
, 0xe7e37fc6, 0xff00197f, 0xc142fc65, 0x17ed5bfb
, 0x56db699e, 0x27f14f89, 0xf4cb7b85, 0x5bcd3924
, 0xb5d1ed5d, 0x3cc8b4db, 0x08a4ddf6, 0x6b387cc6
, 0x09182599, 0x99e595e5, 0x9e69a693, 0xbaf0dffc
, 0x1c9dff00, 0x050aff00, 0x82637837, 0x44fd94be
, 0x11e89f0f, 0xfc61e16d, 0x334c5b8f, 0x0f37c45d
, 0x26fef2eb, 0x46b56778, 0xd34db796, 0xd6fadbfd
, 0x0e2f2898, 0xa3903b42, 0xb21891d6, 0x08e08623
, 0xfe0e4ef0, 0xdf837fe0, 0x98dff050, 0xbb2f847f
, 0xb2978274, 0xcd33c2de, 0x30f87f69, 0xe2e6f0f5
, 0xe44ef6ba, 0x35d5c5fe, 0xa16b2dad, 0x8246d1f9
, 0x167fe84b, 0x2a40772c, 0x2d33c717, 0x9702c304
, 0x5fb0dff0, 0x4abff825, 0x5ffc13d7, 0xc55ff04f
, 0x5f845f17, 0x3e2e7ec8, 0xbf0ffe21, 0xf8a7e21f
, 0xc3fd1fc5, 0xde21f10f, 0xc45f0758, 0x6b774b75
, 0xa9584174, 0xf6b6ef75, 0x0b7d9ace, 0x1f304514
, 0x11ed50a8, 0x647f3279, 0x679e5fcf, 0x720cbb37
, 0xc3f1257a, 0x95eb7343, 0xdebabc9d, 0xeef4d1ab
, 0x2b7e1b2d, 0x0fec0f16, 0xb8c7c3cc, 0xdbc15caf
, 0x0795e59e, 0xc710fd97, 0x2cfd9d38, 0xf2f241aa
, 0x9efc64e5, 0x2e67dd7b, 0xdf14acd1, 0xffd90000
};
static private byte[] wordsToBytes(int[] wordArray) {
byte[] bytes = new byte[wordArray.length * 4];
int inx = bytes.length;
for (int i = wordArray.length-1; i >= 0; --i) {
int word = wordArray[i];
for (int j = 0; j < 4; ++j) {
bytes[--inx] = (byte)(word & 0xff);
word = word >>> 8;
}
}
return bytes;
}
static Icon stopSignIcon = new ImageIcon(wordsToBytes(stopSignWords));
static Icon blankIcon = new ImageIcon(wordsToBytes(blank));
static Icon execIcon = new ImageIcon(wordsToBytes(exec));
}

View File

@@ -0,0 +1,278 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.File;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.filechooser.*;
//### Renamed from 'ExampleFileFilter.java' provided with Swing demos.
/**
* A convenience implementation of FileFilter that filters out
* all files except for those type extensions that it knows about.
*
* Extensions are of the type ".foo", which is typically found on
* Windows and Unix boxes, but not on Macinthosh. Case is ignored.
*
* Example - create a new filter that filerts out all files
* but gif and jpg image files:
*
* JFileChooser chooser = new JFileChooser();
* ExampleFileFilter filter = new ExampleFileFilter(
* new String{"gif", "jpg"}, "JPEG & GIF Images")
* chooser.addChoosableFileFilter(filter);
* chooser.showOpenDialog(this);
*
* @author Jeff Dinkins
*/
public class JDBFileFilter extends FileFilter {
private static String TYPE_UNKNOWN = "Type Unknown";
private static String HIDDEN_FILE = "Hidden File";
private Hashtable<String, JDBFileFilter> filters = null;
private String description = null;
private String fullDescription = null;
private boolean useExtensionsInDescription = true;
/**
* Creates a file filter. If no filters are added, then all
* files are accepted.
*
* @see #addExtension
*/
public JDBFileFilter() {
this.filters = new Hashtable<String, JDBFileFilter>();
}
/**
* Creates a file filter that accepts files with the given extension.
* Example: new JDBFileFilter("jpg");
*
* @see #addExtension
*/
public JDBFileFilter(String extension) {
this(extension,null);
}
/**
* Creates a file filter that accepts the given file type.
* Example: new JDBFileFilter("jpg", "JPEG Image Images");
*
* Note that the "." before the extension is not needed. If
* provided, it will be ignored.
*
* @see #addExtension
*/
public JDBFileFilter(String extension, String description) {
this();
if(extension!=null) {
addExtension(extension);
}
if(description!=null) {
setDescription(description);
}
}
/**
* Creates a file filter from the given string array.
* Example: new JDBFileFilter(String {"gif", "jpg"});
*
* Note that the "." before the extension is not needed adn
* will be ignored.
*
* @see #addExtension
*/
public JDBFileFilter(String[] filters) {
this(filters, null);
}
/**
* Creates a file filter from the given string array and description.
* Example: new JDBFileFilter(String {"gif", "jpg"}, "Gif and JPG Images");
*
* Note that the "." before the extension is not needed and will be ignored.
*
* @see #addExtension
*/
public JDBFileFilter(String[] filters, String description) {
this();
for (String filter : filters) {
// add filters one by one
addExtension(filter);
}
if(description!=null) {
setDescription(description);
}
}
/**
* Return true if this file should be shown in the directory pane,
* false if it shouldn't.
*
* Files that begin with "." are ignored.
*
* @see #getExtension
* @see FileFilter#accepts
*/
@Override
public boolean accept(File f) {
if(f != null) {
if(f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if(extension != null && filters.get(getExtension(f)) != null) {
return true;
};
}
return false;
}
/**
* Return the extension portion of the file's name .
*
* @see #getExtension
* @see FileFilter#accept
*/
public String getExtension(File f) {
if(f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if(i>0 && i<filename.length()-1) {
return filename.substring(i+1).toLowerCase();
};
}
return null;
}
/**
* Adds a filetype "dot" extension to filter against.
*
* For example: the following code will create a filter that filters
* out all files except those that end in ".jpg" and ".tif":
*
* JDBFileFilter filter = new JDBFileFilter();
* filter.addExtension("jpg");
* filter.addExtension("tif");
*
* Note that the "." before the extension is not needed and will be ignored.
*/
public void addExtension(String extension) {
if(filters == null) {
filters = new Hashtable<String, JDBFileFilter>(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
/**
* Returns the human readable description of this filter. For
* example: "JPEG and GIF Image Files (*.jpg, *.gif)"
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
* @see FileFilter#getDescription
*/
@Override
public String getDescription() {
if(fullDescription == null) {
if(description == null || isExtensionListInDescription()) {
fullDescription = description==null ? "(" : description + " (";
// build the description from the extension list
Enumeration<String> extensions = filters.keys();
if(extensions != null) {
fullDescription += "." + extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", " + extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
}
/**
* Sets the human readable description of this filter. For
* example: filter.setDescription("Gif and JPG Images");
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
*/
public void setDescription(String description) {
this.description = description;
fullDescription = null;
}
/**
* Determines whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see isExtensionListInDescription
*/
public void setExtensionListInDescription(boolean b) {
useExtensionsInDescription = b;
fullDescription = null;
}
/**
* Returns whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see setExtensionListInDescription
*/
public boolean isExtensionListInDescription() {
return useExtensionsInDescription;
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import java.util.List;
import com.sun.tools.example.debug.bdi.*;
//### This is currently just a placeholder!
class JDBMenuBar extends JMenuBar {
Environment env;
ExecutionManager runtime;
ClassManager classManager;
SourceManager sourceManager;
CommandInterpreter interpreter;
JDBMenuBar(Environment env) {
this.env = env;
this.runtime = env.getExecutionManager();
this.classManager = env.getClassManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env, true);
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open...", 'O');
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openCommand();
}
});
fileMenu.add(openItem);
addTool(fileMenu, "Exit debugger", "Exit", "exit");
JMenu cmdMenu = new JMenu("Commands");
addTool(cmdMenu, "Step into next line", "Step", "step");
addTool(cmdMenu, "Step over next line", "Next", "next");
cmdMenu.addSeparator();
addTool(cmdMenu, "Step into next instruction",
"Step Instruction", "stepi");
addTool(cmdMenu, "Step over next instruction",
"Next Instruction", "nexti");
cmdMenu.addSeparator();
addTool(cmdMenu, "Step out of current method call",
"Step Up", "step up");
cmdMenu.addSeparator();
addTool(cmdMenu, "Suspend execution", "Interrupt", "interrupt");
addTool(cmdMenu, "Continue execution", "Continue", "cont");
cmdMenu.addSeparator();
addTool(cmdMenu, "Display current stack", "Where", "where");
cmdMenu.addSeparator();
addTool(cmdMenu, "Move up one stack frame", "Up", "up");
addTool(cmdMenu, "Move down one stack frame", "Down", "down");
cmdMenu.addSeparator();
JMenuItem monitorItem = new JMenuItem("Monitor Expression...", 'M');
monitorItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
monitorCommand();
}
});
cmdMenu.add(monitorItem);
JMenuItem unmonitorItem = new JMenuItem("Unmonitor Expression...");
unmonitorItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
unmonitorCommand();
}
});
cmdMenu.add(unmonitorItem);
JMenu breakpointMenu = new JMenu("Breakpoint");
JMenuItem stopItem = new JMenuItem("Stop in...", 'S');
stopItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buildBreakpoint();
}
});
breakpointMenu.add(stopItem);
JMenu helpMenu = new JMenu("Help");
addTool(helpMenu, "Display command list", "Help", "help");
this.add(fileMenu);
this.add(cmdMenu);
// this.add(breakpointMenu);
this.add(helpMenu);
}
private void buildBreakpoint() {
Frame frame = JOptionPane.getRootFrame();
JDialog dialog = new JDialog(frame, "Specify Breakpoint");
Container contents = dialog.getContentPane();
Vector<String> classes = new Vector<String>();
classes.add("Foo");
classes.add("Bar");
JList list = new JList(classes);
JScrollPane scrollPane = new JScrollPane(list);
contents.add(scrollPane);
dialog.show();
}
private void monitorCommand() {
String expr = (String)JOptionPane.showInputDialog(null,
"Expression to monitor:", "Add Monitor",
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (expr != null) {
interpreter.executeCommand("monitor " + expr);
}
}
private void unmonitorCommand() {
List monitors = env.getMonitorListModel().monitors();
String expr = (String)JOptionPane.showInputDialog(null,
"Expression to unmonitor:", "Remove Monitor",
JOptionPane.QUESTION_MESSAGE, null,
monitors.toArray(),
monitors.get(monitors.size()-1));
if (expr != null) {
interpreter.executeCommand("unmonitor " + expr);
}
}
private void openCommand() {
JFileChooser chooser = new JFileChooser();
JDBFileFilter filter = new JDBFileFilter("java", "Java source code");
chooser.setFileFilter(filter);
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Chose file: " + chooser.getSelectedFile().getName());
}
}
private void addTool(JMenu menu, String toolTip, String labelText,
String command) {
JMenuItem mi = new JMenuItem(labelText);
mi.setToolTipText(toolTip);
final String cmd = command;
mi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(cmd);
}
});
menu.add(mi);
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import java.awt.event.*;
import com.sun.tools.example.debug.bdi.*;
class JDBToolBar extends JToolBar {
Environment env;
ExecutionManager runtime;
ClassManager classManager;
SourceManager sourceManager;
CommandInterpreter interpreter;
JDBToolBar(Environment env) {
this.env = env;
this.runtime = env.getExecutionManager();
this.classManager = env.getClassManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env, true);
//===== Configure toolbar here =====
addTool("Run application", "run", "run");
addTool("Connect to application", "connect", "connect");
addSeparator();
addTool("Step into next line", "step", "step");
addTool("Step over next line", "next", "next");
// addSeparator();
// addTool("Step into next instruction", "stepi", "stepi");
// addTool("Step over next instruction", "nexti", "nexti");
// addSeparator();
addTool("Step out of current method call", "step up", "step up");
addSeparator();
addTool("Suspend execution", "interrupt", "interrupt");
addTool("Continue execution", "cont", "cont");
addSeparator();
// addTool("Display current stack", "where", "where");
// addSeparator();
addTool("Move up one stack frame", "up", "up");
addTool("Move down one stack frame", "down", "down");
// addSeparator();
// addTool("Display command list", "help", "help");
// addSeparator();
// addTool("Exit debugger", "exit", "exit");
//==================================
}
private void addTool(String toolTip, String labelText, String command) {
JButton button = new JButton(labelText);
button.setToolTipText(toolTip);
final String cmd = command;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(cmd);
}
});
this.add(button);
}
}

View File

@@ -0,0 +1,272 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import com.sun.jdi.*;
import com.sun.jdi.connect.*;
import com.sun.tools.example.debug.bdi.*;
class LaunchTool {
private final ExecutionManager runtime;
private abstract class ArgRep {
final Connector.Argument arg;
final JPanel panel;
ArgRep(Connector.Argument arg) {
this.arg = arg;
panel = new JPanel();
Border etched = BorderFactory.createEtchedBorder();
Border titled = BorderFactory.createTitledBorder(etched,
arg.description(),
TitledBorder.LEFT, TitledBorder.TOP);
panel.setBorder(titled);
}
abstract String getText();
boolean isValid() {
return arg.isValid(getText());
}
boolean isSpecified() {
String value = getText();
return (value != null && value.length() > 0) ||
!arg.mustSpecify();
}
void install() {
arg.setValue(getText());
}
}
private class StringArgRep extends ArgRep {
final JTextField textField;
StringArgRep(Connector.Argument arg, JPanel comp) {
super(arg);
textField = new JTextField(arg.value(), 50 );
textField.setBorder(BorderFactory.createLoweredBevelBorder());
panel.add(new JLabel(arg.label(), SwingConstants.RIGHT));
panel.add(textField); // , BorderLayout.CENTER);
comp.add(panel);
}
@Override
String getText() {
return textField.getText();
}
}
private class BooleanArgRep extends ArgRep {
final JCheckBox check;
BooleanArgRep(Connector.BooleanArgument barg, JPanel comp) {
super(barg);
check = new JCheckBox(barg.label());
check.setSelected(barg.booleanValue());
panel.add(check);
comp.add(panel);
}
@Override
String getText() {
return ((Connector.BooleanArgument)arg)
.stringValueOf(check.getModel().isSelected());
}
}
private LaunchTool(ExecutionManager runtime) {
this.runtime = runtime;
}
private Connector selectConnector() {
final JDialog dialog = new JDialog();
Container content = dialog.getContentPane();
final JPanel radioPanel = new JPanel();
final ButtonGroup radioGroup = new ButtonGroup();
VirtualMachineManager manager = Bootstrap.virtualMachineManager();
List<Connector> all = manager.allConnectors();
Map<ButtonModel, Connector> modelToConnector = new HashMap<ButtonModel, Connector>(all.size(), 0.5f);
dialog.setModal(true);
dialog.setTitle("Select Connector Type");
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
for (Connector connector : all) {
JRadioButton radio = new JRadioButton(connector.description());
modelToConnector.put(radio.getModel(), connector);
radioPanel.add(radio);
radioGroup.add(radio);
}
content.add(radioPanel);
final boolean[] oked = {false};
JPanel buttonPanel = okCancel( dialog, new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (radioGroup.getSelection() == null) {
JOptionPane.showMessageDialog(dialog,
"Please select a connector type",
"No Selection",
JOptionPane.ERROR_MESSAGE);
} else {
oked[0] = true;
dialog.setVisible(false);
dialog.dispose();
}
}
} );
content.add(BorderLayout.SOUTH, buttonPanel);
dialog.pack();
dialog.setVisible(true);
return oked[0] ?
modelToConnector.get(radioGroup.getSelection()) :
null;
}
private void configureAndConnect(final Connector connector) {
final JDialog dialog = new JDialog();
final Map<String, Connector.Argument> args = connector.defaultArguments();
dialog.setModal(true);
dialog.setTitle("Connector Arguments");
Container content = dialog.getContentPane();
JPanel guts = new JPanel();
Border etched = BorderFactory.createEtchedBorder();
BorderFactory.createTitledBorder(etched,
connector.description(),
TitledBorder.LEFT, TitledBorder.TOP);
guts.setBorder(etched);
guts.setLayout(new BoxLayout(guts, BoxLayout.Y_AXIS));
// guts.add(new JLabel(connector.description()));
final List<ArgRep> argReps = new ArrayList<ArgRep>(args.size());
for (Connector.Argument arg : args.values()) {
ArgRep ar;
if (arg instanceof Connector.BooleanArgument) {
ar = new BooleanArgRep((Connector.BooleanArgument)arg, guts);
} else {
ar = new StringArgRep(arg, guts);
}
argReps.add(ar);
}
content.add(guts);
JPanel buttonPanel = okCancel( dialog, new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
for (ArgRep ar : argReps) {
if (!ar.isSpecified()) {
JOptionPane.showMessageDialog(dialog,
ar.arg.label() +
": Argument must be specified",
"No argument", JOptionPane.ERROR_MESSAGE);
return;
}
if (!ar.isValid()) {
JOptionPane.showMessageDialog(dialog,
ar.arg.label() +
": Bad argument value: " +
ar.getText(),
"Bad argument", JOptionPane.ERROR_MESSAGE);
return;
}
ar.install();
}
try {
if (runtime.explictStart(connector, args)) {
dialog.setVisible(false);
dialog.dispose();
} else {
JOptionPane.showMessageDialog(dialog,
"Bad arguments values: See diagnostics window.",
"Bad arguments", JOptionPane.ERROR_MESSAGE);
}
} catch (VMLaunchFailureException exc) {
JOptionPane.showMessageDialog(dialog,
"Launch Failure: " + exc,
"Launch Failed",JOptionPane.ERROR_MESSAGE);
}
}
} );
content.add(BorderLayout.SOUTH, buttonPanel);
dialog.pack();
dialog.setVisible(true);
}
private JPanel okCancel(final JDialog dialog, ActionListener okListener) {
JPanel buttonPanel = new JPanel();
JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
buttonPanel.add(ok);
buttonPanel.add(cancel);
ok.addActionListener(okListener);
cancel.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
dialog.setVisible(false);
dialog.dispose();
}
} );
return buttonPanel;
}
static void queryAndLaunchVM(ExecutionManager runtime)
throws VMLaunchFailureException {
LaunchTool lt = new LaunchTool(runtime);
Connector connector = lt.selectConnector();
if (connector != null) {
lt.configureAndConnect(connector);
}
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.*;
import javax.swing.AbstractListModel;
public class MonitorListModel extends AbstractListModel {
private final List<String> monitors = new ArrayList<String>();
MonitorListModel(Environment env) {
// Create listener.
MonitorListListener listener = new MonitorListListener();
env.getContextManager().addContextListener(listener);
//### remove listeners on exit!
}
@Override
public Object getElementAt(int index) {
return monitors.get(index);
}
@Override
public int getSize() {
return monitors.size();
}
public void add(String expr) {
monitors.add(expr);
int newIndex = monitors.size()-1; // order important
fireIntervalAdded(this, newIndex, newIndex);
}
public void remove(String expr) {
int index = monitors.indexOf(expr);
remove(index);
}
public void remove(int index) {
monitors.remove(index);
fireIntervalRemoved(this, index, index);
}
public List<String> monitors() {
return Collections.unmodifiableList(monitors);
}
public Iterator<?> iterator() {
return monitors().iterator();
}
private void invalidate() {
fireContentsChanged(this, 0, monitors.size()-1);
}
private class MonitorListListener implements ContextListener {
@Override
public void currentFrameChanged(final CurrentFrameChangedEvent e) {
invalidate();
}
}
}

View File

@@ -0,0 +1,134 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
import com.sun.tools.example.debug.expr.ExpressionParser;
import com.sun.tools.example.debug.expr.ParseException;
public class MonitorTool extends JPanel {
private static final long serialVersionUID = -645235951031726647L;
private ExecutionManager runtime;
private ContextManager context;
private JList list;
public MonitorTool(Environment env) {
super(new BorderLayout());
this.runtime = env.getExecutionManager();
this.context = env.getContextManager();
list = new JList(env.getMonitorListModel());
list.setCellRenderer(new MonitorRenderer());
JScrollPane listView = new JScrollPane(list);
add(listView);
// Create listener.
MonitorToolListener listener = new MonitorToolListener();
list.addListSelectionListener(listener);
//### remove listeners on exit!
}
private class MonitorToolListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
int index = list.getSelectedIndex();
if (index != -1) {
}
}
}
private Value evaluate(String expr) throws ParseException,
InvocationException,
InvalidTypeException,
ClassNotLoadedException,
IncompatibleThreadStateException {
ExpressionParser.GetFrame frameGetter =
new ExpressionParser.GetFrame() {
@Override
public StackFrame get()
throws IncompatibleThreadStateException
{
try {
return context.getCurrentFrame();
} catch (VMNotInterruptedException exc) {
throw new IncompatibleThreadStateException();
}
}
};
return ExpressionParser.evaluate(expr, runtime.vm(), frameGetter);
}
private class MonitorRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//### We should indicate the current thread independently of the
//### selection, e.g., with an icon, because the user may change
//### the selection graphically without affecting the current
//### thread.
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value == null) {
this.setText("<unavailable>");
} else {
String expr = (String)value;
try {
Value result = evaluate(expr);
this.setText(expr + " = " + result);
} catch (ParseException exc) {
this.setText(expr + " ? " + exc.getMessage());
} catch (IncompatibleThreadStateException exc) {
this.setText(expr + " ...");
} catch (Exception exc) {
this.setText(expr + " ? " + exc);
}
}
return this;
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
// This class is used in 'CommandInterpreter' as a hook to
// allow messagebox style command output as an alternative
// to a typescript. It should be an interface, not a class.
public class OutputSink extends PrintWriter {
// Currently, we do no buffering,
// so 'show' is a no-op.
OutputSink(Writer writer) {
super(writer);
}
public void show() {
// ignore
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
public class SearchPath {
private String pathString;
private String[] pathArray;
public SearchPath(String searchPath) {
//### Should check searchpath for well-formedness.
StringTokenizer st = new StringTokenizer(searchPath, File.pathSeparator);
List<String> dlist = new ArrayList<String>();
while (st.hasMoreTokens()) {
dlist.add(st.nextToken());
}
pathString = searchPath;
pathArray = dlist.toArray(new String[dlist.size()]);
}
public boolean isEmpty() {
return (pathArray.length == 0);
}
public String asString() {
return pathString;
}
public String[] asArray() {
return pathArray.clone();
}
public File resolve(String relativeFileName) {
for (String element : pathArray) {
File path = new File(element, relativeFileName);
if (path.exists()) {
return path;
}
}
return null;
}
//### return List?
public String[] children(String relativeDirName, FilenameFilter filter) {
// If a file appears at the same relative path
// with respect to multiple entries on the classpath,
// the one corresponding to the earliest entry on the
// classpath is retained. This is the one that will be
// found if we later do a 'resolve'.
SortedSet<String> s = new TreeSet<String>(); // sorted, no duplicates
for (String element : pathArray) {
File path = new File(element, relativeDirName);
if (path.exists()) {
String[] childArray = path.list(filter);
if (childArray != null) {
for (int j = 0; j < childArray.length; j++) {
if (!s.contains(childArray[j])) {
s.add(childArray[j]);
}
}
}
}
}
return s.toArray(new String[s.size()]);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.tree.*;
public class SingleLeafTreeSelectionModel extends DefaultTreeSelectionModel {
private static final long serialVersionUID = -7849105107888117679L;
SingleLeafTreeSelectionModel() {
super();
selectionMode = SINGLE_TREE_SELECTION;
}
@Override
public void setSelectionPath(TreePath path) {
if(((TreeNode)(path.getLastPathComponent())).isLeaf()) {
super.setSelectionPath(path);
}
}
@Override
public void setSelectionPaths(TreePath[] paths) {
// Only look at first path, as all others will be
// ignored anyway in single tree selection mode.
if(((TreeNode)(paths[0].getLastPathComponent())).isLeaf()) {
super.setSelectionPaths(paths);
}
}
@Override
public void addSelectionPath(TreePath path) {
if(((TreeNode)(path.getLastPathComponent())).isLeaf()) {
super.setSelectionPath(path);
}
}
@Override
public void addSelectionPaths(TreePath[] paths) {
// Only look at first path, as all others will be
// ignored anyway in single tree selection mode.
if(((TreeNode)(paths[0].getLastPathComponent())).isLeaf()) {
super.addSelectionPaths(paths);
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
public interface SourceListener {
void sourcepathChanged(SourcepathChangedEvent e);
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
/**
* Manage the list of source files.
* Origin of SourceListener events.
*/
public class SourceManager {
//### TODO: The source cache should be aged, and some cap
//### put on memory consumption by source files loaded into core.
private List<SourceModel> sourceList;
private SearchPath sourcePath;
private ArrayList<SourceListener> sourceListeners = new ArrayList<SourceListener>();
private Map<ReferenceType, SourceModel> classToSource = new HashMap<ReferenceType, SourceModel>();
private Environment env;
/**
* Hold on to it so it can be removed.
*/
private SMClassListener classListener = new SMClassListener();
public SourceManager(Environment env) {
this(env, new SearchPath(""));
}
public SourceManager(Environment env, SearchPath sourcePath) {
this.env = env;
this.sourceList = new LinkedList<SourceModel>();
this.sourcePath = sourcePath;
env.getExecutionManager().addJDIListener(classListener);
}
/**
* Set path for access to source code.
*/
public void setSourcePath(SearchPath sp) {
sourcePath = sp;
// Old cached sources are now invalid.
sourceList = new LinkedList<SourceModel>();
notifySourcepathChanged();
classToSource = new HashMap<ReferenceType, SourceModel>();
}
public void addSourceListener(SourceListener l) {
sourceListeners.add(l);
}
public void removeSourceListener(SourceListener l) {
sourceListeners.remove(l);
}
private void notifySourcepathChanged() {
ArrayList<SourceListener> l = new ArrayList<SourceListener>(sourceListeners);
SourcepathChangedEvent evt = new SourcepathChangedEvent(this);
for (int i = 0; i < l.size(); i++) {
l.get(i).sourcepathChanged(evt);
}
}
/**
* Get path for access to source code.
*/
public SearchPath getSourcePath() {
return sourcePath;
}
/**
* Get source object associated with a Location.
*/
public SourceModel sourceForLocation(Location loc) {
return sourceForClass(loc.declaringType());
}
/**
* Get source object associated with a class or interface.
* Returns null if not available.
*/
public SourceModel sourceForClass(ReferenceType refType) {
SourceModel sm = classToSource.get(refType);
if (sm != null) {
return sm;
}
try {
String filename = refType.sourceName();
String refName = refType.name();
int iDot = refName.lastIndexOf('.');
String pkgName = (iDot >= 0)? refName.substring(0, iDot+1) : "";
String full = pkgName.replace('.', File.separatorChar) + filename;
File path = sourcePath.resolve(full);
if (path != null) {
sm = sourceForFile(path);
classToSource.put(refType, sm);
return sm;
}
return null;
} catch (AbsentInformationException e) {
return null;
}
}
/**
* Get source object associated with an absolute file path.
*/
//### Use hash table for this?
public SourceModel sourceForFile(File path) {
Iterator<SourceModel> iter = sourceList.iterator();
SourceModel sm = null;
while (iter.hasNext()) {
SourceModel candidate = iter.next();
if (candidate.fileName().equals(path)) {
sm = candidate;
iter.remove(); // Will move to start of list.
break;
}
}
if (sm == null && path.exists()) {
sm = new SourceModel(env, path);
}
if (sm != null) {
// At start of list for faster access
sourceList.add(0, sm);
}
return sm;
}
private class SMClassListener extends JDIAdapter
implements JDIListener {
@Override
public void classPrepare(ClassPrepareEventSet e) {
ReferenceType refType = e.getReferenceType();
SourceModel sm = sourceForClass(refType);
if (sm != null) {
sm.addClass(refType);
}
}
@Override
public void classUnload(ClassUnloadEventSet e) {
//### iterate through looking for (e.getTypeName()).
//### then remove it.
}
}
}

View File

@@ -0,0 +1,256 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
import javax.swing.*;
/**
* Represents and manages one source file.
* Caches source lines. Holds other source file info.
*/
public class SourceModel extends AbstractListModel {
private File path;
boolean isActuallySource = true;
private List<ReferenceType> classes = new ArrayList<ReferenceType>();
private Environment env;
// Cached line-by-line access.
//### Unify this with source model used in source view?
//### What is our cache-management policy for these?
//### Even with weak refs, we won't discard any part of the
//### source if the SourceModel object is reachable.
/**
* List of Line.
*/
private List<Line> sourceLines = null;
public static class Line {
public String text;
public boolean hasBreakpoint = false;
public ReferenceType refType = null;
Line(String text) {
this.text = text;
}
public boolean isExecutable() {
return refType != null;
}
public boolean hasBreakpoint() {
return hasBreakpoint;
}
};
// 132 characters long, all printable characters.
public static final Line prototypeCellValue = new Line(
"abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"1234567890~!@#$%^&*()_+{}|" +
":<>?`-=[];',.XXXXXXXXXXXX/\\\"");
SourceModel(Environment env, File path) {
this.env = env;
this.path = path;
}
public SourceModel(String message) {
this.path = null;
setMessage(message);
}
private void setMessage(String message) {
isActuallySource = false;
sourceLines = new ArrayList<Line>();
sourceLines.add(new Line(message));
}
// **** Implement ListModel *****
@Override
public Object getElementAt(int index) {
if (sourceLines == null) {
initialize();
}
return sourceLines.get(index);
}
@Override
public int getSize() {
if (sourceLines == null) {
initialize();
}
return sourceLines.size();
}
// ***** Other functionality *****
public File fileName() {
return path;
}
public BufferedReader sourceReader() throws IOException {
return new BufferedReader(new FileReader(path));
}
public Line line(int lineNo) {
if (sourceLines == null) {
initialize();
}
int index = lineNo - 1; // list is 0-indexed
if (index >= sourceLines.size() || index < 0) {
return null;
} else {
return sourceLines.get(index);
}
}
public String sourceLine(int lineNo) {
Line line = line(lineNo);
if (line == null) {
return null;
} else {
return line.text;
}
}
void addClass(ReferenceType refType) {
// Logically is Set
if (classes.indexOf(refType) == -1) {
classes.add(refType);
if (sourceLines != null) {
markClassLines(refType);
}
}
}
/**
* @return List of currently known {@link com.sun.jdi.ReferenceType}
* in this source file.
*/
public List<ReferenceType> referenceTypes() {
return Collections.unmodifiableList(classes);
}
private void initialize() {
try {
rawInit();
} catch (IOException exc) {
setMessage("[Error reading source code]");
}
}
public void showBreakpoint(int ln, boolean hasBreakpoint) {
line(ln).hasBreakpoint = hasBreakpoint;
fireContentsChanged(this, ln, ln);
}
public void showExecutable(int ln, ReferenceType refType) {
line(ln).refType = refType;
fireContentsChanged(this, ln, ln);
}
/**
* Mark executable lines and breakpoints, but only
* when sourceLines is set.
*/
private void markClassLines(ReferenceType refType) {
for (Method meth : refType.methods()) {
try {
for (Location loc : meth.allLineLocations()) {
showExecutable(loc.lineNumber(), refType);
}
} catch (AbsentInformationException exc) {
// do nothing
}
}
for (BreakpointRequest bp :
env.getExecutionManager().eventRequestManager().breakpointRequests()) {
if (bp.location() != null) {
Location loc = bp.location();
if (loc.declaringType().equals(refType)) {
showBreakpoint(loc.lineNumber(),true);
}
}
}
}
private void rawInit() throws IOException {
sourceLines = new ArrayList<Line>();
BufferedReader reader = sourceReader();
try {
String line = reader.readLine();
while (line != null) {
sourceLines.add(new Line(expandTabs(line)));
line = reader.readLine();
}
} finally {
reader.close();
}
for (ReferenceType refType : classes) {
markClassLines(refType);
}
}
private String expandTabs(String s) {
int col = 0;
int len = s.length();
StringBuffer sb = new StringBuffer(132);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
sb.append(c);
if (c == '\t') {
int pad = (8 - (col % 8));
for (int j = 0; j < pad; j++) {
sb.append(' ');
}
col += pad;
} else {
col++;
}
}
return sb.toString();
}
}

View File

@@ -0,0 +1,392 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
import com.sun.tools.example.debug.bdi.*;
public class SourceTool extends JPanel {
private static final long serialVersionUID = -5461299294186395257L;
private Environment env;
private ExecutionManager runtime;
private ContextManager context;
private SourceManager sourceManager;
private JList list;
private ListModel sourceModel;
// Information on source file that is on display, or failed to be
// displayed due to inaccessible source. Used to update display
// when sourcepath is changed.
private String sourceName; // relative path name, if showSourceFile
private Location sourceLocn; // location, if showSourceForLocation
private CommandInterpreter interpreter;
public SourceTool(Environment env) {
super(new BorderLayout());
this.env = env;
runtime = env.getExecutionManager();
sourceManager = env.getSourceManager();
this.context = env.getContextManager();
this.interpreter = new CommandInterpreter(env, true);
sourceModel = new DefaultListModel(); // empty
list = new JList(sourceModel);
list.setCellRenderer(new SourceLineRenderer());
list.setPrototypeCellValue(SourceModel.prototypeCellValue);
SourceToolListener listener = new SourceToolListener();
context.addContextListener(listener);
runtime.addSpecListener(listener);
sourceManager.addSourceListener(listener);
MouseListener squeek = new STMouseListener();
list.addMouseListener(squeek);
add(new JScrollPane(list));
}
public void setTextFont(Font f) {
list.setFont(f);
list.setPrototypeCellValue(SourceModel.prototypeCellValue);
}
private class SourceToolListener
implements ContextListener, SourceListener, SpecListener
{
// ContextListener
@Override
public void currentFrameChanged(CurrentFrameChangedEvent e) {
showSourceContext(e.getThread(), e.getIndex());
}
// Clear source view.
// sourceModel = new DefaultListModel(); // empty
// SourceListener
@Override
public void sourcepathChanged(SourcepathChangedEvent e) {
// Reload source view if its contents depend
// on the source path.
if (sourceName != null) {
showSourceFile(sourceName);
} else if (sourceLocn != null) {
showSourceForLocation(sourceLocn);
}
}
// SpecListener
@Override
public void breakpointSet(SpecEvent e) {
breakpointResolved(e);
}
@Override
public void breakpointDeferred(SpecEvent e) { }
@Override
public void breakpointDeleted(SpecEvent e) {
BreakpointRequest req = (BreakpointRequest)e.getEventRequest();
Location loc = req.location();
if (loc != null) {
try {
SourceModel sm = sourceManager.sourceForLocation(loc);
sm.showBreakpoint(loc.lineNumber(), false);
showSourceForLocation(loc);
} catch (Exception exc) {
}
}
}
@Override
public void breakpointResolved(SpecEvent e) {
BreakpointRequest req = (BreakpointRequest)e.getEventRequest();
Location loc = req.location();
try {
SourceModel sm = sourceManager.sourceForLocation(loc);
sm.showBreakpoint(loc.lineNumber(), true);
showSourceForLocation(loc);
} catch (Exception exc) {
}
}
@Override
public void breakpointError(SpecErrorEvent e) {
breakpointDeleted(e);
}
@Override
public void watchpointSet(SpecEvent e) {
}
@Override
public void watchpointDeferred(SpecEvent e) {
}
@Override
public void watchpointDeleted(SpecEvent e) {
}
@Override
public void watchpointResolved(SpecEvent e) {
}
@Override
public void watchpointError(SpecErrorEvent e) {
}
@Override
public void exceptionInterceptSet(SpecEvent e) {
}
@Override
public void exceptionInterceptDeferred(SpecEvent e) {
}
@Override
public void exceptionInterceptDeleted(SpecEvent e) {
}
@Override
public void exceptionInterceptResolved(SpecEvent e) {
}
@Override
public void exceptionInterceptError(SpecErrorEvent e) {
}
}
private void showSourceContext(ThreadReference thread, int index) {
//### Should use ThreadInfo here.
StackFrame frame = null;
if (thread != null) {
try {
frame = thread.frame(index);
} catch (IncompatibleThreadStateException e) {}
}
if (frame == null) {
return;
}
Location locn = frame.location();
/*****
if (!showSourceForLocation(locn)) {
env.notice("Could not display source for "
+ Utils.locationString(locn));
}
*****/
showSourceForLocation(locn);
}
public boolean showSourceForLocation(Location locn) {
sourceName = null;
sourceLocn = locn;
int lineNo = locn.lineNumber();
if (lineNo != -1) {
SourceModel source = sourceManager.sourceForLocation(locn);
if (source != null) {
showSourceAtLine(source, lineNo-1);
return true;
}
}
// Here if we could not display source.
showSourceUnavailable();
return false;
}
public boolean showSourceFile(String fileName) {
sourceLocn = null;
File file;
if (!fileName.startsWith(File.separator)) {
sourceName = fileName;
SearchPath sourcePath = sourceManager.getSourcePath();
file = sourcePath.resolve(fileName);
if (file == null) {
//env.failure("Source not found on current source path.");
showSourceUnavailable();
return false;
}
} else {
sourceName = null; // Absolute pathname does not depend on sourcepath.
file = new File(fileName);
}
SourceModel source = sourceManager.sourceForFile(file);
if (source != null) {
showSource(source);
return true;
}
showSourceUnavailable();
return false;
}
private void showSource(SourceModel model) {
setViewModel(model);
}
private void showSourceAtLine(SourceModel model, int lineNo) {
setViewModel(model);
if (model.isActuallySource && (lineNo < model.getSize())) {
list.setSelectedIndex(lineNo);
if (lineNo+4 < model.getSize()) {
list.ensureIndexIsVisible(lineNo+4); // give some context
}
list.ensureIndexIsVisible(lineNo);
}
}
private void showSourceUnavailable() {
SourceModel model = new SourceModel("[Source code is not available]");
setViewModel(model);
}
private void setViewModel(SourceModel model) {
if (model != sourceModel) {
// install new model
list.setModel(model);
sourceModel = model;
}
}
private class SourceLineRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//### Should set background highlight and/or icon if breakpoint on this line.
// Configures "this"
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
SourceModel.Line line = (SourceModel.Line)value;
//### Tab expansion is now done when source file is read in,
//### to speed up display. This costs a lot of space, slows
//### down source file loading, and has not been demonstrated
//### to yield an observable improvement in display performance.
//### Measurements may be appropriate here.
//String sourceLine = expandTabs((String)value);
setText(line.text);
if (line.hasBreakpoint) {
setIcon(Icons.stopSignIcon);
} else if (line.isExecutable()) {
setIcon(Icons.execIcon);
} else {
setIcon(Icons.blankIcon);
}
return this;
}
@Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
return new Dimension(dim.width, dim.height-5);
}
}
private class STMouseListener extends MouseAdapter implements MouseListener {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu((Component)e.getSource(),
e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu((Component)e.getSource(),
e.getX(), e.getY());
}
}
private void showPopupMenu(Component invoker, int x, int y) {
JList list = (JList)invoker;
int ln = list.getSelectedIndex() + 1;
SourceModel.Line line =
(SourceModel.Line)list.getSelectedValue();
JPopupMenu popup = new JPopupMenu();
if (line == null) {
popup.add(new JMenuItem("please select a line"));
} else if (line.isExecutable()) {
String className = line.refType.name();
if (line.hasBreakpoint()) {
popup.add(commandItem("Clear Breakpoint",
"clear " + className +
":" + ln));
} else {
popup.add(commandItem("Set Breakpoint",
"stop at " + className +
":" + ln));
}
} else {
popup.add(new JMenuItem("not an executable line"));
}
popup.show(invoker,
x + popup.getWidth()/2, y + popup.getHeight()/2);
}
private JMenuItem commandItem(String label, final String cmd) {
JMenuItem item = new JMenuItem(label);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(cmd);
}
});
return item;
}
}
}

View File

@@ -0,0 +1,292 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.tools.example.debug.bdi.*;
public class SourceTreeTool extends JPanel {
private static final long serialVersionUID = 3336680912107956419L;
private Environment env;
private ExecutionManager runtime;
private SourceManager sourceManager;
private ClassManager classManager;
private JTree tree;
private SourceTreeNode root;
private SearchPath sourcePath;
private CommandInterpreter interpreter;
private static String HEADING = "SOURCES";
public SourceTreeTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env);
sourcePath = sourceManager.getSourcePath();
root = createDirectoryTree(HEADING);
// Create a tree that allows one selection at a time.
tree = new JTree(new DefaultTreeModel(root));
tree.setSelectionModel(new SingleLeafTreeSelectionModel());
/******
// Listen for when the selection changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
SourceTreeNode node = (SourceTreeNode)
(e.getPath().getLastPathComponent());
interpreter.executeCommand("view " + node.getRelativePath());
}
});
******/
MouseListener ml = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
SourceTreeNode node =
(SourceTreeNode)selPath.getLastPathComponent();
// If user clicks on leaf, select it, and issue 'view' command.
if (node.isLeaf()) {
tree.setSelectionPath(selPath);
interpreter.executeCommand("view " + node.getRelativePath());
}
}
}
}
};
tree.addMouseListener(ml);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);
// Create listener for source path changes.
SourceTreeToolListener listener = new SourceTreeToolListener();
sourceManager.addSourceListener(listener);
//### remove listeners on exit!
}
private class SourceTreeToolListener implements SourceListener {
@Override
public void sourcepathChanged(SourcepathChangedEvent e) {
sourcePath = sourceManager.getSourcePath();
root = createDirectoryTree(HEADING);
tree.setModel(new DefaultTreeModel(root));
}
}
private static class SourceOrDirectoryFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return (name.endsWith(".java") ||
new File(dir, name).isDirectory());
}
}
private static FilenameFilter filter = new SourceOrDirectoryFilter();
SourceTreeNode createDirectoryTree(String label) {
try {
return new SourceTreeNode(label, null, "", true);
} catch (SecurityException e) {
env.failure("Cannot access source file or directory");
return null;
}
}
class SourceTreeNode implements TreeNode {
private String name;
private boolean isDirectory;
private SourceTreeNode parent;
private SourceTreeNode[] children;
private String relativePath;
private boolean isExpanded;
private SourceTreeNode(String label,
SourceTreeNode parent,
String relativePath,
boolean isDirectory) {
this.name = label;
this.relativePath = relativePath;
this.parent = parent;
this.isDirectory = isDirectory;
}
@Override
public String toString() {
return name;
}
public String getRelativePath() {
return relativePath;
}
private void expandIfNeeded() {
try {
if (!isExpanded && isDirectory) {
String[] files = sourcePath.children(relativePath, filter);
children = new SourceTreeNode[files.length];
for (int i = 0; i < files.length; i++) {
String childName =
(relativePath.equals(""))
? files[i]
: relativePath + File.separator + files[i];
File file = sourcePath.resolve(childName);
boolean isDir = (file != null && file.isDirectory());
children[i] =
new SourceTreeNode(files[i], this, childName, isDir);
}
}
isExpanded = true;
} catch (SecurityException e) {
children = null;
env.failure("Cannot access source file or directory");
}
}
// -- interface TreeNode --
/*
* Returns the child <code>TreeNode</code> at index
* <code>childIndex</code>.
*/
@Override
public TreeNode getChildAt(int childIndex) {
expandIfNeeded();
return children[childIndex];
}
/**
* Returns the number of children <code>TreeNode</code>s the receiver
* contains.
*/
@Override
public int getChildCount() {
expandIfNeeded();
return children.length;
}
/**
* Returns the parent <code>TreeNode</code> of the receiver.
*/
@Override
public TreeNode getParent() {
return parent;
}
/**
* Returns the index of <code>node</code> in the receivers children.
* If the receiver does not contain <code>node</code>, -1 will be
* returned.
*/
@Override
public int getIndex(TreeNode node) {
expandIfNeeded();
for (int i = 0; i < children.length; i++) {
if (children[i] == node) {
return i;
}
}
return -1;
}
/**
* Returns true if the receiver allows children.
*/
@Override
public boolean getAllowsChildren() {
return isDirectory;
}
/**
* Returns true if the receiver is a leaf.
*/
@Override
public boolean isLeaf() {
expandIfNeeded();
return !isDirectory;
}
/**
* Returns the children of the receiver as an Enumeration.
*/
@Override
public Enumeration children() {
expandIfNeeded();
return new Enumeration() {
int i = 0;
@Override
public boolean hasMoreElements() {
return (i < children.length);
}
@Override
public Object nextElement() throws NoSuchElementException {
if (i >= children.length) {
throw new NoSuchElementException();
}
return children[i++];
}
};
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.EventObject;
public class SourcepathChangedEvent extends EventObject {
private static final long serialVersionUID = 8762169481005804121L;
public SourcepathChangedEvent(Object source) {
super(source);
}
}

View File

@@ -0,0 +1,207 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
public class StackTraceTool extends JPanel {
private static final long serialVersionUID = 9140041989427965718L;
private Environment env;
private ExecutionManager runtime;
private ContextManager context;
private ThreadInfo tinfo;
private JList list;
private ListModel stackModel;
public StackTraceTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.context = env.getContextManager();
stackModel = new DefaultListModel(); // empty
list = new JList(stackModel);
list.setCellRenderer(new StackFrameRenderer());
JScrollPane listView = new JScrollPane(list);
add(listView);
// Create listener.
StackTraceToolListener listener = new StackTraceToolListener();
context.addContextListener(listener);
list.addListSelectionListener(listener);
//### remove listeners on exit!
}
private class StackTraceToolListener
implements ContextListener, ListSelectionListener
{
// ContextListener
// If the user selects a new current frame, display it in
// this view.
//### I suspect we handle the case badly that the VM is not interrupted.
@Override
public void currentFrameChanged(CurrentFrameChangedEvent e) {
// If the current frame of the thread appearing in this
// view is changed, move the selection to track it.
int frameIndex = e.getIndex();
ThreadInfo ti = e.getThreadInfo();
if (e.getInvalidate() || tinfo != ti) {
tinfo = ti;
showStack(ti, frameIndex);
} else {
if (frameIndex < stackModel.getSize()) {
list.setSelectedIndex(frameIndex);
list.ensureIndexIsVisible(frameIndex);
}
}
}
// ListSelectionListener
@Override
public void valueChanged(ListSelectionEvent e) {
int index = list.getSelectedIndex();
if (index != -1) {
//### should use listener?
try {
context.setCurrentFrameIndex(index);
} catch (VMNotInterruptedException exc) {
}
}
}
}
private class StackFrameRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//### We should indicate the current thread independently of the
//### selection, e.g., with an icon, because the user may change
//### the selection graphically without affecting the current
//### thread.
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value == null) {
this.setText("<unavailable>");
} else {
StackFrame frame = (StackFrame)value;
Location loc = frame.location();
Method meth = loc.method();
String methName =
meth.declaringType().name() + '.' + meth.name();
String position = "";
if (meth.isNative()) {
position = " (native method)";
} else if (loc.lineNumber() != -1) {
position = ":" + loc.lineNumber();
} else {
long pc = loc.codeIndex();
if (pc != -1) {
position = ", pc = " + pc;
}
}
// Indices are presented to the user starting from 1, not 0.
this.setText("[" + (index+1) +"] " + methName + position);
}
return this;
}
}
// Point this view at the given thread and frame.
private void showStack(ThreadInfo tinfo, int selectFrame) {
StackTraceListModel model = new StackTraceListModel(tinfo);
stackModel = model;
list.setModel(stackModel);
list.setSelectedIndex(selectFrame);
list.ensureIndexIsVisible(selectFrame);
}
private static class StackTraceListModel extends AbstractListModel {
private final ThreadInfo tinfo;
public StackTraceListModel(ThreadInfo tinfo) {
this.tinfo = tinfo;
}
@Override
public Object getElementAt(int index) {
try {
return tinfo == null? null : tinfo.getFrame(index);
} catch (VMNotInterruptedException e) {
//### Is this the right way to handle this?
//### Would happen if user scrolled stack trace
//### while not interrupted -- should probably
//### block user interaction in this case.
return null;
}
}
@Override
public int getSize() {
try {
return tinfo == null? 1 : tinfo.getFrameCount();
} catch (VMNotInterruptedException e) {
//### Is this the right way to handle this?
return 0;
}
}
}
}

View File

@@ -0,0 +1,355 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.*;
import java.util.List; // Must import explicitly due to conflict with javax.awt.List
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
import com.sun.tools.example.debug.bdi.*;
//### Bug: If the name of a thread is changed via Thread.setName(), the
//### thread tree view does not reflect this. The name of the thread at
//### the time it is created is used throughout its lifetime.
public class ThreadTreeTool extends JPanel {
private static final long serialVersionUID = 4168599992853038878L;
private Environment env;
private ExecutionManager runtime;
private SourceManager sourceManager;
private ClassManager classManager;
private JTree tree;
private DefaultTreeModel treeModel;
private ThreadTreeNode root;
private SearchPath sourcePath;
private CommandInterpreter interpreter;
private static String HEADING = "THREADS";
public ThreadTreeTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env);
root = createThreadTree(HEADING);
treeModel = new DefaultTreeModel(root);
// Create a tree that allows one selection at a time.
tree = new JTree(treeModel);
tree.setSelectionModel(new SingleLeafTreeSelectionModel());
MouseListener ml = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
ThreadTreeNode node =
(ThreadTreeNode)selPath.getLastPathComponent();
// If user clicks on leaf, select it, and issue 'thread' command.
if (node.isLeaf()) {
tree.setSelectionPath(selPath);
interpreter.executeCommand("thread " +
node.getThreadId() +
" (\"" +
node.getName() + "\")");
}
}
}
}
};
tree.addMouseListener(ml);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);
// Create listener.
ThreadTreeToolListener listener = new ThreadTreeToolListener();
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
//### remove listeners on exit!
}
HashMap<ThreadReference, List<String>> threadTable = new HashMap<ThreadReference, List<String>>();
private List<String> threadPath(ThreadReference thread) {
// May exit abnormally if VM disconnects.
List<String> l = new ArrayList<String>();
l.add(0, thread.name());
ThreadGroupReference group = thread.threadGroup();
while (group != null) {
l.add(0, group.name());
group = group.parent();
}
return l;
}
private class ThreadTreeToolListener extends JDIAdapter
implements JDIListener, SessionListener {
// SessionListener
@Override
public void sessionStart(EventObject e) {
try {
for (ThreadReference thread : runtime.allThreads()) {
root.addThread(thread);
}
} catch (VMDisconnectedException ee) {
// VM went away unexpectedly.
} catch (NoSessionException ee) {
// Ignore. Should not happen.
}
}
@Override
public void sessionInterrupt(EventObject e) {}
@Override
public void sessionContinue(EventObject e) {}
// JDIListener
@Override
public void threadStart(ThreadStartEventSet e) {
root.addThread(e.getThread());
}
@Override
public void threadDeath(ThreadDeathEventSet e) {
root.removeThread(e.getThread());
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
// Clear the contents of this view.
root = createThreadTree(HEADING);
treeModel = new DefaultTreeModel(root);
tree.setModel(treeModel);
threadTable = new HashMap<ThreadReference, List<String>>();
}
}
ThreadTreeNode createThreadTree(String label) {
return new ThreadTreeNode(label, null);
}
class ThreadTreeNode extends DefaultMutableTreeNode {
String name;
ThreadReference thread; // null if thread group
long uid;
String description;
ThreadTreeNode(String name, ThreadReference thread) {
if (name == null) {
name = "<unnamed>";
}
this.name = name;
this.thread = thread;
if (thread == null) {
this.uid = -1;
this.description = name;
} else {
this.uid = thread.uniqueID();
this.description = name + " (t@" + Long.toHexString(uid) + ")";
}
}
@Override
public String toString() {
return description;
}
public String getName() {
return name;
}
public ThreadReference getThread() {
return thread;
}
public String getThreadId() {
return "t@" + Long.toHexString(uid);
}
private boolean isThreadGroup() {
return (thread == null);
}
@Override
public boolean isLeaf() {
return !isThreadGroup();
}
public void addThread(ThreadReference thread) {
// This can fail if the VM disconnects.
// It is important to do all necessary JDI calls
// before modifying the tree, so we don't abort
// midway through!
if (threadTable.get(thread) == null) {
// Add thread only if not already present.
try {
List<String> path = threadPath(thread);
// May not get here due to exception.
// If we get here, we are committed.
// We must not leave the tree partially updated.
try {
threadTable.put(thread, path);
addThread(path, thread);
} catch (Throwable tt) {
//### Assertion failure.
throw new RuntimeException("ThreadTree corrupted");
}
} catch (VMDisconnectedException ee) {
// Ignore. Thread will not be added.
}
}
}
private void addThread(List<String> threadPath, ThreadReference thread) {
int size = threadPath.size();
if (size == 0) {
return;
} else if (size == 1) {
String name = threadPath.get(0);
insertNode(name, thread);
} else {
String head = threadPath.get(0);
List<String> tail = threadPath.subList(1, size);
ThreadTreeNode child = insertNode(head, null);
child.addThread(tail, thread);
}
}
private ThreadTreeNode insertNode(String name, ThreadReference thread) {
for (int i = 0; i < getChildCount(); i++) {
ThreadTreeNode child = (ThreadTreeNode)getChildAt(i);
int cmp = name.compareTo(child.getName());
if (cmp == 0 && thread == null) {
// A like-named interior node already exists.
return child;
} else if (cmp < 0) {
// Insert new node before the child.
ThreadTreeNode newChild = new ThreadTreeNode(name, thread);
treeModel.insertNodeInto(newChild, this, i);
return newChild;
}
}
// Insert new node after last child.
ThreadTreeNode newChild = new ThreadTreeNode(name, thread);
treeModel.insertNodeInto(newChild, this, getChildCount());
return newChild;
}
public void removeThread(ThreadReference thread) {
List<String> threadPath = threadTable.get(thread);
// Only remove thread if we recorded it in table.
// Original add may have failed due to VM disconnect.
if (threadPath != null) {
removeThread(threadPath, thread);
}
}
private void removeThread(List<String> threadPath, ThreadReference thread) {
int size = threadPath.size();
if (size == 0) {
return;
} else if (size == 1) {
String name = threadPath.get(0);
ThreadTreeNode child = findLeafNode(thread, name);
treeModel.removeNodeFromParent(child);
} else {
String head = threadPath.get(0);
List<String> tail = threadPath.subList(1, size);
ThreadTreeNode child = findInternalNode(head);
child.removeThread(tail, thread);
if (child.isThreadGroup() && child.getChildCount() < 1) {
// Prune non-leaf nodes with no children.
treeModel.removeNodeFromParent(child);
}
}
}
private ThreadTreeNode findLeafNode(ThreadReference thread, String name) {
for (int i = 0; i < getChildCount(); i++) {
ThreadTreeNode child = (ThreadTreeNode)getChildAt(i);
if (child.getThread() == thread) {
if (!name.equals(child.getName())) {
//### Assertion failure.
throw new RuntimeException("name mismatch");
}
return child;
}
}
//### Assertion failure.
throw new RuntimeException("not found");
}
private ThreadTreeNode findInternalNode(String name) {
for (int i = 0; i < getChildCount(); i++) {
ThreadTreeNode child = (ThreadTreeNode)getChildAt(i);
if (name.equals(child.getName())) {
return child;
}
}
//### Assertion failure.
throw new RuntimeException("not found");
}
}
}

View File

@@ -0,0 +1,132 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TypeScript extends JPanel {
private static final long serialVersionUID = -983704841363534885L;
private JTextArea history;
private JTextField entry;
private JLabel promptLabel;
private JScrollBar historyVScrollBar;
private JScrollBar historyHScrollBar;
private boolean echoInput = false;
private static String newline = System.getProperty("line.separator");
public TypeScript(String prompt) {
this(prompt, true);
}
public TypeScript(String prompt, boolean echoInput) {
this.echoInput = echoInput;
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
//setBorder(new EmptyBorder(5, 5, 5, 5));
history = new JTextArea(0, 0);
history.setEditable(false);
JScrollPane scroller = new JScrollPane(history);
historyVScrollBar = scroller.getVerticalScrollBar();
historyHScrollBar = scroller.getHorizontalScrollBar();
add(scroller);
JPanel cmdLine = new JPanel();
cmdLine.setLayout(new BoxLayout(cmdLine, BoxLayout.X_AXIS));
//cmdLine.setBorder(new EmptyBorder(5, 5, 0, 0));
promptLabel = new JLabel(prompt + " ");
cmdLine.add(promptLabel);
entry = new JTextField();
//### Swing bug workaround.
entry.setMaximumSize(new Dimension(1000, 20));
cmdLine.add(entry);
add(cmdLine);
}
/******
public void setFont(Font f) {
entry.setFont(f);
history.setFont(f);
}
******/
public void setPrompt(String prompt) {
promptLabel.setText(prompt + " ");
}
public void append(String text) {
history.append(text);
historyVScrollBar.setValue(historyVScrollBar.getMaximum());
historyHScrollBar.setValue(historyHScrollBar.getMinimum());
}
public void newline() {
history.append(newline);
historyVScrollBar.setValue(historyVScrollBar.getMaximum());
historyHScrollBar.setValue(historyHScrollBar.getMinimum());
}
public void flush() {}
public void addActionListener(ActionListener a) {
entry.addActionListener(a);
}
public void removeActionListener(ActionListener a) {
entry.removeActionListener(a);
}
public String readln() {
String text = entry.getText();
entry.setText("");
if (echoInput) {
history.append(">>>");
history.append(text);
history.append(newline);
historyVScrollBar.setValue(historyVScrollBar.getMaximum());
historyHScrollBar.setValue(historyHScrollBar.getMinimum());
}
return text;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import com.sun.tools.example.debug.bdi.OutputListener;
public class TypeScriptOutputListener implements OutputListener {
private TypeScript script;
private boolean appendNewline;
public TypeScriptOutputListener(TypeScript script) {
this(script, false);
}
public TypeScriptOutputListener(TypeScript script, boolean appendNewline) {
this.script = script;
this.appendNewline = appendNewline;
}
@Override
public void putString(String s) {
script.append(s);
if (appendNewline) {
script.newline();
}
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
public class TypeScriptWriter extends Writer {
TypeScript script;
public TypeScriptWriter(TypeScript script) {
this.script = script;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
script.append(String.valueOf(cbuf, off, len));
}
@Override
public void flush() {
script.flush();
}
@Override
public void close() {
script.flush();
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.tty;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
class AccessWatchpointSpec extends WatchpointSpec {
AccessWatchpointSpec(ReferenceTypeSpec refSpec, String fieldId)
throws MalformedMemberNameException {
super(refSpec, fieldId);
}
/**
* The 'refType' is known to match, return the EventRequest.
*/
@Override
EventRequest resolveEventRequest(ReferenceType refType)
throws NoSuchFieldException {
Field field = refType.fieldByName(fieldId);
EventRequestManager em = refType.virtualMachine().eventRequestManager();
EventRequest wp = em.createAccessWatchpointRequest(field);
wp.setSuspendPolicy(suspendPolicy);
wp.enable();
return wp;
}
@Override
public String toString() {
return MessageOutput.format("watch accesses of",
new Object [] {refSpec.toString(),
fieldId});
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.tty;
public class AmbiguousMethodException extends Exception
{
private static final long serialVersionUID = -5372629264936918654L;
public AmbiguousMethodException()
{
super();
}
public AmbiguousMethodException(String s)
{
super(s);
}
}

View File

@@ -0,0 +1,391 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.tty;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
import java.util.ArrayList;
import java.util.List;
class BreakpointSpec extends EventRequestSpec {
String methodId;
List<String> methodArgs;
int lineNumber;
BreakpointSpec(ReferenceTypeSpec refSpec, int lineNumber) {
super(refSpec);
this.methodId = null;
this.methodArgs = null;
this.lineNumber = lineNumber;
}
BreakpointSpec(ReferenceTypeSpec refSpec, String methodId,
List<String> methodArgs) throws MalformedMemberNameException {
super(refSpec);
this.methodId = methodId;
this.methodArgs = methodArgs;
this.lineNumber = 0;
if (!isValidMethodName(methodId)) {
throw new MalformedMemberNameException(methodId);
}
}
/**
* The 'refType' is known to match, return the EventRequest.
*/
@Override
EventRequest resolveEventRequest(ReferenceType refType)
throws AmbiguousMethodException,
AbsentInformationException,
InvalidTypeException,
NoSuchMethodException,
LineNotFoundException {
Location location = location(refType);
if (location == null) {
throw new InvalidTypeException();
}
EventRequestManager em = refType.virtualMachine().eventRequestManager();
EventRequest bp = em.createBreakpointRequest(location);
bp.setSuspendPolicy(suspendPolicy);
bp.enable();
return bp;
}
String methodName() {
return methodId;
}
int lineNumber() {
return lineNumber;
}
List<String> methodArgs() {
return methodArgs;
}
boolean isMethodBreakpoint() {
return (methodId != null);
}
@Override
public int hashCode() {
return refSpec.hashCode() + lineNumber +
((methodId != null) ? methodId.hashCode() : 0) +
((methodArgs != null) ? methodArgs.hashCode() : 0);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof BreakpointSpec) {
BreakpointSpec breakpoint = (BreakpointSpec)obj;
return ((methodId != null) ?
methodId.equals(breakpoint.methodId)
: methodId == breakpoint.methodId) &&
((methodArgs != null) ?
methodArgs.equals(breakpoint.methodArgs)
: methodArgs == breakpoint.methodArgs) &&
refSpec.equals(breakpoint.refSpec) &&
(lineNumber == breakpoint.lineNumber);
} else {
return false;
}
}
@Override
String errorMessageFor(Exception e) {
if (e instanceof AmbiguousMethodException) {
return (MessageOutput.format("Method is overloaded; specify arguments",
methodName()));
/*
* TO DO: list the methods here
*/
} else if (e instanceof NoSuchMethodException) {
return (MessageOutput.format("No method in",
new Object [] {methodName(),
refSpec.toString()}));
} else if (e instanceof AbsentInformationException) {
return (MessageOutput.format("No linenumber information for",
refSpec.toString()));
} else if (e instanceof LineNotFoundException) {
return (MessageOutput.format("No code at line",
new Object [] {new Long (lineNumber()),
refSpec.toString()}));
} else if (e instanceof InvalidTypeException) {
return (MessageOutput.format("Breakpoints can be located only in classes.",
refSpec.toString()));
} else {
return super.errorMessageFor( e);
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer(refSpec.toString());
if (isMethodBreakpoint()) {
buffer.append('.');
buffer.append(methodId);
if (methodArgs != null) {
boolean first = true;
buffer.append('(');
for (String arg : methodArgs) {
if (!first) {
buffer.append(',');
}
buffer.append(arg);
first = false;
}
buffer.append(")");
}
} else {
buffer.append(':');
buffer.append(lineNumber);
}
return MessageOutput.format("breakpoint", buffer.toString());
}
private Location location(ReferenceType refType) throws
AmbiguousMethodException,
AbsentInformationException,
NoSuchMethodException,
LineNotFoundException {
Location location = null;
if (isMethodBreakpoint()) {
Method method = findMatchingMethod(refType);
location = method.location();
} else {
// let AbsentInformationException be thrown
List<Location> locs = refType.locationsOfLine(lineNumber());
if (locs.size() == 0) {
throw new LineNotFoundException();
}
// TO DO: handle multiple locations
location = locs.get(0);
if (location.method() == null) {
throw new LineNotFoundException();
}
}
return location;
}
private boolean isValidMethodName(String s) {
return isJavaIdentifier(s) ||
s.equals("<init>") ||
s.equals("<clinit>");
}
/*
* Compare a method's argument types with a Vector of type names.
* Return true if each argument type has a name identical to the
* corresponding string in the vector (allowing for varars)
* and if the number of arguments in the method matches the
* number of names passed
*/
private boolean compareArgTypes(Method method, List<String> nameList) {
List<String> argTypeNames = method.argumentTypeNames();
// If argument counts differ, we can stop here
if (argTypeNames.size() != nameList.size()) {
return false;
}
// Compare each argument type's name
int nTypes = argTypeNames.size();
for (int i = 0; i < nTypes; ++i) {
String comp1 = argTypeNames.get(i);
String comp2 = nameList.get(i);
if (! comp1.equals(comp2)) {
/*
* We have to handle varargs. EG, the
* method's last arg type is xxx[]
* while the nameList contains xxx...
* Note that the nameList can also contain
* xxx[] in which case we don't get here.
*/
if (i != nTypes - 1 ||
!method.isVarArgs() ||
!comp2.endsWith("...")) {
return false;
}
/*
* The last types differ, it is a varargs
* method and the nameList item is varargs.
* We just have to compare the type names, eg,
* make sure we don't have xxx[] for the method
* arg type and yyy... for the nameList item.
*/
int comp1Length = comp1.length();
if (comp1Length + 1 != comp2.length()) {
// The type names are different lengths
return false;
}
// We know the two type names are the same length
if (!comp1.regionMatches(0, comp2, 0, comp1Length - 2)) {
return false;
}
// We do have xxx[] and xxx... as the last param type
return true;
}
}
return true;
}
/*
* Remove unneeded spaces and expand class names to fully
* qualified names, if necessary and possible.
*/
private String normalizeArgTypeName(String name) {
/*
* Separate the type name from any array modifiers,
* stripping whitespace after the name ends
*/
int i = 0;
StringBuffer typePart = new StringBuffer();
StringBuffer arrayPart = new StringBuffer();
name = name.trim();
int nameLength = name.length();
/*
* For varargs, there can be spaces before the ... but not
* within the ... So, we will just ignore the ...
* while stripping blanks.
*/
boolean isVarArgs = name.endsWith("...");
if (isVarArgs) {
nameLength -= 3;
}
while (i < nameLength) {
char c = name.charAt(i);
if (Character.isWhitespace(c) || c == '[') {
break; // name is complete
}
typePart.append(c);
i++;
}
while (i < nameLength) {
char c = name.charAt(i);
if ( (c == '[') || (c == ']')) {
arrayPart.append(c);
} else if (!Character.isWhitespace(c)) {
throw new IllegalArgumentException
(MessageOutput.format("Invalid argument type name"));
}
i++;
}
name = typePart.toString();
/*
* When there's no sign of a package name already, try to expand the
* the name to a fully qualified class name
*/
if ((name.indexOf('.') == -1) || name.startsWith("*.")) {
try {
ReferenceType argClass = Env.getReferenceTypeFromToken(name);
if (argClass != null) {
name = argClass.name();
}
} catch (IllegalArgumentException e) {
// We'll try the name as is
}
}
name += arrayPart.toString();
if (isVarArgs) {
name += "...";
}
return name;
}
/*
* Attempt an unambiguous match of the method name and
* argument specification to a method. If no arguments
* are specified, the method must not be overloaded.
* Otherwise, the argument types much match exactly
*/
private Method findMatchingMethod(ReferenceType refType)
throws AmbiguousMethodException,
NoSuchMethodException {
// Normalize the argument string once before looping below.
List<String> argTypeNames = null;
if (methodArgs() != null) {
argTypeNames = new ArrayList<String>(methodArgs().size());
for (String name : methodArgs()) {
name = normalizeArgTypeName(name);
argTypeNames.add(name);
}
}
// Check each method in the class for matches
Method firstMatch = null; // first method with matching name
Method exactMatch = null; // (only) method with same name & sig
int matchCount = 0; // > 1 implies overload
for (Method candidate : refType.methods()) {
if (candidate.name().equals(methodName())) {
matchCount++;
// Remember the first match in case it is the only one
if (matchCount == 1) {
firstMatch = candidate;
}
// If argument types were specified, check against candidate
if ((argTypeNames != null)
&& compareArgTypes(candidate, argTypeNames) == true) {
exactMatch = candidate;
break;
}
}
}
// Determine method for breakpoint
Method method = null;
if (exactMatch != null) {
// Name and signature match
method = exactMatch;
} else if ((argTypeNames == null) && (matchCount > 0)) {
// At least one name matched and no arg types were specified
if (matchCount == 1) {
method = firstMatch; // Only one match; safe to use it
} else {
throw new AmbiguousMethodException();
}
} else {
throw new NoSuchMethodException(methodName());
}
return method;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,331 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.tty;
import com.sun.jdi.*;
import com.sun.jdi.request.StepRequest;
import com.sun.jdi.request.MethodEntryRequest;
import com.sun.jdi.request.MethodExitRequest;
import java.util.*;
import java.io.*;
class Env {
static EventRequestSpecList specList = new EventRequestSpecList();
private static VMConnection connection;
private static SourceMapper sourceMapper = new SourceMapper("");
private static List<String> excludes;
private static final int SOURCE_CACHE_SIZE = 5;
private static List<SourceCode> sourceCache = new LinkedList<SourceCode>();
private static HashMap<String, Value> savedValues = new HashMap<String, Value>();
private static Method atExitMethod;
static void init(String connectSpec, boolean openNow, int flags) {
connection = new VMConnection(connectSpec, flags);
if (!connection.isLaunch() || openNow) {
connection.open();
}
}
static VMConnection connection() {
return connection;
}
static VirtualMachine vm() {
return connection.vm();
}
static void shutdown() {
shutdown(null);
}
static void shutdown(String message) {
if (connection != null) {
try {
connection.disposeVM();
} catch (VMDisconnectedException e) {
// Shutting down after the VM has gone away. This is
// not an error, and we just ignore it.
}
}
if (message != null) {
MessageOutput.lnprint(message);
MessageOutput.println();
}
System.exit(0);
}
static void setSourcePath(String srcPath) {
sourceMapper = new SourceMapper(srcPath);
sourceCache.clear();
}
static void setSourcePath(List<String> srcList) {
sourceMapper = new SourceMapper(srcList);
sourceCache.clear();
}
static String getSourcePath() {
return sourceMapper.getSourcePath();
}
static private List<String> excludes() {
if (excludes == null) {
setExcludes("java.*, javax.*, sun.*, com.sun.*");
}
return excludes;
}
static String excludesString() {
StringBuffer buffer = new StringBuffer();
for (String pattern : excludes()) {
buffer.append(pattern);
buffer.append(",");
}
return buffer.toString();
}
static void addExcludes(StepRequest request) {
for (String pattern : excludes()) {
request.addClassExclusionFilter(pattern);
}
}
static void addExcludes(MethodEntryRequest request) {
for (String pattern : excludes()) {
request.addClassExclusionFilter(pattern);
}
}
static void addExcludes(MethodExitRequest request) {
for (String pattern : excludes()) {
request.addClassExclusionFilter(pattern);
}
}
static void setExcludes(String excludeString) {
StringTokenizer t = new StringTokenizer(excludeString, " ,;");
List<String> list = new ArrayList<String>();
while (t.hasMoreTokens()) {
list.add(t.nextToken());
}
excludes = list;
}
static Method atExitMethod() {
return atExitMethod;
}
static void setAtExitMethod(Method mmm) {
atExitMethod = mmm;
}
/**
* Return a Reader cooresponding to the source of this location.
* Return null if not available.
* Note: returned reader must be closed.
*/
static BufferedReader sourceReader(Location location) {
return sourceMapper.sourceReader(location);
}
static synchronized String sourceLine(Location location, int lineNumber)
throws IOException {
if (lineNumber == -1) {
throw new IllegalArgumentException();
}
try {
String fileName = location.sourceName();
Iterator<SourceCode> iter = sourceCache.iterator();
SourceCode code = null;
while (iter.hasNext()) {
SourceCode candidate = iter.next();
if (candidate.fileName().equals(fileName)) {
code = candidate;
iter.remove();
break;
}
}
if (code == null) {
BufferedReader reader = sourceReader(location);
if (reader == null) {
throw new FileNotFoundException(fileName);
}
code = new SourceCode(fileName, reader);
if (sourceCache.size() == SOURCE_CACHE_SIZE) {
sourceCache.remove(sourceCache.size() - 1);
}
}
sourceCache.add(0, code);
return code.sourceLine(lineNumber);
} catch (AbsentInformationException e) {
throw new IllegalArgumentException();
}
}
/** Return a description of an object. */
static String description(ObjectReference ref) {
ReferenceType clazz = ref.referenceType();
long id = ref.uniqueID();
if (clazz == null) {
return toHex(id);
} else {
return MessageOutput.format("object description and hex id",
new Object [] {clazz.name(),
toHex(id)});
}
}
/** Convert a long to a hexadecimal string. */
static String toHex(long n) {
char s1[] = new char[16];
char s2[] = new char[18];
/* Store digits in reverse order. */
int i = 0;
do {
long d = n & 0xf;
s1[i++] = (char)((d < 10) ? ('0' + d) : ('a' + d - 10));
} while ((n >>>= 4) > 0);
/* Now reverse the array. */
s2[0] = '0';
s2[1] = 'x';
int j = 2;
while (--i >= 0) {
s2[j++] = s1[i];
}
return new String(s2, 0, j);
}
/** Convert hexadecimal strings to longs. */
static long fromHex(String hexStr) {
String str = hexStr.startsWith("0x") ?
hexStr.substring(2).toLowerCase() : hexStr.toLowerCase();
if (hexStr.length() == 0) {
throw new NumberFormatException();
}
long ret = 0;
for (int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (c >= '0' && c <= '9') {
ret = (ret * 16) + (c - '0');
} else if (c >= 'a' && c <= 'f') {
ret = (ret * 16) + (c - 'a' + 10);
} else {
throw new NumberFormatException();
}
}
return ret;
}
static ReferenceType getReferenceTypeFromToken(String idToken) {
ReferenceType cls = null;
if (Character.isDigit(idToken.charAt(0))) {
cls = null;
} else if (idToken.startsWith("*.")) {
// This notation saves typing by letting the user omit leading
// package names. The first
// loaded class whose name matches this limited regular
// expression is selected.
idToken = idToken.substring(1);
for (ReferenceType type : Env.vm().allClasses()) {
if (type.name().endsWith(idToken)) {
cls = type;
break;
}
}
} else {
// It's a class name
List<ReferenceType> classes = Env.vm().classesByName(idToken);
if (classes.size() > 0) {
// TO DO: handle multiples
cls = classes.get(0);
}
}
return cls;
}
static Set<String> getSaveKeys() {
return savedValues.keySet();
}
static Value getSavedValue(String key) {
return savedValues.get(key);
}
static void setSavedValue(String key, Value value) {
savedValues.put(key, value);
}
static class SourceCode {
private String fileName;
private List<String> sourceLines = new ArrayList<String>();
SourceCode(String fileName, BufferedReader reader) throws IOException {
this.fileName = fileName;
try {
String line = reader.readLine();
while (line != null) {
sourceLines.add(line);
line = reader.readLine();
}
} finally {
reader.close();
}
}
String fileName() {
return fileName;
}
String sourceLine(int number) {
int index = number - 1; // list is 0-indexed
if (index >= sourceLines.size()) {
return null;
} else {
return sourceLines.get(index);
}
}
}
}

View File

@@ -0,0 +1,290 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.tty;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.EventRequest;
public class EventHandler implements Runnable {
EventNotifier notifier;
Thread thread;
volatile boolean connected = true;
boolean completed = false;
String shutdownMessageKey;
boolean stopOnVMStart;
EventHandler(EventNotifier notifier, boolean stopOnVMStart) {
this.notifier = notifier;
this.stopOnVMStart = stopOnVMStart;
this.thread = new Thread(this, "event-handler");
this.thread.start();
}
synchronized void shutdown() {
connected = false; // force run() loop termination
thread.interrupt();
while (!completed) {
try {wait();} catch (InterruptedException exc) {}
}
}
@Override
public void run() {
EventQueue queue = Env.vm().eventQueue();
while (connected) {
try {
EventSet eventSet = queue.remove();
boolean resumeStoppedApp = false;
EventIterator it = eventSet.eventIterator();
while (it.hasNext()) {
resumeStoppedApp |= !handleEvent(it.nextEvent());
}
if (resumeStoppedApp) {
eventSet.resume();
} else if (eventSet.suspendPolicy() == EventRequest.SUSPEND_ALL) {
setCurrentThread(eventSet);
notifier.vmInterrupted();
}
} catch (InterruptedException exc) {
// Do nothing. Any changes will be seen at top of loop.
} catch (VMDisconnectedException discExc) {
handleDisconnectedException();
break;
}
}
synchronized (this) {
completed = true;
notifyAll();
}
}
private boolean handleEvent(Event event) {
notifier.receivedEvent(event);
if (event instanceof ExceptionEvent) {
return exceptionEvent(event);
} else if (event instanceof BreakpointEvent) {
return breakpointEvent(event);
} else if (event instanceof WatchpointEvent) {
return fieldWatchEvent(event);
} else if (event instanceof StepEvent) {
return stepEvent(event);
} else if (event instanceof MethodEntryEvent) {
return methodEntryEvent(event);
} else if (event instanceof MethodExitEvent) {
return methodExitEvent(event);
} else if (event instanceof ClassPrepareEvent) {
return classPrepareEvent(event);
} else if (event instanceof ClassUnloadEvent) {
return classUnloadEvent(event);
} else if (event instanceof ThreadStartEvent) {
return threadStartEvent(event);
} else if (event instanceof ThreadDeathEvent) {
return threadDeathEvent(event);
} else if (event instanceof VMStartEvent) {
return vmStartEvent(event);
} else {
return handleExitEvent(event);
}
}
private boolean vmDied = false;
private boolean handleExitEvent(Event event) {
if (event instanceof VMDeathEvent) {
vmDied = true;
return vmDeathEvent(event);
} else if (event instanceof VMDisconnectEvent) {
connected = false;
if (!vmDied) {
vmDisconnectEvent(event);
}
/*
* Inform jdb command line processor that jdb is being shutdown. JDK-8154144.
*/
((TTY)notifier).setShuttingDown(true);
Env.shutdown(shutdownMessageKey);
return false;
} else {
throw new InternalError(MessageOutput.format("Unexpected event type",
new Object[] {event.getClass()}));
}
}
synchronized void handleDisconnectedException() {
/*
* A VMDisconnectedException has happened while dealing with
* another event. We need to flush the event queue, dealing only
* with exit events (VMDeath, VMDisconnect) so that we terminate
* correctly.
*/
EventQueue queue = Env.vm().eventQueue();
while (connected) {
try {
EventSet eventSet = queue.remove();
EventIterator iter = eventSet.eventIterator();
while (iter.hasNext()) {
handleExitEvent(iter.next());
}
} catch (InterruptedException exc) {
// ignore
} catch (InternalError exc) {
// ignore
}
}
}
private ThreadReference eventThread(Event event) {
if (event instanceof ClassPrepareEvent) {
return ((ClassPrepareEvent)event).thread();
} else if (event instanceof LocatableEvent) {
return ((LocatableEvent)event).thread();
} else if (event instanceof ThreadStartEvent) {
return ((ThreadStartEvent)event).thread();
} else if (event instanceof ThreadDeathEvent) {
return ((ThreadDeathEvent)event).thread();
} else if (event instanceof VMStartEvent) {
return ((VMStartEvent)event).thread();
} else {
return null;
}
}
private void setCurrentThread(EventSet set) {
ThreadReference thread;
if (set.size() > 0) {
/*
* If any event in the set has a thread associated with it,
* they all will, so just grab the first one.
*/
Event event = set.iterator().next(); // Is there a better way?
thread = eventThread(event);
} else {
thread = null;
}
setCurrentThread(thread);
}
private void setCurrentThread(ThreadReference thread) {
ThreadInfo.invalidateAll();
ThreadInfo.setCurrentThread(thread);
}
private boolean vmStartEvent(Event event) {
VMStartEvent se = (VMStartEvent)event;
notifier.vmStartEvent(se);
return stopOnVMStart;
}
private boolean breakpointEvent(Event event) {
BreakpointEvent be = (BreakpointEvent)event;
notifier.breakpointEvent(be);
return true;
}
private boolean methodEntryEvent(Event event) {
MethodEntryEvent me = (MethodEntryEvent)event;
notifier.methodEntryEvent(me);
return true;
}
private boolean methodExitEvent(Event event) {
MethodExitEvent me = (MethodExitEvent)event;
return notifier.methodExitEvent(me);
}
private boolean fieldWatchEvent(Event event) {
WatchpointEvent fwe = (WatchpointEvent)event;
notifier.fieldWatchEvent(fwe);
return true;
}
private boolean stepEvent(Event event) {
StepEvent se = (StepEvent)event;
notifier.stepEvent(se);
return true;
}
private boolean classPrepareEvent(Event event) {
ClassPrepareEvent cle = (ClassPrepareEvent)event;
notifier.classPrepareEvent(cle);
if (!Env.specList.resolve(cle)) {
MessageOutput.lnprint("Stopping due to deferred breakpoint errors.");
return true;
} else {
return false;
}
}
private boolean classUnloadEvent(Event event) {
ClassUnloadEvent cue = (ClassUnloadEvent)event;
notifier.classUnloadEvent(cue);
return false;
}
private boolean exceptionEvent(Event event) {
ExceptionEvent ee = (ExceptionEvent)event;
notifier.exceptionEvent(ee);
return true;
}
private boolean threadDeathEvent(Event event) {
ThreadDeathEvent tee = (ThreadDeathEvent)event;
ThreadInfo.removeThread(tee.thread());
return false;
}
private boolean threadStartEvent(Event event) {
ThreadStartEvent tse = (ThreadStartEvent)event;
ThreadInfo.addThread(tse.thread());
notifier.threadStartEvent(tse);
return false;
}
public boolean vmDeathEvent(Event event) {
shutdownMessageKey = "The application exited";
notifier.vmDeathEvent((VMDeathEvent)event);
return false;
}
public boolean vmDisconnectEvent(Event event) {
shutdownMessageKey = "The application has been disconnected";
notifier.vmDisconnectEvent((VMDisconnectEvent)event);
return false;
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.tty;
import com.sun.jdi.event.*;
interface EventNotifier {
void vmStartEvent(VMStartEvent e);
void vmDeathEvent(VMDeathEvent e);
void vmDisconnectEvent(VMDisconnectEvent e);
void threadStartEvent(ThreadStartEvent e);
void threadDeathEvent(ThreadDeathEvent e);
void classPrepareEvent(ClassPrepareEvent e);
void classUnloadEvent(ClassUnloadEvent e);
void breakpointEvent(BreakpointEvent e);
void fieldWatchEvent(WatchpointEvent e);
void stepEvent(StepEvent e);
void exceptionEvent(ExceptionEvent e);
void methodEntryEvent(MethodEntryEvent e);
boolean methodExitEvent(MethodExitEvent e);
void vmInterrupted();
void receivedEvent(Event event);
}

Some files were not shown because too many files have changed in this diff Show More