Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-4894: Improve and better test Java debug connector.

d-millarcce33f772e0e
diff --git a/Ghidra/Debug/Debugger-jpda/data/debugger-launchers/local-java.jsh b/Ghidra/Debug/Debugger-jpda/data/debugger-launchers/local-java.jsh
index 409b733e43..ef53572a03 100755
--- a/Ghidra/Debug/Debugger-jpda/data/debugger-launchers/local-java.jsh
+++ b/Ghidra/Debug/Debugger-jpda/data/debugger-launchers/local-java.jsh
@@ -1,5 +1,6 @@
-//@title java launch
-//@timeout 20000
+//@title java
+////@image-opt env:OPT_TARGET_CLASS
+//@timeout 2000000
//@desc <html><body width="300px">
//@desc <h3>Launch with <tt>java</tt></h3>
//@desc <p>
@@ -10,10 +11,11 @@
//@menu-group local
//@icon icon.debugger
//@help TraceRmiLauncherServicePlugin#java
+//@env OPT_TARGET_CLASS:str="" "Image" "The Main Class to launch (defaults to current program)."
+//@env OPT_TARGET_CLASSPATH:str="" "ClassPath" "The JVM classpath"
//@args "Arguments" "Command-line arguments to pass to the target"
//@enum Arch:str JVM Dalvik
//@env OPT_ARCH:Arch="JVM" "Arch" "Either 'JVM' or 'Dalvik'"
-//@env OPT_TARGET_CLASS:str="" "Image" "The Main Class to launch (defaults to current program)."
////@env OPT_SUSPEND:bool=true "Suspend" "Suspend the VM on launch."
//@env OPT_INCLUDE:str=n "Include virtual threads" "Include virtual threads."
//@env OPT_JSHELL_PATH:file="" "JShell cmd (if desired)" "The full path to jshell."
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/JdiEventHandler.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/JdiEventHandler.java
index 10176849da..2efc29bfcc 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/JdiEventHandler.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/JdiEventHandler.java
@@ -140,6 +140,7 @@ public class JdiEventHandler implements Runnable {
//System.err.println(event + ":" + vm);
return switch (event) {
case ExceptionEvent ev -> processException(ev);
+ case BreakpointEvent ev -> processBreakpoint(ev);
case AccessWatchpointEvent ev -> processAccessWatchpoint(ev);
case ModificationWatchpointEvent ev -> processWatchpointModification(ev);
case WatchpointEvent ev -> processWatchpoint(ev);
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/impl/JdiManagerImpl.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/impl/JdiManagerImpl.java
index d8c58efe95..f71e379d0f 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/impl/JdiManagerImpl.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/manager/impl/JdiManagerImpl.java
@@ -17,7 +17,7 @@ package ghidra.dbg.jdi.manager.impl;
import static ghidra.lifecycle.Unfinished.TODO;
-import java.io.IOException;
+import java.io.*;
import java.util.*;
import java.util.concurrent.*;
@@ -29,6 +29,7 @@ import com.sun.jdi.event.Event;
import ghidra.dbg.jdi.manager.*;
import ghidra.dbg.jdi.manager.JdiCause.Causes;
+import ghidra.dbg.jdi.rmi.jpda.JdiArguments;
import ghidra.util.Msg;
import ghidra.util.datastruct.ListenerSet;
@@ -61,23 +62,40 @@ public class JdiManagerImpl implements JdiManager {
virtualMachineManager = Bootstrap.virtualMachineManager();
}
+ private static void pumpStream(InputStream in, OutputStream out) {
+ try {
+ in.transferTo(out);
+ }
+ catch (IOException e) {
+ // We're done!
+ }
+ }
+
public VirtualMachine connectVM(Connector cx, Map<String, Connector.Argument> arguments)
throws Exception {
- if (cx instanceof LaunchingConnector) {
- LaunchingConnector lcx = (LaunchingConnector) cx;
- return lcx.launch(arguments);
+ if (cx instanceof LaunchingConnector lcx) {
+ VirtualMachine vm = lcx.launch(arguments);
+ new Thread(() -> pumpStream(vm.process().getErrorStream(), System.err)).start();
+ new Thread(() -> pumpStream(vm.process().getInputStream(), System.out)).start();
+ return vm;
}
- if (cx instanceof AttachingConnector) {
- AttachingConnector acx = (AttachingConnector) cx;
+ if (cx instanceof AttachingConnector acx) {
return acx.attach(arguments);
}
- if (cx instanceof ListeningConnector) {
- ListeningConnector lcx = (ListeningConnector) cx;
+ if (cx instanceof ListeningConnector lcx) {
return lcx.accept(arguments);
}
throw new Exception("Unknown connector type");
}
+ public VirtualMachine createVM(Map<String, String> env) {
+ JdiArguments args = new JdiArguments(env);
+ Connector cx = args.getConnector(virtualMachineManager);
+ Map<String, Connector.Argument> defaultArguments = cx.defaultArguments();
+ args.putArguments(defaultArguments);
+ return addVM(cx, defaultArguments);
+ }
+
@Override
public void terminate() {
/**
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiArch.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiArch.java
similarity index 98%
rename from Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiArch.java
rename to Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiArch.java
index 93d360eacd..27d444eb98 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiArch.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiArch.java
@@ -23,7 +23,7 @@ import ghidra.app.plugin.core.debug.client.tracermi.DefaultRegisterMapper;
import ghidra.program.model.lang.*;
import ghidra.program.util.DefaultLanguageService;
-public class TraceJdiArch {
+public class JdiArch {
private LanguageID langID;
private Language language;
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiArguments.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiArguments.java
new file mode 100644
index 0000000000..01073ca7eb
--- /dev/null
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiArguments.java
@@ -0,0 +1,109 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.dbg.jdi.rmi.jpda;
+
+import java.util.Map;
+
+import com.sun.jdi.VirtualMachineManager;
+import com.sun.jdi.connect.AttachingConnector;
+import com.sun.jdi.connect.Connector;
+import com.sun.jdi.connect.Connector.Argument;
+
+import ghidra.dbg.util.ShellUtils;
+
+public class JdiArguments {
+ enum Mode {
+ ATTACH_PORT, ATTACH_PID, LAUNCH;
+ }
+
+ private final Map<String, String> env;
+ private final Mode mode;
+
+ public JdiArguments(Map<String, String> env) {
+ this.env = Map.copyOf(env);
+ this.mode = computeMode();
+ }
+
+ /**
+ * Compute/detect the launch mode using the environment map.
+ *
+ * <p>
+ * It'd be nice if this were selected/specified in the script body, rather than by what options
+ * are present in its header. The reason we can't, though, is that the JDI client thread needs
+ * to also work within Ghidra's JVM, i.e., without launching a jshell subprocess. By far, the
+ * simplest way to accomplish this is to keep all the logic here, and just pass the environment
+ * map in. For the jshell-subprocess case, it's the environment map proper. For the
+ * in-Ghidra's-VM case, it's the map we would have passed when creating the subprocess.
+ *
+ * @return the mode.
+ */
+ protected Mode computeMode() {
+ if (env.containsKey("OPT_PORT")) {
+ return Mode.ATTACH_PORT;
+ }
+ if (env.containsKey("OPT_PID")) {
+ return Mode.ATTACH_PID;
+ }
+ return Mode.LAUNCH;
+ }
+
+ protected AttachingConnector findConnectorByArgKey(VirtualMachineManager vmm, String key) {
+ return vmm.attachingConnectors()
+ .stream()
+ .filter(ac -> ac.defaultArguments().containsKey(key))
+ .findFirst()
+ .orElseThrow();
+ }
+
+ public Connector getConnector(VirtualMachineManager vmm) {
+ return switch (mode) {
+ case ATTACH_PORT -> findConnectorByArgKey(vmm, "port");
+ case ATTACH_PID -> findConnectorByArgKey(vmm, "pid");
+ case LAUNCH -> vmm.defaultConnector();
+ };
+ }
+
+ public void putArguments(Map<String, Argument> args) {
+ switch (mode) {
+ case ATTACH_PORT -> {
+ args.get("hostname").setValue(env.get("OPT_HOST").toString());
+ args.get("port").setValue(env.get("OPT_PORT").toString());
+ args.get("timeout").setValue(env.get("OPT_TIMEOUT").toString());
+ }
+ case ATTACH_PID -> {
+ args.get("pid").setValue(env.get("OPT_PID").toString());
+ args.get("timeout").setValue(env.get("OPT_TIMEOUT").toString());
+ }
+ case LAUNCH -> {
+ args.get("main").setValue(env.get("OPT_TARGET_CLASS"));
+ Argument argSuspend = args.get("suspend");
+ String optSuspend = env.get("OPT_SUSPEND");
+ if (argSuspend != null && optSuspend != null) {
+ argSuspend.setValue(optSuspend);
+ }
+ Argument argIncludeVirtualThreads = args.get("includevirtualthreads");
+ String optInclude = env.get("OPT_INCLUDE");
+ if (argIncludeVirtualThreads != null && optInclude != null) {
+ argIncludeVirtualThreads.setValue(optInclude);
+ }
+ String cp = env.get("OPT_TARGET_CLASSPATH");
+ if (!cp.isBlank()) {
+ args.get("options").setValue("-cp " + ShellUtils.generateArgument(cp));
+ }
+ }
+ }
+ }
+}
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiClientThread.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiClientThread.java
index ab2ac07b91..ae0c79d45a 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiClientThread.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiClientThread.java
@@ -17,7 +17,6 @@ package ghidra.dbg.jdi.rmi.jpda;
import java.util.Map;
-import com.sun.jdi.connect.AttachingConnector;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.Connector.Argument;
@@ -26,70 +25,31 @@ import ghidra.dbg.jdi.manager.impl.JdiManagerImpl;
import ghidra.util.Msg;
public class JdiClientThread extends Thread {
- enum Mode {
- ATTACH_PORT, ATTACH_PID, LAUNCH;
- }
private final Map<String, String> env;
- private final Mode mode;
+ private final JdiArguments arguments;
private JdiManagerImpl manager;
- private TraceJdiManager traceJdiManager;
+ private JdiManager jdiManager;
public JdiClientThread(Map<String, String> env) {
this.env = env;
- this.mode = computeMode();
- }
-
- /**
- * Compute/detect the launch mode using the environment map.
- *
- * <p>
- * It'd be nice if this were selected/specified in the script body, rather than by what options
- * are present in its header. The reason we can't, though, is that the JDI client thread needs
- * to also work within Ghidra's JVM, i.e., without launching a jshell subprocess. By far, the
- * simplest way to accomplish this is to keep all the logic here, and just pass the environment
- * map in. For the jshell-subprocess case, it's the environment map proper. For the
- * in-Ghidra's-VM case, it's the map we would have passed when creating the subprocess.
- *
- * @return the mode.
- */
- Mode computeMode() {
- if (env.containsKey("OPT_PORT")) {
- return Mode.ATTACH_PORT;
- }
- if (env.containsKey("OPT_PID")) {
- return Mode.ATTACH_PID;
- }
- return Mode.LAUNCH;
- }
-
- AttachingConnector findConnectorByArgKey(String key) {
- return manager.getVirtualMachineManager()
- .attachingConnectors()
- .stream()
- .filter(ac -> ac.defaultArguments().containsKey(key))
- .findFirst()
- .orElseThrow();
+ this.arguments = new JdiArguments(env);
}
@Override
public void run() {
try {
manager = new JdiManagerImpl();
- traceJdiManager = new TraceJdiManager(manager, env);
+ jdiManager = new JdiManager(manager, env);
- Connector cx = switch (mode) {
- case ATTACH_PORT -> findConnectorByArgKey("port");
- case ATTACH_PID -> findConnectorByArgKey("pid");
- case LAUNCH -> manager.getVirtualMachineManager().defaultConnector();
- };
+ Connector cx = arguments.getConnector(manager.getVirtualMachineManager());
Map<String, Argument> args = cx.defaultArguments();
- putArguments(args);
+ arguments.putArguments(args);
if (manager.addVM(cx, args) != null) {
- traceJdiManager.getCommands().ghidraTraceSyncEnable();
- traceJdiManager.getHooks().vmStarted(null, Causes.UNCLAIMED);
+ jdiManager.getCommands().ghidraTraceSyncEnable();
+ jdiManager.getHooks().vmStarted(null, Causes.UNCLAIMED);
}
else {
// Nothing. addVM should already have reported the error.
@@ -100,30 +60,11 @@ public class JdiClientThread extends Thread {
}
}
- protected void putArguments(Map<String, Argument> args) {
- switch (mode) {
- case ATTACH_PORT -> {
- args.get("hostname").setValue(env.get("OPT_HOST").toString());
- args.get("port").setValue(env.get("OPT_PORT").toString());
- args.get("timeout").setValue(env.get("OPT_TIMEOUT").toString());
- }
- case ATTACH_PID -> {
- args.get("pid").setValue(env.get("OPT_PID").toString());
- args.get("timeout").setValue(env.get("OPT_TIMEOUT").toString());
- }
- case LAUNCH -> {
- args.get("main").setValue(env.get("OPT_TARGET_CLASS"));
- //args.get("suspend").setValue(env.get("OPT_SUSPEND"));
- args.get("includevirtualthreads").setValue(env.get("OPT_INCLUDE"));
- }
- }
- }
-
- public TraceJdiManager mgr() {
- return traceJdiManager;
+ public JdiManager mgr() {
+ return jdiManager;
}
- public TraceJdiCommands cmds() {
- return traceJdiManager.getCommands();
+ public JdiCommands cmds() {
+ return jdiManager.getCommands();
}
}
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiCommands.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiCommands.java
similarity index 81%
rename from Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiCommands.java
rename to Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiCommands.java
index 4299d79b2b..75fff119cb 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiCommands.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiCommands.java
@@ -15,7 +15,10 @@
*/
package ghidra.dbg.jdi.rmi.jpda;
+import static ghidra.dbg.jdi.rmi.jpda.JdiManager.*;
+
import java.io.IOException;
+import java.io.PrintStream;
import java.lang.ProcessHandle.Info;
import java.math.BigInteger;
import java.net.InetSocketAddress;
@@ -23,6 +26,9 @@ import java.nio.channels.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
+import java.util.stream.IntStream;
+
+import org.apache.commons.lang3.StringUtils;
import com.sun.jdi.*;
import com.sun.jdi.Method;
@@ -36,6 +42,7 @@ import ghidra.program.model.address.*;
import ghidra.program.model.lang.*;
import ghidra.program.model.lang.Language;
import ghidra.rmi.trace.TraceRmi.*;
+import ghidra.trace.model.Lifespan;
import ghidra.util.Msg;
/*
@@ -49,7 +56,7 @@ import ghidra.util.Msg;
class State {
- RmiClient client;
+ public RmiClient client;
public RmiTrace trace;
RmiTransaction tx;
@@ -109,25 +116,16 @@ class State {
}
-public class TraceJdiCommands {
+public class JdiCommands {
- private TraceJdiManager manager;
+ private JdiManager manager;
private JdiManagerImpl jdi;
public State state;
private String[] regNames = { "PC", "return_address" };
public long MAX_REFS = 100;
-// protected static final TargetStepKindSet SUPPORTED_KINDS = TargetStepKindSet.of( //
-// TargetStepKind.FINISH, //
-// TargetStepKind.LINE, //
-// TargetStepKind.OVER, //
-// TargetStepKind.OVER_LINE, //
-// TargetStepKind.RETURN, //
-// TargetStepKind.UNTIL, //
-// TargetStepKind.EXTENDED);
-
- public TraceJdiCommands(TraceJdiManager manager) {
+ public JdiCommands(JdiManager manager) {
this.manager = manager;
this.jdi = manager.getJdi();
state = new State();
@@ -145,7 +143,7 @@ public class TraceJdiCommands {
state.client = new RmiClient(channel, "jdi");
state.client.setRegistry(manager.remoteMethodRegistry);
state.client.negotiate("Connect");
- Msg.info(this, "Connected to " + state.client.getDescription() + " at " + address);
+ Msg.out("Connected to " + state.client.getDescription());
}
catch (NumberFormatException e) {
throw new RuntimeException("Port must be numeric");
@@ -187,8 +185,7 @@ public class TraceJdiCommands {
state.client = new RmiClient(client, "jdi");
state.client.setRegistry(manager.remoteMethodRegistry);
client.configureBlocking(false);
- Msg.info(this, "Connected from " + state.client.getDescription() + " at " +
- client.getLocalAddress());
+ Msg.out("Connected from " + state.client.getDescription());
}
}
keyIterator.remove();
@@ -219,7 +216,7 @@ public class TraceJdiCommands {
}
public void startTrace(String name) {
- TraceJdiArch arch = manager.getArch();
+ JdiArch arch = manager.getArch();
LanguageID language = arch.computeGhidraLanguage();
CompilerSpecID compiler = arch.computeGhidraCompiler(language);
state.trace = state.client.createTrace(name, language, compiler);
@@ -245,6 +242,9 @@ public class TraceJdiCommands {
if (name == null) {
name = computeName();
}
+ else if (name.contains("/")) {
+ name = name.substring(name.lastIndexOf("/"));
+ }
state.requireNoTrace();
startTrace(name);
}
@@ -266,19 +266,26 @@ public class TraceJdiCommands {
startTrace(name);
}
+ public VirtualMachine ghidraTraceCreate(Map<String, String> env) {
+ return manager.getJdi().createVM(env);
+ }
+
public void ghidraTraceInfo() {
if (state.client == null) {
Msg.error(this, "Not connected to Ghidra");
+ return;
}
- Msg.info(this, "Connected to" + state.client.getDescription());
+ Msg.info(this, "Connected to " + state.client.getDescription());
if (state.trace == null) {
Msg.error(this, "No trace");
}
- Msg.info(this, "Trace active");
+ else {
+ Msg.info(this, "Trace active");
+ }
}
public void ghidraTraceInfoLcsp() {
- TraceJdiArch arch = manager.getArch();
+ JdiArch arch = manager.getArch();
LanguageID language = arch.computeGhidraLanguage();
CompilerSpecID compiler = arch.computeGhidraCompiler(language);
Msg.info(this, "Selected Ghidra language: " + language);
@@ -286,7 +293,7 @@ public class TraceJdiCommands {
}
public void ghidraTraceTxStart(String description) {
- state.requireTx();
+ state.requireNoTx();
state.tx = state.requireTrace().startTx(description, false);
}
@@ -332,7 +339,6 @@ public class TraceJdiCommands {
public void ghidraTraceDelMem(Address address, long length) {
state.requireTrace();
try (RmiTransaction tx = state.trace.startTx("ghidraTraceDelMem", false)) {
- VirtualMachine currentVM = manager.getJdi().getCurrentVM();
Address mapped = state.trace.memoryMapper.map(address);
AddressRangeImpl range = new AddressRangeImpl(mapped, mapped.add(length - 1));
state.trace.deleteBytes(range, state.trace.getSnap());
@@ -369,19 +375,26 @@ public class TraceJdiCommands {
public void ghidraTraceInsertObj(String path) {
state.requireTx();
try (RmiTransaction tx = state.trace.startTx("ghidraTraceInsertObj", false)) {
- state.trace.proxyObjectPath(path).insert(state.trace.getSnap(), Resolution.CR_ADJUST);
+ Lifespan span = state.trace.proxyObjectPath(path)
+ .insert(state.trace.getSnap(), Resolution.CR_ADJUST);
+ System.out.println("Inserted object: lifespan=" + span);
}
}
public void ghidraTraceRemoveObj(String path) {
state.requireTx();
try (RmiTransaction tx = state.trace.startTx("ghidraTraceRemoveObj", false)) {
- state.trace.proxyObjectPath(path).remove(state.trace.getSnap(), false);
+ Lifespan span = state.trace.proxyObjectPath(path).remove(state.trace.getSnap(), false);
+ System.out.println("Removed object: lifespan=" + span);
}
}
-// public void ghidraTraceSetValue(String path, String key, Object value, TargetObjectSchema schema) {
-// }
+ public void ghidraTraceSetValue(String path, String key, Object value) {
+ state.requireTx();
+ try (RmiTransaction tx = state.trace.startTx("ghidraTraceSetValue", false)) {
+ setValue(path, key, value);
+ }
+ }
public void ghidraTraceRetainValues(String kind, String path, Set<String> keys) {
state.requireTx();
@@ -405,11 +418,77 @@ public class TraceJdiCommands {
return state.trace.proxyObjectPath(path);
}
-// public void ghidraTraceGetValues(String pattern) {
-// }
-//
-// public void ghidraTraceGetValuesRng() {
-// }
+ public static class Tabulator {
+ static class Column {
+ int width;
+
+ public void measure(String string) {
+ width = Math.max(width, string.length());
+ }
+
+ public void print(PrintStream out, String string) {
+ out.print(pad(string));
+ }
+
+ private String pad(String string) {
+ return StringUtils.rightPad(string, width);
+ }
+ }
+
+ private final PrintStream out;
+ private final List<Column> columns;
+
+ public Tabulator(PrintStream out, int colCount) {
+ this.out = out;
+ this.columns = IntStream.range(0, colCount).mapToObj(i -> new Column()).toList();
+ }
+
+ public void measure(Object... row) {
+ if (row.length != columns.size()) {
+ throw new IllegalArgumentException("Column count mismatch");
+ }
+ for (int i = 0; i < row.length; i++) {
+ columns.get(i).measure(row[i].toString());
+ }
+ }
+
+ public void print(Object... row) {
+ if (row.length != columns.size()) {
+ throw new IllegalArgumentException("Column count mismatch");
+ }
+ for (int i = 0; i < row.length; i++) {
+ if (i != 0) {
+ out.print(" ");
+ }
+ columns.get(i).print(out, row[i].toString());
+ }
+ out.println();
+ }
+ }
+
+ public void printValues(List<RmiTraceObjectValue> values) {
+ Tabulator tab = new Tabulator(System.out, 5);
+ tab.measure("Parent", "Key", "Span", "Value", "Type");
+ for (RmiTraceObjectValue d : values) {
+ tab.measure(d.parent().getPath(), d.span(), d.key(), d.value(), d.schema());
+ }
+ tab.print("Parent", "Key", "Span", "Value", "Type");
+ for (RmiTraceObjectValue d : values) {
+ tab.print(d.parent().getPath(), d.span(), d.key(), d.value(), d.schema());
+ }
+ }
+
+ public void ghidraTraceGetValues(String pattern) {
+ state.requireTrace();
+ List<RmiTraceObjectValue> values = state.trace.getValues(pattern);
+ printValues(values);
+ }
+
+ public void ghidraTraceGetValuesRng(Address addr, long sz) {
+ state.requireTrace();
+ List<RmiTraceObjectValue> values = state.trace.getValuesRng(addr, sz);
+ printValues(values);
+ }
public void ghidraTracePutVMs() {
state.requireTrace();
@@ -467,7 +546,6 @@ public class TraceJdiCommands {
public void ghidraTraceDisassemble(Address address) {
state.requireTrace();
- VirtualMachine currentVM = manager.getJdi().getCurrentVM();
MemoryMapper mapper = state.trace.memoryMapper;
Address mappedAddress = mapper.map(address);
AddressSpace addressSpace = mappedAddress.getAddressSpace();
@@ -480,7 +558,6 @@ public class TraceJdiCommands {
// STATE //
public void putMemState(Address start, long length, MemoryState memState, boolean usePages) {
- VirtualMachine currentVM = manager.getJdi().getCurrentVM();
Address mapped = state.trace.memoryMapper.map(start);
if (mapped.getAddressSpace() != start.getAddressSpace() &&
!memState.equals(MemoryState.MS_UNKNOWN)) {
@@ -503,7 +580,7 @@ public class TraceJdiCommands {
}
public RegisterValue[] putRegisters(StackFrame frame, String ppath) {
- TraceJdiArch arch = manager.getArch();
+ JdiArch arch = manager.getArch();
Language lang = arch.getLanguage();
Set<String> keys = new HashSet<>();
RegisterValue[] rvs = new RegisterValue[regNames.length];
@@ -568,7 +645,7 @@ public class TraceJdiCommands {
Address addr = manager.getAddressFromLocation(loc);
RegisterMapper mapper = state.trace.registerMapper;
String regName = mapper.mapName(name);
- TraceJdiArch arch = manager.getArch();
+ JdiArch arch = manager.getArch();
Language lang = arch.getLanguage();
Register register = lang.getRegister(name);
RegisterValue rv = new RegisterValue(register, addr.getOffsetAsBigInteger());
@@ -584,7 +661,6 @@ public class TraceJdiCommands {
}
public void putMem(Address address, long length, boolean create) {
- VirtualMachine vm = manager.getJdi().getCurrentVM();
MemoryMapper mapper = state.trace.memoryMapper;
Address mappedAddress = mapper.map(address);
AddressSpace addressSpace = mappedAddress.getAddressSpace();
@@ -636,8 +712,8 @@ public class TraceJdiCommands {
}
public void putTypeDetails(String path, Type type) {
- setValue(path, "_display", "Type: " + type.name());
- setValue(path, "Signature", type.signature());
+ setValue(path, ATTR_DISPLAY, "Type: " + type.name());
+ setValue(path, ATTR_SIGNATURE, type.signature());
}
public void putReferenceTypeContainer(String ppath, List<ReferenceType> reftypes) {
@@ -666,17 +742,28 @@ public class TraceJdiCommands {
if (name.indexOf(".") > 0) {
name = name.substring(name.lastIndexOf(".") + 1);
}
- setValue(path, TraceJdiManager.MODULE_NAME_ATTRIBUTE_NAME, name + ".class");
+ setValue(path, ATTR_MODULE_NAME, name + ".class");
putRefTypeAttributes(path, reftype);
- createObject(path + ".Fields");
- createObject(path + ".Instances");
- createObject(path + ".Locations");
- //createObject(path + ".Methods");
+ String fpath = createObject(path + ".Fields");
+ String ipath = createObject(path + ".Instances");
+ String lpath = createObject(path + ".Locations");
+ insertObject(fpath);
+ insertObject(ipath);
+ insertObject(lpath);
putMethodContainer(path + ".Methods", reftype);
String rpath = createObject(path + ".Relations");
+ insertObject(rpath);
ModuleReference module = reftype.module();
- createObject(module, module.name(), rpath + ".ModuleRef");
+ String moduleName = module.name();
+ if (moduleName == null) {
+ moduleName = "<unnamed>";
+ }
+ if (moduleName.contains(".")) {
+ moduleName = "\"" + moduleName + "\"";
+ }
+ String mrpath = createObject(module, moduleName, rpath + ".ModuleRef");
+ insertObject(mrpath);
if (reftype instanceof ArrayType at) {
putArrayTypeDetails(rpath, at);
}
@@ -713,6 +800,7 @@ public class TraceJdiCommands {
setValue(path, "defaultStratum", reftype.defaultStratum());
setValue(path, "availableStata", reftype.availableStrata());
setValue(path, "failedToInitialize", reftype.failedToInitialize());
+ insertObject(path);
}
private void registerMemory(String path, ReferenceType reftype) {
@@ -727,17 +815,17 @@ public class TraceJdiCommands {
bounds.add(range);
String mpath = createObject(mempath + manager.key(m.toString()));
- setValue(mpath, "Range", range);
- insertObject(path);
+ setValue(mpath, ATTR_RANGE, range);
+ insertObject(mpath);
}
}
}
AddressRange range = manager.putAddressRange(reftype, bounds);
- setValue(path, "Range", range);
+ setValue(path, ATTR_RANGE, range);
- setValue(path, "Count", reftype.constantPoolCount());
+ setValue(path, ATTR_COUNT, reftype.constantPoolCount());
range = manager.getPoolAddressRange(reftype, getSize(reftype) - 1);
- setValue(path, "RangeCP", range);
+ setValue(path, ATTR_RANGE_CP, range);
try {
putMem(range.getMinAddress(), range.getLength(), true);
}
@@ -755,19 +843,24 @@ public class TraceJdiCommands {
}
}
- public void loadReferenceType(String ppath, List<ReferenceType> reftypes, String targetClass) {
+ public boolean loadReferenceType(String ppath, List<ReferenceType> reftypes,
+ String targetClass) {
+ boolean result = false;
List<ReferenceType> classes = reftypes;
for (ReferenceType ref : classes) {
if (ref.name().contains(targetClass)) {
putReferenceType(ppath, ref, true);
+ result = true;
}
}
+ return result;
}
public void putArrayTypeDetails(String path, ArrayType type) {
+ String cpath = createObject(path + ".ComponentType");
setValue(path, "ComponentSignature", type.componentSignature());
setValue(path, "ComponentTypeName", type.componentTypeName());
- createObject(path + ".ComponentType");
+ insertObject(cpath);
}
public void putClassTypes(String ppath, List<ClassType> reftypes) {
@@ -781,10 +874,14 @@ public class TraceJdiCommands {
public void putClassTypeDetails(String path, ClassType type) {
setValue(path, "IsEnum", type.isEnum());
- createObject(path + ".AllInterfaces");
- createObject(path + ".Interfaces");
- createObject(path + ".SubClasses");
- createObject(path + ".ClassType");
+ String aipath = createObject(path + ".AllInterfaces");
+ String ipath = createObject(path + ".Interfaces");
+ String scpath = createObject(path + ".SubClasses");
+ String cpath = createObject(path + ".ClassType");
+ insertObject(aipath);
+ insertObject(ipath);
+ insertObject(scpath);
+ insertObject(cpath);
}
public void putInterfaceTypes(String ppath, List<InterfaceType> reftypes) {
@@ -797,9 +894,12 @@ public class TraceJdiCommands {
}
public void putInterfaceTypeDetails(String path, InterfaceType type) {
- createObject(path + ".Implementors");
- createObject(path + ".SubInterfaces");
- createObject(path + ".SuperInterfaces");
+ String impath = createObject(path + ".Implementors");
+ String sbpath = createObject(path + ".SubInterfaces");
+ String sppath = createObject(path + ".SuperInterfaces");
+ insertObject(impath);
+ insertObject(sbpath);
+ insertObject(sppath);
}
// VALUES //
@@ -812,7 +912,7 @@ public class TraceJdiCommands {
public void putValue(String ppath, String key, Value value) {
String path = createObject(value, key, ppath);
- setValue(path, "_display", "Value: " + value.toString());
+ setValue(path, ATTR_DISPLAY, "Value: " + value.toString());
//putValueDetailsByType(path, value);
insertObject(path);
}
@@ -848,35 +948,35 @@ public class TraceJdiCommands {
}
public void putValueDetails(String path, Value value) {
- putType(path, "Type", value.type());
+ putType(path, ATTR_TYPE, value.type());
}
public void putPrimitiveValue(String ppath, PrimitiveValue value) {
String path = createObject(value, value.toString(), ppath);
putValueDetails(path, value);
if (value instanceof BooleanValue v) {
- setValue(path, "Value", v.booleanValue());
+ setValue(path, ATTR_VALUE, v.booleanValue());
}
if (value instanceof ByteValue b) {
- setValue(path, "Value", b.byteValue());
+ setValue(path, ATTR_VALUE, b.byteValue());
}
if (value instanceof CharValue v) {
- setValue(path, "Value", v.charValue());
+ setValue(path, ATTR_VALUE, v.charValue());
}
if (value instanceof ShortValue v) {
- setValue(path, "Value", v.shortValue());
+ setValue(path, ATTR_VALUE, v.shortValue());
}
if (value instanceof IntegerValue v) {
- setValue(path, "Value", v.intValue());
+ setValue(path, ATTR_VALUE, v.intValue());
}
if (value instanceof LongValue v) {
- setValue(path, "Value", v.longValue());
+ setValue(path, ATTR_VALUE, v.longValue());
}
if (value instanceof FloatValue v) {
- setValue(path, "Value", v.floatValue());
+ setValue(path, ATTR_VALUE, v.floatValue());
}
if (value instanceof DoubleValue v) {
- setValue(path, "Value", v.doubleValue());
+ setValue(path, ATTR_VALUE, v.doubleValue());
}
insertObject(path);
}
@@ -962,7 +1062,8 @@ public class TraceJdiCommands {
public void putObjectContainer(String path, List<ObjectReference> objects) {
for (ObjectReference obj : objects) {
- createObject(obj, obj.toString(), path);
+ String opath = createObject(obj, obj.toString(), path);
+ insertObject(opath);
}
}
@@ -983,27 +1084,34 @@ public class TraceJdiCommands {
// IGNORE
}
setValue(apath, "isCollected", ref.isCollected());
+ insertObject(apath);
String rpath = createObject(path + ".Relations");
try {
if (ref.owningThread() != null) {
- createObject(rpath + ".OwningThread");
+ String otpath = createObject(rpath + ".OwningThread");
+ insertObject(otpath);
}
if (ref.waitingThreads() != null) {
- createObject(rpath + ".WaitingThreads");
+ String wtpath = createObject(rpath + ".WaitingThreads");
+ insertObject(wtpath);
}
}
catch (IncompatibleThreadStateException e) {
// IGNORE
}
if (ref.referenceType() != null) {
- createObject(rpath + ".ReferenceType");
+ String rtpath = createObject(rpath + ".ReferenceType");
+ insertObject(rtpath);
}
if (ref.referringObjects(MAX_REFS) != null) {
- createObject(rpath + ".ReferringObjects");
+ String ropath = createObject(rpath + ".ReferringObjects");
+ insertObject(ropath);
}
if (!(ref instanceof ArrayReference)) {
- createObject(path + ".Variables");
+ String vpath = createObject(path + ".Variables");
+ insertObject(vpath);
}
+ insertObject(rpath);
}
public void putArrayReference(String ppath, ArrayReference ref) {
@@ -1014,8 +1122,9 @@ public class TraceJdiCommands {
public void putArrayReferenceDetails(String path, ArrayReference ref) {
putObjectReferenceDetails(path, ref);
- setValue(path, "Length", ref.length());
- createObject(path + ".Values");
+ setValue(path, ATTR_LENGTH, ref.length());
+ String vpath = createObject(path + ".Values");
+ insertObject(vpath);
}
public void putClassLoaderReference(String ppath, ClassLoaderReference ref) {
@@ -1026,8 +1135,10 @@ public class TraceJdiCommands {
public void putClassLoaderReferenceDetails(String path, ClassLoaderReference ref) {
putObjectReferenceDetails(path, ref);
- createObject(path + ".DefinedClasses");
- createObject(path + ".VisibleClasses");
+ String dcpath = createObject(path + ".DefinedClasses");
+ String vcpath = createObject(path + ".VisibleClasses");
+ insertObject(dcpath);
+ insertObject(vcpath);
}
public void putClassObjectReference(String ppath, ClassObjectReference ref) {
@@ -1038,7 +1149,8 @@ public class TraceJdiCommands {
public void putClassObjectReferenceDetails(String path, ClassObjectReference ref) {
putObjectReferenceDetails(path, ref);
- createObject(path + ".ReflectedType");
+ String rtpath = createObject(path + ".ReflectedType");
+ insertObject(rtpath);
}
public void putModuleReferenceContainer() {
@@ -1048,7 +1160,8 @@ public class TraceJdiCommands {
List<ModuleReference> modules = vm.allModules();
for (ModuleReference ref : modules) {
keys.add(manager.key(ref.name()));
- createObject(ref, ref.name(), ppath);
+ String mpath = createObject(ref, ref.name(), ppath);
+ insertObject(mpath);
}
retainKeys(ppath, keys);
}
@@ -1061,7 +1174,8 @@ public class TraceJdiCommands {
public void putModuleReferenceDetails(String path, ModuleReference ref) {
putObjectReferenceDetails(path, ref);
- createObject(path + ".ClassLoader");
+ String clpath = createObject(path + ".ClassLoader");
+ insertObject(clpath);
}
public void putStringReference(String ppath, StringReference ref) {
@@ -1072,7 +1186,7 @@ public class TraceJdiCommands {
public void putStringReferenceDetails(String path, StringReference ref) {
putObjectReferenceDetails(path, ref);
- setValue(path, "Value", ref.value());
+ setValue(path, ATTR_VALUE, ref.value());
}
public void putThreadGroupContainer(String refpath, List<ThreadGroupReference> refs) {
@@ -1094,10 +1208,13 @@ public class TraceJdiCommands {
public void putThreadGroupReferenceDetails(String path, ThreadGroupReference ref) {
putObjectReferenceDetails(path, ref);
if (ref.parent() != null) {
- createObject(path + ".Parent");
+ String ppath = createObject(path + ".Parent");
+ insertObject(ppath);
}
- createObject(path + ".ThreadGroups");
- createObject(path + ".Threads");
+ String tgpath = createObject(path + ".ThreadGroups");
+ String tpath = createObject(path + ".Threads");
+ insertObject(tgpath);
+ insertObject(tpath);
}
public void putThreadContainer(String refpath, List<ThreadReference> refs, boolean asLink) {
@@ -1123,13 +1240,18 @@ public class TraceJdiCommands {
public void putThreadReferenceDetails(String path, ThreadReference ref) {
putObjectReferenceDetails(path, ref);
- createObject(path + ".Stack");
+ String spath = createObject(path + ".Stack");
String rpath = createObject(path + ".Relations");
- createObject(rpath + ".CurrentContendedMonitor");
- createObject(rpath + ".OwnedMonitors");
- createObject(rpath + ".OwnedMonitorsAndFrames");
- createObject(rpath + ".ThreadGroup");
+ String ccpath = createObject(rpath + ".CurrentContendedMonitor");
+ String ompath = createObject(rpath + ".OwnedMonitors");
+ String omfpath = createObject(rpath + ".OwnedMonitorsAndFrames");
+ String tgpath = createObject(rpath + ".ThreadGroup");
putThreadAttributes(ref, path);
+ insertObject(spath);
+ insertObject(ccpath);
+ insertObject(ompath);
+ insertObject(omfpath);
+ insertObject(tgpath);
}
void putThreadAttributes(ThreadReference thread, String ppath) {
@@ -1152,18 +1274,22 @@ public class TraceJdiCommands {
// Ignore
}
setValue(path, "suspendCount", thread.suspendCount());
+ insertObject(path);
}
public void putMonitorInfoContainer(String path, List<MonitorInfo> info) {
for (MonitorInfo f : info) {
- createObject(f, f.toString(), path);
+ String ipath = createObject(f, f.toString(), path);
+ insertObject(ipath);
}
}
public void putMonitorInfoDetails(String path, MonitorInfo info) {
setValue(path, "StackDepth", info.stackDepth());
- createObject(path + ".Monitor");
- createObject(path + ".Thread");
+ String mpath = createObject(path + ".Monitor");
+ String tpath = createObject(path + ".Thread");
+ insertObject(mpath);
+ insertObject(tpath);
}
// TYPE COMPONENTS
@@ -1183,6 +1309,7 @@ public class TraceJdiCommands {
catch (IllegalArgumentException iae) {
// IGNORE
}
+ keys.add(manager.key(f.name()));
putField(path, f, value);
}
retainKeys(path, keys);
@@ -1201,6 +1328,7 @@ public class TraceJdiCommands {
catch (IllegalArgumentException iae) {
// IGNORE
}
+ keys.add(manager.key(f.name()));
putField(path, f, value);
}
retainKeys(path, keys);
@@ -1210,23 +1338,23 @@ public class TraceJdiCommands {
String path = createObject(f, f.name(), ppath);
putFieldDetails(path, f);
if (value != null) {
- putValue(path, "Value", value);
- setValue(path, "_display", f.name() + " (" + f.typeName() + ") : " + value);
+ putValue(path, ATTR_VALUE, value);
+ setValue(path, ATTR_DISPLAY, f.name() + " (" + f.typeName() + ") : " + value);
}
else {
- setValue(path, "_display", f.name() + " (" + f.typeName() + ")");
+ setValue(path, ATTR_DISPLAY, f.name() + " (" + f.typeName() + ")");
}
insertObject(path);
}
public void putFieldDetails(String path, Field f) {
- setValue(path, TraceJdiManager.MODULE_NAME_ATTRIBUTE_NAME, f.declaringType().name());
+ setValue(path, ATTR_MODULE_NAME, f.declaringType().name());
if (f.genericSignature() != null) {
setValue(path, "GenericSignature", f.genericSignature());
}
putFieldAttributes(path, f);
try {
- putType(path, "Type", f.type());
+ putType(path, ATTR_TYPE, f.type());
}
catch (ClassNotLoadedException e) {
// IGNORE
@@ -1247,6 +1375,7 @@ public class TraceJdiCommands {
setValue(path, "isSynthetic", f.isSynthetic());
setValue(path, "isTransient", f.isTransient());
setValue(path, "isVolatile", f.isVolatile());
+ insertObject(path);
}
public void putMethodContainer(String path, ReferenceType reftype) {
@@ -1268,24 +1397,27 @@ public class TraceJdiCommands {
public void putMethodDetails(String path, Method m, boolean partial) {
ReferenceType declaringType = m.declaringType();
- setValue(path, TraceJdiManager.MODULE_NAME_ATTRIBUTE_NAME, declaringType.name());
+ setValue(path, ATTR_MODULE_NAME, declaringType.name());
createLink(m, "DeclaringType", declaringType);
if (!partial) {
- createObject(path + ".Arguments");
+ String apath = createObject(path + ".Arguments");
if (m.genericSignature() != null) {
setValue(path, "GenericSignature", m.genericSignature());
}
- createObject(path + ".Locations");
+ String lpath = createObject(path + ".Locations");
setValue(path, "Modifiers", m.modifiers());
setValue(path, "ReturnType", m.returnTypeName());
setValue(path, "Signature", m.signature());
- createObject(path + ".Variables");
+ String vpath = createObject(path + ".Variables");
putMethodAttributes(path, m);
+ insertObject(apath);
+ insertObject(lpath);
+ insertObject(vpath);
}
if (m.location() != null) {
AddressRange range = manager.getAddressRange(m);
if (!range.equals(manager.defaultRange)) {
- setValue(path, "Range", range);
+ setValue(path, ATTR_RANGE, range);
}
}
String bytes = "";
@@ -1308,6 +1440,12 @@ public class TraceJdiCommands {
setValue(path, "isPrivate", m.isPrivate());
setValue(path, "isProtected", m.isProtected());
setValue(path, "isPublic", m.isPublic());
+ setValue(path, "isStatic", m.isStatic());
+ setValue(path, "isStaticInitializer", m.isStaticInitializer());
+ setValue(path, "isSynchronized", m.isSynchronized());
+ setValue(path, "isSynthetic", m.isSynthetic());
+ setValue(path, "isVarArgs", m.isVarArgs());
+ insertObject(path);
}
// OTHER OBJECTS //
@@ -1334,17 +1472,21 @@ public class TraceJdiCommands {
}
public void putVMDetails(String path, VirtualMachine vm) {
- createObject(path + ".Classes");
- createObject(path + ".Memory");
- createObject(path + ".ThreadGroups");
- createObject(path + ".Threads");
+ String cpath = createObject(path + ".Classes");
+ String mpath = createObject(path + ".Memory");
+ String tgpath = createObject(path + ".ThreadGroups");
+ String tpath = createObject(path + ".Threads");
Event currentEvent = jdi.getCurrentEvent();
String shortName = vm.name().substring(0, vm.name().indexOf(" "));
String display = currentEvent == null ? shortName : shortName + " [" + currentEvent + "]";
- setValue(path, TraceJdiManager.DISPLAY_ATTRIBUTE_NAME, display);
- setValue(path, TraceJdiManager.ARCH_ATTRIBUTE_NAME, vm.name());
- setValue(path, TraceJdiManager.DEBUGGER_ATTRIBUTE_NAME, vm.description());
- setValue(path, TraceJdiManager.OS_ATTRIBUTE_NAME, vm.version());
+ setValue(path, ATTR_DISPLAY, display);
+ setValue(path, ATTR_ARCH, vm.name());
+ setValue(path, ATTR_DEBUGGER, vm.description());
+ setValue(path, ATTR_OS, vm.version());
+ insertObject(cpath);
+ insertObject(mpath);
+ insertObject(tgpath);
+ insertObject(tpath);
}
public void putProcesses() {
@@ -1383,13 +1525,13 @@ public class TraceJdiCommands {
Info info = proc.info();
Optional<String> optional = info.command();
if (optional.isPresent()) {
- setValue(path, "Executable", optional.get());
+ setValue(path, ATTR_EXECUTABLE, optional.get());
}
optional = info.commandLine();
if (optional.isPresent()) {
- setValue(path, "CommandLine", optional.get());
+ setValue(path, ATTR_COMMAND_LINE, optional.get());
}
- setValue(path, "Alive", proc.isAlive());
+ setValue(path, ATTR_ALIVE, proc.isAlive());
}
public void putFrames() {
@@ -1409,6 +1551,7 @@ public class TraceJdiCommands {
// IGNORE
}
retainKeys(ppath, keys);
+ insertObject(ppath);
}
private void putFrame(String ppath, StackFrame frame, String key) {
@@ -1419,17 +1562,20 @@ public class TraceJdiCommands {
private void putFrameDetails(String path, StackFrame frame, String key) {
Location location = frame.location();
- setValue(path, "_display", "[" + key + "] " + location + ":" + location.method().name() +
+ setValue(path, ATTR_DISPLAY, "[" + key + "] " + location + ":" + location.method().name() +
":" + location.codeIndex());
- putLocation(path, "Location", location);
+ putLocation(path, ATTR_LOCATION, location);
Address addr = manager.getAddressFromLocation(location);
- setValue(path, "PC", addr);
+ setValue(path, ATTR_PC, addr);
String rpath = createObject(path + ".Registers");
putRegisters(frame, rpath);
- createObject(path + ".Variables");
+ insertObject(rpath);
+ String vpath = createObject(path + ".Variables");
+ insertObject(vpath);
try {
- createObject(frame.thisObject(), "This", path);
+ String thpath = createObject(frame.thisObject(), "This", path);
+ insertObject(thpath);
}
catch (Exception e) {
// Ignore
@@ -1439,7 +1585,8 @@ public class TraceJdiCommands {
public void putLocationContainer(String path, Method m) {
try {
for (Location loc : m.allLineLocations()) {
- createObject(loc, loc.toString(), path);
+ String lpath = createObject(loc, loc.toString(), path);
+ insertObject(lpath);
}
}
catch (AbsentInformationException e) {
@@ -1450,7 +1597,8 @@ public class TraceJdiCommands {
public void putLocationContainer(String path, ReferenceType ref) {
try {
for (Location loc : ref.allLineLocations()) {
- createObject(loc, loc.toString(), path);
+ String lpath = createObject(loc, loc.toString(), path);
+ insertObject(lpath);
}
}
catch (AbsentInformationException e) {
@@ -1467,29 +1615,32 @@ public class TraceJdiCommands {
public void putLocationDetails(String path, Location location) {
Address addr = manager.getAddressFromLocation(location);
if (isLoaded(location)) {
- setValue(path, "_display", manager.key(location.toString()) + ": " + addr);
- setValue(path, "Addr", addr);
+ setValue(path, ATTR_DISPLAY, manager.key(location.toString()) + ": " + addr);
+ setValue(path, ATTR_ADDRESS, addr);
}
- setValue(path, "Index", location.codeIndex());
- setValue(path, "Line#", location.lineNumber());
+ setValue(path, ATTR_INDEX, location.codeIndex());
+ setValue(path, ATTR_LINENO, location.lineNumber());
try {
- setValue(path, "Name", location.sourceName());
+ setValue(path, ATTR_NAME, location.sourceName());
}
catch (AbsentInformationException e) {
- // IGNORE
+ // sourceName is not available. IGNORE
}
try {
setValue(path, "Path", location.sourcePath());
}
catch (AbsentInformationException e) {
- // IGNORE
+ // sourcePath is not available. IGNORE
}
Method method = location.method();
+ RmiTraceObject methodObject = proxyObject(method);
+ if (methodObject == null) {
+ String ppath = getVmPath(method.virtualMachine()) + ".Classes";
+ putReferenceType(ppath, method.declaringType(), true);
+ }
createLink(location, "Method", method);
createLink(location, "DeclaringType", location.declaringType());
createLink(location, "ModuleRef", location.declaringType().module());
- //createObject(method, method.name(), path+".Method");
- //putMethodDetails(path, method);
}
private boolean isLoaded(Location location) {
@@ -1513,15 +1664,15 @@ public class TraceJdiCommands {
String path = createObject(lv, lv.name(), ppath);
putLocalVariableDetails(path, lv);
if (value != null) {
- putValue(path, "Value", value);
- setValue(path, "_display", lv.name() + ": " + value);
+ putValue(path, ATTR_VALUE, value);
+ setValue(path, ATTR_DISPLAY, lv.name() + ": " + value);
}
insertObject(path);
}
public void putLocalVariableDetails(String path, LocalVariable lv) {
try {
- putType(path, "Type", lv.type());
+ putType(path, ATTR_TYPE, lv.type());
}
catch (ClassNotLoadedException e) {
// IGNORE
@@ -1536,16 +1687,19 @@ public class TraceJdiCommands {
setValue(path, "GenericSignature", lv.genericSignature());
}
setValue(path, "Signature", lv.signature());
+ insertObject(path);
}
public void putMethodTypeContainer(String ppath, Method m) {
try {
for (Type type : m.argumentTypes()) {
- createObject(type, type.name(), ppath);
+ String tpath = createObject(type, type.name(), ppath);
+ insertObject(tpath);
}
}
catch (ClassNotLoadedException e) {
- createObject(ppath + "Class Not Loaded");
+ String epath = createObject(ppath + "Class Not Loaded");
+ insertObject(epath);
}
}
@@ -1553,7 +1707,7 @@ public class TraceJdiCommands {
VirtualMachine vm = manager.getJdi().getCurrentVM();
EventRequestManager requestManager = vm.eventRequestManager();
String ppath = getPath(vm) + ".Breakpoints";
- createObject(ppath);
+ String path = createObject(ppath);
Set<String> keys = new HashSet<>();
List<BreakpointRequest> brkReqs = requestManager.breakpointRequests();
@@ -1579,13 +1733,14 @@ public class TraceJdiCommands {
}
retainKeys(ppath, keys);
+ insertObject(path);
}
public void putEvents() {
VirtualMachine vm = manager.getJdi().getCurrentVM();
EventRequestManager requestManager = vm.eventRequestManager();
String ppath = getPath(vm) + ".Events";
- createObject(ppath);
+ String path = createObject(ppath);
Set<String> keys = new HashSet<>();
List<VMDeathRequest> deathReqs = requestManager.vmDeathRequests();
@@ -1669,6 +1824,7 @@ public class TraceJdiCommands {
}
retainKeys(ppath, keys);
+ insertObject(path);
}
// REQUESTS //
@@ -1711,13 +1867,14 @@ public class TraceJdiCommands {
private void putReqBreakpointDetails(String path, BreakpointRequest req, String key) {
Location location = req.location();
- setValue(path, "_display", "[" + key + "] " + location + ":" + location.method().name() +
+ setValue(path, ATTR_DISPLAY, "[" + key + "] " + location + ":" + location.method().name() +
":" + location.codeIndex());
Address addr = manager.getAddressFromLocation(location);
AddressRangeImpl range = new AddressRangeImpl(addr, addr);
- setValue(path, "Range", range);
- createObject(location, location.toString(), path + ".Location");
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_RANGE, range);
+ String lpath = createObject(location, location.toString(), path + ".Location");
+ insertObject(lpath);
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1730,13 +1887,14 @@ public class TraceJdiCommands {
private void putReqAccessWatchpointDetails(String path, AccessWatchpointRequest req,
String key) {
Field field = req.field();
- setValue(path, "_display", "[" + key + "] " + field + ":" + field.declaringType());
+ setValue(path, ATTR_DISPLAY, "[" + key + "] " + field + ":" + field.declaringType());
// NB: This isn't correct, but we need a range (any range)
AddressRange range =
manager.getPoolAddressRange(field.declaringType(), getSize(field.declaringType()));
- setValue(path, "Range", range);
- createObject(field, field.toString(), path + ".Field");
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_RANGE, range);
+ String fpath = createObject(field, field.toString(), path + ".Field");
+ insertObject(fpath);
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1750,13 +1908,14 @@ public class TraceJdiCommands {
private void putReqModificationWatchpointDetails(String path, ModificationWatchpointRequest req,
String key) {
Field field = req.field();
- setValue(path, "_display", "[" + key + "] " + field + ":" + field.declaringType());
+ setValue(path, ATTR_DISPLAY, "[" + key + "] " + field + ":" + field.declaringType());
// NB: This isn't correct, but we need a range (any range)
AddressRange range =
manager.getPoolAddressRange(field.declaringType(), getSize(field.declaringType()));
- setValue(path, "Range", range);
- createObject(field, field.toString(), path + ".Field");
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_RANGE, range);
+ String fpath = createObject(field, field.toString(), path + ".Field");
+ insertObject(fpath);
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1767,7 +1926,7 @@ public class TraceJdiCommands {
}
private void putReqExceptionDetails(String path, ExceptionRequest req, String key) {
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_ENABLED, req.isEnabled());
}
private void putReqClassLoad(String ppath, ClassPrepareRequest req, String key) {
@@ -1777,7 +1936,7 @@ public class TraceJdiCommands {
}
private void putReqClassLoadDetails(String path, ClassPrepareRequest req, String key) {
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1788,7 +1947,7 @@ public class TraceJdiCommands {
}
private void putReqClassUnloadDetails(String path, ClassUnloadRequest req, String key) {
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1799,7 +1958,7 @@ public class TraceJdiCommands {
}
private void putReqMethodEntryDetails(String path, MethodEntryRequest req, String key) {
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1810,7 +1969,7 @@ public class TraceJdiCommands {
}
private void putReqMethodExitDetails(String path, MethodExitRequest req, String key) {
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1821,7 +1980,7 @@ public class TraceJdiCommands {
}
private void putReqStepRequestDetails(String path, StepRequest req, String key) {
- setValue(path, "Enabled", req.isEnabled());
+ setValue(path, ATTR_ENABLED, req.isEnabled());
putFilterDetails(path, req);
}
@@ -1873,19 +2032,19 @@ public class TraceJdiCommands {
Object property = req.getProperty("Class");
if (property != null) {
if (property instanceof ReferenceType reftype) {
- setValue(path, "Class", reftype.name());
+ setValue(path, ATTR_CLASS, reftype.name());
}
}
property = req.getProperty("Instance");
if (property != null) {
if (property instanceof ObjectReference ref) {
- setValue(path, "Instance", ref.toString());
+ setValue(path, ATTR_INSTANCE, ref.toString());
}
}
property = req.getProperty("Thread");
if (property != null) {
if (property instanceof ThreadReference ref) {
- setValue(path, "Thread", ref.name());
+ setValue(path, ATTR_THREAD, ref.name());
}
}
}
@@ -1946,7 +2105,7 @@ public class TraceJdiCommands {
public void ghidraTraceSyncEnable() {
try (RmiTransaction tx = state.trace.startTx("ghidraTraceSyncEnable", false)) {
- TraceJdiHooks hooks = manager.getHooks();
+ JdiHooks hooks = manager.getHooks();
hooks.installHooks();
hooks.enableCurrentVM();
}
@@ -1981,6 +2140,28 @@ public class TraceJdiCommands {
}
}
+ public void execute(ClassType ct, ThreadReference thread, Method method, List<Value> args,
+ int options) {
+ try {
+ Value val = ct.invokeMethod(thread, method, args, options);
+ System.err.println(val);
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ public void execute(ObjectReference ref, ThreadReference thread, Method method,
+ List<Value> args, int options) {
+ try {
+ Value val = ref.invokeMethod(thread, method, args, options);
+ System.out.println(val);
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
private int getSize(ReferenceType reftype) {
byte[] cp = reftype.constantPool();
int sz = 1;
@@ -1998,7 +2179,7 @@ public class TraceJdiCommands {
return manager.pathForObj(obj);
}
- RmiTraceObject proxyObject(Object obj) {
+ public RmiTraceObject proxyObject(Object obj) {
String path = getPath(obj);
return path == null ? null : RmiTraceObject.fromPath(state.trace, path);
}
@@ -2038,7 +2219,8 @@ public class TraceJdiCommands {
if (child instanceof Method m) {
key = m.name();
}
- createObject(child, key, ppath + "." + label);
+ String lpath = createObject(child, key, ppath + "." + label);
+ insertObject(lpath);
}
}
@@ -2070,12 +2252,13 @@ public class TraceJdiCommands {
String shortName = vm.name().substring(0, vm.name().indexOf(" "));
name = currentEvent == null ? shortName : shortName + " [" + currentEvent + "]";
}
- setValue(path, TraceJdiManager.ACCESSIBLE_ATTRIBUTE_NAME, suspended);
+ setValue(path, ATTR_ACCESSIBLE, suspended);
String annotation = suspended ? "(S)" : "(R)";
- setValue(path, TraceJdiManager.DISPLAY_ATTRIBUTE_NAME, name + " " + annotation);
+ setValue(path, ATTR_DISPLAY, name + " " + annotation);
String tstate = suspended ? "STOPPED" : "RUNNING";
- setValue(path, TraceJdiManager.STATE_ATTRIBUTE_NAME, tstate);
+ setValue(path, ATTR_STATE, tstate);
stopped |= suspended;
return stopped;
}
+
}
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiHooks.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiHooks.java
similarity index 87%
rename from Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiHooks.java
rename to Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiHooks.java
index 3375788ab1..e5e5a8484f 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiHooks.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiHooks.java
@@ -15,47 +15,35 @@
*/
package ghidra.dbg.jdi.rmi.jpda;
+import static ghidra.dbg.jdi.rmi.jpda.JdiManager.*;
+
import java.util.*;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
-import ghidra.app.plugin.core.debug.client.tracermi.RmiTrace;
-import ghidra.app.plugin.core.debug.client.tracermi.RmiTransaction;
+import ghidra.app.plugin.core.debug.client.tracermi.*;
import ghidra.dbg.jdi.manager.*;
import ghidra.dbg.jdi.manager.impl.DebugStatus;
import ghidra.dbg.jdi.manager.impl.JdiManagerImpl;
class HookState {
- private TraceJdiCommands cmds;
- private Object batch;
+ private JdiCommands cmds;
- public HookState(TraceJdiCommands cmds) {
+ public HookState(JdiCommands cmds) {
this.cmds = cmds;
- this.batch = null;
}
- public void ensureBatch() {
- if (batch == null) {
- batch = cmds.state.client.startBatch();
- }
+ public RmiBatch batch() {
+ return cmds.state.client.startBatch();
}
-
- public void endBatch() {
- if (batch == null) {
- return;
- }
- batch = null;
- cmds.state.client.endBatch();
- }
-
}
class VmState {
- private TraceJdiManager manager;
- private TraceJdiCommands cmds;
+ private JdiManager manager;
+ private JdiCommands cmds;
private boolean firstPass;
boolean classes;
boolean modules;
@@ -65,7 +53,7 @@ class VmState {
boolean events;
Set<Object> visited;
- public VmState(TraceJdiManager manager) {
+ public VmState(JdiManager manager) {
this.manager = manager;
this.cmds = manager.getCommands();
this.firstPass = true;
@@ -109,9 +97,14 @@ class VmState {
}
StackFrame frame = manager.getJdi().getCurrentFrame();
if (frame != null) {
- if (first || !visited.contains(frame)) {
- cmds.putReg(frame);
- visited.add(frame);
+ try {
+ if (first || !visited.contains(frame)) {
+ cmds.putReg(frame);
+ visited.add(frame);
+ }
+ }
+ catch (InvalidStackFrameException e) {
+ manager.getJdi().setCurrentFrame(null);
}
}
}
@@ -154,7 +147,7 @@ class VmState {
Process proc = vm.process();
String path = cmds.getPath(proc);
if (path != null) {
- cmds.setValue(path, "Alive", proc.isAlive());
+ cmds.setValue(path, ATTR_ALIVE, proc.isAlive());
}
setState(vm);
}
@@ -168,8 +161,8 @@ class VmState {
if (process != null) {
exitCode = process.exitValue();
String procpath = cmds.getPath(vm.process());
- cmds.setValue(procpath, "ExitCode", exitCode);
- cmds.setValue(procpath, TraceJdiManager.STATE_ATTRIBUTE_NAME, "TERMINATED");
+ cmds.setValue(procpath, ATTR_EXIT_CODE, exitCode);
+ cmds.setValue(procpath, ATTR_STATE, "TERMINATED");
}
}
catch (IllegalThreadStateException e) {
@@ -178,25 +171,25 @@ class VmState {
if (description != null) {
cmds.state.trace.snapshot(description, "", null);
}
- cmds.setValue(path, "ExitCode", exitCode);
- cmds.setValue(path, TraceJdiManager.STATE_ATTRIBUTE_NAME, "TERMINATED");
+ cmds.setValue(path, ATTR_EXIT_CODE, exitCode);
+ cmds.setValue(path, ATTR_STATE, "TERMINATED");
}
}
-public class TraceJdiHooks implements JdiEventsListenerAdapter {
+public class JdiHooks implements JdiEventsListenerAdapter {
- private TraceJdiManager manager;
- private TraceJdiCommands cmds;
+ private JdiManager manager;
+ private JdiCommands cmds;
private HookState hookState;
private Map<VirtualMachine, VmState> vmStates = new HashMap<>();
- public TraceJdiHooks(TraceJdiManager manager) {
+ public JdiHooks(JdiManager manager, JdiCommands cmds) {
this.manager = manager;
- this.cmds = manager.getCommands();
+ this.cmds = cmds;
}
- private void setCommands(TraceJdiCommands commands) {
+ private void setCommands(JdiCommands commands) {
this.cmds = commands;
hookState = new HookState(commands);
}
@@ -204,17 +197,19 @@ public class TraceJdiHooks implements JdiEventsListenerAdapter {
@Override
public DebugStatus vmStarted(VMStartEvent event, JdiCause cause) {
setCommands(manager.getCommands());
- hookState.ensureBatch();
- RmiTrace trace = cmds.state.trace;
JdiManagerImpl jdi = manager.getJdi();
VirtualMachine vm = event == null ? jdi.getCurrentVM() : event.virtualMachine();
- try (RmiTransaction tx = trace.openTx("New VM " + vm.description())) {
- jdi.setCurrentVM(vm);
- jdi.addVM(vm);
+ jdi.setCurrentVM(vm);
+ jdi.addVM(vm);
+ RmiTrace trace = cmds.state.trace;
+ if (trace == null) {
+ return DebugStatus.NO_CHANGE;
+ }
+ try (RmiBatch batch = hookState.batch();
+ RmiTransaction tx = trace.openTx("New VM " + vm.description())) {
cmds.putVMs();
enableCurrentVM();
}
- hookState.endBatch();
return DebugStatus.NO_CHANGE;
}
@@ -417,12 +412,11 @@ public class TraceJdiHooks implements JdiEventsListenerAdapter {
}
VmState state = vmStates.get(vm);
state.visited.clear();
- hookState.ensureBatch();
- try (RmiTransaction tx = trace.openTx("Stopped")) {
+ try (RmiBatch batch = hookState.batch();
+ RmiTransaction tx = trace.openTx("Stopped")) {
state.recordState("Stopped");
cmds.activate(null);
}
- hookState.endBatch();
}
private void setCurrent(Event event) {
@@ -446,12 +440,11 @@ public class TraceJdiHooks implements JdiEventsListenerAdapter {
void onContinue() {
VirtualMachine currentVM = manager.getJdi().getCurrentVM();
VmState state = vmStates.get(currentVM);
- hookState.ensureBatch();
- try (RmiTransaction tx = cmds.state.trace.openTx("Continue")) {
+ try (RmiBatch batch = hookState.batch();
+ RmiTransaction tx = cmds.state.trace.openTx("Continue")) {
state.recordStateContinued(currentVM);
cmds.activate(null);
}
- hookState.endBatch();
}
public void installHooks() {
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiManager.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiManager.java
similarity index 57%
rename from Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiManager.java
rename to Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiManager.java
index eec55960f5..ce7ba8a173 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiManager.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiManager.java
@@ -21,6 +21,7 @@ import java.util.Map;
import com.sun.jdi.*;
import ghidra.app.plugin.core.debug.client.tracermi.*;
+import ghidra.app.plugin.core.debug.client.tracermi.RmiMethodRegistry.TraceMethod;
import ghidra.dbg.jdi.manager.impl.DebugStatus;
import ghidra.dbg.jdi.manager.impl.JdiManagerImpl;
import ghidra.dbg.target.schema.EnumerableTargetObjectSchema;
@@ -28,65 +29,87 @@ import ghidra.dbg.target.schema.TargetObjectSchema;
import ghidra.program.model.address.*;
import ghidra.util.Msg;
-public class TraceJdiManager {
+public class JdiManager {
private static final int STATIC_METHOD_SEPARATION = 3;
public static final long BLOCK_SIZE = 0x1000L;
public static final long DEFAULT_SECTION = 0x0000L;
- public static final String PREFIX_INVISIBLE = "_";
- public static final String DISPLAY_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "display";
- public static final String STATE_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "state";
- public static final String MODULE_NAME_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "module_name";
- public static final String ARCH_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "arch";
- public static final String DEBUGGER_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "debugger";
- public static final String OS_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "os";
- public static final String ENDIAN_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "endian";
- public static final String ACCESSIBLE_ATTRIBUTE_NAME = PREFIX_INVISIBLE + "accessible";
-
- private JdiManagerImpl manager;
- private TraceJdiArch arch;
- private TraceJdiHooks hooks;
- private TraceJdiMethods methods;
- private TraceJdiCommands commands;
-
- Map<String, Object> objectRegistry = new HashMap<>();
- Map<Object, String> reverseRegistry = new HashMap<>();
- RmiMethodRegistry remoteMethodRegistry = new RmiMethodRegistry();
- Map<Object, Boolean> scopeRegistry = new HashMap<>();
+ public static final String ATTR_DISPLAY = "_display";
+ public static final String ATTR_STATE = "_state";
+ public static final String ATTR_MODULE_NAME = "_module_name";
+ public static final String ATTR_ARCH = "_arch";
+ public static final String ATTR_DEBUGGER = "_debugger";
+ public static final String ATTR_OS = "_os";
+ public static final String ATTR_ENDIAN = "_endian";
+ public static final String ATTR_ACCESSIBLE = "_accessible";
+ public static final String ATTR_ADDRESS = "Address";
+ public static final String ATTR_ALIVE = "Alive";
+ public static final String ATTR_CLASS = "Class";
+ public static final String ATTR_COMMAND_LINE = "CommandLine";
+ public static final String ATTR_COUNT = "Count";
+ public static final String ATTR_ENABLED = "Enabled";
+ public static final String ATTR_EXECUTABLE = "Executable";
+ public static final String ATTR_EXIT_CODE = "ExitCode";
+ public static final String ATTR_INDEX = "Index";
+ public static final String ATTR_INSTANCE = "Instance";
+ public static final String ATTR_LENGTH = "Length";
+ public static final String ATTR_LINENO = "LineNo";
+ public static final String ATTR_LOCATION = "Location";
+ public static final String ATTR_NAME = "Name";
+ public static final String ATTR_PC = "PC";
+ public static final String ATTR_PLATFORM_ONLY = "PlatformOnly";
+ public static final String ATTR_RANGE = "Range";
+ public static final String ATTR_RANGE_CP = "RangeCP"; // Constant pool
+ public static final String ATTR_SIGNATURE = "Signature";
+ public static final String ATTR_THREAD = "Thread";
+ public static final String ATTR_TYPE = "Type";
+ public static final String ATTR_VALUE = "Value";
+ public static final String ATTR_EXCLUDE = "Exclude";
+ public static final String ATTR_INCLUDE = "Include";
+
+ private final JdiManagerImpl manager;
+ private final JdiArch arch;
+ private final JdiHooks hooks;
+ private final JdiMethods methods;
+ private final JdiCommands commands;
+
+ final Map<String, Object> objectRegistry = new HashMap<>();
+ final Map<Object, String> reverseRegistry = new HashMap<>();
+ final RmiMethodRegistry remoteMethodRegistry = new RmiMethodRegistry();
+ final Map<Object, Boolean> scopeRegistry = new HashMap<>();
protected final AddressSpace ram = new GenericAddressSpace("ram", 64, AddressSpace.TYPE_RAM, 0);
- protected Long ramIndex = Long.valueOf(BLOCK_SIZE);
+ protected Long ramIndex = BLOCK_SIZE;
protected final AddressSpace pool =
new GenericAddressSpace("constantPool", 64, AddressSpace.TYPE_RAM, 0);
- protected Long poolIndex = Long.valueOf(0x0L);
- public AddressRangeImpl defaultRange;
+ protected Long poolIndex = 0x0L;
+ public final AddressRangeImpl defaultRange;
- private Map<String, AddressRange> addressRangeByMethod = new HashMap<>();
- private Map<String, Method> methodsByKey = new HashMap<>();
- private Map<ReferenceType, AddressRange> addressRangeByClass = new HashMap<>();
- private Map<ReferenceType, AddressRange> cpAddressRangeByClass = new HashMap<>();
+ private final Map<String, AddressRange> addressRangeByMethod = new HashMap<>();
+ private final Map<String, Method> methodsByKey = new HashMap<>();
+ private final Map<ReferenceType, AddressRange> addressRangeByClass = new HashMap<>();
+ private final Map<ReferenceType, AddressRange> cpAddressRangeByClass = new HashMap<>();
- private Map<String, DebugStatus> returnStatusMap = new HashMap<>();
- TargetObjectSchema rootSchema;
+ private final Map<String, DebugStatus> returnStatusMap = new HashMap<>();
+ final TargetObjectSchema rootSchema;
- public TraceJdiManager(JdiManagerImpl manager, Map<String, String> env) {
+ public JdiManager(JdiManagerImpl manager, Map<String, String> env) {
this(manager);
commands.ghidraTraceConnect(env.get("GHIDRA_TRACE_RMI_ADDR"));
commands.ghidraTraceStart(env.get("OPT_TARGET_CLASS"));
}
- // NB: Needed for testing
- public TraceJdiManager(JdiManagerImpl manager) {
+ public JdiManager(JdiManagerImpl manager) {
this.manager = manager;
Address start = ram.getAddress(DEFAULT_SECTION);
defaultRange = new AddressRangeImpl(start, start.add(BLOCK_SIZE - 1));
rootSchema = RmiClient.loadSchema("jdi_schema.xml", "Debugger");
- arch = new TraceJdiArch();
- commands = new TraceJdiCommands(this); // Must precede methods/hooks
- methods = new TraceJdiMethods(this);
- hooks = new TraceJdiHooks(this);
+ arch = new JdiArch();
+ commands = new JdiCommands(this); // Must precede methods/hooks
+ methods = new JdiMethods(this, commands);
+ hooks = new JdiHooks(this, commands);
hooks.installHooks();
}
@@ -94,19 +117,19 @@ public class TraceJdiManager {
return manager;
}
- public TraceJdiArch getArch() {
+ public JdiArch getArch() {
return arch;
}
- public TraceJdiCommands getCommands() {
+ public JdiCommands getCommands() {
return commands;
}
- public TraceJdiMethods getMethods() {
+ public JdiMethods getMethods() {
return methods;
}
- public TraceJdiHooks getHooks() {
+ public JdiHooks getHooks() {
return hooks;
}
@@ -114,12 +137,11 @@ public class TraceJdiManager {
return commands.state.client;
}
- public void registerRemoteMethod(TraceJdiMethods methods, java.lang.reflect.Method m,
- String name) {
+ public void registerRemoteMethod(JdiMethods methods, java.lang.reflect.Method m, String name) {
String action = name;
String display = name;
String description = name;
- RmiMethodRegistry.TraceMethod annot = m.getAnnotation(RmiMethodRegistry.TraceMethod.class);
+ TraceMethod annot = m.getAnnotation(TraceMethod.class);
if (annot == null) {
return;
}
@@ -134,6 +156,10 @@ public class TraceJdiManager {
if (pcount < 1) {
return;
}
+ /**
+ * TODO: The return type should be reflected from the method; however, none of the parameter
+ * collection routines currently use the return type, so just use ANY for now.
+ */
TargetObjectSchema schema = EnumerableTargetObjectSchema.ANY;
RmiRemoteMethod method = new RmiRemoteMethod(rootSchema.getContext(), name, action, display,
description, schema, methods, m);
@@ -152,27 +178,33 @@ public class TraceJdiManager {
}
public AddressRange putAddressRange(ReferenceType cls, AddressSet set) {
- if (set.isEmpty()) {
- addressRangeByClass.put(cls, defaultRange);
- return defaultRange;
+ synchronized (addressRangeByClass) {
+ if (set.isEmpty()) {
+ addressRangeByClass.put(cls, defaultRange);
+ return defaultRange;
+ }
+ AddressRange range = new AddressRangeImpl(set.getMinAddress(), set.getMaxAddress());
+ addressRangeByClass.put(cls, range);
+ return range;
}
- AddressRange range = new AddressRangeImpl(set.getMinAddress(), set.getMaxAddress());
- addressRangeByClass.put(cls, range);
- return range;
}
public AddressRange getAddressRange(ReferenceType cls) {
if (cls == null) {
return defaultRange;
}
- return addressRangeByClass.get(cls);
+ synchronized (addressRangeByClass) {
+ return addressRangeByClass.get(cls);
+ }
}
public ReferenceType getReferenceTypeForAddress(Address address) {
- for (ReferenceType ref : addressRangeByClass.keySet()) {
- AddressRange range = addressRangeByClass.get(ref);
- if (range.contains(address)) {
- return ref;
+ synchronized (addressRangeByClass) {
+ for (ReferenceType ref : addressRangeByClass.keySet()) {
+ AddressRange range = addressRangeByClass.get(ref);
+ if (range.contains(address)) {
+ return ref;
+ }
}
}
return null;
@@ -182,19 +214,21 @@ public class TraceJdiManager {
if (cls == null) {
return defaultRange;
}
- AddressRange range = cpAddressRangeByClass.get(cls);
- if (range == null) {
- registerConstantPool(cls, sz);
- range = cpAddressRangeByClass.get(cls);
+ synchronized (cpAddressRangeByClass) {
+ AddressRange range = cpAddressRangeByClass.get(cls);
+ if (range == null) {
+ registerConstantPool(cls, sz);
+ range = cpAddressRangeByClass.get(cls);
+ }
+ return range;
}
- return range;
}
public void registerConstantPool(ReferenceType declaringType, int sz) {
- if (!cpAddressRangeByClass.containsKey(declaringType)) {
- if (manager.getCurrentVM().canGetConstantPool()) {
- long length = sz == 0 ? 2 : sz;
- synchronized (cpAddressRangeByClass) {
+ synchronized (cpAddressRangeByClass) {
+ if (!cpAddressRangeByClass.containsKey(declaringType)) {
+ if (manager.getCurrentVM().canGetConstantPool()) {
+ long length = sz == 0 ? 2 : sz;
Address start = pool.getAddress(poolIndex);
AddressRangeImpl range =
new AddressRangeImpl(start, start.add(length - 1));
@@ -208,10 +242,12 @@ public class TraceJdiManager {
}
public ReferenceType getReferenceTypeForPoolAddress(Address address) {
- for (ReferenceType ref : cpAddressRangeByClass.keySet()) {
- AddressRange range = cpAddressRangeByClass.get(ref);
- if (range.contains(address)) {
- return ref;
+ synchronized (cpAddressRangeByClass) {
+ for (ReferenceType ref : cpAddressRangeByClass.keySet()) {
+ AddressRange range = cpAddressRangeByClass.get(ref);
+ if (range.contains(address)) {
+ return ref;
+ }
}
}
return null;
@@ -221,21 +257,25 @@ public class TraceJdiManager {
if (method == null) {
return defaultRange;
}
- AddressRange range = addressRangeByMethod.get(methodToKey(method));
- if (range == null) {
- return defaultRange;
+ synchronized (addressRangeByMethod) {
+ AddressRange range = addressRangeByMethod.get(methodToKey(method));
+ if (range == null) {
+ return defaultRange;
+ }
+ return range;
}
- return range;
}
public Method getMethodForAddress(Address address) {
- for (String methodName : addressRangeByMethod.keySet()) {
- AddressRange range = addressRangeByMethod.get(methodName);
- if (range.contains(address)) {
- return methodsByKey.get(methodName);
+ synchronized (addressRangeByMethod) {
+ for (String methodName : addressRangeByMethod.keySet()) {
+ AddressRange range = addressRangeByMethod.get(methodName);
+ if (range.contains(address)) {
+ return methodsByKey.get(methodName);
+ }
}
+ return null;
}
- return null;
}
public Address getAddressFromLocation(Location location) {
@@ -364,5 +404,4 @@ public class TraceJdiManager {
}
}
}
-
}
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiMethods.java b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiMethods.java
similarity index 53%
rename from Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiMethods.java
rename to Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiMethods.java
index 46771fdb6a..1ed7dabdfc 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/TraceJdiMethods.java
+++ b/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/rmi/jpda/JdiMethods.java
@@ -15,6 +15,8 @@
*/
package ghidra.dbg.jdi.rmi.jpda;
+import static ghidra.dbg.jdi.rmi.jpda.JdiManager.*;
+
import java.io.IOException;
import java.util.*;
@@ -22,47 +24,36 @@ import com.sun.jdi.*;
import com.sun.jdi.request.*;
import ghidra.app.plugin.core.debug.client.tracermi.*;
-import ghidra.dbg.target.TargetMethod;
+import ghidra.app.plugin.core.debug.client.tracermi.RmiMethodRegistry.TraceMethod;
+import ghidra.dbg.target.TargetMethod.Param;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.rmi.trace.TraceRmi.MemoryState;
import ghidra.util.Msg;
-public class TraceJdiMethods implements RmiMethods {
+public class JdiMethods implements RmiMethods {
- private TraceJdiManager manager;
- private TraceJdiCommands cmds;
+ private JdiManager manager;
+ private JdiCommands cmds;
- public TraceJdiMethods(TraceJdiManager manager) {
+ public JdiMethods(JdiManager manager, JdiCommands cmds) {
this.manager = manager;
- this.cmds = manager.getCommands();
+ this.cmds = cmds;
registerMethods();
}
public void registerMethods() {
Class<?> cls = this.getClass();
for (java.lang.reflect.Method m : cls.getMethods()) {
- RmiMethodRegistry.TraceMethod annot =
- m.getAnnotation(RmiMethodRegistry.TraceMethod.class);
+ TraceMethod annot = m.getAnnotation(TraceMethod.class);
if (annot != null) {
manager.registerRemoteMethod(this, m, m.getName());
}
}
}
-// public void execute(String cmd) {
-//
-// }
-
-// public void refresh_available(Object obj) {
-//
-// }
-
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh VM",
- schema = "VirtualMachine")
- public void refresh_vm(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh VM")
+ public void refresh_vm(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshVM")) {
String path = obj.getPath();
VirtualMachine vm = (VirtualMachine) getObjectFromPath(path);
@@ -70,11 +61,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh process",
- schema = "ProcessRef")
- public void refresh_process(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh process")
+ public void refresh_process(
+ @Param(schema = "ProcessRef", name = "process") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshProcess")) {
String path = obj.getPath();
Process proc = (Process) getObjectFromPath(path);
@@ -82,11 +71,11 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh thread groups",
- schema = "ThreadGroupReferenceContainer")
- public void refresh_thread_groups(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh thread groups")
+ public void refresh_thread_groups(
+ @Param(
+ schema = "ThreadGroupReferenceContainer",
+ name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshThreadGroups")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -100,11 +89,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh thread group",
- schema = "ThreadGroupReferenceProxy")
- public void refresh_thread_group_proxy(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh thread group")
+ public void refresh_thread_group_proxy(
+ @Param(schema = "ThreadGroupReferenceProxy", name = "proxy") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshThreadGroup")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -118,11 +105,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh thread group",
- schema = "ThreadGroupReference")
- public void refresh_thread_group(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh thread group")
+ public void refresh_thread_group(
+ @Param(schema = "ThreadGroupReference", name = "group") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshThreadGroup")) {
String path = obj.getPath();
ThreadGroupReference ref = (ThreadGroupReference) getObjectFromPath(path);
@@ -130,11 +115,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh threads",
- schema = "ThreadContainer")
- public void refresh_threads(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh threads")
+ public void refresh_threads(
+ @Param(schema = "ThreadContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshThreads")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -143,11 +126,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh threads",
- schema = "ThreadReferenceContainer")
- public void refresh_threadrefs(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh threads")
+ public void refresh_threadrefs(
+ @Param(schema = "ThreadReferenceContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshThreads")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -166,11 +147,8 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh Thread",
- schema = "Thread")
- public void refresh_thread(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh thread")
+ public void refresh_thread(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshThread")) {
String path = obj.getPath();
ThreadReference ref = (ThreadReference) getObjectFromPath(path);
@@ -178,38 +156,32 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(action = "refresh", display = "Refresh Stack", schema = "Stack")
- public void refresh_stack(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh stack")
+ public void refresh_stack(@Param(schema = "Stack", name = "stack") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshStack")) {
cmds.ghidraTracePutFrames();
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh registers",
- schema = "RegisterContainer")
- public void refresh_registers(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh registers")
+ public void refresh_registers(
+ @Param(schema = "RegisterContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshRegisters")) {
cmds.ghidraTracePutFrames();
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh modules",
- schema = "ModuleReferenceContainer")
- public void refresh_modules(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh modules")
+ public void refresh_modules(
+ @Param(schema = "ModuleReferenceContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshModules")) {
cmds.putModuleReferenceContainer();
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh module",
- schema = "ModuleReference")
- public void refresh_module(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh module")
+ public void refresh_module(
+ @Param(schema = "ModuleReference", name = "module") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshModule")) {
String path = obj.getPath();
ModuleReference ref = (ModuleReference) getObjectFromPath(path);
@@ -217,11 +189,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh monitor info",
- schema = "MonitorInfoContainer")
- public void refresh_monitors(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh monitor info")
+ public void refresh_monitors(
+ @Param(schema = "MonitorInfoContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshMonitorInfo")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -233,11 +203,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh monitor info",
- schema = "MonitorInfo")
- public void refresh_monitor_info(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh monitor info")
+ public void refresh_monitor_info(
+ @Param(schema = "MonitorInfo", name = "monitor_info") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshMonitorInfo")) {
String path = obj.getPath();
MonitorInfo mi = (MonitorInfo) getObjectFromPath(path);
@@ -245,11 +213,15 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh fields",
- schema = "FieldContainer")
- public void refresh_fields(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh fields")
+ public void refresh_canonical_fields(
+ @Param(schema = "CanonicalFieldContainer", name = "container") RmiTraceObject obj) {
+ refresh_fields(obj);
+ }
+
+ @TraceMethod(action = "refresh", display = "Refresh fields")
+ public void refresh_fields(
+ @Param(schema = "FieldContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshFields")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -263,20 +235,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
-// @RmiMethodRegistry.method(action = "refresh", display = "Refresh Field", schema = "Field")
-// public void refresh_field(RmiTraceObject obj) {
-// try (RmiTransaction tx = cmds.state.trace.openTx("RefreshField")) {
-// String path = obj.getPath();
-// Field field = (Field) getObjectFromPath(path);
-// cmds.putFieldDetails(path, field);
-// }
-// }
-
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh objects",
- schema = "ObjectReferenceContainer")
- public void refresh_objects(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh objects")
+ public void refresh_objects(
+ @Param(schema = "ObjectReferenceContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshObjects")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -300,11 +261,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh object",
- schema = "ObjectReferenceProxy")
- public void refresh_object_proxy(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh object")
+ public void refresh_object_proxy(
+ @Param(schema = "ObjectReferenceProxy", name = "proxy") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshObject")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -324,11 +283,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh object",
- schema = "ObjectReference")
- public void refresh_object(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh object")
+ public void refresh_object(
+ @Param(schema = "ObjectReference", name = "object") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshInstance")) {
String path = obj.getPath();
ObjectReference method = (ObjectReference) getObjectFromPath(path);
@@ -336,11 +293,15 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh methods",
- schema = "MethodContainer")
- public void refresh_methods(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh methods")
+ public void refresh_canonical_methods(
+ @Param(schema = "CanonicalMethodContainer", name = "container") RmiTraceObject obj) {
+ refresh_methods(obj);
+ }
+
+ @TraceMethod(action = "refresh", display = "Refresh methods")
+ public void refresh_methods(
+ @Param(schema = "MethodContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshMethods")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -349,11 +310,8 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh method",
- schema = "Method")
- public void refresh_method(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh method")
+ public void refresh_method(@Param(schema = "Method", name = "method") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshMethod")) {
String path = obj.getPath();
Method method = (Method) getObjectFromPath(path);
@@ -361,11 +319,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh arguments",
- schema = "ArgumentContainer")
- public void refresh_arguments(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh arguments")
+ public void refresh_arguments(
+ @Param(schema = "ArgumentContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshArguments")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -374,12 +330,14 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "load_class",
- display = "Load class",
- schema = "ReferenceTypeContainer")
- public void find_class(RmiTraceObject obj,
- @TargetMethod.Param(
+ @TraceMethod(display = "Load class")
+ public boolean find_class(
+ @Param(
+ schema = "ReferenceTypeContainer",
+ description = "Container",
+ display = "Container",
+ name = "container") RmiTraceObject obj,
+ @Param(
description = "Class to open",
display = "Class",
name = "find") String targetClass) {
@@ -388,24 +346,34 @@ public class TraceJdiMethods implements RmiMethods {
String ppath = cmds.getParentPath(path);
Object parent = getObjectFromPath(ppath);
if (parent instanceof VirtualMachine vm) {
- cmds.loadReferenceType(path, vm.allClasses(), targetClass);
+ return cmds.loadReferenceType(path, vm.allClasses(), targetClass);
}
+ return false;
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh_memory",
- display = "Refresh memory",
- schema = "Memory")
- public void refresh_memory(RmiTraceObject obj) {
+ /**
+ * NB. Did not assign action="refresh" because this method is expensive. Assigning that action
+ * name will cause the UI to do it upon expanding the node, which we <em>do not</em> want.
+ */
+ @TraceMethod(display = "Refresh memory")
+ public void refresh_memory(@Param(schema = "Memory", name = "memory") RmiTraceObject obj) {
refresh_reference_types(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh_types",
- display = "Refresh reference types",
- schema = "ReferenceTypeContainer")
- public void refresh_reference_types(RmiTraceObject obj) {
+ @TraceMethod(display = "Refresh reference types")
+ public void refresh_canonical_reference_types(
+ @Param(schema = "CanonicalReferenceTypeContainer", name = "container") RmiTraceObject obj) {
+ refresh_reference_types(obj);
+ }
+
+ /**
+ * NB. Did not assign action="refresh" because this method is expensive. Assigning that action
+ * name will cause the UI to do it upon expanding the node, which we <em>do not</em> want.
+ */
+ @TraceMethod(display = "Refresh reference types")
+ public void refresh_reference_types(
+ @Param(schema = "ReferenceTypeContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshReferenceTypes")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -446,11 +414,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh reference type",
- schema = "ReferenceTypeProxy")
- public void refresh_reference_type_proxy(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh reference type")
+ public void refresh_reference_type_proxy(
+ @Param(schema = "ReferenceTypeProxy", name = "proxy") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshReferenceType")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -470,11 +436,15 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh reference type",
- schema = "ReferenceType")
- public void refresh_reference_type(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh reference type")
+ public void refresh_canonical_reference_type(
+ @Param(schema = "CanonicalReferenceType", name = "container") RmiTraceObject obj) {
+ refresh_reference_type(obj);
+ }
+
+ @TraceMethod(action = "refresh", display = "Refresh reference type")
+ public void refresh_reference_type(
+ @Param(schema = "ReferenceType", name = "reference_type") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshReferenceType")) {
String path = obj.getPath();
ReferenceType refType = (ReferenceType) getObjectFromPath(path);
@@ -482,11 +452,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "load",
- display = "Load reference",
- schema = "ReferenceType")
- public void load_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Load reference type")
+ public void load_reftype(
+ @Param(schema = "ReferenceType", name = "reference_type") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshReferenceType")) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
String path = obj.getPath();
@@ -496,11 +464,15 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh variables",
- schema = "VariableContainer")
- public void refresh_variables(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh variables")
+ public void refresh_canonical_variables(
+ @Param(schema = "CanonicalVariableContainer", name = "container") RmiTraceObject obj) {
+ refresh_variables(obj);
+ }
+
+ @TraceMethod(action = "refresh", display = "Refresh variables")
+ public void refresh_variables(
+ @Param(schema = "VariableContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshVariables")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -525,11 +497,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh variable",
- schema = "Variable")
- public void refresh_variable(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh variable")
+ public void refresh_variable(
+ @Param(schema = "Variable", name = "variable") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshVariable")) {
String path = obj.getPath();
Object object = getObjectFromPath(path);
@@ -539,11 +509,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh locations",
- schema = "LocationContainer")
- public void refresh_locations(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh locations")
+ public void refresh_locations(
+ @Param(schema = "LocationContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshLocations")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -559,11 +527,9 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh location",
- schema = "Location")
- public void refresh_location(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh location")
+ public void refresh_location(
+ @Param(schema = "Location", name = "location") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshLocation")) {
String path = obj.getPath();
Location loc = (Location) getObjectFromPath(path);
@@ -571,31 +537,25 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh breakpoints",
- schema = "BreakpointContainer")
- public void refresh_breakpoints(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh breakpoints")
+ public void refresh_breakpoints(
+ @Param(schema = "BreakpointContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshBreakpoints")) {
cmds.putBreakpoints();
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh events",
- schema = "EventContainer")
- public void refresh_events(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh events")
+ public void refresh_events(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshEvents")) {
cmds.putEvents();
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh values",
- schema = "ValueContainer")
- public void refresh_values(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh values")
+ public void refresh_values(
+ @Param(schema = "ValueContainer", name = "container") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshValues")) {
String path = obj.getPath();
String ppath = cmds.getParentPath(path);
@@ -606,11 +566,8 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "refresh",
- display = "Refresh value",
- schema = "Value")
- public void refresh_value(RmiTraceObject obj) {
+ @TraceMethod(action = "refresh", display = "Refresh value")
+ public void refresh_value(@Param(schema = "Value", name = "value") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshLocation")) {
String path = obj.getPath();
Value val = (Value) getObjectFromPath(path);
@@ -618,11 +575,17 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "set",
- display = "Set value",
- schema = "Variable")
- public void set_value_lvar(RmiTraceObject obj, String value) {
+ @TraceMethod(display = "Set value")
+ public void set_value_lvar(
+ @Param(
+ schema = "Variable",
+ description = "Variable",
+ display = "Variable",
+ name = "variable") RmiTraceObject obj,
+ @Param(
+ description = "Value",
+ display = "Value",
+ name = "value") String value) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshLocation")) {
String path = obj.getPath();
LocalVariable lvar = (LocalVariable) getObjectFromPath(path);
@@ -630,11 +593,17 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "set",
- display = "Set value",
- schema = "Field")
- public void set_value_field(RmiTraceObject obj, String value) {
+ @TraceMethod(display = "Set value")
+ public void set_value_field(
+ @Param(
+ schema = "Field",
+ description = "Field",
+ display = "Field",
+ name = "field") RmiTraceObject obj,
+ @Param(
+ description = "Value",
+ display = "Value",
+ name = "value") String value) {
try (RmiTransaction tx = cmds.state.trace.openTx("RefreshLocation")) {
String path = obj.getPath();
Field field = (Field) getObjectFromPath(path);
@@ -642,16 +611,18 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(action = "activate", display = "Activate", schema = "ANY")
- public void activate(RmiTraceObject obj) {
+ @TraceMethod(action = "activate", display = "Activate")
+ public void activate(@Param(schema = "OBJECT", name = "object") RmiTraceObject obj) {
try (RmiTransaction tx = cmds.state.trace.openTx("Activate")) {
String path = obj.getPath();
cmds.activate(path);
}
}
- @RmiMethodRegistry.TraceMethod(action = "kill", display = "Kill", schema = "VirtualMachine")
- public void kill(RmiTraceObject obj) {
+ @TraceMethod(action = "kill", display = "Terminate")
+ public void kill(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
+ VirtualMachine vm = (VirtualMachine) getObjectFromPath(obj.getPath());
+ vm.exit(143);
try {
manager.getJdi().sendInterruptNow();
}
@@ -660,52 +631,40 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(action = "resume", display = "Resume", schema = "VirtualMachine")
- public void resume_vm(RmiTraceObject obj) {
+ @TraceMethod(action = "resume", display = "Resume")
+ public void resume_vm(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
VirtualMachine vm = (VirtualMachine) getObjectFromPath(obj.getPath());
vm.resume();
manager.getHooks().setState(vm);
}
- @RmiMethodRegistry.TraceMethod(action = "resume", display = "Resume", schema = "Thread")
- public void resume(RmiTraceObject obj) {
+ @TraceMethod(action = "resume", display = "Resume")
+ public void resume_thread(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
ThreadReference thread = (ThreadReference) getObjectFromPath(obj.getPath());
thread.resume();
manager.getHooks().setState(thread.virtualMachine());
}
- @RmiMethodRegistry.TraceMethod(
- action = "suspend",
- display = "Suspend",
- schema = "VirtualMachine")
- public void suspend(RmiTraceObject obj) {
- Object object = getObjectFromPath(obj.getPath());
- if (object instanceof ThreadReference thread) {
- thread.suspend();
- manager.getHooks().setState(thread.virtualMachine());
- }
- else {
- VirtualMachine vm = manager.getJdi().getCurrentVM();
- vm.suspend();
- manager.getHooks().setState(vm);
- }
+ @TraceMethod(action = "interrupt", display = "Suspend")
+ public void suspend_vm(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
+ VirtualMachine vm = (VirtualMachine) getObjectFromPath(obj.getPath());
+ vm.suspend();
+ manager.getHooks().setState(vm);
}
- @RmiMethodRegistry.TraceMethod(
- action = "interrupt",
- display = "Interrupt",
- schema = "VirtualMachine")
- public void interrupt(RmiTraceObject obj) {
- suspend(obj);
+ @TraceMethod(action = "interrupt", display = "Suspend")
+ public void suspend_thread(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
+ ThreadReference thread = (ThreadReference) getObjectFromPath(obj.getPath());
+ thread.suspend();
+ manager.getHooks().setState(thread.virtualMachine());
}
- // NB: For the VirtualMachine, the step methods add requests for break-on-step for all threads.
- // These requests will remain pending until the VM is resumed.
- @RmiMethodRegistry.TraceMethod(
- action = "step_into",
- display = "Step into",
- schema = "VirtualMachine")
- public void step_vm_into(RmiTraceObject obj) {
+ /**
+ * NB: For the VirtualMachine, the step methods add requests for break-on-step for all threads.
+ * These requests will remain pending until the VM is resumed.
+ */
+ @TraceMethod(action = "step_into", display = "Step into")
+ public void step_vm_into(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
List<ThreadReference> threads = getThreadsFromValue(obj);
for (ThreadReference thread : threads) {
@@ -722,11 +681,8 @@ public class TraceJdiMethods implements RmiMethods {
vm.resume();
}
- @RmiMethodRegistry.TraceMethod(
- action = "step_over",
- display = "Step over",
- schema = "VirtualMachine")
- public void step_vm_over(RmiTraceObject obj) {
+ @TraceMethod(action = "step_over", display = "Step over")
+ public void step_vm_over(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
List<ThreadReference> threads = getThreadsFromValue(obj);
for (ThreadReference thread : threads) {
@@ -743,11 +699,8 @@ public class TraceJdiMethods implements RmiMethods {
vm.resume();
}
- @RmiMethodRegistry.TraceMethod(
- action = "step_out",
- display = "Step out",
- schema = "VirtualMachine")
- public void step_vm_out(RmiTraceObject obj) {
+ @TraceMethod(action = "step_out", display = "Step out")
+ public void step_vm_out(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
List<ThreadReference> threads = getThreadsFromValue(obj);
for (ThreadReference thread : threads) {
@@ -764,8 +717,8 @@ public class TraceJdiMethods implements RmiMethods {
vm.resume();
}
- @RmiMethodRegistry.TraceMethod(action = "step_into", display = "Step into", schema = "Thread")
- public void step_into(RmiTraceObject obj) {
+ @TraceMethod(action = "step_into", display = "Step into")
+ public void step_into(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
ThreadReference thread = (ThreadReference) getObjectFromPath(obj.getPath());
StepRequest stepReq = vm.eventRequestManager()
@@ -775,36 +728,30 @@ public class TraceJdiMethods implements RmiMethods {
vm.resume();
}
- @RmiMethodRegistry.TraceMethod(action = "step_over", display = "Step over", schema = "Thread")
- public void step_over(RmiTraceObject obj) {
+ @TraceMethod(action = "step_over", display = "Step over")
+ public void step_over(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
ThreadReference thread = (ThreadReference) getObjectFromPath(obj.getPath());
StepRequest stepReq = vm.eventRequestManager()
- .createStepRequest(thread, StepRequest.STEP_OVER,
- StepRequest.STEP_INTO);
+ .createStepRequest(thread, StepRequest.STEP_MIN,
+ StepRequest.STEP_OVER);
stepReq.enable();
vm.resume();
}
- @RmiMethodRegistry.TraceMethod(action = "step_out", display = "Step out", schema = "Thread")
- public void step_out(RmiTraceObject obj) {
+ @TraceMethod(action = "step_out", display = "Step out")
+ public void step_out(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
ThreadReference thread = (ThreadReference) getObjectFromPath(obj.getPath());
StepRequest stepReq = vm.eventRequestManager()
- .createStepRequest(thread, StepRequest.STEP_OUT,
- StepRequest.STEP_INTO);
+ .createStepRequest(thread, StepRequest.STEP_MIN,
+ StepRequest.STEP_OUT);
stepReq.enable();
vm.resume();
}
-// public void step_advance(Object obj) {}
-// public void step_return(Object obj) {}
-
- @RmiMethodRegistry.TraceMethod(
- action = "thread_interrupt",
- display = "Thread Interrupt",
- schema = "Thread")
- public void thread_interrupt(RmiTraceObject obj) {
+ @TraceMethod(display = "Thread Interrupt")
+ public void thread_interrupt(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
Object object = getObjectFromPath(obj.getPath());
if (object instanceof ThreadReference thread) {
thread.interrupt();
@@ -812,11 +759,8 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "pop_stack",
- display = "Pop stack",
- schema = "StackFrame")
- public void pop_stack(RmiTraceObject obj) {
+ @TraceMethod(action = "step_ext", display = "Pop stack")
+ public void pop_stack(@Param(schema = "StackFrame", name = "frame") RmiTraceObject obj) {
StackFrame frame = (StackFrame) getObjectFromPath(obj.getPath());
ThreadReference thread = frame.thread();
try {
@@ -827,11 +771,8 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_location",
- display = "Break on execute",
- schema = "Location")
- public void break_location(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on execute")
+ public void break_location(@Param(schema = "Location", name = "location") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof Location loc) {
@@ -842,11 +783,8 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_field_access",
- display = "Break on access",
- schema = "Field")
- public void break_access(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on access")
+ public void break_access(@Param(schema = "Field", name = "field") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof Field field) {
@@ -857,11 +795,8 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_field_modified",
- display = "Break on modify",
- schema = "Field")
- public void break_modify(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on modify")
+ public void break_modify(@Param(schema = "Field", name = "field") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof Field field) {
@@ -872,19 +807,21 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_exception",
- display = "Break on exception",
- schema = "ReferenceType")
- public void break_exception(RmiTraceObject obj,
- @TargetMethod.Param(
+ @TraceMethod(display = "Break on exception")
+ public void break_exception(
+ @Param(
+ schema = "ReferenceType",
+ description = "Reference Type (Class)",
+ display = "Type",
+ name = "reference_type") RmiTraceObject obj,
+ @Param(
description = "Caught exceptions will be notified",
display = "NotifyCaught",
- name = "notifyC") Boolean notifyCaught,
- @TargetMethod.Param(
+ name = "notify_caught") boolean notifyCaught,
+ @Param(
description = "Uncaught exceptions will be notified",
display = "NotifyUncaught",
- name = "notifyU") Boolean notifyUncaught) {
+ name = "notify_uncaught") boolean notifyUncaught) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof ReferenceType reftype) {
@@ -908,19 +845,15 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_started",
- display = "Break on thread start",
- schema = "EventContainer")
- public void break_started_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on thread start")
+ public void break_started_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_started(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_started",
- display = "Break on thread start",
- schema = "Thread")
- public void break_started_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on thread start")
+ public void break_started_thread(
+ @Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_started(obj);
}
@@ -937,27 +870,19 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_death",
- display = "Break on thread exit",
- schema = "EventContainer")
- public void break_death_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on thread exit")
+ public void break_death_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_death(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_death",
- display = "Break on thread exit",
- schema = "Thread")
- public void break_death_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on thread exit")
+ public void break_death_thread(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_death(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_vm_death",
- display = "Break on VM death",
- schema = "VirtualMachine")
- public void break_vm_death(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on VM death")
+ public void break_vm_death(@Param(schema = "VirtualMachine", name = "vm") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
VMDeathRequest brkReq = vm.eventRequestManager()
.createVMDeathRequest();
@@ -986,35 +911,26 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_enter",
- display = "Break on method enter",
- schema = "EventContainer")
- public void break_enter_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method enter")
+ public void break_enter_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_enter(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_enter",
- display = "Break on method enter",
- schema = "ReferenceType")
- public void break_enter_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method enter")
+ public void break_enter_reftype(
+ @Param(schema = "ReferenceType", name = "class") RmiTraceObject obj) {
break_enter(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_enter_instance",
- display = "Break on method enter",
- schema = "ObjectReference")
- public void break_enter_instance(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method enter")
+ public void break_enter_instance(
+ @Param(schema = "ObjectReference", name = "instance") RmiTraceObject obj) {
break_enter(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_enter_thread",
- display = "Break on method enter",
- schema = "Thread")
- public void break_enter_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method enter")
+ public void break_enter_thread(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_enter(obj);
}
@@ -1039,35 +955,26 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_exit",
- display = "Break on method exit",
- schema = "EventContainer")
- public void break_exit_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method exit")
+ public void break_exit_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_exit(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_exit",
- display = "Break on method exit",
- schema = "ReferenceType")
- public void break_exit_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method exit")
+ public void break_exit_reftype(
+ @Param(schema = "ReferenceType", name = "class") RmiTraceObject obj) {
break_exit(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_exit",
- display = "Break on method exit",
- schema = "ObjectReference")
- public void break_exit_instance(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method exit")
+ public void break_exit_instance(
+ @Param(schema = "ObjectReference", name = "instance") RmiTraceObject obj) {
break_exit(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_exit",
- display = "Break on method exit",
- schema = "Thread")
- public void break_exit_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on method exit")
+ public void break_exit_thread(@Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_exit(obj);
}
@@ -1084,19 +991,15 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_load",
- display = "Break on class load",
- schema = "EventContainer")
- public void break_load_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on class load")
+ public void break_load_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_load(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_load",
- display = "Break on class load",
- schema = "ReferenceType")
- public void break_load_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on class load")
+ public void break_load_reftype(
+ @Param(schema = "ReferenceType", name = "class") RmiTraceObject obj) {
break_load(obj);
}
@@ -1108,11 +1011,9 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_unload",
- display = "Break on class unload",
- schema = "EventContainer")
- public void break_unload_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on class unload")
+ public void break_unload_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_unload(obj);
}
@@ -1137,35 +1038,27 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_enter_contention",
- display = "Break on monitor contended enter",
- schema = "EventContainer")
- public void break_mon_enter_contention_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contended enter")
+ public void break_mon_enter_contention_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_mon_enter_contention(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_enter_contention",
- display = "Break on monitor contended enter",
- schema = "ReferenceType")
- public void break_mon_enter_contention_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contended enter")
+ public void break_mon_enter_contention_reftype(
+ @Param(schema = "ReferenceType", name = "class") RmiTraceObject obj) {
break_mon_enter_contention(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_enter_contention",
- display = "Break on monitor contended enter",
- schema = "ObjectReference")
- public void break_mon_enter_contention_instance(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contended enter")
+ public void break_mon_enter_contention_instance(
+ @Param(schema = "ObjectReference", name = "instance") RmiTraceObject obj) {
break_mon_enter_contention(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_enter_contention",
- display = "Break on monitor contended enter",
- schema = "Thread")
- public void break_mon_enter_contention_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contended enter")
+ public void break_mon_enter_contention_thread(
+ @Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_mon_enter_contention(obj);
}
@@ -1190,35 +1083,27 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_entered_contention",
- display = "Break on monitor contented entered",
- schema = "EventContainer")
- public void break_mon_entered_contention_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contented entered")
+ public void break_mon_entered_contention_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_mon_entered_contention(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_entered_contention",
- display = "Break on monitor contented entered",
- schema = "ReferenceType")
- public void break_mon_entered_contention_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contented entered")
+ public void break_mon_entered_contention_reftype(
+ @Param(schema = "ReferenceType", name = "class") RmiTraceObject obj) {
break_mon_entered_contention(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_entered_contention",
- display = "Break on monitor contented entered",
- schema = "ObjectReference")
- public void break_mon_entered_contention_instance(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contented entered")
+ public void break_mon_entered_contention_instance(
+ @Param(schema = "ObjectReference", name = "instance") RmiTraceObject obj) {
break_mon_entered_contention(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_entered_contention",
- display = "Break on monitor contented entered",
- schema = "Thread")
- public void break_mon_entered_contention_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor contented entered")
+ public void break_mon_entered_contention_thread(
+ @Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_mon_entered_contention(obj);
}
@@ -1243,35 +1128,27 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_wait",
- display = "Break on monitor wait",
- schema = "EventContainer")
- public void break_mon_wait_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor wait")
+ public void break_mon_wait_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_mon_wait(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_wait",
- display = "Break on monitor wait",
- schema = "ReferenceType")
- public void break_mon_wait_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor wait")
+ public void break_mon_wait_reftype(
+ @Param(schema = "ReferenceType", name = "class") RmiTraceObject obj) {
break_mon_wait(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_wait",
- display = "Break on monitor wait",
- schema = "ObjectReference")
- public void break_mon_wait_instance(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor wait")
+ public void break_mon_wait_instance(
+ @Param(schema = "ObjectReference", name = "instance") RmiTraceObject obj) {
break_mon_wait(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_wait",
- display = "Break on monitor wait",
- schema = "Thread")
- public void break_mon_wait_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor wait")
+ public void break_mon_wait_thread(
+ @Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_mon_wait(obj);
}
@@ -1296,47 +1173,41 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_waited",
- display = "Break on monitor waited",
- schema = "EventContainer")
- public void break_mon_waited_container(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor waited")
+ public void break_mon_waited_container(
+ @Param(schema = "EventContainer", name = "container") RmiTraceObject obj) {
break_mon_waited(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_waited",
- display = "Break on monitor waited",
- schema = "ReferenceType")
- public void break_mon_waited_reftype(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor waited")
+ public void break_mon_waited_reftype(
+ @Param(schema = "ReferenceType", name = "class") RmiTraceObject obj) {
break_mon_waited(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_waited",
- display = "Break on monitor waited",
- schema = "ObjectReference")
- public void break_mon_waited_instance(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor waited")
+ public void break_mon_waited_instance(
+ @Param(schema = "ObjectReference", name = "instance") RmiTraceObject obj) {
break_mon_waited(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "break_mon_waited",
- display = "Break on monitor waited",
- schema = "Thread")
- public void break_mon_waited_thread(RmiTraceObject obj) {
+ @TraceMethod(display = "Break on monitor waited")
+ public void break_mon_waited_thread(
+ @Param(schema = "Thread", name = "thread") RmiTraceObject obj) {
break_mon_waited(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "add_count_filter",
- display = "Add count filter",
- schema = "Event")
- public void add_count_filter(RmiTraceObject obj,
- @TargetMethod.Param(
+ @TraceMethod(display = "Add count filter")
+ public void add_count_filter(
+ @Param(
+ schema = "Event",
+ description = "Event",
+ display = "Event",
+ name = "event") RmiTraceObject obj,
+ @Param(
description = "Count",
display = "MaxCount",
- name = "count") Integer count) {
+ name = "count") int count) {
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof EventRequest req) {
req.disable();
@@ -1347,128 +1218,132 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "set_class_filter",
- display = "Set class filter",
- schema = "Event")
- public void set_class_filter(RmiTraceObject obj,
- @TargetMethod.Param(
+ @TraceMethod(display = "Set class filter")
+ public void set_class_filter(
+ @Param(
+ schema = "Event",
+ description = "Event",
+ display = "Event",
+ name = "event") RmiTraceObject obj,
+ @Param(
description = "Filter Pattern",
display = "Filter",
name = "filter") String filter,
- @TargetMethod.Param(
+ @Param(
description = "Exclude",
display = "Exclude",
- name = "exclude") String exclude) {
+ name = "exclude") boolean exclude) {
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof MethodEntryRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
if (ctxt instanceof MethodExitRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
if (ctxt instanceof ClassPrepareRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
if (ctxt instanceof ClassUnloadRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
if (ctxt instanceof MonitorContendedEnterRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
if (ctxt instanceof MonitorContendedEnteredRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
if (ctxt instanceof MonitorWaitRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
if (ctxt instanceof MonitorWaitedRequest req) {
req.disable();
- if (exclude.equals("true")) {
+ if (exclude) {
req.addClassExclusionFilter(filter);
- cmds.setValue(obj.getPath(), "Exclude", filter);
+ cmds.setValue(obj.getPath(), ATTR_EXCLUDE, filter);
}
else {
req.addClassFilter(filter);
- cmds.setValue(obj.getPath(), "Include", filter);
+ cmds.setValue(obj.getPath(), ATTR_INCLUDE, filter);
}
req.enable();
}
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "set_source_filter",
- display = "Set source filter",
- schema = "Event")
- public void set_source_filter(RmiTraceObject obj,
- @TargetMethod.Param(
+ @TraceMethod(display = "Set source filter")
+ public void set_source_filter(
+ @Param(
+ schema = "Event",
+ description = "Event",
+ display = "Event",
+ name = "event") RmiTraceObject obj,
+ @Param(
description = "Source Name Pattern",
display = "SourceName",
- name = "srcname") String srcname) {
+ name = "source_name") String srcname) {
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof ClassPrepareRequest req) {
req.disable();
@@ -1479,32 +1354,27 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "set_platform_filter",
- display = "Set platform filter",
- schema = "Event")
- public void set_platform_filter(RmiTraceObject obj) {
+ @TraceMethod(display = "Set platform filter")
+ public void set_platform_filter(@Param(schema = "Event", name = "event") RmiTraceObject obj) {
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof ThreadStartRequest req) {
req.disable();
req.addPlatformThreadsOnlyFilter();
- cmds.setValue(obj.getPath(), "PlatformOnly", true);
+ cmds.setValue(obj.getPath(), ATTR_PLATFORM_ONLY, true);
req.enable();
}
if (ctxt instanceof ThreadDeathRequest req) {
req.disable();
req.addPlatformThreadsOnlyFilter();
- cmds.setValue(obj.getPath(), "PlatformOnly", true);
+ cmds.setValue(obj.getPath(), ATTR_PLATFORM_ONLY, true);
req.enable();
}
cmds.putEvents();
}
- @RmiMethodRegistry.TraceMethod(
- action = "toggle_breakpoint",
- display = "Toggle breakpoint",
- schema = "BreakpointSpec")
- public void toggle_breakpoint(RmiTraceObject obj) {
+ @TraceMethod(action = "toggle", display = "Toggle breakpoint")
+ public void toggle_breakpoint(
+ @Param(schema = "BreakpointSpec", name = "breakpoint") RmiTraceObject obj) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof Field field) {
@@ -1523,11 +1393,19 @@ public class TraceJdiMethods implements RmiMethods {
cmds.putBreakpoints();
}
- @RmiMethodRegistry.TraceMethod(
- action = "toggle_event",
- display = "Toggle event",
- schema = "Event")
- public void toggle_event(RmiTraceObject obj) {
+ @TraceMethod(action = "delete", display = "Delete breakpoint")
+ public void delete_breakpoint(
+ @Param(schema = "BreakpointSpec", name = "breakpoint") RmiTraceObject obj) {
+ VirtualMachine vm = manager.getJdi().getCurrentVM();
+ Object ctxt = getObjectFromPath(obj.getPath());
+ if (ctxt instanceof EventRequest req) {
+ vm.eventRequestManager().deleteEventRequest(req);
+ }
+ cmds.putBreakpoints();
+ }
+
+ @TraceMethod(action = "toggle", display = "Toggle event")
+ public void toggle_event(@Param(schema = "Event", name = "event") RmiTraceObject obj) {
Object ctxt = getObjectFromPath(obj.getPath());
if (ctxt instanceof EventRequest req) {
if (req.isEnabled()) {
@@ -1540,22 +1418,28 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(
- action = "toggle_scope",
- display = "Toggle scope",
- schema = "MethodContainer")
- public void toggle_scope_methods(RmiTraceObject obj) {
+ @TraceMethod(action = "delete", display = "Delete Event")
+ public void delete_event(@Param(schema = "Event", name = "event") RmiTraceObject obj) {
+ VirtualMachine vm = manager.getJdi().getCurrentVM();
+ Object ctxt = getObjectFromPath(obj.getPath());
+ if (ctxt instanceof EventRequest req) {
+ vm.eventRequestManager().deleteEventRequest(req);
+ }
+ cmds.putEvents();
+ }
+
+ @TraceMethod(action = "toggle", display = "Toggle scope")
+ public void toggle_scope_methods(
+ @Param(schema = "MethodContainer", name = "container") RmiTraceObject obj) {
String ppath = cmds.getParentPath(obj.getPath());
Object parent = getObjectFromPath(ppath);
manager.toggleScope(parent);
refresh_methods(obj);
}
- @RmiMethodRegistry.TraceMethod(
- action = "toggle_scope",
- display = "Toggle scope",
- schema = "FieldContainer")
- public void toggle_scope_fields(RmiTraceObject obj) {
+ @TraceMethod(action = "toggle", display = "Toggle scope")
+ public void toggle_scope_fields(
+ @Param(schema = "FieldContainer", name = "container") RmiTraceObject obj) {
String ppath = cmds.getParentPath(obj.getPath());
Object parent = getObjectFromPath(ppath);
manager.toggleScope(parent);
@@ -1567,8 +1451,17 @@ public class TraceJdiMethods implements RmiMethods {
}
}
- @RmiMethodRegistry.TraceMethod(action = "read_mem", display = "", schema = "VirtualMachine")
- public long read_mem(RmiTraceObject obj, AddressRange range) {
+ @TraceMethod(action = "read_mem", display = "Read Memory")
+ public long read_mem(
+ @Param(
+ schema = "VirtualMachine",
+ description = "VirtualMachine",
+ display = "VirtualMachine",
+ name = "vm") RmiTraceObject obj,
+ @Param(
+ description = "Range",
+ display = "Range",
+ name = "range") AddressRange range) {
VirtualMachine vm = manager.getJdi().getCurrentVM();
MemoryMapper mapper = cmds.state.trace.memoryMapper;
Address start = mapper.mapBack(range.getMinAddress());
@@ -1582,6 +1475,127 @@ public class TraceJdiMethods implements RmiMethods {
return range.getLength();
}
+ @TraceMethod(display = "Invoke method (no args)")
+ public void execute_on_instance(
+ @Param(
+ schema = "ObjectReference",
+ description = "Object Reference",
+ display = "Object",
+ name = "object") RmiTraceObject obj,
+ @Param(
+ description = "Thread Name",
+ display = "ThreadName",
+ name = "thread_name") String threadName,
+ @Param(
+ description = "Method Name",
+ display = "MethodName",
+ name = "method_name") String methodName) {
+ VirtualMachine vm = manager.getJdi().getCurrentVM();
+ ObjectReference ref = (ObjectReference) getObjectFromPath(obj.getPath());
+ List<Method> methods = ref.referenceType().methodsByName(methodName);
+ if (methods.size() > 1) {
+ Msg.warn(this, "Method " + methodName + " is not unique - using first variant");
+ }
+ for (ThreadReference thread : vm.allThreads()) {
+ if (thread.name().equals(threadName)) {
+ cmds.execute(ref, thread, methods.get(0), new ArrayList<Value>(), 0);
+ }
+ }
+ }
+
+ @TraceMethod(display = "Invoke static method (no args)")
+ public void execute_on_class(
+ @Param(
+ schema = "ReferenceType",
+ description = "Class",
+ display = "Class",
+ name = "class") RmiTraceObject obj,
+ @Param(
+ description = "Thread Name",
+ display = "ThreadName",
+ name = "thread_name") String threadName,
+ @Param(
+ description = "Method Name",
+ display = "MethodName",
+ name = "method_name") String methodName) {
+ VirtualMachine vm = manager.getJdi().getCurrentVM();
+ ReferenceType reftype = (ReferenceType) getObjectFromPath(obj.getPath());
+ if (reftype instanceof ClassType cls) {
+ List<Method> methods = cls.methodsByName(methodName);
+ if (methods.size() > 1) {
+ Msg.warn(this, "Method " + methodName + " is not unique - using first variant");
+ }
+ if (!methods.get(0).isStatic()) {
+ Msg.error(this, "Method " + methodName + " is not static");
+ return;
+ }
+ for (ThreadReference thread : vm.allThreads()) {
+ if (thread.name().equals(threadName)) {
+ cmds.execute(cls, thread, methods.get(0), new ArrayList<Value>(), 0);
+ }
+ }
+ }
+ }
+
+ @TraceMethod(display = "Invoke method (no args)")
+ public void execute_method(
+ @Param(
+ schema = "Method",
+ description = "Method",
+ display = "Method",
+ name = "method") RmiTraceObject obj,
+ @Param(
+ description = "Instance Pattern",
+ display = "InstancePattern",
+ name = "instance_pattern") String instancePattern,
+ @Param(
+ description = "Thread Name",
+ display = "ThreadName",
+ name = "thread_name") String threadName) {
+ VirtualMachine vm = manager.getJdi().getCurrentVM();
+ String path = obj.getPath();
+ Method method = (Method) getObjectFromPath(path);
+ ReferenceType declaringType = method.declaringType();
+ List<ObjectReference> instances = declaringType.instances(0);
+ for (ObjectReference ref : instances) {
+ if (ref.toString().contains(instancePattern)) {
+ for (ThreadReference thread : vm.allThreads()) {
+ if (thread.name().equals(threadName)) {
+ cmds.execute(ref, thread, method, new ArrayList<Value>(), 0);
+ }
+ }
+ }
+ }
+ }
+
+ @TraceMethod(display = "Invoke static method (no args)")
+ public void execute_static_method(
+ @Param(
+ schema = "Method",
+ description = "Method",
+ display = "Method",
+ name = "method") RmiTraceObject obj,
+ @Param(
+ description = "Thread Name",
+ display = "ThreadName",
+ name = "thread_name") String threadName) {
+ VirtualMachine vm = manager.getJdi().getCurrentVM();
+ String path = obj.getPath();
+ Method method = (Method) getObjectFromPath(path);
+ if (!method.isStatic()) {
+ Msg.error(this, "Method " + method.name() + " is not static");
+ return;
+ }
+ ReferenceType reftype = method.declaringType();
+ if (reftype instanceof ClassType ct) {
+ for (ThreadReference thread : vm.allThreads()) {
+ if (thread.name().equals(threadName)) {
+ cmds.execute(ct, thread, method, new ArrayList<Value>(), 0);
+ }
+ }
+ }
+ }
+
private List<ThreadReference> getThreadsFromValue(RmiTraceObject obj) {
Object object = getObjectFromPath(obj.getPath());
if (object instanceof VirtualMachine vm) {
diff --git a/Ghidra/Debug/Debugger-jpda/src/main/resources/ghidra/app/plugin/core/debug/client/tracermi/jdi_schema.xml b/Ghidra/Debug/Debugger-jpda/src/main/resources/ghidra/app/plugin/core/debug/client/tracermi/jdi_schema.xml
index 14b0cee484..b17969eb38 100644
--- a/Ghidra/Debug/Debugger-jpda/src/main/resources/ghidra/app/plugin/core/debug/client/tracermi/jdi_schema.xml
+++ b/Ghidra/Debug/Debugger-jpda/src/main/resources/ghidra/app/plugin/core/debug/client/tracermi/jdi_schema.xml
@@ -162,7 +162,7 @@
<attribute name="Threads" schema="ThreadContainer" required="yes" fixed="yes" />
<attribute name="Breakpoints" schema="BreakpointContainer" required="yes" fixed="yes" />
<attribute name="Events" schema="EventContainer" required="yes" fixed="yes" />
- <attribute name="Classes" schema="ReferenceTypeContainer" required="yes" fixed="yes" />
+ <attribute name="Classes" schema="CanonicalReferenceTypeContainer" required="yes" fixed="yes" />
<attribute name="Memory" schema="Memory" required="yes" fixed="yes" />
<attribute name="ModuleRefs" schema="ModuleReferenceContainer" required="yes" fixed="yes" />
<attribute schema="ANY" />
@@ -361,7 +361,7 @@
<attribute name="_order" schema="INT" hidden="yes" />
<attribute schema="ANY" />
</schema>
- <schema name="Event" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <schema name="Event" elementResync="NEVER" attributeResync="NEVER">
<interface name="Deletable" />
<element schema="OBJECT" />
<attribute name="_enabled" schema="BOOL" required="yes" hidden="yes" />
@@ -483,13 +483,32 @@
<attribute name="Virtual" schema="OBJECT" />
<attribute schema="ANY" />
</schema>
- <schema name="ReferenceTypeContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <schema name="CanonicalReferenceTypeContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <element schema="CanonicalReferenceType" />
+ <attribute schema="ANY" />
+ </schema>
+ <schema name="ReferenceTypeContainer" canonical="no" elementResync="NEVER" attributeResync="NEVER">
<element schema="ReferenceType" />
<attribute schema="ANY" />
</schema>
<schema name="ReferenceTypeProxy" elementResync="NEVER" attributeResync="NEVER">
<element schema="ReferenceType" />
</schema>
+ <schema name="CanonicalReferenceType" elementResync="NEVER" attributeResync="ALWAYS">
+ <interface name="Module" />
+ <interface name="Aggregate" />
+ <element schema="ANY" />
+ <attribute name="Fields" schema="CanonicalFieldContainer" fixed="yes" />
+ <attribute name="Instances" schema="ObjectReferenceContainer" fixed="yes" />
+ <attribute name="Locations" schema="LocationContainer" fixed="yes" />
+ <attribute name="Methods" schema="CanonicalMethodContainer" required="no" fixed="yes" />
+ <attribute name="Relations" schema="ReferenceTypeRelations" required="no" fixed="yes" />
+ <attribute name="_module_name" schema="STRING" hidden="yes" />
+ <attribute name="Range" schema="RANGE" />
+ <attribute name="RangeCP" schema="RANGE" />
+ <attribute-alias from="_range" to="Range" />
+ <attribute schema="ANY" />
+ </schema>
<schema name="ReferenceType" elementResync="NEVER" attributeResync="ALWAYS">
<interface name="Module" />
<interface name="Aggregate" />
@@ -519,7 +538,11 @@
<attribute name="SuperInterfaces" schema="ReferenceTypeContainer" fixed="yes" />
<attribute schema="ANY" />
</schema>
- <schema name="FieldContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <schema name="CanonicalFieldContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <element schema="Field" />
+ <attribute schema="ANY" />
+ </schema>
+ <schema name="FieldContainer" canonical="no" elementResync="NEVER" attributeResync="NEVER">
<element schema="Field" />
<attribute schema="ANY" />
</schema>
@@ -529,7 +552,12 @@
<attribute name="Value" schema="Value" required="no" />
<attribute schema="ANY" />
</schema>
- <schema name="MethodContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <schema name="CanonicalMethodContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <interface name="SectionContainer" />
+ <element schema="Method" />
+ <attribute schema="ANY" />
+ </schema>
+ <schema name="MethodContainer" canonical="no" elementResync="NEVER" attributeResync="NEVER">
<interface name="SectionContainer" />
<element schema="Method" />
<attribute schema="ANY" />
@@ -547,7 +575,7 @@
<attribute name="Locations" schema="LocationContainer" fixed="yes" />
<attribute name="Range" schema="RANGE" />
<attribute-alias from="_range" to="Range" />
- <attribute name="Variables" schema="VariableContainer" fixed="yes" />
+ <attribute name="Variables" schema="CanonicalVariableContainer" fixed="yes" />
<attribute name="_display" schema="STRING" fixed="yes" hidden="yes" />
<attribute name="_return_type" schema="TYPE" fixed="yes" hidden="yes" />
<attribute name="_parameters" schema="MAP_PARAMETERS" fixed="yes" hidden="yes" />
@@ -557,7 +585,11 @@
<element schema="Type" />
<attribute schema="ANY" />
</schema>
- <schema name="VariableContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <schema name="CanonicalVariableContainer" canonical="yes" elementResync="NEVER" attributeResync="NEVER">
+ <element schema="Variable" />
+ <attribute schema="ANY" />
+ </schema>
+ <schema name="VariableContainer" canonical="no" elementResync="NEVER" attributeResync="NEVER">
<element schema="Variable" />
<attribute schema="ANY" />
</schema>
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/help/help/topics/TraceRmiLauncherServicePlugin/TraceRmiLauncherServicePlugin.html b/Ghidra/Debug/Debugger-rmi-trace/src/main/help/help/topics/TraceRmiLauncherServicePlugin/TraceRmiLauncherServicePlugin.html
index 7ca467ef03..6dd087a1be 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/help/help/topics/TraceRmiLauncherServicePlugin/TraceRmiLauncherServicePlugin.html
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/help/help/topics/TraceRmiLauncherServicePlugin/TraceRmiLauncherServicePlugin.html
@@ -857,7 +857,7 @@ bdcedit /dbgsettings NET HOSTIP:IP PORT:54321 KEY:1.1.1.1
<P>The following launchers based on the Java Debugger are included out of the box:</P>
- <H3><A name="java"></A>java launch</H3>
+ <H3><A name="java"></A>java</H3>
<P>This launcher uses the native Java Debug Interface (JDI) to launch the current
<TT>.class</TT> file.</P>
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/ProtobufSocket.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/ProtobufSocket.java
index 6372ca0c9b..933d543c74 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/ProtobufSocket.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/ProtobufSocket.java
@@ -77,4 +77,14 @@ public class ProtobufSocket<T extends AbstractMessage> {
Msg.error(this, "Unable to close ProtobufSocket");
}
}
+
+ public String getRemoteAddress() {
+ try {
+ return channel.getRemoteAddress().toString();
+ }
+ catch (IOException e) {
+ return null;
+ }
+ }
+
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiBatch.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiBatch.java
index 65a8c393b5..261591db96 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiBatch.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiBatch.java
@@ -15,14 +15,21 @@
*/
package ghidra.app.plugin.core.debug.client.tracermi;
-import java.util.HashSet;
-import java.util.Set;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
-public class RmiBatch {
+import ghidra.app.plugin.core.debug.client.tracermi.RmiClient.RequestResult;
+public class RmiBatch implements AutoCloseable {
- private int refCount = 0;
- private Set<Object> futures = new HashSet<>();
+ private final RmiClient client;
+ private volatile int refCount = 0;
+ private final List<RequestResult> futures = new ArrayList<>();
+
+ public RmiBatch(RmiClient client) {
+ this.client = client;
+ }
public void inc() {
refCount++;
@@ -31,14 +38,35 @@ public class RmiBatch {
public int dec() {
return --refCount;
}
-
- public void append(Object f) {
- futures.add(f);
+
+ @Override
+ public void close() {
+ try {
+ client.endBatch(this);
+ }
+ catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
}
- public Object results() {
- return null;
+ public void append(RequestResult f) {
+ synchronized (futures) {
+ futures.add(f);
+ }
}
+ public List<Object> results() throws InterruptedException, ExecutionException {
+ List<RequestResult> futures = futures();
+ List<Object> results = new ArrayList<>(futures.size());
+ for (RequestResult r : futures) {
+ results.add(r.get());
+ }
+ return results;
+ }
+ public List<RequestResult> futures() {
+ synchronized (futures) {
+ return List.copyOf(futures);
+ }
+ }
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiClient.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiClient.java
index 37af45ff1a..66f2327afa 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiClient.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiClient.java
@@ -18,9 +18,9 @@ package ghidra.app.plugin.core.debug.client.tracermi;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Parameter;
import java.nio.channels.SocketChannel;
import java.util.*;
+import java.util.concurrent.*;
import org.jdom.JDOMException;
@@ -37,18 +37,51 @@ import ghidra.rmi.trace.TraceRmi.Language;
import ghidra.rmi.trace.TraceRmi.Value.Builder;
import ghidra.trace.model.Lifespan;
import ghidra.util.Msg;
+import ghidra.util.Swing;
public class RmiClient {
+
+ static class RequestResult extends CompletableFuture<Object> {
+ public final RootMessage request;
+
+ public RequestResult(RootMessage req) {
+ this.request = req;
+ }
+
+ @Override
+ public Object get() throws InterruptedException, ExecutionException {
+ if (Swing.isSwingThread()) {
+ throw new AssertionError("Refusing indefinite wait on Swing thread");
+ }
+ return super.get();
+ }
+
+ @Override
+ public Object get(long timeout, TimeUnit unit)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ if (Swing.isSwingThread() && unit.toSeconds(timeout) > 1) {
+ throw new AssertionError("Refusing a timeout > 1 second on Swing thread");
+ }
+ return super.get(timeout, unit);
+ }
+ }
+
+ public static class RmiException extends RuntimeException {
+ public RmiException(String message) {
+ super(message);
+ }
+ }
+
private final ProtobufSocket<RootMessage> socket;
private final String description;
private int nextTraceId = 0;
- private RmiBatch currentBatch = null;
+ private volatile RmiBatch currentBatch = null;
Map<Integer, RmiTrace> traces = new HashMap<>();
private SchemaContext schemaContext;
- private RmiMethodHandlerThread handler;
+ private RmiReplyHandlerThread handler;
private static RmiMethodRegistry methodRegistry;
- private Deque<RootMessage> requests = new LinkedList<>();
+ private Deque<RequestResult> requests = new LinkedList<>();
public static TargetObjectSchema loadSchema(String resourceName, String rootName) {
XmlSchemaContext schemaContext;
@@ -64,19 +97,10 @@ public class RmiClient {
}
}
-// public static TargetObjectSchema getSchema(String name) {
-// try {
-// return SCHEMA_CTX.getSchema(new SchemaName(name));
-// } catch (NullPointerException e) {
-// System.err.println("Possibly non-existent schema: "+name);
-// return SCHEMA_CTX.getSchema(new SchemaName("OBJECT"));
-// }
-// }
-
public static enum TraceRmiResolution {
- RES_ADJUST("adjust", Resolution.CR_ADJUST), //
- RES_DENY("deny", Resolution.CR_DENY), //
- RES_TRUNCATE("truncate", Resolution.CR_TRUNCATE), //
+ RES_ADJUST("adjust", Resolution.CR_ADJUST),
+ RES_DENY("deny", Resolution.CR_DENY),
+ RES_TRUNCATE("truncate", Resolution.CR_TRUNCATE),
;
TraceRmiResolution(String val, TraceRmi.Resolution description) {
@@ -89,9 +113,9 @@ public class RmiClient {
}
public static enum TraceRmiValueKinds {
- ATTRIBUTES("attributes", ValueKinds.VK_ATTRIBUTES), //
- ELEMENTS("elements", ValueKinds.VK_ELEMENTS), //
- BOTH("both", ValueKinds.VK_BOTH), //
+ ATTRIBUTES("attributes", ValueKinds.VK_ATTRIBUTES),
+ ELEMENTS("elements", ValueKinds.VK_ELEMENTS),
+ BOTH("both", ValueKinds.VK_BOTH),
;
TraceRmiValueKinds(String val, TraceRmi.ValueKinds description) {
@@ -106,16 +130,12 @@ public class RmiClient {
public RmiClient(SocketChannel channel, String description) {
this.socket = new ProtobufSocket<>(channel, RootMessage::parseFrom);
this.description = description;
- this.handler = new RmiMethodHandlerThread(this, socket);
+ this.handler = new RmiReplyHandlerThread(this, socket);
handler.start();
}
- public ProtobufSocket<RootMessage> getSocket() {
- return socket;
- }
-
public String getDescription() {
- return description;
+ return description + " at " + socket.getRemoteAddress();
}
public void close() {
@@ -123,10 +143,18 @@ public class RmiClient {
socket.close();
}
- private void send(RootMessage msg) {
+ private RequestResult send(RootMessage msg) {
try {
- requests.push(msg);
- socket.send(msg);
+ RequestResult result = new RequestResult(msg);
+ synchronized (requests) {
+ socket.send(msg);
+ requests.push(result);
+ }
+ RmiBatch cb = currentBatch;
+ if (cb != null) {
+ cb.append(result);
+ }
+ return result;
}
catch (IOException e) {
throw new RuntimeException(e);
@@ -137,12 +165,11 @@ public class RmiClient {
if (compiler == null) {
compiler = new CompilerSpecID("default");
}
- RmiTrace trace = new RmiTrace(this, nextTraceId);
- traces.put(nextTraceId, trace);
- send(RootMessage.newBuilder()
+ int traceId = nextTraceId++;
+ RequestResult result = send(RootMessage.newBuilder()
.setRequestCreateTrace(RequestCreateTrace.newBuilder()
.setOid(DomObjId.newBuilder()
- .setId(nextTraceId++))
+ .setId(traceId))
.setLanguage(Language.newBuilder()
.setId(language.getIdAsString()))
.setCompiler(Compiler.newBuilder()
@@ -150,6 +177,8 @@ public class RmiClient {
.setPath(FilePath.newBuilder()
.setPath(path)))
.build());
+ RmiTrace trace = new RmiTrace(this, traceId, result);
+ traces.put(traceId, trace);
return trace;
}
@@ -159,6 +188,7 @@ public class RmiClient {
.setOid(DomObjId.newBuilder()
.setId(id)))
.build());
+ traces.remove(id);
}
public void saveTrace(int id) {
@@ -248,7 +278,7 @@ public class RmiClient {
.setRange(AddrRange.newBuilder()
.setSpace(range.getAddressSpace().getName())
.setOffset(range.getMinAddress().getOffset())
- .setExtend(range.getLength())))
+ .setExtend(range.getLength() - 1)))
.build());
}
@@ -279,7 +309,7 @@ public class RmiClient {
.setSpace(ppath);
for (int i = 0; i < names.length; i++) {
String name = names[i];
- builder.setNames(i, name);
+ builder.addNames(name);
}
send(RootMessage.newBuilder()
.setRequestDeleteRegisterValue(builder)
@@ -298,9 +328,8 @@ public class RmiClient {
.build());
}
- public void createObject(int traceId, String path) {
- //System.err.println("createObject:"+path);
- send(RootMessage.newBuilder()
+ RequestResult createObject(int traceId, String path) {
+ return send(RootMessage.newBuilder()
.setRequestCreateObject(RequestCreateObject.newBuilder()
.setOid(DomObjId.newBuilder()
.setId(traceId))
@@ -323,12 +352,13 @@ public class RmiClient {
.build());
}
- public void insertObject(int traceId, ObjSpec object, Lifespan span, Resolution r) {
+ public void insertObject(int traceId, long id, Lifespan span, Resolution r) {
send(RootMessage.newBuilder()
.setRequestInsertObject(RequestInsertObject.newBuilder()
.setOid(DomObjId.newBuilder()
.setId(traceId))
- .setObject(object)
+ .setObject(ObjSpec.newBuilder()
+ .setId(id))
.setSpan(Span.newBuilder()
.setMin(span.lmin())
.setMax(span.lmax()))
@@ -336,12 +366,28 @@ public class RmiClient {
.build());
}
- public void removeObject(int traceId, ObjSpec object, Lifespan span, boolean tree) {
+ public void removeObject(int traceId, String path, Lifespan span, boolean tree) {
+ send(RootMessage.newBuilder()
+ .setRequestRemoveObject(RequestRemoveObject.newBuilder()
+ .setOid(DomObjId.newBuilder()
+ .setId(traceId))
+ .setObject(ObjSpec.newBuilder()
+ .setPath(ObjPath.newBuilder()
+ .setPath(path)))
+ .setSpan(Span.newBuilder()
+ .setMin(span.lmin())
+ .setMax(span.lmax()))
+ .setTree(tree))
+ .build());
+ }
+
+ public void removeObject(int traceId, long id, Lifespan span, boolean tree) {
send(RootMessage.newBuilder()
.setRequestRemoveObject(RequestRemoveObject.newBuilder()
.setOid(DomObjId.newBuilder()
.setId(traceId))
- .setObject(object)
+ .setObject(ObjSpec.newBuilder()
+ .setId(id))
.setSpan(Span.newBuilder()
.setMin(span.lmin())
.setMax(span.lmax()))
@@ -389,19 +435,18 @@ public class RmiClient {
}
public void getObject(int traceId, String path) {
- RequestGetObject.Builder builder = RequestGetObject.newBuilder()
- .setOid(DomObjId.newBuilder()
- .setId(traceId))
- .setObject(ObjSpec.newBuilder()
- .setPath(ObjPath.newBuilder()
- .setPath(path)));
send(RootMessage.newBuilder()
- .setRequestGetObject(builder)
+ .setRequestGetObject(RequestGetObject.newBuilder()
+ .setOid(DomObjId.newBuilder()
+ .setId(traceId))
+ .setObject(ObjSpec.newBuilder()
+ .setPath(ObjPath.newBuilder()
+ .setPath(path))))
.build());
}
- public void getValues(int traceId, Lifespan span, String pattern) {
- send(RootMessage.newBuilder()
+ RequestResult getValues(int traceId, Lifespan span, String pattern) {
+ return send(RootMessage.newBuilder()
.setRequestGetValues(RequestGetValues.newBuilder()
.setOid(DomObjId.newBuilder()
.setId(traceId))
@@ -412,9 +457,9 @@ public class RmiClient {
.build());
}
- public void getValuesIntersecting(int traceId, Lifespan span, AddressRange range,
+ RequestResult getValuesIntersecting(int traceId, Lifespan span, AddressRange range,
String key) {
- send(RootMessage.newBuilder()
+ return send(RootMessage.newBuilder()
.setRequestGetValuesIntersecting(RequestGetValuesIntersecting.newBuilder()
.setOid(DomObjId.newBuilder()
.setId(traceId))
@@ -445,6 +490,9 @@ public class RmiClient {
@SuppressWarnings("unchecked")
private Builder buildValue(Object value) {
Builder builder = Value.newBuilder();
+ if (value == null) {
+ return builder.setNullValue(Null.newBuilder());
+ }
if (value instanceof String str) {
return builder.setStringValue(str);
}
@@ -497,7 +545,11 @@ public class RmiClient {
return builder.setBoolArrValue(b.build());
}
if (list.get(0) instanceof Short) {
- ShortArr.Builder b = ShortArr.newBuilder().addAllArr((List<Integer>) list);
+ List<Integer> newList = new ArrayList<>();
+ for (Object object : list) {
+ newList.add(((Short) object).intValue());
+ }
+ ShortArr.Builder b = ShortArr.newBuilder().addAllArr(newList);
return builder.setShortArrValue(b.build());
}
if (list.get(0) instanceof Integer) {
@@ -570,12 +622,12 @@ public class RmiClient {
.setDisplay(param.getDisplay())
.setDescription(param.getDescription())
.setType(param.getType())
- .setDefaultValue(param.getDefaultValue())
+ .setDefaultValue(buildValue(param.getDefaultValue()))
.setRequired(param.isRequired())
.build();
}
- public void handleInvokeMethod(int traceId, XRequestInvokeMethod req) {
+ public XReplyInvokeMethod handleInvokeMethod(int traceId, XRequestInvokeMethod req) {
RmiRemoteMethod rm = getMethod(req.getName());
Object[] arglist = new Object[req.getArgumentsCount()];
java.lang.reflect.Method m = rm.getMethod();
@@ -585,57 +637,50 @@ public class RmiClient {
argmap.put(arg.getName(), arg);
}
int i = 0;
- for (Parameter p : m.getParameters()) {
+ for (RmiRemoteMethodParameter p : rm.getParameters()) {
MethodArgument arg = argmap.get(p.getName());
if (arg != null) {
- Object obj = argToObject(traceId, arg);
+ Object obj = argToObject(traceId, arg.getValue());
arglist[i++] = obj;
}
}
try {
Object ret = m.invoke(rm.getContainer(), arglist);
if (ret != null) {
- socket.send(RootMessage.newBuilder()
- .setXreplyInvokeMethod(XReplyInvokeMethod.newBuilder()
- .setReturnValue(buildValue(ret)))
- .build());
+ return XReplyInvokeMethod.newBuilder()
+ .setReturnValue(buildValue(ret))
+ .build();
}
+ return XReplyInvokeMethod.newBuilder()
+ .setReturnValue(buildValue(true))
+ .build();
}
- catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
- | IOException e) {
+ catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
String message = e.getMessage();
if (message != null) {
- Msg.error(this, message);
- try {
- socket.send(RootMessage.newBuilder()
- .setXreplyInvokeMethod(
- XReplyInvokeMethod.newBuilder().setError(message))
- .build());
- }
- catch (IOException e1) {
- Msg.error(this, e1.getMessage());
- }
+ Msg.error(this, "Error handling method invocation:" + message);
+ return XReplyInvokeMethod.newBuilder()
+ .setError(message)
+ .build();
}
+ return XReplyInvokeMethod.newBuilder()
+ .setError(e.toString())
+ .build();
}
-
}
- private Object argToObject(int traceId, MethodArgument arg) {
- if (arg == null) {
- throw new RuntimeException("Null argument passed to argToObject");
- }
- Value value = arg.getValue();
+ Object argToObject(int traceId, Value value) {
if (value.hasStringValue()) {
return value.getStringValue();
}
if (value.hasStringArrValue()) {
- return value.getStringArrValue();
+ return value.getStringArrValue().getArrList();
}
if (value.hasBoolValue()) {
return value.getBoolValue();
}
if (value.hasBoolArrValue()) {
- return value.getBoolArrValue();
+ return value.getBoolArrValue().getArrList();
}
if (value.hasCharValue()) {
return value.getCharValue();
@@ -647,19 +692,19 @@ public class RmiClient {
return value.getShortValue();
}
if (value.hasShortArrValue()) {
- return value.getShortArrValue();
+ return value.getShortArrValue().getArrList();
}
if (value.hasIntValue()) {
return value.getIntValue();
}
if (value.hasIntArrValue()) {
- return value.getIntArrValue();
+ return value.getIntArrValue().getArrList();
}
if (value.hasLongValue()) {
return value.getLongValue();
}
if (value.hasLongArrValue()) {
- return value.getLongArrValue();
+ return value.getLongArrValue().getArrList();
}
if (value.hasAddressValue()) {
return decodeAddr(traceId, value.getAddressValue());
@@ -681,6 +726,61 @@ public class RmiClient {
return proxyObjectPath(traceId, path);
}
+ String argToType(Value value) {
+ if (value.hasStringValue()) {
+ return "STRING";
+ }
+ if (value.hasStringArrValue()) {
+ return "STRING_ARR";
+ }
+ if (value.hasBoolValue()) {
+ return "BOOL";
+ }
+ if (value.hasBoolArrValue()) {
+ return "BOOL_ARR";
+ }
+ if (value.hasCharValue()) {
+ return "CHAR";
+ }
+ if (value.hasCharArrValue()) {
+ return "CHAR_ARR";
+ }
+ if (value.hasShortValue()) {
+ return "SHORT";
+ }
+ if (value.hasShortArrValue()) {
+ return "SHORT_ARR";
+ }
+ if (value.hasIntValue()) {
+ return "INT";
+ }
+ if (value.hasIntArrValue()) {
+ return "INT_ARR";
+ }
+ if (value.hasLongValue()) {
+ return "LONG";
+ }
+ if (value.hasLongArrValue()) {
+ return "LONG_ARR";
+ }
+ if (value.hasAddressValue()) {
+ return "ADDRESS";
+ }
+ if (value.hasRangeValue()) {
+ return "RANGE";
+ }
+ if (value.hasByteValue()) {
+ return "BYTE";
+ }
+ if (value.hasBytesValue()) {
+ return "BYTE_ARR";
+ }
+ if (value.hasNullValue()) {
+ return "NULL";
+ }
+ return "OBJECT";
+ }
+
private Address decodeAddr(int id, Addr addr) {
RmiTrace trace = traces.get(id);
return trace.memoryMapper.genAddr(addr.getSpace(), addr.getOffset());
@@ -700,32 +800,33 @@ public class RmiClient {
return methodRegistry.getMap().get(name);
}
- public Object startBatch() {
+ public RmiBatch startBatch() {
if (currentBatch == null) {
- currentBatch = new RmiBatch();
+ currentBatch = new RmiBatch(this);
}
currentBatch.inc();
return currentBatch;
}
- public Object endBatch() {
- RmiBatch cb = null;
- if (0 == currentBatch.dec()) {
- cb = currentBatch;
+ boolean hasBatch() {
+ return currentBatch != null;
+ }
+
+ void endBatch(RmiBatch batch) throws InterruptedException, ExecutionException {
+ if (currentBatch.dec() == 0) {
+ RmiBatch cb = currentBatch;
currentBatch = null;
+ cb.results();
}
- if (cb != null) {
- return cb.results();
- }
- return null;
}
public TargetObjectSchema getSchema(String schema) {
return schemaContext.getSchema(new SchemaName(schema));
}
- public RootMessage getRequestsPoll() {
- return requests.poll();
+ public RequestResult pollRequest() {
+ synchronized (requests) {
+ return requests.poll();
+ }
}
-
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiMethodHandlerThread.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiMethodHandlerThread.java
deleted file mode 100644
index f932496598..0000000000
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiMethodHandlerThread.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/* ###
- * IP: GHIDRA
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package ghidra.app.plugin.core.debug.client.tracermi;
-
-import ghidra.rmi.trace.TraceRmi.*;
-import ghidra.util.Msg;
-
-public class RmiMethodHandlerThread extends Thread {
-
- private RmiClient client;
- private ProtobufSocket<RootMessage> socket;
- private boolean terminated = false;
-
- public RmiMethodHandlerThread(RmiClient client, ProtobufSocket<RootMessage> socket) {
- this.client = client;
- this.socket = socket;
- }
-
- @Override
- public void run() {
- while (!terminated) {
- try {
- RootMessage msg = socket.recv();
- if (msg.hasXrequestInvokeMethod()) {
- try {
- XRequestInvokeMethod req = msg.getXrequestInvokeMethod();
- int id = req.getOid().getId();
- RmiTrace trace = client.traces.get(id);
- trace.handleInvokeMethod(req);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- continue;
- }
- RootMessage request = client.getRequestsPoll();
- if (msg.hasError()) {
- Msg.error(this, msg);
- }
- else if (msg.hasReplyCreateObject()) {
- ReplyCreateObject reply = msg.getReplyCreateObject();
- RmiTrace trace = client.traces.get(request.getRequestCreateObject().getOid().getId());
- trace.handleCreateObject(reply);
- }
- else if (msg.hasReplyCreateTrace()) {
- ReplyCreateTrace reply = msg.getReplyCreateTrace();
- RmiTrace trace = client.traces.get(request.getRequestCreateTrace().getOid().getId());
- trace.handleCreateTrace(reply);
- }
- }
- catch (Exception e) {
- Msg.error(this, e.getMessage());
- }
- }
- Msg.info(this, "Handler exiting");
- }
-
- public void close() {
- terminated = true;
- }
-
-}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiMethodRegistry.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiMethodRegistry.java
index 6205f5ff8f..c00d65f37a 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiMethodRegistry.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiMethodRegistry.java
@@ -27,12 +27,13 @@ public class RmiMethodRegistry {
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public static @interface TraceMethod {
- String action();
- String display() default "";
- String description() default "";
- String schema() default "ANY";
+ String action() default "";
+
+ String display() default "";
+
+ String description() default "";
}
-
+
Map<String, RmiRemoteMethod> map = new HashMap<>();
public RmiRemoteMethod getMethod(String key) {
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethod.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethod.java
index 30d6210266..9ee4b6efcb 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethod.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethod.java
@@ -19,14 +19,12 @@ import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import ghidra.dbg.target.TargetMethod;
+import ghidra.dbg.target.TargetMethod.ParameterDescription;
import ghidra.dbg.target.schema.*;
import ghidra.dbg.target.schema.TargetObjectSchema.SchemaName;
-import ghidra.program.model.address.Address;
-import ghidra.program.model.address.AddressRange;
-import ghidra.rmi.trace.TraceRmi.Value;
public class RmiRemoteMethod {
-
+
private final SchemaContext schemaContext;
private String name;
private String action;
@@ -37,7 +35,8 @@ public class RmiRemoteMethod {
private RmiMethods instance;
private Method m;
- public RmiRemoteMethod(SchemaContext schemaContext, String name, String action, String display, String description, TargetObjectSchema schema, RmiMethods instance, Method m) {
+ public RmiRemoteMethod(SchemaContext schemaContext, String name, String action, String display,
+ String description, TargetObjectSchema schema, RmiMethods instance, Method m) {
this.schemaContext = schemaContext;
this.name = name;
this.action = action;
@@ -46,54 +45,23 @@ public class RmiRemoteMethod {
this.params = new RmiRemoteMethodParameter[m.getParameterCount()];
this.schema = schema;
this.instance = instance;
- this.m = m;
-
+ this.m = m;
+
int i = 0;
for (Parameter p : m.getParameters()) {
- TargetObjectSchema pschema = getSchemaFromParameter(p);
- String pname = p.getName(); // NB: don't change this unless yuou resolve the ordering issues
- String pdesc = pname;
- String pdisp = pname;
- if (i == 0) {
- RmiMethodRegistry.TraceMethod annot = m.getAnnotation(RmiMethodRegistry.TraceMethod.class);
- if (annot != null) {
- pschema = schemaContext.getSchema(new SchemaName(annot.schema()));
- }
- pdisp = "Object";
+ ParameterDescription<?> desc = TargetMethod.ParameterDescription.annotated(p);
+ TargetObjectSchema pschema;
+ if (desc.type != RmiTraceObject.class) {
+ pschema = EnumerableTargetObjectSchema.schemaForPrimitive(desc.type);
}
- Value pdef = null;
- TargetMethod.Param pannot = p.getAnnotation(TargetMethod.Param.class);
- if (pannot != null) {
- pdesc = pannot.description();
- pdisp = pannot.display();
+ else {
+ pschema = schemaContext.getSchema(new SchemaName(desc.schema));
}
- boolean required = i != 0;
- params[i++] = new RmiRemoteMethodParameter(pname, pschema, required, pdef, pdisp, pdesc);
+ params[i++] = new RmiRemoteMethodParameter(desc.name, pschema, desc.required,
+ desc.defaultValue, desc.display, desc.description);
}
}
- private TargetObjectSchema getSchemaFromParameter(Parameter p) {
- if (p.getAnnotatedType().getType().equals(String.class)) {
- return EnumerableTargetObjectSchema.STRING;
- }
- if (p.getAnnotatedType().getType().equals(Boolean.class)) {
- return EnumerableTargetObjectSchema.BOOL;
- }
- if (p.getAnnotatedType().getType().equals(Integer.class)) {
- return EnumerableTargetObjectSchema.INT;
- }
- if (p.getAnnotatedType().getType().equals(Long.class)) {
- return EnumerableTargetObjectSchema.LONG;
- }
- if (p.getAnnotatedType().getType().equals(Address.class)) {
- return EnumerableTargetObjectSchema.ADDRESS;
- }
- if (p.getAnnotatedType().getType().equals(AddressRange.class)) {
- return EnumerableTargetObjectSchema.RANGE;
- }
- return EnumerableTargetObjectSchema.ANY;
- }
-
public String getName() {
return name;
}
@@ -125,5 +93,4 @@ public class RmiRemoteMethod {
public RmiMethods getContainer() {
return instance;
}
-
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethodParameter.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethodParameter.java
index 0994c27b47..2dc3d77f4e 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethodParameter.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiRemoteMethodParameter.java
@@ -19,24 +19,24 @@ import ghidra.dbg.target.schema.TargetObjectSchema;
import ghidra.rmi.trace.TraceRmi.*;
public class RmiRemoteMethodParameter {
-
+
private final String name;
private final TargetObjectSchema schema;
private final boolean required;
- private final Value defaultValue;
+ private final Object defaultValue;
private final String display;
private final String description;
- public RmiRemoteMethodParameter(String name, TargetObjectSchema schema, boolean required,
- Value defaultValue, String display, String description) {
+ public RmiRemoteMethodParameter(String name, TargetObjectSchema schema, boolean required,
+ Object defaultValue, String display, String description) {
this.name = name;
this.schema = schema;
this.required = required;
this.defaultValue = defaultValue;
this.display = display;
- this.description = description;
+ this.description = description;
}
-
+
public String getName() {
return name;
}
@@ -57,15 +57,11 @@ public class RmiRemoteMethodParameter {
return ValueType.newBuilder().setName(schemaName).build();
}
- public Value getDefaultValue() {
- if (defaultValue != null) {
- return defaultValue;
- }
- return Value.newBuilder().setNullValue(Null.newBuilder()).build();
+ public Object getDefaultValue() {
+ return defaultValue;
}
public boolean isRequired() {
return required;
}
-
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiReplyHandlerThread.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiReplyHandlerThread.java
new file mode 100644
index 0000000000..c6d9af0f68
--- /dev/null
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiReplyHandlerThread.java
@@ -0,0 +1,112 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.plugin.core.debug.client.tracermi;
+
+import ghidra.app.plugin.core.debug.client.tracermi.RmiClient.RequestResult;
+import ghidra.app.plugin.core.debug.client.tracermi.RmiClient.RmiException;
+import ghidra.rmi.trace.TraceRmi.*;
+import ghidra.util.Msg;
+
+public class RmiReplyHandlerThread extends Thread {
+
+ private RmiClient client;
+ private ProtobufSocket<RootMessage> socket;
+ private boolean terminated = false;
+
+ public RmiReplyHandlerThread(RmiClient client, ProtobufSocket<RootMessage> socket) {
+ this.client = client;
+ this.socket = socket;
+ }
+
+ @Override
+ public void run() {
+ while (!terminated) {
+ try {
+ RootMessage msg = socket.recv();
+ if (msg.hasXrequestInvokeMethod()) {
+ try {
+ XRequestInvokeMethod req = msg.getXrequestInvokeMethod();
+ int id = req.getOid().getId();
+ RmiTrace trace = client.traces.get(id);
+ XReplyInvokeMethod reply = trace.handleInvokeMethod(req);
+ socket.send(RootMessage.newBuilder().setXreplyInvokeMethod(reply).build());
+ }
+ catch (Exception e) {
+ Msg.error(this, "Error handling method invocation", e);
+ socket.send(RootMessage.newBuilder()
+ .setXreplyInvokeMethod(
+ XReplyInvokeMethod.newBuilder().setError(e.toString()))
+ .build());
+ }
+ continue;
+ }
+
+ RequestResult result = client.pollRequest();
+ if (result == null) {
+ System.err.println("REPLY without request: " + msg);
+ continue;
+ }
+ RootMessage request = result.request;
+
+ switch (msg.getMsgCase()) {
+ case ERROR -> {
+ Msg.error(this, msg.getError().getMessage());
+ result.completeExceptionally(new RmiException(msg.getError().getMessage()));
+ }
+ case REPLY_CREATE_OBJECT -> {
+ ReplyCreateObject reply = msg.getReplyCreateObject();
+ RmiTrace trace =
+ client.traces.get(request.getRequestCreateObject().getOid().getId());
+ result.complete(trace.handleCreateObject(reply));
+ }
+ case REPLY_CREATE_TRACE -> {
+ ReplyCreateTrace reply = msg.getReplyCreateTrace();
+ RmiTrace trace =
+ client.traces.get(request.getRequestCreateTrace().getOid().getId());
+ result.complete(trace.handleCreateTrace(reply));
+ }
+ case REPLY_GET_VALUES -> {
+ ReplyGetValues reply = msg.getReplyGetValues();
+ RmiTrace trace =
+ client.traces.get(request.getRequestGetValues().getOid().getId());
+ result.complete(trace.handleGetValues(reply));
+ }
+ case REPLY_DISASSEMBLE -> {
+ ReplyDisassemble reply = msg.getReplyDisassemble();
+ RmiTrace trace =
+ client.traces.get(request.getRequestDisassemble().getOid().getId());
+ result.complete(trace.handleDisassemble(reply));
+ }
+ default -> result.complete(null);
+ }
+ }
+ catch (Exception e) {
+ if (e.getMessage() == null) {
+ Msg.error(this, "Error processing reply", e);
+ }
+ else {
+ Msg.error(this, e.getMessage());
+ }
+ }
+ }
+ Msg.info(this, "Handler exiting");
+ }
+
+ public void close() {
+ terminated = true;
+ }
+
+}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTrace.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTrace.java
index e364af9617..a4f2dabafc 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTrace.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTrace.java
@@ -15,14 +15,15 @@
*/
package ghidra.app.plugin.core.debug.client.tracermi;
-import java.util.HashSet;
-import java.util.Set;
+import java.util.*;
+import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
+import ghidra.app.plugin.core.debug.client.tracermi.RmiClient.RequestResult;
import ghidra.dbg.target.schema.SchemaContext;
-import ghidra.program.model.address.Address;
-import ghidra.program.model.address.AddressRange;
+import ghidra.dbg.target.schema.TargetObjectSchema;
+import ghidra.program.model.address.*;
import ghidra.program.model.lang.RegisterValue;
import ghidra.rmi.trace.TraceRmi.*;
import ghidra.trace.model.Lifespan;
@@ -30,14 +31,15 @@ import ghidra.util.LockHold;
import ghidra.util.Msg;
public class RmiTrace {
-
+
final RmiClient client;
private final int id;
-
+ private RequestResult createResult;
+
private int nextTx = 0;
private Object txLock = new Object();
private ReadWriteLock snLock = new ReentrantReadWriteLock();
-
+
private Set<String> overlays = new HashSet<>();
private long currentSnap = -1;
private boolean closed = false;
@@ -45,11 +47,17 @@ public class RmiTrace {
public MemoryMapper memoryMapper;
public RegisterMapper registerMapper;
- public RmiTrace(RmiClient client, int id) {
+ public RmiTrace(RmiClient client, int id, RequestResult createResult) {
this.client = client;
- this.id = id;
+ this.id = id;
+ this.createResult = createResult;
}
-
+
+ public void checkResult(long timeoutMs)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ createResult.get(timeoutMs, TimeUnit.MILLISECONDS);
+ }
+
public void close() {
if (closed) {
return;
@@ -63,7 +71,7 @@ public class RmiTrace {
public RmiTransaction startTx(String description, boolean undoable) {
int txid;
- synchronized(txLock) {
+ synchronized (txLock) {
txid = nextTx++;
}
client.startTx(id, description, undoable, txid);
@@ -74,17 +82,20 @@ public class RmiTrace {
return startTx(description, false);
}
- public void endTx(int txid, boolean abort) {
+ public void endTx(int txid, boolean abort) {
client.endTx(id, txid, abort);
}
-
+
public long nextSnap() {
try (LockHold hold = LockHold.lock(snLock.writeLock())) {
return ++currentSnap;
}
}
-
+
public long snapshot(String description, String datatime, Long snap) {
+ if (datatime == null) {
+ datatime = "";
+ }
if (snap == null) {
snap = nextSnap();
}
@@ -97,68 +108,90 @@ public class RmiTrace {
return currentSnap;
}
}
-
+
public void setSnap(long snap) {
try (LockHold hold = LockHold.lock(snLock.writeLock())) {
this.currentSnap = snap;
}
}
-
+
public long snapOrCurrent(Long snap) {
try (LockHold hold = LockHold.lock(snLock.readLock())) {
return snap == null ? this.currentSnap : snap.longValue();
}
}
-
+
public void createOverlaySpace(String base, String name) {
if (overlays.contains(name)) {
return;
}
client.createOverlaySpace(id, base, name);
}
-
+
public void createOverlaySpace(Address repl, Address orig) {
createOverlaySpace(repl.getAddressSpace().getName(), orig.getAddressSpace().getName());
}
- public void putBytes(Address addr, byte[] data, Long snap) {
+ public void putBytes(Address addr, byte[] data, Long snap) {
client.putBytes(id, snapOrCurrent(snap), addr, data);
}
-
+
public void setMemoryState(AddressRange range, MemoryState state, Long snap) {
client.setMemoryState(id, snapOrCurrent(snap), range, state);
}
-
+
public void deleteBytes(AddressRange range, Long snap) {
client.deleteBytes(id, snapOrCurrent(snap), range);
}
-
+
public void putRegisters(String ppath, RegisterValue[] values, Long snap) {
client.putRegisters(id, snapOrCurrent(snap), ppath, values);
}
-
+
public void deleteRegisters(String ppath, String[] names, Long snap) {
client.deleteRegisters(id, snapOrCurrent(snap), ppath, names);
}
-
+
public void createRootObject(SchemaContext schemaContext, String schema) {
client.createRootObject(id, schemaContext, schema);
}
-
- public void createObject(String path) {
- client.createObject(id, path);
+
+ public RmiTraceObject createObject(String path) {
+ RequestResult result = client.createObject(id, path);
+ return new RmiTraceObject(this, path, result);
+ }
+
+ public RmiTraceObject createAndInsertObject(String path) {
+ RmiTraceObject object = createObject(path);
+ object.insert(currentSnap, null);
+ return object;
}
- public void handleCreateObject(ReplyCreateObject reply) {
- RmiTraceObject obj = new RmiTraceObject(this, reply.getObject());
- try (RmiTransaction tx = startTx("CreateObject", false); LockHold hold = LockHold.lock(snLock.readLock())) {
- obj.insert(currentSnap, null);
- }
+ long handleCreateObject(ReplyCreateObject reply) {
+ return reply.getObject().getId();
}
-
- public void handleCreateTrace(ReplyCreateTrace reply) {
+
+ public Void handleCreateTrace(ReplyCreateTrace reply) {
+ return null;
+ }
+
+ public List<RmiTraceObjectValue> handleGetValues(ReplyGetValues reply) {
+ List<RmiTraceObjectValue> result = new ArrayList<>();
+ for (ValDesc d : reply.getValuesList()) {
+ RmiTraceObject parent = proxyObject(d.getParent());
+ Lifespan span = Lifespan.span(d.getSpan().getMin(), d.getSpan().getMax());
+ Object value = client.argToObject(id, d.getValue());
+ TargetObjectSchema schema = client.getSchema(client.argToType(d.getValue()));
+ result.add(new RmiTraceObjectValue(parent, span, d.getKey(), value, schema));
+ }
+ return result;
+ }
+
+ public long handleDisassemble(ReplyDisassemble reply) {
+ Msg.info(this, "Disassembled " + reply.getLength() + " bytes");
+ return reply.getLength();
}
-
+
public void insertObject(String path) {
Lifespan span = getLifespan();
client.insertObject(id, path, span, Resolution.CR_ADJUST);
@@ -174,29 +207,71 @@ public class RmiTrace {
Lifespan span = getLifespan();
client.setValue(id, ppath, span, key, value, null);
}
-
+
public void retainValues(String ppath, Set<String> keys, ValueKinds kinds) {
Lifespan span = getLifespan();
client.retainValues(id, ppath, span, kinds, keys);
}
-
+
+ @SuppressWarnings("unchecked")
+ private <T> T doSync(RequestResult r) {
+ if (client.hasBatch()) {
+ return null;
+ }
+ try {
+ return (T) r.get();
+ }
+ catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public RequestResult getValuesAsync(String pattern) {
+ Lifespan span = getLifespan();
+ return client.getValues(id, span, pattern);
+ }
+
+ public List<RmiTraceObjectValue> getValues(String pattern) {
+ return doSync(getValuesAsync(pattern));
+ }
+
+ public RequestResult getValuesRngAsync(Address start, long length) {
+ Lifespan span = getLifespan();
+ try {
+ AddressRange range = new AddressRangeImpl(start, length);
+ return client.getValuesIntersecting(id, span, range, "");
+ }
+ catch (AddressOverflowException e) {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ public List<RmiTraceObjectValue> getValuesRng(Address start, long length) {
+ return doSync(getValuesRngAsync(start, length));
+ }
+
public void activate(String path) {
if (path == null) {
Msg.error(this, "Attempt to activate null");
+ return;
}
client.activate(id, path);
}
-
- public void disassemble(Address start, Long snap) {
+
+ public void disassemble(Address start, Long snap) {
client.disassemble(id, snapOrCurrent(snap), start);
}
-
- public void handleInvokeMethod(XRequestInvokeMethod req) {
- try (RmiTransaction tx = startTx("InvokeMethod", false)) {
- client.handleInvokeMethod(id, req);
- }
+
+ public XReplyInvokeMethod handleInvokeMethod(XRequestInvokeMethod req) {
+ try (RmiTransaction tx = startTx("InvokeMethod", false)) {
+ return client.handleInvokeMethod(id, req);
+ }
+ }
+
+ private RmiTraceObject proxyObject(ObjDesc desc) {
+ return client.proxyObjectPath(id, desc.getId(), desc.getPath().getPath());
}
-
+
public RmiTraceObject proxyObjectId(Long objectId) {
return client.proxyObjectId(id, objectId);
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTraceObject.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTraceObject.java
index cd9b247c48..7ec5c5b5b0 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTraceObject.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTraceObject.java
@@ -17,45 +17,65 @@ package ghidra.app.plugin.core.debug.client.tracermi;
import java.util.Set;
-import ghidra.rmi.trace.TraceRmi.*;
+import ghidra.app.plugin.core.debug.client.tracermi.RmiClient.RequestResult;
+import ghidra.rmi.trace.TraceRmi.Resolution;
+import ghidra.rmi.trace.TraceRmi.ValueKinds;
import ghidra.trace.model.Lifespan;
public class RmiTraceObject {
-
- private RmiTrace trace;
- private ObjSpec spec;
- private String path;
- public RmiTraceObject(RmiTrace trace, ObjSpec spec) {
+ private final RmiTrace trace;
+ private final String path;
+ private volatile Long id;
+
+ public RmiTraceObject(RmiTrace trace, String path) {
+ this.trace = trace;
+ this.path = path;
+ }
+
+ RmiTraceObject(RmiTrace trace, String path, RequestResult result) {
this.trace = trace;
- this.spec = spec;
- this.path = spec.getPath().getPath();
+ this.path = path;
+ result.thenAccept(id -> this.id = (Long) id);
}
-
+
public RmiTraceObject(RmiTrace trace, Long id, String path) {
this.trace = trace;
+ this.id = id;
this.path = path;
}
-
+
public static RmiTraceObject fromId(RmiTrace trace, long id) {
return new RmiTraceObject(trace, id, null);
}
-
+
public static RmiTraceObject fromPath(RmiTrace trace, String path) {
return new RmiTraceObject(trace, null, path);
}
-
- public void insert(long snap, Resolution resolution) {
+
+ public Lifespan insert(long snap, Resolution resolution) {
if (resolution == null) {
resolution = Resolution.CR_ADJUST;
}
Lifespan span = Lifespan.nowOn(snap);
- trace.client.insertObject(trace.getId(), spec, span, resolution);
+ if (id != null) {
+ trace.client.insertObject(trace.getId(), id, span, resolution);
+ }
+ else {
+ trace.client.insertObject(trace.getId(), path, span, resolution);
+ }
+ return span;
}
- public void remove(long snap, boolean tree) {
+ public Lifespan remove(long snap, boolean tree) {
Lifespan span = Lifespan.nowOn(snap);
- trace.client.removeObject(trace.getId(), spec, span, tree);
+ if (id != null) {
+ trace.client.removeObject(trace.getId(), id, span, tree);
+ }
+ else {
+ trace.client.removeObject(trace.getId(), path, span, tree);
+ }
+ return span;
}
public void setValue(String key, Object value, long snap, String resolution) {
@@ -71,7 +91,7 @@ public class RmiTraceObject {
public void activate() {
trace.client.activate(trace.getId(), path);
}
-
+
public String getPath() {
return path;
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTraceObjectValue.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTraceObjectValue.java
new file mode 100644
index 0000000000..fcc483ff42
--- /dev/null
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTraceObjectValue.java
@@ -0,0 +1,22 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.plugin.core.debug.client.tracermi;
+
+import ghidra.dbg.target.schema.TargetObjectSchema;
+import ghidra.trace.model.Lifespan;
+
+public record RmiTraceObjectValue(RmiTraceObject parent, Lifespan span, String key, Object value,
+ TargetObjectSchema schema) {}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTransaction.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTransaction.java
index 4bb6075ab2..78ab72821a 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTransaction.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/client/tracermi/RmiTransaction.java
@@ -57,8 +57,4 @@ public class RmiTransaction implements AutoCloseable {
commit();
}
- public RmiTransaction startTx(String description, boolean b) {
- // TODO Auto-generated method stub
- return null;
- }
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/RemoteMethodInvocationDialog.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/RemoteMethodInvocationDialog.java
index cb049e0540..9001ed2c5a 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/RemoteMethodInvocationDialog.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/RemoteMethodInvocationDialog.java
@@ -130,10 +130,19 @@ public class RemoteMethodInvocationDialog extends AbstractDebuggerParameterDialo
ConfigStateField.getState(state, parameterType(parameter), key));
}
+ protected ValStr<?> forMissingDefault(RemoteParameter param) {
+ Class<?> type = parameterType(param);
+ if (type == Boolean.class || type == boolean.class) {
+ return ValStr.from(false);
+ }
+ return new ValStr<>(null, "");
+ }
+
@Override
protected void setEditorValue(PropertyEditor editor, RemoteParameter param, ValStr<?> val) {
ValStr<?> v = switch (val.val()) {
- case Missing __ -> new ValStr<>(null, "");
+ case null -> forMissingDefault(param);
+ case Missing __ -> forMissingDefault(param);
case TraceObject obj -> new ValStr<>(obj, obj.getCanonicalPath().toString());
default -> val;
};
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePlugin.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePlugin.java
index e502f02c9e..4ad0f60145 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePlugin.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePlugin.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -42,8 +42,13 @@ import ghidra.framework.model.DomainFile;
import ghidra.framework.options.*;
import ghidra.framework.plugintool.*;
import ghidra.framework.plugintool.util.PluginStatus;
-import ghidra.program.model.listing.Program;
-import ghidra.program.model.listing.ProgramUserData;
+import ghidra.program.model.address.AddressSpace;
+import ghidra.program.model.data.Composite;
+import ghidra.program.model.data.DataTypeComponent;
+import ghidra.program.model.lang.Processor;
+import ghidra.program.model.lang.ProcessorNotFoundException;
+import ghidra.program.model.listing.*;
+import ghidra.program.model.scalar.Scalar;
import ghidra.util.Msg;
import ghidra.util.bean.opteditor.OptionsVetoException;
import ghidra.util.classfinder.ClassSearcher;
@@ -124,6 +129,102 @@ public class TraceRmiLauncherServicePlugin extends Plugin
}
}
+ public static class FieldIndex {
+ public static FieldIndex fromData(Data data) {
+ if (!(data.getDataType() instanceof Composite dt)) {
+ return null;
+ }
+ return new FieldIndex(dt);
+ }
+
+ private final Map<String, DataTypeComponent> byName;
+
+ public FieldIndex(Composite dt) {
+ byName = Stream.of(dt.getComponents())
+ .collect(Collectors.toMap(c -> c.getFieldName(), c -> c));
+ }
+
+ public Data getField(Data data, String name) {
+ DataTypeComponent dtComp = byName.get(name);
+ if (dtComp == null) {
+ return null;
+ }
+ return data.getComponent(dtComp.getOrdinal());
+ }
+ }
+
+ public static String tryProgramJvmClass(Program program) {
+ Processor procJvm;
+ try {
+ procJvm = Processor.toProcessor("JVM");
+ }
+ catch (ProcessorNotFoundException e) {
+ return null;
+ }
+ if (program.getLanguage().getProcessor() != procJvm) {
+ return null;
+ }
+ AddressSpace cpool =
+ program.getLanguage().getAddressFactory().getAddressSpace("constantPool");
+
+ Data dClassFile = program.getListing().getDataAt(cpool.getAddress(0));
+ if (dClassFile == null) {
+ return null;
+ }
+ FieldIndex fiClassFile = FieldIndex.fromData(dClassFile);
+ if (fiClassFile == null) {
+ return null;
+ }
+ Data dThisClass = fiClassFile.getField(dClassFile, "this_class");
+ if (dThisClass == null || !(dThisClass.getValue() instanceof Scalar sThisClass)) {
+ return null;
+ }
+ long thisClassCpi = sThisClass.getValue();
+
+ Data dConstantPool = fiClassFile.getField(dClassFile, "constant_pool");
+ if (dConstantPool == null) {
+ return null;
+ }
+ FieldIndex fiConstantPool = FieldIndex.fromData(dConstantPool);
+ if (fiConstantPool == null) {
+ return null;
+ }
+ Data dThisClassConst =
+ fiConstantPool.getField(dConstantPool, "constant_pool_0x%x".formatted(thisClassCpi));
+ if (dThisClassConst == null ||
+ !"CONSTANT_Class_info".equals(dThisClassConst.getDataType().getName())) {
+ return null;
+ }
+
+ FieldIndex fiConstantClassInfo = FieldIndex.fromData(dThisClassConst);
+ if (fiConstantClassInfo == null) {
+ return null;
+ }
+ Data dThisClassNameIndex = fiConstantClassInfo.getField(dThisClassConst, "name_index");
+ if (dThisClassNameIndex == null ||
+ !(dThisClassNameIndex.getValue() instanceof Scalar sThisClassNameIndex)) {
+ return null;
+ }
+ long thisClassNameIndexCpi = sThisClassNameIndex.getValue();
+
+ Data dThisClassNameConst = fiConstantPool.getField(dConstantPool,
+ "constant_pool_0x%x".formatted(thisClassNameIndexCpi));
+ if (dThisClassNameConst == null ||
+ !dThisClassNameConst.getDataType().getName().startsWith("CONSTANT_Utf8_info")) {
+ return null;
+ }
+
+ FieldIndex fiUtf8InfoN = FieldIndex.fromData(dThisClassNameConst);
+ if (fiUtf8InfoN == null) {
+ return null;
+ }
+ Data dThisClassNameData = fiUtf8InfoN.getField(dThisClassNameConst, "data");
+ if (!(dThisClassNameData.getValue() instanceof String thisClassName)) {
+ return null;
+ }
+ return thisClassName;
+ }
+
public static File tryProgramPath(String path) {
if (path == null) {
return null;
@@ -154,6 +255,12 @@ public class TraceRmiLauncherServicePlugin extends Plugin
if (program == null) {
return null;
}
+ // TODO: All these tryers should be extension points...?
+ // Probably applicable by language/file type.
+ String jvmClass = tryProgramJvmClass(program);
+ if (jvmClass != null) {
+ return jvmClass;
+ }
File exec = tryProgramPath(program.getExecutablePath());
if (exec != null) {
return exec.getAbsolutePath();
@@ -371,8 +478,7 @@ public class TraceRmiLauncherServicePlugin extends Plugin
toolLaunchConfigs.putSaveState(name, state);
}
- protected record ConfigLast(String configName, long last, Program program) {
- }
+ protected record ConfigLast(String configName, long last, Program program) {}
protected ConfigLast checkSavedConfig(Program program, ProgramUserData userData,
String propName) {
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiHandler.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiHandler.java
index f074f847de..fd974c2d4c 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiHandler.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiHandler.java
@@ -448,12 +448,13 @@ public class TraceRmiHandler implements TraceRmiConnection {
return true;
}
catch (IOException e) {
- Msg.error(this, "Cannot send reply", e);
+ Msg.error(this, "Cannot send reply: " + e);
return false;
}
}
public void receiveLoop() {
+ boolean canSend = true;
try {
while (true) {
RootMessage req = receive();
@@ -468,8 +469,15 @@ public class TraceRmiHandler implements TraceRmiConnection {
continue;
}
- if (!send(rep)) {
- return;
+ /**
+ * The likely cause of this failing is that the remote end has closed the socket.
+ * However, we don't return, because there may be commands still in the queue, and
+ * we should process them until we reach the end of input. This will ensure clients
+ * that brazenly send a bunch of commands and then disconnect before receiving the
+ * replies will have their commands processed, even if unsuccessfully.
+ */
+ if (canSend) {
+ canSend = send(rep);
}
}
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiPlugin.java b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiPlugin.java
index e0734327f3..913ce2d9e5 100644
--- a/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiPlugin.java
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/main/java/ghidra/app/plugin/core/debug/service/tracermi/TraceRmiPlugin.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,6 +25,7 @@ import ghidra.app.plugin.core.debug.event.TraceActivatedPluginEvent;
import ghidra.app.plugin.core.debug.event.TraceClosedPluginEvent;
import ghidra.app.services.*;
import ghidra.debug.api.progress.CloseableTaskMonitor;
+import ghidra.debug.api.target.Target;
import ghidra.debug.api.tracermi.*;
import ghidra.debug.api.tracermi.TraceRmiServiceListener.ConnectMode;
import ghidra.framework.plugintool.*;
@@ -71,8 +72,8 @@ public class TraceRmiPlugin extends Plugin implements InternalTraceRmiService {
}
}
- @AutoServiceConsumed
- private DebuggerTargetService targetService;
+ // @AutoServiceConsumed // via method
+ private volatile DebuggerTargetService targetService;
@AutoServiceConsumed
private ProgressService progressService;
@SuppressWarnings("unused")
@@ -94,6 +95,25 @@ public class TraceRmiPlugin extends Plugin implements InternalTraceRmiService {
autoServiceWiring = AutoService.wireServicesProvidedAndConsumed(this);
}
+ @AutoServiceConsumed
+ public void setTargetService(DebuggerTargetService targetService) {
+ this.targetService = targetService;
+ record ConnAndTarget(TraceRmiConnection conn, Target target) {}
+ List<ConnAndTarget> targets = new ArrayList<>();
+ synchronized (handlers) {
+ for (TraceRmiConnection conn : getAllConnections()) {
+ for (Target target : conn.getTargets()) {
+ targets.add(new ConnAndTarget(conn, target));
+ }
+ }
+ }
+
+ for (ConnAndTarget cat : targets) {
+ targetService.publishTarget(cat.target);
+ listeners.invoke().targetPublished(cat.conn, cat.target);
+ }
+ }
+
protected CloseableTaskMonitor createMonitor() {
if (progressService == null) {
return fallbackMonitor;
@@ -201,6 +221,15 @@ public class TraceRmiPlugin extends Plugin implements InternalTraceRmiService {
void publishTarget(TraceRmiHandler handler, TraceRmiTarget target) {
Swing.runIfSwingOrRunLater(() -> {
+ if (targetService == null) {
+ /**
+ * I have no idea how this is happening, given targetService is a required service,
+ * and I don't see any way the rmi server can be started before the services are
+ * wired in. Whatever. I'll have to publish all the targets when the service
+ * appears, I guess.
+ */
+ return;
+ }
targetService.publishTarget(target);
listeners.invoke().targetPublished(handler, target);
});
@@ -208,6 +237,10 @@ public class TraceRmiPlugin extends Plugin implements InternalTraceRmiService {
void withdrawTarget(TraceRmiTarget target) {
Swing.runIfSwingOrRunLater(() -> {
+ if (targetService == null) {
+ // This can happen during tear down.
+ return;
+ }
targetService.withdrawTarget(target);
});
}
diff --git a/Ghidra/Debug/Debugger-rmi-trace/src/test/java/ghidra/app/plugin/core/debug/gui/tracermi/RemoteMethodInvocationDialogTest.java b/Ghidra/Debug/Debugger-rmi-trace/src/test/java/ghidra/app/plugin/core/debug/gui/tracermi/RemoteMethodInvocationDialogTest.java
new file mode 100644
index 0000000000..7f870a417f
--- /dev/null
+++ b/Ghidra/Debug/Debugger-rmi-trace/src/test/java/ghidra/app/plugin/core/debug/gui/tracermi/RemoteMethodInvocationDialogTest.java
@@ -0,0 +1,141 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.plugin.core.debug.gui.tracermi;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.awt.Component;
+import java.lang.reflect.Method;
+import java.lang.reflect.Parameter;
+import java.util.*;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Test;
+
+import ghidra.app.plugin.core.debug.gui.AbstractGhidraHeadedDebuggerTest;
+import ghidra.app.plugin.core.debug.gui.InvocationDialogHelper;
+import ghidra.app.plugin.core.debug.service.tracermi.TestTraceRmiConnection.TestRemoteMethod;
+import ghidra.app.plugin.core.debug.service.tracermi.TestTraceRmiConnection.TestRemoteParameter;
+import ghidra.async.SwingExecutorService;
+import ghidra.dbg.target.TargetMethod.Param;
+import ghidra.dbg.target.TargetMethod.ParameterDescription;
+import ghidra.dbg.target.schema.*;
+import ghidra.dbg.target.schema.EnumerableTargetObjectSchema.MinimalSchemaContext;
+import ghidra.dbg.target.schema.TargetObjectSchema.SchemaName;
+import ghidra.debug.api.ValStr;
+import ghidra.debug.api.tracermi.RemoteMethod;
+import ghidra.debug.api.tracermi.RemoteParameter;
+import ghidra.framework.options.PropertyBoolean;
+
+public class RemoteMethodInvocationDialogTest extends AbstractGhidraHeadedDebuggerTest {
+
+ private static final SchemaContext CTX = MinimalSchemaContext.INSTANCE;
+
+ public static TestRemoteMethod createTestMethod(Method m) {
+ Map<String, RemoteParameter> params = new LinkedHashMap<>();
+ for (Parameter p : m.getParameters()) {
+ TestRemoteParameter parameter = createParameter(p);
+ params.put(parameter.name(), parameter);
+ }
+ return new TestRemoteMethod(m.getName(), null, "Test", "A test method", params,
+ EnumerableTargetObjectSchema.schemaForPrimitive(m.getReturnType()));
+ }
+
+ public static TestRemoteParameter createParameter(Parameter p) {
+ ParameterDescription<?> desc = ParameterDescription.annotated(p);
+ TargetObjectSchema schema = EnumerableTargetObjectSchema.schemaForPrimitive(desc.type);
+ if (schema == EnumerableTargetObjectSchema.OBJECT ||
+ schema == EnumerableTargetObjectSchema.ANY) {
+ schema = CTX.getSchema(new SchemaName(desc.schema));
+ }
+ return new TestRemoteParameter(desc.name, schema, desc.required, desc.defaultValue,
+ desc.display, desc.description);
+ }
+
+ public static Map<String, Object> getDefaults(RemoteMethod method) {
+ Map<String, Object> result = new HashMap<>();
+ for (Map.Entry<String, RemoteParameter> ent : method.parameters().entrySet()) {
+ result.put(ent.getKey(), ent.getValue().getDefaultValue());
+ }
+ return result;
+ }
+
+ record TestBits(TestRemoteMethod method, CompletableFuture<Map<String, ValStr<?>>> future,
+ InvocationDialogHelper<RemoteParameter, ?> helper) {
+ Component getComponent(String name) {
+ return helper.getEditorComponent(method.parameters().get(name));
+ }
+
+ void setArg(String name, Object value) {
+ helper.setArg(method.parameters().get(name), value);
+ }
+
+ Map<String, Object> invoke() throws Exception {
+ helper.invoke();
+ Map<String, ValStr<?>> args = future.get(1, TimeUnit.SECONDS);
+ return args == null ? null : ValStr.toPlainMap(args);
+ }
+ }
+
+ protected TestBits startTest(Method m) throws Exception {
+ TestRemoteMethod method = createTestMethod(m);
+ Map<String, Object> defaults = getDefaults(method);
+
+ Map<String, ValStr<?>> defs = ValStr.fromPlainMap(defaults);
+ RemoteMethodInvocationDialog dialog =
+ new RemoteMethodInvocationDialog(tool, CTX, method.display(), method.display(), null);
+ CompletableFuture<Map<String, ValStr<?>>> future = CompletableFuture.supplyAsync(
+ () -> dialog.promptArguments(method.parameters(), defs, defs),
+ SwingExecutorService.LATER);
+ // Yes, I have it in hand, but I still must wait for it to appear on screen.
+ InvocationDialogHelper<RemoteParameter, ?> helper =
+ InvocationDialogHelper.waitFor(RemoteMethodInvocationDialog.class);
+
+ return new TestBits(method, future, helper);
+ }
+
+ public static class MethodTakesBooleanPrimitive {
+ public void theMethod(@Param(name = "b") boolean b) {
+ }
+ }
+
+ @Test
+ public void testBooleanPrimitiveField() throws Exception {
+ TestBits bits =
+ startTest(MethodTakesBooleanPrimitive.class.getMethod("theMethod", boolean.class));
+ assertTrue(bits.getComponent("b") instanceof PropertyBoolean);
+ bits.setArg("b", true);
+ Map<String, Object> values = bits.invoke();
+ assertEquals(true, values.get("b"));
+ }
+
+ public static class MethodTakesBooleanBoxed {
+ public void theMethod(@Param(name = "b") Boolean b) {
+ }
+ }
+
+ @Test
+ public void testBooleanBoxedField() throws Exception {
+ TestBits bits =
+ startTest(MethodTakesBooleanBoxed.class.getMethod("theMethod", Boolean.class));
+ assertTrue(bits.getComponent("b") instanceof PropertyBoolean);
+ bits.setArg("b", true);
+ Map<String, Object> values = bits.invoke();
+ assertEquals(true, values.get("b"));
+ }
+}
diff --git a/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/InvocationDialogHelper.java b/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/InvocationDialogHelper.java
index b65286bbbe..ce9b22b57f 100644
--- a/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/InvocationDialogHelper.java
+++ b/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/InvocationDialogHelper.java
@@ -15,6 +15,7 @@
*/
package ghidra.app.plugin.core.debug.gui;
+import java.awt.Component;
import java.beans.PropertyEditor;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@@ -23,6 +24,7 @@ import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import docking.test.AbstractDockingTest;
+import ghidra.app.plugin.core.debug.utils.MiscellaneousUtils;
import ghidra.async.SwingExecutorService;
import ghidra.debug.api.ValStr;
import ghidra.framework.options.SaveState;
@@ -55,6 +57,11 @@ public class InvocationDialogHelper<P, D extends AbstractDebuggerParameterDialog
runSwing(() -> editor.setValue(value));
}
+ public Component getEditorComponent(P param) {
+ PropertyEditor editor = dialog.getEditor(param);
+ return MiscellaneousUtils.getEditorComponent(editor);
+ }
+
protected void runSwing(Runnable r) {
try {
CompletableFuture.runAsync(r, SwingExecutorService.LATER).get();
diff --git a/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/target/TargetMethod.java b/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/target/TargetMethod.java
index bdd50e1e42..66acb362ec 100644
--- a/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/target/TargetMethod.java
+++ b/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/target/TargetMethod.java
@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -223,11 +223,13 @@ public interface TargetMethod extends TargetObject {
p -> new BytesValue.Val(p.defaultBytes()),
p -> new StringValue.Val(p.defaultString()));
- String name();
+ String name() default "";
- String display();
+ String display() default "";
- String description();
+ String description() default "";
+
+ String schema() default "ANY";
// TODO: Something that hints at changes in activation?
@@ -259,6 +261,25 @@ public interface TargetMethod extends TargetObject {
* @param <T> the type of the parameter
*/
class ParameterDescription<T> {
+ /**
+ * Create a parameter
+ *
+ * @param <T> the type of the parameter
+ * @param type the class representing the type of the parameter
+ * @param name the name of the parameter
+ * @param required true if this parameter must be provided
+ * @param defaultValue the default value of this parameter
+ * @param display the human-readable name of this parameter
+ * @param description the human-readable description of this parameter
+ * @param schema the parameter's schema
+ * @return the new parameter description
+ */
+ public static <T> ParameterDescription<T> create(Class<T> type, String name,
+ boolean required, T defaultValue, String display, String description, String schema) {
+ return new ParameterDescription<>(type, name, required, defaultValue, display,
+ description, schema, List.of());
+ }
+
/**
* Create a parameter
*
@@ -274,7 +295,7 @@ public interface TargetMethod extends TargetObject {
public static <T> ParameterDescription<T> create(Class<T> type, String name,
boolean required, T defaultValue, String display, String description) {
return new ParameterDescription<>(type, name, required, defaultValue, display,
- description, List.of());
+ description, "ANY", List.of());
}
/**
@@ -292,7 +313,7 @@ public interface TargetMethod extends TargetObject {
Collection<T> choices, String display, String description) {
T defaultValue = choices.iterator().next();
return new ParameterDescription<>(type, name, false, defaultValue, display, description,
- choices);
+ "ANY", choices);
}
/**
@@ -313,7 +334,7 @@ public interface TargetMethod extends TargetObject {
throw new IllegalArgumentException("Default must be one of the choices.");
}
return new ParameterDescription<>(type, name, false, defaultValue, display, description,
- choices);
+ "ANY", choices);
}
protected static boolean isRequired(Class<?> type, Param param) {
@@ -369,11 +390,11 @@ public interface TargetMethod extends TargetObject {
return type.cast(dv);
}
- protected static <T> ParameterDescription<T> annotated(Class<T> type, Param annot) {
+ protected static <T> ParameterDescription<T> annotated(Class<T> type, Param annot, String name) {
boolean required = isRequired(type, annot);
T defaultValue = getDefault(type, annot);
- return ParameterDescription.create(type, annot.name(),
- required, defaultValue, annot.display(), annot.description());
+ return ParameterDescription.create(type, name,
+ required, defaultValue, annot.display(), annot.description(), annot.schema());
}
public static ParameterDescription<?> annotated(Parameter parameter) {
@@ -382,15 +403,16 @@ public interface TargetMethod extends TargetObject {
throw new IllegalArgumentException(
"Missing @" + Param.class.getSimpleName() + " on " + parameter);
}
+ String name = annot.name().equals("") ? parameter.getName() : annot.name();
if (annot.choicesString().specified()) {
if (parameter.getType() != String.class) {
throw new IllegalArgumentException(
"Can only specify choices for String parameter");
}
- return ParameterDescription.choices(String.class, annot.name(),
- List.of(annot.choicesString().value()), annot.display(), annot.description());
+ return ParameterDescription.choices(String.class, name,
+ List.of(annot.choicesString().value()), annot.display(), annot.description(), annot.schema());
}
- return annotated(MethodType.methodType(parameter.getType()).wrap().returnType(), annot);
+ return annotated(MethodType.methodType(parameter.getType()).wrap().returnType(), annot, name);
}
public final Class<T> type;
@@ -399,16 +421,18 @@ public interface TargetMethod extends TargetObject {
public final boolean required;
public final String display;
public final String description;
+ public final String schema;
public final Set<T> choices;
private ParameterDescription(Class<T> type, String name, boolean required, T defaultValue,
- String display, String description, Collection<T> choices) {
+ String display, String description, String schema, Collection<T> choices) {
this.type = type;
this.name = name;
this.defaultValue = defaultValue;
this.required = required;
this.display = display;
this.description = description;
+ this.schema = schema;
this.choices = Set.copyOf(choices);
}
diff --git a/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/util/ShellUtils.java b/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/util/ShellUtils.java
index 7e4f09e6d0..bad064ff55 100644
--- a/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/util/ShellUtils.java
+++ b/Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/util/ShellUtils.java
@@ -132,15 +132,15 @@ public class ShellUtils {
if (args.isEmpty()) {
return "";
}
- StringBuilder line = new StringBuilder(genreateArgument(args.get(0)));
+ StringBuilder line = new StringBuilder(generateArgument(args.get(0)));
for (int i = 1; i < args.size(); i++) {
String a = args.get(i);
- line.append(" " + genreateArgument(a));
+ line.append(" " + generateArgument(a));
}
return line.toString();
}
- public static String genreateArgument(String a) {
+ public static String generateArgument(String a) {
if (a.contains(" ")) {
if (a.contains("\"")) {
if (a.contains("'")) {
diff --git a/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/ToyDBTraceBuilder.java b/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/ToyDBTraceBuilder.java
index b805b355a2..180a3ff91f 100644
--- a/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/ToyDBTraceBuilder.java
+++ b/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/ToyDBTraceBuilder.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -30,6 +30,7 @@ import java.util.List;
import db.DBHandle;
import db.Transaction;
+import generic.test.AbstractGenericTest;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.dbg.target.TargetExecutionStateful.TargetExecutionState;
@@ -800,13 +801,19 @@ public class ToyDBTraceBuilder implements AutoCloseable {
/**
* Get an object by its path pattern
*
- * @param path the path pattern
+ * @param path the path pattern <em>at snapshot 0 only!</em>
* @return the object or null
*/
- public TraceObject objAny(String path) {
+ public TraceObject objAny0(String path) {
return objAny(path, Lifespan.at(0));
}
+ /**
+ * Get an object by its path pattern intersecting the given lifespan
+ *
+ * @param path the path pattern
+ * @return the object or null
+ */
public TraceObject objAny(String path, Lifespan span) {
return trace.getObjectManager()
.getObjectsByPath(span, TraceObjectKeyPath.parse(path))
@@ -844,6 +851,7 @@ public class ToyDBTraceBuilder implements AutoCloseable {
@Override
public void close() {
if (trace.getConsumerList().contains(this)) {
+ AbstractGenericTest.waitFor(() -> !trace.isLocked());
trace.release(this);
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/misc/RecoverySnapshotMgrPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/misc/RecoverySnapshotMgrPlugin.java
index 4b6671e0f0..05816479f3 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/misc/RecoverySnapshotMgrPlugin.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/misc/RecoverySnapshotMgrPlugin.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -180,6 +180,7 @@ public class RecoverySnapshotMgrPlugin extends Plugin
public void dispose() {
ToolOptions opt = tool.getOptions(OPTIONS_TITLE);
opt.removeOptionsChangeListener(this);
+ stopSnapshotTimer();
super.dispose();
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/options/editor/StringEditor.java b/Ghidra/Framework/Docking/src/main/java/docking/options/editor/StringEditor.java
index 4aa63fbe56..7db8cd3790 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/options/editor/StringEditor.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/options/editor/StringEditor.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,4 +22,31 @@ public class StringEditor extends PropertyEditorSupport {
public StringEditor() {
super();
}
+
+ /**
+ * The comment in the parent "PropertyEditorSupport" reads:
+ *
+ * <blockquote>
+ * <p>
+ * Sets the property value by parsing a given String. May raise
+ * java.lang.IllegalArgumentException if either the String is badly formatted or if this kind of
+ * property can't be expressed as text.
+ * </p>
+ * </blockquote>
+ *
+ * <p>
+ * which would be fine, except for the fact that Java initializes "value" to null, so every use
+ * of this method has to insure that setValue has been called at least once with a non-null
+ * value. If not, the method throws the IllegalArgumentException despite the fact that the input
+ * is not badly formatted and CAN be expressed as text.
+ */
+ @Override
+ public void setAsText(String text) throws java.lang.IllegalArgumentException {
+ Object value = getValue();
+ if (value == null || value instanceof String) {
+ setValue(text);
+ return;
+ }
+ throw new java.lang.IllegalArgumentException(text);
+ }
}
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngHooksTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngHooksTest.java
index 0383fbb296..f143df3169 100644
--- a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngHooksTest.java
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngHooksTest.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -95,7 +95,7 @@ public class DbgEngHooksTest extends AbstractDbgEngTraceRmiTest {
txPut(conn, "processes");
waitForPass(() -> {
- TraceObject proc = tb.objAny("Processes[]");
+ TraceObject proc = tb.objAny0("Processes[]");
assertNotNull(proc);
assertEquals("STOPPED", tb.objValue(proc, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -107,7 +107,7 @@ public class DbgEngHooksTest extends AbstractDbgEngTraceRmiTest {
// Via method, go is asynchronous
RemoteMethod go = conn.conn.getMethod("go");
- TraceObject proc = tb.objAny("Processes[]");
+ TraceObject proc = tb.objAny0("Processes[]");
go.invoke(Map.of("process", proc));
waitForPass(
@@ -273,7 +273,7 @@ public class DbgEngHooksTest extends AbstractDbgEngTraceRmiTest {
""");
waitRunning("Missed running after go");
- TraceObject proc = waitForValue(() -> tb.objAny("Processes[]"));
+ TraceObject proc = waitForValue(() -> tb.objAny0("Processes[]"));
waitForPass(() -> {
assertEquals("RUNNING", tb.objValue(proc, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -285,7 +285,7 @@ public class DbgEngHooksTest extends AbstractDbgEngTraceRmiTest {
try (PythonAndTrace conn = startAndSyncPython("notepad.exe")) {
txPut(conn, "processes");
- TraceObject proc = waitForValue(() -> tb.objAny("Processes[]"));
+ TraceObject proc = waitForValue(() -> tb.objAny0("Processes[]"));
waitForPass(() -> {
assertEquals("STOPPED", tb.objValue(proc, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -307,7 +307,7 @@ public class DbgEngHooksTest extends AbstractDbgEngTraceRmiTest {
assertNotNull(snapshot);
assertEquals("Exited with code 0", snapshot.getDescription());
- TraceObject proc = tb.objAny("Processes[]");
+ TraceObject proc = tb.objAny0("Processes[]");
assertNotNull(proc);
Object val = tb.objValue(proc, lastSnap(conn), "_exit_code");
assertThat(val, instanceOf(Number.class));
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngMethodsTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngMethodsTest.java
index d8592ae7b0..f6decb6c61 100644
--- a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngMethodsTest.java
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/dbgeng/rmi/DbgEngMethodsTest.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -82,7 +82,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
RemoteMethod refreshAvailable = conn.getMethod("refresh_available");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/noname")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject available = Objects.requireNonNull(tb.objAny("Available"));
+ TraceObject available = Objects.requireNonNull(tb.objAny0("Available"));
refreshAvailable.invoke(Map.of("node", available));
@@ -111,7 +111,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
conn.execute("util.dbg.ba(expr=pc+4)");
txPut(conn, "breakpoints");
TraceObject breakpoints =
- Objects.requireNonNull(tb.objAny("Processes[].Breakpoints"));
+ Objects.requireNonNull(tb.objAny0("Processes[].Breakpoints"));
refreshBreakpoints.invoke(Map.of("node", breakpoints));
List<TraceObjectValue> procBreakLocVals = tb.trace.getObjectManager()
@@ -150,7 +150,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
conn.execute("util.dbg.ba(expr=pc+4, access=DbgEng.DEBUG_BREAK_READ)");
conn.execute("util.dbg.ba(expr=pc+8, access=DbgEng.DEBUG_BREAK_WRITE)");
TraceObject locations =
- Objects.requireNonNull(tb.objAny("Processes[].Breakpoints"));
+ Objects.requireNonNull(tb.objAny0("Processes[].Breakpoints"));
refreshProcWatchpoints.invoke(Map.of("node", locations));
List<TraceObjectValue> procBreakVals = tb.trace.getObjectManager()
@@ -193,7 +193,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
RemoteMethod refreshProcesses = conn.getMethod("refresh_processes");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/noname")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject processes = Objects.requireNonNull(tb.objAny("Processes"));
+ TraceObject processes = Objects.requireNonNull(tb.objAny0("Processes"));
refreshProcesses.invoke(Map.of("node", processes));
@@ -217,7 +217,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
RemoteMethod refreshEnvironment = conn.getMethod("refresh_environment");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/notepad.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject env = Objects.requireNonNull(tb.objAny(path));
+ TraceObject env = Objects.requireNonNull(tb.objAny0(path));
refreshEnvironment.invoke(Map.of("node", env));
@@ -240,7 +240,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
RemoteMethod refreshThreads = conn.getMethod("refresh_threads");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/notepad.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject threads = Objects.requireNonNull(tb.objAny(path));
+ TraceObject threads = Objects.requireNonNull(tb.objAny0(path));
refreshThreads.invoke(Map.of("node", threads));
@@ -263,7 +263,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
txPut(conn, "frames");
- TraceObject stack = Objects.requireNonNull(tb.objAny(path));
+ TraceObject stack = Objects.requireNonNull(tb.objAny0(path));
refreshStack.invoke(Map.of("node", stack));
// Would be nice to control / validate the specifics
@@ -315,7 +315,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
RemoteMethod refreshMappings = conn.getMethod("refresh_mappings");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/notepad.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject memory = Objects.requireNonNull(tb.objAny(path));
+ TraceObject memory = Objects.requireNonNull(tb.objAny0(path));
refreshMappings.invoke(Map.of("node", memory));
@@ -337,7 +337,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
RemoteMethod refreshModules = conn.getMethod("refresh_modules");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/notepad.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject modules = Objects.requireNonNull(tb.objAny(path));
+ TraceObject modules = Objects.requireNonNull(tb.objAny0(path));
refreshModules.invoke(Map.of("node", modules));
@@ -390,7 +390,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/netstat.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc2 = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc2 = Objects.requireNonNull(tb.objAny0("Processes[]"));
removeProcess.invoke(Map.of("process", proc2));
String out = conn.executeCapture("print(list(util.process_list()))");
@@ -451,7 +451,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/netstat.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
detach.invoke(Map.of("process", proc));
String out = conn.executeCapture("print(list(util.process_list()))");
@@ -512,7 +512,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped("Missed initial stop");
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
kill.invoke(Map.of("process", proc));
String out = conn.executeCapture("print(list(util.process_list()))");
@@ -535,7 +535,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped("Missed initial stop");
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
for (int i = 0; i < 5; i++) {
go.invoke(Map.of("process", proc));
@@ -561,7 +561,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
waitStopped("Missed initial stop");
txPut(conn, "threads");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
while (!getInst(conn).contains("call")) {
stepInto.invoke(Map.of("thread", thread));
@@ -595,7 +595,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
waitStopped("Missed initial stop");
txPut(conn, "threads");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
while (!getInst(conn).contains("call")) {
stepOver.invoke(Map.of("thread", thread));
@@ -623,7 +623,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
txPut(conn, "threads");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
while (!getInst(conn).contains("call")) {
stepInto.invoke(Map.of("thread", thread));
}
@@ -656,7 +656,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
waitStopped("Missed initial stop");
txPut(conn, "threads");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
while (!getInst(conn).contains("call")) {
stepInto.invoke(Map.of("thread", thread));
@@ -683,7 +683,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/notepad.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = getAddressAtOffset(conn, 0);
breakAddress.invoke(Map.of("process", proc, "address", tb.addr(address)));
@@ -723,7 +723,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/pydbg/notepad.exe")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = getAddressAtOffset(conn, 0);
breakAddress.invoke(Map.of("process", proc, "address", tb.addr(address)));
@@ -764,7 +764,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped("Missed initial stop");
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = getAddressAtOffset(conn, 0);
AddressRange range = tb.range(address, address + 3); // length 4
breakRange.invoke(Map.of("process", proc, "range", range));
@@ -809,7 +809,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped("Missed initial stop");
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = getAddressAtOffset(conn, 0);
AddressRange range = tb.range(address, address + 3); // length 4
breakRange.invoke(Map.of("process", proc, "range", range));
@@ -854,7 +854,7 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped("Missed initial stop");
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = getAddressAtOffset(conn, 0);
AddressRange range = tb.range(address, address + 3); // length 4
breakRange.invoke(Map.of("process", proc, "range", range));
@@ -900,11 +900,11 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
long address = getAddressAtOffset(conn, 0);
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
breakAddress.invoke(Map.of("process", proc, "address", tb.addr(address)));
txPut(conn, "breakpoints");
- TraceObject bpt = Objects.requireNonNull(tb.objAny("Processes[].Breakpoints[]"));
+ TraceObject bpt = Objects.requireNonNull(tb.objAny0("Processes[].Breakpoints[]"));
toggleBreakpoint.invoke(Map.of("breakpoint", bpt, "enabled", false));
@@ -926,11 +926,11 @@ public class DbgEngMethodsTest extends AbstractDbgEngTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
long address = getAddressAtOffset(conn, 0);
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
breakAddress.invoke(Map.of("process", proc, "address", tb.addr(address)));
txPut(conn, "breakpoints");
- TraceObject bpt = Objects.requireNonNull(tb.objAny("Processes[].Breakpoints[]"));
+ TraceObject bpt = Objects.requireNonNull(tb.objAny0("Processes[].Breakpoints[]"));
deleteBreakpoint.invoke(Map.of("breakpoint", bpt));
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/AbstractJavaTraceRmiTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/AbstractJavaTraceRmiTest.java
new file mode 100644
index 0000000000..9eb9ff8ff8
--- /dev/null
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/AbstractJavaTraceRmiTest.java
@@ -0,0 +1,581 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package agent.java.rmi;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.net.*;
+import java.nio.file.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.function.*;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.junit.Before;
+
+import generic.Unique;
+import generic.jar.ResourceFile;
+import ghidra.app.plugin.core.debug.gui.AbstractGhidraHeadedDebuggerTest;
+import ghidra.app.plugin.core.debug.service.tracermi.TraceRmiPlugin;
+import ghidra.app.plugin.core.debug.utils.ManagedDomainObject;
+import ghidra.app.plugin.core.misc.RecoverySnapshotMgrPlugin;
+import ghidra.app.services.TraceRmiService;
+import ghidra.dbg.util.PathPredicates;
+import ghidra.debug.api.tracermi.*;
+import ghidra.framework.Application;
+import ghidra.framework.main.ApplicationLevelOnlyPlugin;
+import ghidra.framework.main.FrontEndTool;
+import ghidra.framework.model.DomainFile;
+import ghidra.framework.plugintool.Plugin;
+import ghidra.framework.plugintool.PluginsConfiguration;
+import ghidra.framework.plugintool.util.*;
+import ghidra.program.model.address.Address;
+import ghidra.trace.model.Lifespan;
+import ghidra.trace.model.target.TraceObject;
+import ghidra.trace.model.target.TraceObjectValue;
+import ghidra.util.Msg;
+import junit.framework.AssertionFailedError;
+
+public abstract class AbstractJavaTraceRmiTest extends AbstractGhidraHeadedDebuggerTest {
+
+ /**
+ * TODO: It would be nice if we didn't have to initialize a "Ghidra application" in order to use
+ * the RmiClient; however, I'm not sure that's worth it.
+ */
+ public static final String PREAMBLE = """
+ import java.io.*;
+ import java.util.*;
+ import com.sun.jdi.*;
+ import com.sun.jdi.request.*;
+ import ghidra.dbg.jdi.rmi.jpda.*;
+ import ghidra.dbg.jdi.manager.impl.*;
+ import ghidra.framework.Application;
+ import ghidra.framework.GhidraApplicationConfiguration;
+ import ghidra.GhidraApplicationLayout;
+ import ghidra.program.model.address.*;
+ import ghidra.app.plugin.core.debug.client.tracermi.*;
+ import ghidra.rmi.trace.TraceRmi.MemoryState;
+
+ GhidraApplicationLayout layout = new GhidraApplicationLayout();
+ GhidraApplicationConfiguration config = new GhidraApplicationConfiguration();
+ config.setShowSplashScreen(false);
+ Application.initializeApplication(layout, config);
+
+ JdiManagerImpl manager = new JdiManagerImpl();
+ JdiManager jdiManager = new JdiManager(manager);
+ JdiCommands cmds = jdiManager.getCommands();
+ JdiMethods meths = jdiManager.getMethods();
+ JdiHooks hooks = jdiManager.getHooks();
+ hooks.installHooks();
+ """;
+ // Connecting should be the first thing the script does, so use a tight timeout.
+ protected static final int CONNECT_TIMEOUT_MS = 3000;
+ protected static final int TIMEOUT_SECONDS = 300;
+ protected static final int QUIT_TIMEOUT_MS = 1000;
+ protected static final long EXT_TIMEOUT_MS = 5000;
+ protected static final long EXT_RETRY_MS = 500;
+
+ protected TraceRmiService traceRmi;
+ private Path jshellPath;
+ private Path outFile;
+ private Path errFile;
+
+ @Before
+ public void setupTraceRmi() throws Throwable {
+ traceRmi = addPlugin(tool, TraceRmiPlugin.class);
+
+ traceManager.setSaveTracesByDefault(false);
+
+ jshellPath = Paths.get(System.getProperty("java.home")).resolve("bin/jshell");
+ outFile = Files.createTempFile("jshout", null);
+ errFile = Files.createTempFile("jsherr", null);
+
+ FrontEndTool frontEndTool = env.getFrontEndTool();
+ Plugin recoveryPlugin = frontEndTool.getManagedPlugins()
+ .stream()
+ .filter(p -> p instanceof RecoverySnapshotMgrPlugin)
+ .findAny()
+ .get();
+ frontEndTool.removePlugins(List.of(recoveryPlugin));
+ }
+
+ protected void addAllDebuggerPlugins() throws PluginException {
+ PluginsConfiguration plugConf = new PluginsConfiguration() {
+ @Override
+ protected boolean accepts(Class<? extends Plugin> pluginClass) {
+ return !ApplicationLevelOnlyPlugin.class.isAssignableFrom(pluginClass);
+ }
+ };
+
+ for (PluginDescription pd : plugConf
+ .getPluginDescriptions(PluginPackage.getPluginPackage("Debugger"))) {
+ addPlugin(tool, pd.getPluginClass());
+ }
+ }
+
+ protected static String addrToStringForJshell(InetAddress address) {
+ if (address.isAnyLocalAddress()) {
+ return "127.0.0.1"; // Can't connect to 0.0.0.0 as such. Choose localhost.
+ }
+ return address.getHostAddress();
+ }
+
+ protected static String sockToStringForJshell(SocketAddress address) {
+ if (address instanceof InetSocketAddress tcp) {
+ return addrToStringForJshell(tcp.getAddress()) + ":" + tcp.getPort();
+ }
+ throw new AssertionError("Unhandled address type " + address);
+ }
+
+ protected record JshellResult(boolean timedOut, int exitCode, String stdout, String stderr) {
+ protected String handle() {
+ if (stderr.contains("Error:") || (0 != exitCode)) {
+ throw new JshellError(exitCode, stdout, stderr);
+ }
+ System.out.println("--stdout--");
+ System.out.println(stdout);
+ System.out.println("--stderr--");
+ System.out.println(stderr);
+ return stdout;
+ }
+ }
+
+ protected record ExecInJshell(Process jshell, AbstractJavaTraceRmiTest test,
+ CompletableFuture<JshellResult> future) {}
+
+ private String parseClassPath() {
+ String classPath = System.getProperty("java.class.path");
+ String[] split = classPath.split(":");
+ String newClassPath = "";
+ for (String p : split) {
+ File file = new File(p);
+ if (file.exists()) {
+ newClassPath += p + ":";
+ }
+ }
+ return newClassPath;
+ }
+
+ @SuppressWarnings("resource") // Do not close stdin
+ protected ExecInJshell execInJshell(String script) throws IOException {
+ String classPath = parseClassPath();
+ ProcessBuilder pb = new ProcessBuilder(jshellPath.toString(), "--class-path=" + classPath);
+
+ // If commands come from file, jshell will quit after EOF.
+ Msg.info(this, "outFile: " + outFile);
+ Msg.info(this, "errFile: " + errFile);
+
+ ResourceFile rf = Application.getModuleDataFile("TestResources", "HelloWorld.class");
+ pb.environment().put("OPT_TARGET_CLASSPATH", rf.getParentFile().getAbsolutePath());
+ pb.environment().put("OPT_TARGET_CLASS", "HelloWorld");
+ pb.environment().put("OPT_SUSPEND", "true");
+ pb.environment().put("OPT_INCLUDE", "n");
+ //pb.inheritIO();
+ pb.redirectInput(ProcessBuilder.Redirect.PIPE);
+ pb.redirectOutput(outFile.toFile());
+ pb.redirectError(errFile.toFile());
+ Process proc = pb.start();
+ OutputStream stdin = proc.getOutputStream();
+ stdin.write(script.getBytes());
+ stdin.flush();
+ //stdin.close();
+ return new ExecInJshell(proc, this, CompletableFuture.supplyAsync(() -> {
+ try {
+ if (!proc.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
+ Msg.error(this, "Timed out waiting for jshell");
+ proc.destroyForcibly();
+ proc.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ return new JshellResult(true, -1, Files.readString(outFile),
+ Files.readString(errFile));
+ }
+ Msg.info(this, "jshell exited with code " + proc.exitValue());
+ return new JshellResult(false, proc.exitValue(), Files.readString(outFile),
+ Files.readString(errFile));
+ }
+ catch (Exception e) {
+ return ExceptionUtils.rethrow(e);
+ }
+ finally {
+ proc.destroyForcibly();
+ }
+ }));
+ }
+
+ public static class JshellError extends RuntimeException {
+ public final int exitCode;
+ public final String stdout;
+ public final String stderr;
+
+ public JshellError(int exitCode, String stdout, String stderr) {
+ super("""
+ exitCode=%d:
+ ----stdout----
+ %s
+ ----stderr----
+ %s
+ """.formatted(exitCode, stdout, stderr));
+ this.exitCode = exitCode;
+ this.stdout = stdout;
+ this.stderr = stderr;
+ }
+ }
+
+ protected String runThrowError(String script) throws Exception {
+ CompletableFuture<JshellResult> result = execInJshell(script).future;
+ return result.get(TIMEOUT_SECONDS, TimeUnit.SECONDS).handle();
+ }
+
+ protected record JshellAndConnection(ExecInJshell exec, TraceRmiConnection connection)
+ implements AutoCloseable {
+ private static BufferedReader reader = null;
+
+ protected RemoteMethod getMethod(String name) {
+ return Objects.requireNonNull(connection.getMethods().get(name));
+ }
+
+ public void execute(String cmd) {
+ try {
+ cmd += "\n";
+ exec.jshell.getOutputStream().write(cmd.getBytes());
+ exec.jshell.getOutputStream().flush();
+ }
+ catch (IOException e) {
+ throw new AssertionError(e.getMessage());
+ }
+ }
+
+ public RemoteAsyncResult executeAsync(String cmd) {
+ RemoteMethod execute = getMethod("execute");
+ return execute.invokeAsync(Map.of("cmd", cmd));
+ }
+
+ public List<String> executeCapture(String cmd) {
+ try {
+ if (reader == null) {
+ reader = Files.newBufferedReader(exec.test.outFile);
+ }
+ if (cmd != null) {
+ execute(cmd);
+ }
+ List<String> collect = waitForPass(() -> {
+ List<String> list = reader.lines().collect(Collectors.toList());
+ assertFalse(list.isEmpty());
+ return list;
+ });
+ return collect;
+ }
+ catch (IOException e) {
+ throw new AssertionError(e.getMessage());
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ Msg.info(this, "Cleaning up jshell");
+ execute("/exit");
+ try {
+ JshellResult r = exec.future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ r.handle();
+ connection.close();
+ }
+ finally {
+ exec.jshell.destroyForcibly();
+ }
+ }
+
+ public void waitOnClosed() {
+ waitForPass(() -> assertTrue(connection.isClosed()));
+ }
+ }
+
+ protected JshellAndConnection startAndConnectJshell(Function<String, String> scriptSupplier)
+ throws Exception {
+ TraceRmiAcceptor acceptor = traceRmi.acceptOne(null);
+ ExecInJshell exec =
+ execInJshell(scriptSupplier.apply(sockToStringForJshell(acceptor.getAddress())));
+ acceptor.setTimeout(TIMEOUT_SECONDS * 1000);
+ try {
+ TraceRmiConnection connection = acceptor.accept();
+ return new JshellAndConnection(exec, connection);
+ }
+ catch (SocketTimeoutException e) {
+ exec.jshell.destroyForcibly();
+ exec.future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS).handle();
+ throw e;
+ }
+ }
+
+ protected JshellAndConnection startAndConnectJshell() throws Exception {
+ return startAndConnectJshell(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ """.formatted(PREAMBLE, addr));
+ }
+
+ @SuppressWarnings("resource")
+ protected String runThrowError(Function<String, String> scriptSupplier)
+ throws Exception {
+ JshellAndConnection conn = startAndConnectJshell(scriptSupplier);
+ JshellResult r = conn.exec.future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ String stdout = r.handle();
+ /**
+ * We know at this point the process should be terminated. Depending on how cleanly that
+ * happened, the socket may or may not be closed. Do not assert/wait for it to close. Just
+ * clean up by closing our end
+ */
+ conn.connection.close();
+ assertFalse(stdout.contains("Error:"));
+ return stdout;
+ }
+
+ protected void waitStopped(String message, Long snap) {
+ TraceObject proc = Objects.requireNonNull(tb.objAny("VMs[]", Lifespan.at(snap)));
+ waitForPass(() -> assertEquals(message, "STOPPED", tb.objValue(proc, 0, "_state")));
+ waitTxDone();
+ }
+
+ protected void waitRunning(String message, Long snap) {
+ TraceObject proc = Objects.requireNonNull(tb.objAny("VMs[]", Lifespan.at(snap)));
+ waitForPass(() -> assertEquals(message, "RUNNING", tb.objValue(proc, 0, "_state")));
+ waitTxDone();
+ }
+
+ protected void waitAny(String message, Long snap) {
+ TraceObject proc = Objects.requireNonNull(tb.objAny("VMs[]", Lifespan.at(snap)));
+ waitForPass(() -> assertNotNull(message, tb.objValue(proc, 0, "_state")));
+ waitTxDone();
+ }
+
+ protected String extractOutSection(String out, String head) {
+ String[] split = out.split("\n");
+ String xout = "";
+ for (String s : split) {
+ if (!s.startsWith("jshell>") && !s.equals("")) {
+ if (s.startsWith("INFO") || s.startsWith("ERROR") || s.startsWith("WARN")) {
+ if (s.indexOf("(") > 0) {
+ s = s.substring(0, s.lastIndexOf("(")).trim();
+ }
+ }
+ xout += s + "\n";
+ }
+ }
+ return xout.split(head)[1].split("---")[0].replace("jshell>", "").trim();
+ }
+
+ record MemDump(long address, byte[] data) {}
+
+ protected MemDump parseHexDump(String dump) throws IOException {
+ // First, get the address. Assume contiguous, so only need top line.
+ List<String> lines = List.of(dump.split("\n"));
+ String bytes = lines.get(0);
+ bytes = bytes.substring(bytes.indexOf("{") + 1, bytes.indexOf("}"));
+ List<String> toks = List.of(bytes.split(",\\s+"));
+ String addrstr = lines.get(1);
+ long address = Long.parseLong(addrstr, 16);
+
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ byte[] lineData = new byte[toks.size()];
+ int i = 0;
+ for (String t : toks) {
+ lineData[i++] = Byte.parseByte(t.trim());
+ }
+ buf.write(lineData);
+ return new MemDump(address, buf.toByteArray());
+ }
+
+ protected ManagedDomainObject openDomainObject(String path) throws Exception {
+ DomainFile dfx = waitForPass(() -> {
+ DomainFile df = env.getProject().getProjectData().getFile(path);
+ assertNotNull(df);
+ return df;
+ }, TIMEOUT_SECONDS * 1000, 500);
+ return new ManagedDomainObject(dfx, false, false, monitor);
+ }
+
+ protected ManagedDomainObject waitDomainObject(String path) throws Exception {
+ DomainFile df;
+ long start = System.currentTimeMillis();
+ while (true) {
+ df = env.getProject().getProjectData().getFile(path);
+ if (df != null) {
+ return new ManagedDomainObject(df, false, false, monitor);
+ }
+ Thread.sleep(1000);
+ if (System.currentTimeMillis() - start > 30000) {
+ throw new TimeoutException("30 seconds expired waiting for domain file");
+ }
+ }
+ }
+
+ protected void waitTxDone() {
+ waitForCondition(() -> tb.trace.getCurrentTransactionInfo() == null,
+ () -> "Error waiting for transaction to finish");
+ }
+
+ public static <T> T waitForPass(Supplier<T> supplier) {
+ var locals = new Object() {
+ AssertionError lastError;
+ T value;
+ };
+ waitForCondition(() -> {
+ try {
+ locals.value = supplier.get();
+ return true;
+ }
+ catch (AssertionError e) {
+ locals.lastError = e;
+ return false;
+ }
+ }, () -> locals.lastError.getMessage());
+ return locals.value;
+ }
+
+ public static void waitForCondition(BooleanSupplier condition,
+ Supplier<String> failureMessageSupplier) throws AssertionFailedError {
+
+ int totalTime = 0;
+ while (totalTime <= DEFAULT_WAIT_TIMEOUT * 10) {
+
+ if (condition.getAsBoolean()) {
+ return; // success
+ }
+
+ totalTime += sleep(DEFAULT_WAIT_DELAY * 10);
+ }
+
+ String failureMessage = "Timed-out waiting for condition";
+ if (failureMessageSupplier != null) {
+ failureMessage = failureMessageSupplier.get();
+ }
+
+ throw new AssertionFailedError(failureMessage);
+ }
+
+ public static void waitForPass(Runnable runnable, long timeoutMs, long retryDelayMs) {
+ long start = System.currentTimeMillis();
+ AssertionError lastError = null;
+ while (System.currentTimeMillis() - start < timeoutMs) {
+ try {
+ runnable.run();
+ return;
+ }
+ catch (AssertionError e) {
+ lastError = e;
+ }
+ try {
+ Thread.sleep(retryDelayMs);
+ }
+ catch (InterruptedException e) {
+ // Retry sooner, I guess.
+ }
+ }
+ if (lastError == null) {
+ throw new AssertionError("Timed out before first try?");
+ }
+ throw lastError;
+ }
+
+ public static <T> T waitForPass(Supplier<T> supplier, long timeoutMs, long retryDelayMs) {
+ var locals = new Object() {
+ T value;
+ };
+ waitForPass(() -> {
+ locals.value = supplier.get();
+ }, timeoutMs, retryDelayMs);
+ return locals.value;
+ }
+
+ protected long getMaxSnap() {
+ Long maxSnap = tb.trace.getTimeManager().getMaxSnap();
+ return maxSnap == null ? 0 : maxSnap;
+ }
+
+ protected TraceObject waitForObject(String path) {
+ return waitForPass(() -> {
+ TraceObject obj = tb.objAny(path, Lifespan.at(getMaxSnap()));
+ assertNotNull("Object " + path + " never appeared.", obj);
+ return obj;
+ });
+ }
+
+ protected List<TraceObjectValue> getValues(String path) {
+ return tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(getMaxSnap()), PathPredicates.parse(path))
+ .map(p -> p.getLastEntry())
+ .sorted(Comparator.comparing(TraceObjectValue::getEntryKey))
+ .toList();
+ }
+
+ protected List<TraceObjectValue> waitForValuesPass(String path,
+ Consumer<List<TraceObjectValue>> asserter) {
+ return waitForPass(() -> {
+ List<TraceObjectValue> vals = getValues(path);
+ asserter.accept(vals);
+ return vals;
+ });
+ }
+
+ protected List<TraceObjectValue> waitForValues(String path) {
+ return waitForValuesPass(path, vals -> assertFalse(vals.isEmpty()));
+ }
+
+ protected Address getPC() {
+ return (Address) Unique
+ .assertOne(tb.objValues(getMaxSnap(), "VMs[].Threads[main].Stack[0].PC"));
+ }
+
+ protected Address waitForPC(Consumer<Address> asserter) {
+ return waitForPass(() -> {
+ Address pc = getPC();
+ asserter.accept(pc);
+ return pc;
+ });
+ }
+
+ public static void assertMatches(String expectedPattern, TraceObject object) {
+ assertTrue("Expected matches " + expectedPattern + " but was " +
+ object.getCanonicalPath().toString(),
+ PathPredicates.parse(expectedPattern).matches(object.getCanonicalPath().getKeyList()));
+ }
+
+ protected void waitForLocation(String clsName, String methodName, long codeIndex) {
+ try {
+ waitForValuesPass("VMs[].Threads[main].Stack[0].Location.Method", methods -> {
+ assertMatches("VMs[].Classes[" + clsName + "].Methods[" + methodName + "]",
+ Unique.assertOne(methods).getChild());
+ });
+ waitForValuesPass("VMs[].Threads[main].Stack[0].Location.Index", indices -> {
+ assertEquals(codeIndex, Unique.assertOne(indices).getValue());
+ });
+ }
+ catch (AssertionError e) {
+ TraceObjectValue locVal = Unique.assertAtMostOne(
+ getValues("VMs[].Threads[main].Stack[0].Location"));
+ if (locVal == null) {
+ throw new AssertionError("Wrong location. Expected %s.%s:%d but was null"
+ .formatted(clsName, methodName, codeIndex));
+ }
+ TraceObject loc = locVal.getChild();
+ long snap = getMaxSnap();
+ throw new AssertionError("Wrong location. Expected %s.%s:%d but was %s:%d"
+ .formatted(clsName, methodName, codeIndex,
+ loc.getAttribute(snap, "Method").getValue(),
+ loc.getAttribute(snap, "Index").getValue()));
+ }
+ }
+}
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaCommandsTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaCommandsTest.java
new file mode 100644
index 0000000000..ca9d4aa33c
--- /dev/null
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaCommandsTest.java
@@ -0,0 +1,1075 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package agent.java.rmi;
+
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.junit.Assert.*;
+
+import java.nio.ByteBuffer;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+
+import org.junit.Test;
+
+import generic.Unique;
+import ghidra.app.plugin.core.debug.utils.ManagedDomainObject;
+import ghidra.dbg.util.PathPredicates;
+import ghidra.debug.api.tracermi.TraceRmiAcceptor;
+import ghidra.debug.api.tracermi.TraceRmiConnection;
+import ghidra.framework.model.DomainFile;
+import ghidra.lifecycle.Unfinished;
+import ghidra.program.model.address.*;
+import ghidra.program.model.lang.RegisterValue;
+import ghidra.program.model.listing.CodeUnit;
+import ghidra.trace.database.ToyDBTraceBuilder;
+import ghidra.trace.model.*;
+import ghidra.trace.model.memory.*;
+import ghidra.trace.model.modules.TraceModule;
+import ghidra.trace.model.target.*;
+import ghidra.trace.model.thread.TraceThread;
+import ghidra.trace.model.time.TraceSnapshot;
+import ghidra.util.Msg;
+
+public class JavaCommandsTest extends AbstractJavaTraceRmiTest {
+
+ public static final String HWSETUP = """
+ cmds.ghidraTraceStart("HelloWorld.class");
+ cmds.ghidraTraceCreate(System.getenv());
+ cmds.ghidraTraceTxStart("Create snapshot");
+ cmds.ghidraTraceNewSnap("Scripted snapshot");
+ """;
+
+ public static final String HWSETUP_W_STATE =
+ """
+ cmds.ghidraTraceStart("HelloWorld.class");
+ cmds.ghidraTraceCreate(System.getenv());
+ // No state yet
+ ThreadReference thread = manager.getCurrentThread();
+ VirtualMachine vm = manager.getCurrentVM();
+ StepRequest stepReq = vm.eventRequestManager().createStepRequest(thread, StepRequest.STEP_MIN, StepRequest.STEP_INTO);
+ stepReq.enable();
+ vm.resume();
+ cmds.ghidraTraceTxStart("Create snapshot");
+ cmds.ghidraTraceNewSnap("Scripted snapshot");
+ Location loc = manager.getCurrentLocation();
+ Address pc = jdiManager.getAddressFromLocation(loc);
+ """;
+
+ public static final String TESTSETUP = """
+ cmds.ghidraTraceStart("Test");
+ cmds.ghidraTraceTxStart("Create Object")
+ cmds.ghidraTraceNewSnap("Scripted snapshot");
+ System.err.println("Created snapshot");
+ cmds.ghidraTraceCreateObj("Test.Objects[1]");
+ cmds.ghidraTraceInsertObj("Test.Objects[1]");
+ """;
+
+ //@Test
+ public void testManual() throws Exception {
+ TraceRmiAcceptor acceptor = traceRmi.acceptOne(null);
+ Msg.info(this,
+ "Use: cmds.ghidraTraceConnect(" + sockToStringForJshell(acceptor.getAddress()) + ")");
+ TraceRmiConnection connection = acceptor.accept();
+ Msg.info(this, "Connected: " + sockToStringForJshell(connection.getRemoteAddress()));
+ connection.waitClosed();
+ Msg.info(this, "Closed");
+ }
+
+ @Test
+ public void testConnect() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ /exit
+ """.formatted(PREAMBLE, addr));
+ }
+
+ @Test
+ public void testDisconnect() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr));
+ }
+
+ @Test
+ public void testStartTraceDefaults() throws Exception {
+ // Default name and lcsp
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ cmds.ghidraTraceStart("HelloWorld.class");
+ /exit
+ """.formatted(PREAMBLE, addr));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ assertEquals("JVM:BE:32:default",
+ tb.trace.getBaseLanguage().getLanguageID().getIdAsString());
+ assertEquals("default",
+ tb.trace.getBaseCompilerSpec().getCompilerSpecID().getIdAsString());
+ }
+ }
+
+ @Test
+ public void testStartTraceDefaultNoFile() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ cmds.ghidraTraceStart(null);
+ /exit
+ """.formatted(PREAMBLE, addr));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/jdi/noname")) {
+ assertThat(mdo.get(), instanceOf(Trace.class));
+ }
+ }
+
+ @Test
+ public void testStopTrace() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ cmds.ghidraTraceCreate(System.getenv());
+ cmds.ghidraTraceStart("HelloWorld.class");
+ cmds.ghidraTraceStop();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr));
+ DomainFile dfMyToy =
+ env.getProject().getProjectData().getFile("/New Traces/HelloWorld.class");
+ assertNotNull(dfMyToy);
+ assertFalse(dfMyToy.isOpen());
+ }
+
+ @Test
+ public void testInfo() throws Exception {
+ AtomicReference<String> refAddr = new AtomicReference<>();
+ String out = runThrowError(addr -> {
+ refAddr.set(addr);
+ return """
+ %s
+ System.out.println("---Import---");
+ cmds.ghidraTraceInfo();
+ System.out.println("---BeforeConnect---");
+ cmds.ghidraTraceConnect("%s");
+ System.out.println("---Connect---");
+ cmds.ghidraTraceInfo();
+ System.out.println("---Create---");
+ cmds.ghidraTraceStart("HelloWorld.class");
+ cmds.ghidraTraceCreate(System.getenv());
+ System.out.println("---Start---");
+ cmds.ghidraTraceInfo();
+ cmds.ghidraTraceStop();
+ System.out.println("---Stop---");
+ cmds.ghidraTraceInfo();
+ cmds.ghidraTraceDisconnect();
+ System.out.println("---Disconnect---");
+ cmds.ghidraTraceInfo();
+ /exit
+ """.formatted(PREAMBLE, addr);
+ });
+
+ assertEquals("""
+ ERROR Not connected to Ghidra""",
+ extractOutSection(out, "---Import---"));
+ assertEquals("""
+ INFO Connected to jdi at /%s
+ ERROR No trace""".formatted(refAddr.get()),
+ extractOutSection(out, "---Connect---").replaceAll("\r", ""));
+ assertEquals("""
+ INFO Connected to jdi at /%s
+ INFO Trace active""".formatted(refAddr.get()),
+ extractOutSection(out, "---Start---").replaceAll("\r", ""));
+ assertEquals("""
+ ERROR Not connected to Ghidra\n| Goodbye""",
+ extractOutSection(out, "---Disconnect---"));
+ }
+
+ @Test
+ public void testLcsp() throws Exception {
+ String out = runThrowError(
+ """
+ %s
+ System.out.println("---Import---");
+ cmds.ghidraTraceInfoLcsp();
+ System.out.println("---Create---");
+ cmds.ghidraTraceCreate(System.getenv());
+ System.out.println("---File---");
+ cmds.ghidraTraceInfoLcsp();
+ /exit
+ """.formatted(PREAMBLE));
+
+ assertEquals("""
+ INFO Selected Ghidra language: JVM:BE:32:default
+ INFO Selected Ghidra compiler: default
+ | Goodbye""",
+ extractOutSection(out, "---File---").replaceAll("\r", ""));
+ }
+
+ @Test
+ public void testSave() throws Exception {
+ traceManager.setSaveTracesByDefault(false);
+
+ // For sanity check, verify failing to save drops data
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceStop();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ assertEquals(0, tb.trace.getTimeManager().getAllSnapshots().size());
+ }
+ finally {
+ tb.close();
+
+ DomainFile df =
+ env.getProject().getProjectData().getFile("/New Traces/HelloWorld.class");
+ waitForCondition(() -> !df.isOpen());
+ df.delete();
+ }
+
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceStop();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ assertNotEquals(0, tb.trace.getTimeManager().getAllSnapshots().size());
+ }
+ }
+
+ @Test
+ public void testSnapshot() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ assertEquals(2, tb.trace.getTimeManager().getAllSnapshots().size());
+ TraceSnapshot snapshot = getLastSnapshot();
+ assertEquals(1, snapshot.getKey());
+ assertEquals("Scripted snapshot", snapshot.getDescription());
+ }
+ }
+
+ @Test
+ public void testPutMem() throws Exception {
+ String out = runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutMem(pc, 16);
+ cmds.ghidraTraceTxCommit();
+ Method method = jdiManager.getMethodForAddress(pc);
+ System.out.println("---Dump---");
+ byte[] bytecodes = method.bytecodes();
+ System.out.println(pc);
+ System.out.println("---");
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ MemDump dump = parseHexDump(extractOutSection(out, "---Dump---"));
+ ByteBuffer buf = ByteBuffer.allocate(dump.data().length);
+ tb.trace.getMemoryManager().getBytes(snap, tb.addr(dump.address()), buf);
+
+ assertArrayEquals(dump.data(), buf.array());
+ }
+ }
+
+ @Test
+ public void testPutMemState() throws Exception {
+ String out = runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutMemState(pc, 16, MemoryState.MS_KNOWN);
+ cmds.ghidraTraceTxCommit();
+ Method method = jdiManager.getMethodForAddress(pc);
+ System.out.println("---Start---");
+ byte[] bytecodes = method.bytecodes();
+ System.out.println(pc);
+ System.out.println("---");
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ String eval = extractOutSection(out, "---Start---");
+ List<String> lines = List.of(eval.split("\n"));
+ Address addr = tb.addr(Long.parseLong(lines.get(1), 16));
+
+ Entry<TraceAddressSnapRange, TraceMemoryState> entry =
+ tb.trace.getMemoryManager().getMostRecentStateEntry(snap, addr);
+ assertEquals(Map.entry(new ImmutableTraceAddressSnapRange(
+ rng(addr, 16), Lifespan.at(2)), TraceMemoryState.KNOWN), entry);
+ }
+ }
+
+ @Test
+ public void testDelMem() throws Exception {
+ String out = runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceSetSnap(1);
+ cmds.ghidraTraceDelMem(pc, 8);
+ cmds.ghidraTraceTxCommit();
+ Method method = jdiManager.getMethodForAddress(pc);
+ System.out.println("---Dump---");
+ byte[] bytecodes = method.bytecodes();
+ System.out.println(pc);
+ System.out.println("---");
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ MemDump dump = parseHexDump(extractOutSection(out, "---Dump---"));
+ Arrays.fill(dump.data(), 0, 8, (byte) 0);
+ ByteBuffer buf = ByteBuffer.allocate(dump.data().length);
+ tb.trace.getMemoryManager().getBytes(snap, tb.addr(dump.address()), buf);
+ assertArrayEquals(dump.data(), buf.array());
+ }
+ }
+
+ @Test
+ public void testPutReg() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ StackFrame frame = manager.getCurrentFrame();
+ cmds.ghidraTracePutReg(frame);
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ List<TraceObjectValue> regVals = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap),
+ PathPredicates.parse("VMs[].Threads[main].Stack[0].Registers"))
+ .map(p -> p.getLastEntry())
+ .toList();
+ TraceObjectValue tobj = regVals.get(0);
+ AddressSpace t1f0 = tb.trace.getBaseAddressFactory()
+ .getAddressSpace(tobj.getCanonicalPath().toString());
+ TraceMemorySpace regs = tb.trace.getMemoryManager().getMemorySpace(t1f0, false);
+
+ RegisterValue pc = regs.getValue(snap, tb.reg("PC"));
+ assertEquals("1451", pc.getUnsignedValue().toString(16));
+ }
+ }
+
+ @Test
+ public void testDelReg() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceSetSnap(1);
+ StackFrame frame = manager.getCurrentFrame();
+ cmds.ghidraTraceDelReg(frame);
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ // The spaces will be left over, but the values should be zeroed
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ List<TraceObjectValue> regVals = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap),
+ PathPredicates.parse("VMs[].Threads[main].Stack[0].Registers"))
+ .map(p -> p.getLastEntry())
+ .toList();
+ TraceObjectValue tobj = regVals.get(0);
+ AddressSpace t1f0 = tb.trace.getBaseAddressFactory()
+ .getAddressSpace(tobj.getCanonicalPath().toString());
+ TraceMemorySpace regs = tb.trace.getMemoryManager().getMemorySpace(t1f0, false);
+
+ RegisterValue pc = regs.getValue(snap, tb.reg("PC"));
+ assertEquals("0", pc.getUnsignedValue().toString(16));
+ }
+ }
+
+ @Test
+ public void testCreateObj() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceCreateObj("Test.Objects[1].Bob")
+ cmds.ghidraTraceTxCommit()
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, TESTSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/Test")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("Test.Objects[1].Bob"));
+ assertNotNull(object);
+ assertEquals(4L, object.getKey());
+ }
+ }
+
+ @Test
+ public void testInsertObj() throws Exception {
+ String out = runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ System.out.println("---Lifespan---");
+ cmds.ghidraTraceCreateObj("Test.Objects[1].Bob")
+ cmds.ghidraTraceInsertObj("Test.Objects[1].Bob")
+ System.out.println("---");
+ cmds.ghidraTraceTxCommit()
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, TESTSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/Test")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("Test.Objects[1].Bob"));
+ assertNotNull(object);
+ Lifespan life = Unique.assertOne(object.getLife().spans());
+ assertEquals(Lifespan.nowOn(0), life);
+ assertEquals("Inserted object: lifespan=[0..+inf)",
+ extractOutSection(out, "---Lifespan---"));
+ }
+ }
+
+ @Test
+ public void testRemoveObj() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceInsertObj("Test.Objects[1]")
+ cmds.ghidraTraceSetSnap(2);
+ cmds.ghidraTraceRemoveObj("Test.Objects[1]");
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, TESTSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/Test")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("Test.Objects[1]"));
+ assertNotNull(object);
+ Lifespan life = Unique.assertOne(object.getLife().spans());
+ assertEquals(Lifespan.span(0, 1), life);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected <T> T runTestSetValue(String extra, String value, String schema)
+ throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceInsertObj("Test.Objects[1]");
+ %s
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "test", %s);
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, TESTSETUP, extra, value, schema));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/Test")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("Test.Objects[1]"));
+ assertNotNull(object);
+ TraceObjectValue test = object.getValue(snap, "test");
+ return test == null ? null : (T) test.getValue();
+ }
+ }
+
+ @Test
+ public void testSetValueNull() throws Exception {
+ assertNull(runTestSetValue("", "null", "VOID"));
+ }
+
+ @Test
+ public void testSetValueBool() throws Exception {
+ assertEquals(Boolean.TRUE, runTestSetValue("", "true", "BOOL"));
+ }
+
+ @Test
+ public void testSetValueByte() throws Exception {
+ assertEquals(Byte.valueOf((byte) 1), runTestSetValue("", "(byte)1", "BYTE"));
+ }
+
+ @Test
+ public void testSetValueChar() throws Exception {
+ assertEquals(Character.valueOf('A'), runTestSetValue("", "'A'", "CHAR"));
+ }
+
+ @Test
+ public void testSetValueShort() throws Exception {
+ assertEquals(Short.valueOf((short) 1), runTestSetValue("", "(short)1", "SHORT"));
+ }
+
+ @Test
+ public void testSetValueInt() throws Exception {
+ assertEquals(Integer.valueOf(1), runTestSetValue("", "(int)1", "INT"));
+ }
+
+ @Test
+ public void testSetValueLong() throws Exception {
+ assertEquals(Long.valueOf(1), runTestSetValue("", "(long)1", "LONG"));
+ }
+
+ @Test
+ public void testSetValueString() throws Exception {
+ assertEquals("HelloWorld!", runTestSetValue("", "\"HelloWorld!\"", "STRING"));
+ }
+
+ @Test
+ public void testSetValueBoolArr() throws Exception {
+ assertArrayEquals(new boolean[] { true, false },
+ runTestSetValue("", "List.of(true,false)", "BOOL_ARR"));
+ }
+
+ @Test
+ public void testSetValueShortArrUsingArray() throws Exception {
+ assertArrayEquals(new short[] { 'H', 0, 'W' },
+ runTestSetValue("", "List.of((short)'H',(short)0,(short)'W')", "SHORT_ARR"));
+ }
+
+ @Test
+ public void testSetValueIntArrayUsingMixedArray() throws Exception {
+ assertArrayEquals(new int[] { 'H', 0, 'W' },
+ runTestSetValue("", "List.of((int)'H',0,(int)'W')", "INT_ARR"));
+ }
+
+ @Test
+ public void testSetValueIntArrUsingArray() throws Exception {
+ assertArrayEquals(new int[] { 1, 2, 3, 4 },
+ runTestSetValue("", "List.of(1,(int)2L,3,4)", "INT_ARR"));
+ }
+
+ @Test
+ public void testSetValueLongArr() throws Exception {
+ assertArrayEquals(new long[] { 1, 2, 3, 4 },
+ runTestSetValue("", "List.of(1L,(long)2,3L,4L)", "LONG_ARR"));
+ }
+
+ @Test
+ public void testSetValueStringArr() throws Exception {
+ assertArrayEquals(new String[] { "1", "A", "dead", "beef" },
+ runTestSetValue("", "List.of(\"1\",\"A\",\"dead\",\"beef\")", "STRING_ARR"));
+ }
+
+ @Test
+ public void testSetValueAddress() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceInsertObj("Test.Objects[1]")
+ cmds.ghidraTraceSetValue("VMs", "test", pc)
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("VMs"));
+ assertNotNull(object);
+ TraceObjectValue value = object.getValue(snap, "test");
+ Address address = (Address) value.getValue();
+ assertEquals(0x1451L, address.getOffset());
+ assertEquals("ram", address.getAddressSpace().getName());
+ }
+ }
+
+ @Test
+ public void testSetValueObject() throws Exception {
+ runThrowError(
+ addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceInsertObj("Test.Objects[1]")
+ cmds.ghidraTraceSetValue("VMs", "test", cmds.proxyObject(manager.getCurrentThread()))
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """
+ .formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("VMs"));
+ assertNotNull(object);
+ TraceObjectValue value = object.getValue(snap, "test");
+ TraceObject ret = (TraceObject) value.getValue();
+ TraceObject orig = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(
+ TraceObjectKeyPath.parse("VMs[OpenJDK 64-Bit Server VM].Threads[main]"));
+ assertNotNull(ret);
+ assertEquals(orig, ret);
+ }
+ }
+
+ @Test
+ public void testRetainValues() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceInsertObj("Test.Objects[1]");
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "[1]", "'A'");
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "[2]", "'B'");
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "[3]", "'C'");
+ cmds.ghidraTraceSetSnap(10);
+ cmds.ghidraTraceRetainValues("--elements", "Test.Objects[1]", Set.of("[1]","[3]"));
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, TESTSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/Test")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("Test.Objects[1]"));
+ assertNotNull(object);
+ assertEquals(Map.ofEntries(
+ Map.entry("[1]", Lifespan.nowOn(0)),
+ Map.entry("[2]", Lifespan.span(0, 9)),
+ Map.entry("[3]", Lifespan.nowOn(0))),
+ object.getValues(Lifespan.ALL)
+ .stream()
+ .collect(Collectors.toMap(v -> v.getEntryKey(), v -> v.getLifespan())));
+ }
+ }
+
+ @Test
+ public void testGetObj() throws Exception {
+ String out = runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ cmds.ghidraTraceStart(null);
+ cmds.ghidraTraceTxStart("Create Object");
+ System.out.println("---Id---");
+ cmds.ghidraTraceCreateObj("Test.Objects[1]");
+ cmds.ghidraTraceInsertObj("Test.Objects[1]")
+ System.out.println("---");
+ cmds.ghidraTraceTxCommit();
+ RmiTraceObject obj = cmds.ghidraTraceGetObj("Test.Objects[1]");
+ System.out.println("---GetObject---");
+ System.out.println(obj.getPath());
+ System.out.println("---");
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/jdi/noname")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ TraceObject object = tb.trace.getObjectManager()
+ .getObjectByCanonicalPath(TraceObjectKeyPath.parse("Test.Objects[1]"));
+ assertNotNull(object);
+ assertEquals("Test.Objects[1]", extractOutSection(out, "---GetObject---"));
+ }
+ }
+
+ @Test // Good enough for the moment
+ public void testGetValues() throws Exception {
+ String out = runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vnull", "None");
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vbool", true);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vbyte", "(char)1");
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vchar", "'A'");
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vshort", 2);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vint", 3);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vlong", 4L);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vstring", "Hello");
+ List vboolarr = List.of(true,false);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vboolarr", vboolarr);
+ List vshortarr = List.of((short)1, (short)2, (short)3);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vshortarr", vshortarr);
+ List vintarr = List.of(1, 2, 3);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vintarr", vintarr);
+ List vlongarr = List.of(1L, 2L, 3L);
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vlongarr", vlongarr);
+ List vstrarr = List.of("uno", "2", "iii");
+ cmds.ghidraTraceSetValue("Test.Objects[1]", "vstrarr", vstrarr);
+ cmds.ghidraTraceTxCommit();
+ System.out.println("---GetValues---");
+ cmds.ghidraTraceGetValues("Test.Objects[1].");
+ System.out.println("---");
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, TESTSETUP));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/Test")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ assertEquals(
+ "Parent Key Span Value Type \n" +
+ "Test.Objects[1] [0..+inf) vbool true BOOL \n" +
+ "Test.Objects[1] [0..+inf) vboolarr [true, false] BOOL_ARR \n" +
+ "Test.Objects[1] [0..+inf) vbyte (char)1 STRING \n" +
+ "Test.Objects[1] [0..+inf) vchar 'A' STRING \n" +
+ "Test.Objects[1] [0..+inf) vint 3 INT \n" +
+ "Test.Objects[1] [0..+inf) vintarr [1, 2, 3] INT_ARR \n" +
+ "Test.Objects[1] [0..+inf) vlong 4 LONG \n" +
+ "Test.Objects[1] [0..+inf) vlongarr [1, 2, 3] LONG_ARR \n" +
+ "Test.Objects[1] [0..+inf) vnull None STRING \n" +
+ "Test.Objects[1] [0..+inf) vshort 2 INT \n" +
+ "Test.Objects[1] [0..+inf) vshortarr [1, 2, 3] SHORT_ARR \n" +
+ "Test.Objects[1] [0..+inf) vstrarr [uno, 2, iii] STRING_ARR\n" +
+ "Test.Objects[1] [0..+inf) vstring Hello STRING",
+ extractOutSection(out, "---GetValues---").replaceAll("\r", ""));
+// TODO:
+// Test.Objects[1] vbytearr [0,+inf) b'\\x01\\x02\\x03' BYTE_ARR
+// Test.Objects[1] vchararr [0,+inf) 'Hello' CHAR_ARR
+// Test.Objects[1] vobj [0,+inf) Test.Objects[1] OBJECT
+ }
+ }
+
+ // @Test
+ public void testGetValuesRng() throws Exception {
+ Unfinished.TODO();
+ }
+
+ @Test
+ public void testActivateObject() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTraceActivate("VMs[OpenJDK 64-Bit Server VM].Threads[Finalizer]")
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ assertEquals("VMs[OpenJDK 64-Bit Server VM].Threads[Finalizer]",
+ traceManager.getCurrentObject().getCanonicalPath().toString());
+ }
+ }
+
+ //@Test FAIL - Can't seem to get any definedUnits
+ public void testDisassemble() throws Exception {
+ String out = runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ System.out.println("---Disassemble---");
+ cmds.ghidraTraceDisassemble(pc)
+ System.out.println("---");
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ // Not concerned about specifics, so long as disassembly occurs
+ long total = 0;
+ for (CodeUnit cu : tb.trace.getCodeManager().definedUnits().get(snap, true)) {
+ total += cu.getLength();
+ }
+ String extract = extractOutSection(out, "---Disassemble---");
+ String[] split = extract.split("\r\n");
+ assertEquals("Disassembled %d bytes".formatted(total),
+ split[0]);
+ }
+ }
+
+ @Test
+ public void testPutVMs() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutVMs();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ Collection<TraceObject> vms = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap), PathPredicates.parse("VMs[]"))
+ .map(p -> p.getDestination(null))
+ .toList();
+ assertEquals(1, vms.size());
+ }
+ }
+
+ @Test
+ public void testPutProcesses() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutProcesses();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ Collection<TraceObject> processes = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap), PathPredicates.parse("VMs[].Processes"))
+ .map(p -> p.getDestination(null))
+ .toList();
+ assertEquals(1, processes.size());
+ }
+ }
+
+ @Test
+ public void testPutModules() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutModules();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ Collection<? extends TraceModule> all = tb.trace.getModuleManager().getAllModules();
+ TraceModule mod =
+ Unique.assertOne(all.stream().filter(m -> m.getName().contains("Thread.class")));
+ assertEquals(tb.addr(0x1000), Objects.requireNonNull(mod.getBase()));
+ }
+ }
+
+ @Test
+ public void testPutThreads() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutThreads();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ Collection<? extends TraceThread> threads = tb.trace.getThreadManager().getAllThreads();
+ assertEquals(4, threads.size());
+ Set<String> names = new HashSet<>();
+ for (TraceThread t : threads) {
+ String path = t.getPath();
+ names.add(path.substring(path.lastIndexOf("[")));
+ }
+ assertTrue(names.contains("[main]"));
+ assertTrue(names.contains("[Finalizer]"));
+ assertTrue(names.contains("[Reference Handler]"));
+ assertTrue(names.contains("[Signal Dispatcher]"));
+ }
+ }
+
+ @Test
+ public void testPutFrames() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutFrames();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ cmds.ghidraTraceDisconnect();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ List<TraceObject> stack = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap),
+ PathPredicates.parse("VMs[].Threads[main].Stack[]"))
+ .map(p -> p.getDestination(null))
+ .toList();
+ assertEquals(1, stack.size());
+ }
+ }
+
+ @Test
+ public void testPutRegions() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ cmds.ghidraTracePutModules();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ Collection<? extends TraceMemoryRegion> all =
+ tb.trace.getMemoryManager().getAllRegions();
+ assertThat(all.size(), greaterThan(90));
+ }
+ }
+
+ @Test
+ public void testEvents() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ MethodEntryRequest brkReq = vm.eventRequestManager().createMethodEntryRequest();
+ cmds.ghidraTracePutEvents();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ List<TraceObjectValue> events = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap),
+ PathPredicates.parse("VMs[].Events[]"))
+ .map(p -> p.getLastEntry())
+ .sorted(Comparator.comparing(TraceObjectValue::getEntryKey))
+ .toList();
+ assertEquals(2, events.size());
+ }
+ }
+
+ @Test
+ public void testPutBreakpoints() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ Location loc = manager.getCurrentLocation();
+ BreakpointRequest brkReq = vm.eventRequestManager().createBreakpointRequest(loc);
+ cmds.ghidraTracePutBreakpoints();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """.formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ List<TraceObjectValue> breaks = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap),
+ PathPredicates.parse("VMs[].Breakpoints[]"))
+ .map(p -> p.getLastEntry())
+ .sorted(Comparator.comparing(TraceObjectValue::getEntryKey))
+ .toList();
+ assertEquals(1, breaks.size());
+ AddressRange rangeMain =
+ breaks.get(0).getChild().getValue(snap, "Range").castValue();
+ Address bp1 = rangeMain.getMinAddress();
+ assertEquals(0x1451L, bp1.getOffset());
+ }
+ }
+
+ @Test
+ public void testPutBreakpoints2() throws Exception {
+ runThrowError(
+ addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s");
+ %s
+ String path = "VMs[OpenJDK 64-Bit Server VM].Classes[java.lang.Thread]";
+ ReferenceType reftype = (ReferenceType) jdiManager.objForPath(path);
+ Field field = reftype.fieldByName("tid");
+ AccessWatchpointRequest brkReq = vm.eventRequestManager().createAccessWatchpointRequest(field);
+ cmds.ghidraTracePutBreakpoints();
+ cmds.ghidraTraceTxCommit();
+ cmds.ghidraTraceSave();
+ /exit
+ """
+ .formatted(PREAMBLE, addr, HWSETUP_W_STATE));
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ long snap = getLastSnapshot().getKey();
+ List<TraceObjectValue> breaks = tb.trace.getObjectManager()
+ .getValuePaths(Lifespan.at(snap),
+ PathPredicates.parse("VMs[].Breakpoints[]"))
+ .map(p -> p.getLastEntry())
+ .sorted(Comparator.comparing(TraceObjectValue::getEntryKey))
+ .toList();
+ assertEquals(1, breaks.size());
+ AddressRange rangeMain =
+ breaks.get(0).getChild().getValue(snap, "Range").castValue();
+ Address bp1 = rangeMain.getMinAddress();
+ assertEquals(0L, bp1.getOffset());
+ assertEquals("constantPool", bp1.getAddressSpace().getName());
+ }
+ }
+
+ @Test
+ public void testMinimal() throws Exception {
+ runThrowError(addr -> """
+ %s
+ cmds.ghidraTraceConnect("%s")
+ System.out.println("FINISHED")
+ /exit
+ """.formatted(PREAMBLE, addr));
+ }
+
+ private TraceSnapshot getLastSnapshot() {
+ long snap = waitForValue(() -> tb.trace.getTimeManager().getMaxSnap());
+ return tb.trace.getTimeManager().getSnapshot(snap, false);
+ }
+}
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaHooksTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaHooksTest.java
new file mode 100644
index 0000000000..0a07fbfbe3
--- /dev/null
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaHooksTest.java
@@ -0,0 +1,381 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package agent.java.rmi;
+
+import static org.junit.Assert.*;
+
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+
+import generic.Unique;
+import ghidra.app.plugin.core.debug.utils.ManagedDomainObject;
+import ghidra.debug.api.tracermi.RemoteMethod;
+import ghidra.program.model.address.AddressRange;
+import ghidra.trace.database.ToyDBTraceBuilder;
+import ghidra.trace.model.Trace;
+import ghidra.trace.model.target.TraceObject;
+import ghidra.trace.model.target.TraceObjectValue;
+
+public class JavaHooksTest extends AbstractJavaTraceRmiTest {
+
+ @Test
+ public void testOnStep() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshMethod = conn.getMethod("refresh_method");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ conn.execute("VirtualMachine vm = manager.getCurrentVM();");
+ conn.execute("ThreadReference thread = manager.getCurrentThread();");
+ conn.execute("EventRequestManager mgr = vm.eventRequestManager();");
+ conn.execute(
+ "StepRequest req = mgr.createStepRequest(thread, StepRequest.STEP_MIN, StepRequest.STEP_INTO);");
+ conn.execute("req.enable();");
+ conn.execute("vm.resume();");
+
+ txPut(conn, "Threads");
+ waitForObject("VMs[].Threads[main]");
+ txPut(conn, "Frames");
+
+ List<TraceObjectValue> pcs =
+ waitForValues("VMs[].Threads[main].Stack[].Location.Method");
+ assertTrue(pcs.get(0).getValue().toString().contains("<init>"));
+
+ TraceObject checkName = pcs.get(0).getChild();
+ refreshMethod.invoke(Map.of("method", checkName));
+ waitTxDone();
+
+ AddressRange range = Unique
+ .assertOne(
+ waitForValues(checkName.getCanonicalPath().extend("Range").toString()))
+ .castValue();
+ waitForPC(start -> start.equals(range.getMinAddress()));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("Step",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ @Test
+ public void testOnMethodEntry() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod breakOnEnter = conn.getMethod("break_enter_thread");
+ RemoteMethod refreshMethod = conn.getMethod("refresh_method");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ breakOnEnter.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ txPut(conn, "Frames");
+
+ List<TraceObjectValue> eventVals = waitForValues("VMs[].Events[]");
+ assertEquals(2, eventVals.size());
+ assertTrue(eventVals.get(0).getEntryKey().contains("method entry request"));
+
+ List<TraceObjectValue> pcs =
+ waitForValues("VMs[].Threads[main].Stack[].Location.Method");
+ assertTrue(pcs.get(0).getValue().toString().contains("checkName"));
+ assertTrue(pcs.get(1).getValue().toString().contains("<init>"));
+
+ TraceObject checkName = pcs.get(0).getChild();
+ refreshMethod.invoke(Map.of("method", checkName));
+ waitTxDone();
+
+ AddressRange range = Unique
+ .assertOne(
+ waitForValues(checkName.getCanonicalPath().extend("Range").toString()))
+ .castValue();
+ waitForPC(start -> start.equals(range.getMinAddress()));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("MethodEntry",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ @Test
+ public void testOnMethodExit() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod breakOnExit = conn.getMethod("break_exit_thread");
+ RemoteMethod refreshMethod = conn.getMethod("refresh_method");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ breakOnExit.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ txPut(conn, "Frames");
+
+ List<TraceObjectValue> eventVals = waitForValues("VMs[].Events[]");
+ assertEquals(2, eventVals.size());
+ assertTrue(eventVals.get(0).getEntryKey().contains("method exit request"));
+
+ List<TraceObjectValue> pcs =
+ waitForValues("VMs[].Threads[main].Stack[].Location.Method");
+ assertTrue(pcs.get(0).getValue().toString().contains("checkName"));
+ assertTrue(pcs.get(1).getValue().toString().contains("<init>"));
+
+ TraceObject checkName = pcs.get(0).getChild();
+ refreshMethod.invoke(Map.of("method", checkName));
+ waitTxDone();
+
+ AddressRange range = Unique
+ .assertOne(
+ waitForValues(checkName.getCanonicalPath().extend("Range").toString()))
+ .castValue();
+ waitForPC(start -> start.equals(range.getMaxAddress()));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("MethodExit",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ @Test
+ public void testOnClassLoad() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod breakLoad = conn.getMethod("break_load_container");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject events = waitForObject("VMs[].Events");
+ breakLoad.invoke(Map.of("container", events));
+ waitTxDone();
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> eventVals = waitForValues("VMs[].Events[]");
+ assertEquals(2, eventVals.size());
+ assertTrue(eventVals.get(0).getEntryKey().contains("class prepare request"));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("ClassPrepare",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ @Test
+ public void testOnThreadStart() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod breakStart = conn.getMethod("break_started_container");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ TraceObject events = waitForObject("VMs[].Events");
+ breakStart.invoke(Map.of("container", events));
+ waitTxDone();
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> eventVals = waitForValues("VMs[].Events[]");
+ assertTrue(eventVals.get(0).getEntryKey().contains("thread start request"));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("ThreadStart",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ @Test
+ public void testOnThreadDeath() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod breakDeath = conn.getMethod("break_death_container");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject events = waitForObject("VMs[].Events");
+ breakDeath.invoke(Map.of("container", events));
+ waitTxDone();
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> eventVals = waitForValues("VMs[].Events[]");
+ assertEquals(2, eventVals.size());
+ assertTrue(eventVals.get(1).getEntryKey().contains("thread death request"));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("ThreadDeath",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ @Test
+ public void testOnBreakpoint() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod refreshMethod = conn.getMethod("refresh_method");
+ RemoteMethod refreshLocations = conn.getMethod("refresh_locations");
+ RemoteMethod breakOnExecute = conn.getMethod("break_location");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject access =
+ waitForObject("VMs[].Classes[java.lang.Thread].Methods[checkAccess]");
+ refreshMethod.invoke(Map.of("method", access));
+ waitTxDone();
+ TraceObject locCont =
+ waitForObject("VMs[].Classes[java.lang.Thread].Methods[checkAccess].Locations");
+ refreshLocations.invoke(Map.of("container", locCont));
+ waitTxDone();
+ List<TraceObjectValue> locations = waitForValues(
+ "VMs[].Classes[java.lang.Thread].Methods[checkAccess].Locations[]");
+ for (TraceObjectValue loc : locations) {
+ breakOnExecute.invoke(Map.of("location", loc.getChild()));
+ waitTxDone();
+ }
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> brkVals = waitForValues("VMs[].Breakpoints[]");
+ assertEquals(4, brkVals.size());
+
+ txPut(conn, "Frames");
+ waitForValuesPass("VMs[].Threads[main].Stack[0]._display",
+ pcs -> assertContainsString("checkAccess", pcs.get(0).getValue().toString()));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("Breakpoint",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ @Test
+ public void testOnAccessWatchpoint() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod refreshFields = conn.getMethod("refresh_canonical_fields");
+ RemoteMethod breakOnAccess = conn.getMethod("break_access");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject fieldCont = waitForObject("VMs[].Classes[java.lang.Thread].Fields");
+ refreshFields.invoke(Map.of("container", fieldCont));
+ waitTxDone();
+ List<TraceObjectValue> fields =
+ waitForValues("VMs[].Classes[java.lang.Thread].Fields[NEW_THREAD_BINDINGS]");
+ for (TraceObjectValue f : fields) {
+ breakOnAccess.invoke(Map.of("field", f.getChild()));
+ waitTxDone();
+ }
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> brkVals = waitForValues("VMs[].Breakpoints[]");
+ assertEquals(1, brkVals.size());
+
+ txPut(conn, "Frames");
+ List<TraceObjectValue> pcs = waitForValues("VMs[].Threads[main].Stack[0]._display");
+ assertTrue(pcs.get(0).getValue().toString().contains("<init>"));
+
+ waitForValuesPass("VMs[]._display", vms -> assertContainsString("AccessWatchpoint",
+ vms.get(0).getValue().toString()));
+ }
+ }
+ }
+
+ private void start(JshellAndConnection conn, String obj) {
+ if (obj != null) {
+ conn.execute("cmds.ghidraTraceStart(\"" + obj + "\");");
+ }
+ else {
+ conn.execute("mds.ghidraTraceStart();");
+ }
+ conn.execute("cmds.ghidraTraceCreate(System.getenv());");
+ conn.execute("cmds.ghidraTraceTxStart(\"Create snapshot\")");
+ conn.execute("cmds.ghidraTraceNewSnap(\"Scripted snapshot\")");
+ conn.execute("cmds.ghidraTraceTxCommit()");
+ }
+
+ private void txPut(JshellAndConnection conn, String obj) {
+ conn.execute("cmds.ghidraTraceTxStart(\"Tx\");");
+ conn.execute("cmds.ghidraTracePut" + obj + "();");
+ conn.execute("cmds.ghidraTraceTxCommit();");
+ waitTxDone();
+ }
+}
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaMethodsTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaMethodsTest.java
new file mode 100644
index 0000000000..7217a6f1d1
--- /dev/null
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/java/rmi/JavaMethodsTest.java
@@ -0,0 +1,806 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package agent.java.rmi;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+import generic.Unique;
+import ghidra.app.plugin.core.debug.utils.ManagedDomainObject;
+import ghidra.debug.api.tracermi.RemoteMethod;
+import ghidra.program.model.address.Address;
+import ghidra.trace.database.ToyDBTraceBuilder;
+import ghidra.trace.model.Lifespan;
+import ghidra.trace.model.Trace;
+import ghidra.trace.model.target.TraceObject;
+import ghidra.trace.model.target.TraceObjectValue;
+
+public class JavaMethodsTest extends AbstractJavaTraceRmiTest {
+
+ /**
+ * Because we control the target artifact, we know the steps precisely. NOTE: This must be the
+ * same at least for step_into and step_over, otherwise, we can't know for sure step_over
+ * actually behaves any differently than step_into. By matching with step_into, we can assure
+ * ourselves that step_over actually encountered an invoke* bytecode instruction, because if it
+ * didn't then step_into ought to fail.
+ */
+ public void do2Steps(JshellAndConnection conn, RemoteMethod step, TraceObject thread) {
+ step.invoke(Map.of("thread", thread));
+ waitTxDone();
+ txPut(conn, "Frames");
+ waitForLocation("HelloWorld", "main", 3);
+
+ step.invoke(Map.of("thread", thread));
+ waitTxDone();
+ txPut(conn, "Frames");
+ waitForLocation("HelloWorld", "main", 5);
+ }
+
+ @Test
+ public void testEvaluate() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ conn.executeCapture(null);
+ List<String> res = conn.executeCapture("3+4*2;");
+ conn.execute("/exit");
+ assertTrue(res.get(0).contains("11"));
+ }
+ }
+
+ @Test
+ public void testExecute() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ // Just confirm it's present
+ }
+ }
+ }
+
+ @Test
+ public void testRefreshEvents() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshEvents = conn.getMethod("refresh_events");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject events = waitForObject("VMs[].Events");
+ refreshEvents.invoke(Map.of("container", events));
+ waitTxDone();
+
+ List<TraceObjectValue> eventVals = waitForValues("VMs[].Events[]");
+ assertEquals(1, eventVals.size());
+ assertTrue(eventVals.get(0).getEntryKey().contains("step request"));
+
+ conn.execute("VirtualMachine vm = manager.getCurrentVM(); ");
+ conn.execute(
+ "MethodEntryRequest brkReq = vm.eventRequestManager().createMethodEntryRequest();");
+
+ eventVals = waitForPass(() -> {
+ refreshEvents.invoke(Map.of("container", events));
+ List<TraceObjectValue> evs = waitForValues("VMs[].Events[]");
+ assertEquals(2, evs.size());
+ return evs;
+ });
+ assertTrue(eventVals.get(0).getEntryKey().contains("method entry request"));
+
+ }
+ }
+ }
+
+ @Test
+ public void testRefreshBreakpoints() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshBreakpoints = conn.getMethod("refresh_breakpoints");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ conn.execute("VirtualMachine vm = manager.getCurrentVM();");
+ conn.execute("Location loc = manager.getCurrentLocation();");
+ conn.execute(
+ "BreakpointRequest brkReq = vm.eventRequestManager().createBreakpointRequest(loc);");
+
+ TraceObject brkSet = waitForObject("VMs[].Breakpoints");
+ List<TraceObjectValue> brks = waitForPass(() -> {
+ refreshBreakpoints.invoke(Map.of("container", brkSet));
+ List<TraceObjectValue> d = waitForValues("VMs[].Breakpoints[]");
+ assertEquals(1, d.size());
+ return d;
+ });
+ assertTrue(brks.get(0).getEntryKey().contains("breakpoint request"));
+
+ conn.execute(
+ "String path = \"VMs[OpenJDK 64-Bit Server VM].Classes[java.lang.Thread]\";");
+ conn.execute(
+ "ReferenceType reftype = (ReferenceType) jdiManager.objForPath(path);");
+ conn.execute("Field field = reftype.fieldByName(\"tid\");");
+ conn.execute(
+ "AccessWatchpointRequest brkReq = vm.eventRequestManager().createAccessWatchpointRequest(field);");
+
+ TraceObject brkSet2 = waitForObject("VMs[].Breakpoints");
+ brks = waitForPass(() -> {
+ refreshBreakpoints.invoke(Map.of("container", brkSet2));
+ List<TraceObjectValue> d = waitForValues("VMs[].Breakpoints[]");
+ assertEquals(2, d.size());
+ return d;
+ });
+ assertTrue(brks.get(0).getEntryKey().contains("access watchpoint request"));
+ }
+ }
+ }
+
+ @Test
+ public void testRefreshVMs() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshVM = conn.getMethod("refresh_vm");
+ RemoteMethod refreshProcess = conn.getMethod("refresh_process");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "VMs");
+
+ TraceObject vm = waitForObject("VMs[]");
+ List<TraceObjectValue> children = waitForValues("VMs[].");
+ int sz = children.size();
+ refreshVM.invoke(Map.of("vm", vm));
+ children = waitForValues("VMs[].");
+ assertTrue(children.size() >= sz);
+ List<TraceObjectValue> eventThread = waitForValues("VMs[]._event_thread");
+ assertTrue(eventThread.get(0).getValue().toString().contains("main"));
+
+ TraceObject proc = waitForObject("VMs[].Processes[]");
+ refreshProcess.invoke(Map.of("process", proc));
+ children = waitForValues("VMs[].Processes[].");
+ assertTrue(children.get(0).getEntryKey().contains("Alive"));
+ children = waitForValues("VMs[].Processes[].CommandLine");
+ assertTrue(((String) children.get(0).getValue()).contains("HelloWorld"));
+ }
+ }
+ }
+
+ @Test
+ public void testRefreshThreads() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshThreads = conn.getMethod("refresh_threads");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "VMs");
+
+ TraceObject threads = waitForObject("VMs[].Threads");
+ refreshThreads.invoke(Map.of("container", threads));
+ List<TraceObjectValue> children = waitForValues("VMs[].Threads[]");
+ assertEquals(4, children.size());
+ assertTrue(children.get(children.size() - 1).getEntryKey().contains("main"));
+ }
+ }
+ }
+
+ @Test
+ public void testRefreshStack() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod brkEnter = conn.getMethod("break_enter_container");
+ RemoteMethod setClsFilt = conn.getMethod("set_class_filter");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod refreshStack = conn.getMethod("refresh_stack");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject events = waitForObject("VMs[].Events");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ brkEnter.invoke(Map.of("container", events));
+ TraceObject evtEnter = waitForObject("VMs[].Events[]");
+ setClsFilt.invoke(Map.of(
+ "event", evtEnter,
+ "filter", "HelloWorld*",
+ "exclude", false));
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject stack = waitForObject("VMs[].Threads[main].Stack");
+ refreshStack.invoke(Map.of("stack", stack));
+ waitTxDone();
+ waitForValuesPass("VMs[].Threads[main].Stack[]",
+ frames -> assertEquals(1, frames.size()));
+
+ // Because main is static, there is no preceding call to <init>
+ // This class has no <clinit>, so we get main first!
+ waitForLocation("HelloWorld", "main", 0);
+ Address start = getPC();
+
+ do2Steps(conn, stepInto, thread);
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ refreshStack.invoke(Map.of("stack", stack));
+ waitTxDone();
+ waitForValuesPass("VMs[].Threads[main].Stack[]", frames -> {
+ assertEquals(2, frames.size());
+ });
+ waitForValuesPass("VMs[].Threads[main].Stack[].PC", pcs -> {
+ assertEquals(2, pcs.size());
+ assertEquals(start.add(5), pcs.get(1).getValue());
+ });
+ }
+ }
+ }
+
+ @Test
+ public void testRefreshRegisters() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshRegisters = conn.getMethod("refresh_registers");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ for (int i = 0; i < 4; i++) {
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+ }
+
+ TraceObject regContainer = waitForObject("VMs[].Threads[main].Stack[0].Registers");
+ refreshRegisters.invoke(Map.of("container", regContainer));
+ List<TraceObjectValue> registers =
+ waitForValues("VMs[].Threads[main].Stack[0].Registers[]");
+ assertEquals(2, registers.size());
+ assertTrue(registers.get(0).getEntryKey().contains("PC"));
+ assertTrue(registers.get(1).getEntryKey().contains("return_address"));
+
+ waitForObject("VMs[].Threads[main].Stack[1].Registers");
+ refreshRegisters.invoke(Map.of("container", regContainer));
+ registers = waitForValues("VMs[].Threads[main].Stack[1].Registers[]");
+ assertEquals(1, registers.size());
+ assertTrue(registers.get(0).getEntryKey().contains("PC"));
+ }
+ }
+ }
+
+ //@Test Too slow for testing.
+ public void testRefreshMemory() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshMemory = conn.getMethod("refresh_memory");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> children = waitForValues("VMs[].Memory[]");
+ assertTrue(children.size() < 100);
+
+ TraceObject memory = waitForObject("VMs[].Memory");
+ refreshMemory.invoke(Map.of("memory", memory));
+ children = waitForValues("VMs[].Memory[]");
+ assertTrue(children.size() > 100);
+ }
+ }
+ }
+
+ //@Test Too slow for testing.
+ public void testRefreshClasses() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshClasses = conn.getMethod("refresh_reference_types");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> children = waitForValues("VMs[].Classes[]");
+ assertEquals(1, children.size());
+
+ TraceObject classes = waitForObject("VMs[].Classes");
+ refreshClasses.invoke(Map.of("container", classes));
+ children = waitForValues("VMs[].Classes[]");
+ assertTrue(children.size() > 100);
+ }
+ }
+ }
+
+ @Test
+ public void testRefreshModules() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshModules = conn.getMethod("refresh_modules");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> children = waitForValues("VMs[].ModuleRefs[]");
+ assertTrue(children.size() < 100);
+ int sz = children.size();
+
+ TraceObject modules = waitForObject("VMs[].ModuleRefs");
+ refreshModules.invoke(Map.of("container", modules));
+ children = waitForValues("VMs[].ModuleRefs[]");
+ assertEquals(sz, children.size());
+ }
+ }
+ }
+
+ @Test
+ public void testActivate() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshThreads = conn.getMethod("refresh_threads");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "VMs");
+
+ TraceObject threads = waitForObject("VMs[].Threads");
+ refreshThreads.invoke(Map.of("container", threads));
+ List<TraceObjectValue> children = waitForValues("VMs[].Threads[]");
+ assertEquals(4, children.size());
+
+ waitForPass(() -> {
+ TraceObject obj = traceManager.getCurrentObject();
+ assertFalse(obj == null);
+ assertContainsString("[main]", obj.getCanonicalPath().toString());
+ });
+
+ conn.execute(
+ "cmds.ghidraTraceActivate(\"VMs[OpenJDK 64-Bit Server VM].Threads[Finalizer]\")");
+ waitTxDone();
+ Thread.sleep(1000); // Why?
+
+ waitForPass(() -> {
+ TraceObject obj = traceManager.getCurrentObject();
+ assertFalse(obj == null);
+ assertContainsString("[Finalizer]", obj.getCanonicalPath().toString());
+ });
+ }
+ }
+ }
+
+ //@Test Unclear how to test
+ public void testKill() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod kill = conn.getMethod("kill");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "VMs");
+
+ TraceObject vm = waitForObject("VMs[]");
+ kill.invoke(Map.of("vm", vm));
+ waitTxDone();
+ }
+ }
+ }
+
+ @Test
+ @Ignore("Still a race condition between the last call to putFrames and the final assert")
+ public void testStepInto() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ /**
+ * NOTE: If using break_load_container, you'd need to follow with set_source_filter
+ * using "HelloWorld*". I still haven't looked far enough to figure out what the exact
+ * match should be. (It's not "HelloWorld", but maybe it's "HelloWorld.class". I've just
+ * switched over to break_enter_container, instead.
+ */
+
+ RemoteMethod brkEnter = conn.getMethod("break_enter_container");
+ RemoteMethod setClsFilt = conn.getMethod("set_class_filter");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject events = waitForObject("VMs[].Events");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ brkEnter.invoke(Map.of("container", events));
+ TraceObject evtEnter = waitForObject("VMs[].Events[]");
+ setClsFilt.invoke(Map.of(
+ "event", evtEnter,
+ "filter", "HelloWorld*",
+ "exclude", false));
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ txPut(conn, "Frames");
+ // Because main is static, there is no preceding call to <init>
+ // This class has no <clinit>, so we get main first!
+ waitForLocation("HelloWorld", "main", 0);
+ Address start = waitForPC(pc -> assertNotEquals(0, pc.getOffset()));
+
+ do2Steps(conn, stepInto, thread);
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+ txPut(conn, "Frames");
+
+ waitForLocation("java.io.PrintStream", "println", 0);
+ waitForValuesPass("VMs[].Threads[main].Stack[0].Registers[return_address]",
+ rets -> {
+ long ret = Long.parseLong(Unique.assertOne(rets).castValue(), 16);
+ assertEquals(start.getOffset() + 8, ret);
+ });
+ }
+ }
+ }
+
+ @Test
+ @Ignore("Still a race condition between the last call to putFrames and the final assert")
+ public void testStepOver() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod brkEnter = conn.getMethod("break_enter_container");
+ RemoteMethod setClsFilt = conn.getMethod("set_class_filter");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod stepOver = conn.getMethod("step_over");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject events = waitForObject("VMs[].Events");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ brkEnter.invoke(Map.of("container", events));
+ TraceObject evtEnter = waitForObject("VMs[].Events[]");
+ setClsFilt.invoke(Map.of(
+ "event", evtEnter,
+ "filter", "HelloWorld*",
+ "exclude", false));
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ txPut(conn, "Frames");
+ waitForLocation("HelloWorld", "main", 0);
+ Address start = waitForPC(pc -> assertNotEquals(0, pc.getOffset()));
+
+ do2Steps(conn, stepOver, thread);
+
+ stepOver.invoke(Map.of("thread", thread));
+ waitTxDone();
+ txPut(conn, "Frames");
+
+ waitForLocation("HelloWorld", "main", 8);
+ waitForPC(pc -> assertEquals(start.add(8), pc));
+ }
+ }
+ }
+
+ @Test
+ @Ignore("Still a race condition between the last call to putFrames and the final assert")
+ public void testStepOut() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod brkEnter = conn.getMethod("break_enter_container");
+ RemoteMethod setClsFilt = conn.getMethod("set_class_filter");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod stepOut = conn.getMethod("step_out");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject events = waitForObject("VMs[].Events");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ brkEnter.invoke(Map.of("container", events));
+ TraceObject evtEnter = waitForObject("VMs[].Events[]");
+ setClsFilt.invoke(Map.of(
+ "event", evtEnter,
+ "filter", "HelloWorld*",
+ "exclude", false));
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ txPut(conn, "Frames");
+ // Because main is static, there is no preceding call to <init>
+ // This class has no <clinit>, so we get main first!
+ waitForLocation("HelloWorld", "main", 0);
+ Address start = waitForPC(pc -> assertNotEquals(0, pc.getOffset()));
+
+ do2Steps(conn, stepInto, thread);
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+ txPut(conn, "Frames");
+ waitForLocation("java.io.PrintStream", "println", 0);
+
+ stepOut.invoke(Map.of("thread", thread));
+ waitTxDone();
+ waitForLocation("HelloWorld", "main", 8);
+ waitForPC(pc -> assertEquals(start.add(8), pc));
+ }
+ }
+ }
+
+ @Test
+ public void testBreakByEvent() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod breakOnEnter = conn.getMethod("break_enter_thread");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ breakOnEnter.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> eventVals = waitForValues("VMs[].Events[]");
+ assertEquals(2, eventVals.size());
+ assertTrue(eventVals.get(0).getEntryKey().contains("method entry request"));
+
+ List<TraceObjectValue> pcs =
+ waitForValues("VMs[].Threads[main].Stack[].Location.Method");
+ assertTrue(pcs.get(0).getValue().toString().contains("checkName"));
+ assertTrue(pcs.get(1).getValue().toString().contains("<init>"));
+ }
+ }
+ }
+
+ @Test
+ public void testBreakByLocation() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod refreshMethod = conn.getMethod("refresh_method");
+ RemoteMethod refreshLocations = conn.getMethod("refresh_locations");
+ RemoteMethod breakOnExecute = conn.getMethod("break_location");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject access =
+ waitForObject("VMs[].Classes[java.lang.Thread].Methods[checkAccess]");
+ refreshMethod.invoke(Map.of("method", access));
+ waitTxDone();
+ TraceObject locCont =
+ waitForObject("VMs[].Classes[java.lang.Thread].Methods[checkAccess].Locations");
+ refreshLocations.invoke(Map.of("container", locCont));
+ waitTxDone();
+ List<TraceObjectValue> locations = waitForValues(
+ "VMs[].Classes[java.lang.Thread].Methods[checkAccess].Locations[]");
+ for (TraceObjectValue loc : locations) {
+ breakOnExecute.invoke(Map.of("location", loc.getChild()));
+ waitTxDone();
+ }
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> brkVals = waitForValues("VMs[].Breakpoints[]");
+ assertEquals(4, brkVals.size());
+ //assertTrue(eventVals.get(0).getEntryKey().contains("method entry request"));
+
+ txPut(conn, "Frames");
+ waitForValuesPass("VMs[].Threads[main].Stack[0]._display",
+ pcs -> assertContainsString("checkAccess", pcs.get(0).getValue().toString()));
+ ;
+ }
+ }
+ }
+
+ @Test
+ public void testBreakOnAccess() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ RemoteMethod resume = conn.getMethod("resume_thread");
+ RemoteMethod refreshFields = conn.getMethod("refresh_canonical_fields");
+ RemoteMethod breakOnAccess = conn.getMethod("break_access");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ TraceObject fieldCont = waitForObject("VMs[].Classes[java.lang.Thread].Fields");
+ refreshFields.invoke(Map.of("container", fieldCont));
+ waitTxDone();
+ List<TraceObjectValue> fields =
+ waitForValues("VMs[].Classes[java.lang.Thread].Fields[NEW_THREAD_BINDINGS]");
+ for (TraceObjectValue f : fields) {
+ breakOnAccess.invoke(Map.of("field", f.getChild()));
+ waitTxDone();
+ }
+
+ resume.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ List<TraceObjectValue> brkVals = waitForValues("VMs[].Breakpoints[]");
+ assertEquals(1, brkVals.size());
+ //assertTrue(eventVals.get(0).getEntryKey().contains("method entry request"));
+
+ txPut(conn, "Frames");
+ List<TraceObjectValue> pcs = waitForValues("VMs[].Threads[main].Stack[0]._display");
+ assertTrue(pcs.get(0).getValue().toString().contains("<init>"));
+ }
+ }
+ }
+
+ @Test
+ public void testToggleBreakpoint() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshBreakpoints = conn.getMethod("refresh_breakpoints");
+ RemoteMethod toggleBreakpoint = conn.getMethod("toggle_breakpoint");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ conn.execute("VirtualMachine vm = manager.getCurrentVM();");
+ conn.execute("Location loc = manager.getCurrentLocation();");
+ conn.execute(
+ "BreakpointRequest brkReq = vm.eventRequestManager().createBreakpointRequest(loc);");
+
+ TraceObject brkPts = waitForObject("VMs[].Breakpoints");
+ List<TraceObjectValue> descs = waitForPass(() -> {
+ refreshBreakpoints.invoke(Map.of("container", brkPts));
+ List<TraceObjectValue> d = waitForValues("VMs[].Breakpoints[]._display");
+ assertEquals(1, d.size());
+ return d;
+ });
+
+ assertTrue(descs.get(0).getValue().toString().contains("breakpoint request"));
+ assertTrue(descs.get(0).getValue().toString().contains("disabled"));
+
+ TraceObject brk = waitForObject("VMs[].Breakpoints[]");
+ toggleBreakpoint.invoke(Map.of("breakpoint", brk));
+
+ refreshBreakpoints.invoke(Map.of("container", brkPts));
+ descs = waitForValues("VMs[].Breakpoints[]._display");
+ assertTrue(descs.get(0).getValue().toString().contains("enabled"));
+ }
+ }
+ }
+
+ @Test
+ public void testDeleteBreakpoint() throws Exception {
+ try (JshellAndConnection conn = startAndConnectJshell()) {
+ start(conn, "HelloWorld.class");
+
+ RemoteMethod refreshBreakpoints = conn.getMethod("refresh_breakpoints");
+ RemoteMethod deleteBreakpoint = conn.getMethod("delete_breakpoint");
+ RemoteMethod stepInto = conn.getMethod("step_into");
+ try (ManagedDomainObject mdo = openDomainObject("/New Traces/HelloWorld.class")) {
+ tb = new ToyDBTraceBuilder((Trace) mdo.get());
+ txPut(conn, "Threads");
+
+ TraceObject thread = waitForObject("VMs[].Threads[main]");
+ stepInto.invoke(Map.of("thread", thread));
+ waitTxDone();
+
+ conn.execute("VirtualMachine vm = manager.getCurrentVM();");
+ conn.execute("Location loc = manager.getCurrentLocation();");
+ conn.execute(
+ "BreakpointRequest brkReq = vm.eventRequestManager().createBreakpointRequest(loc);");
+
+ TraceObject brkPts = waitForObject("VMs[].Breakpoints");
+ waitForPass(() -> {
+ refreshBreakpoints.invoke(Map.of("container", brkPts));
+ List<TraceObjectValue> d = waitForValues("VMs[].Breakpoints[]._display");
+ assertEquals(1, d.size());
+ });
+
+ TraceObject brk = waitForObject("VMs[].Breakpoints[]");
+ deleteBreakpoint.invoke(Map.of("breakpoint", brk));
+
+ waitForPass(() -> {
+ TraceObject bpts = waitForObject("VMs[].Breakpoints");
+ refreshBreakpoints.invoke(Map.of("container", bpts));
+ Collection<? extends TraceObjectValue> elements =
+ bpts.getElements(Lifespan.at(getMaxSnap()));
+ assertTrue(elements.isEmpty());
+ });
+ }
+ }
+ }
+
+ private void start(JshellAndConnection conn, String obj) {
+ if (obj != null) {
+ conn.execute("cmds.ghidraTraceStart(\"" + obj + "\");");
+ }
+ else {
+ conn.execute("mds.ghidraTraceStart();");
+ }
+ conn.execute("cmds.ghidraTraceCreate(System.getenv());");
+ conn.execute("cmds.ghidraTraceTxStart(\"Create snapshot\")");
+ conn.execute("cmds.ghidraTraceNewSnap(\"Scripted snapshot\")");
+ conn.execute("cmds.ghidraTraceTxCommit()");
+ }
+
+ private void txPut(JshellAndConnection conn, String obj) {
+ conn.execute("cmds.ghidraTraceTxStart(\"Tx\");");
+ conn.execute("cmds.ghidraTracePut" + obj + "();");
+ conn.execute("cmds.ghidraTraceTxCommit();");
+ waitTxDone();
+ }
+}
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbHooksTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbHooksTest.java
index 703e3e582f..c9d40f86ef 100644
--- a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbHooksTest.java
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbHooksTest.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -89,7 +89,7 @@ public class LldbHooksTest extends AbstractLldbTraceRmiTest {
start(conn, "%s".formatted(cloneExit));
conn.execute("break set -n work");
waitForPass(() -> {
- TraceObject proc = tb.objAny("Processes[]");
+ TraceObject proc = tb.objAny0("Processes[]");
assertNotNull(proc);
assertEquals("STOPPED", tb.objValue(proc, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -119,7 +119,7 @@ public class LldbHooksTest extends AbstractLldbTraceRmiTest {
conn.execute("break set -n work");
waitForPass(() -> {
- TraceObject inf = tb.objAny("Processes[]");
+ TraceObject inf = tb.objAny0("Processes[]");
assertNotNull(inf);
assertEquals("STOPPED", tb.objValue(inf, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -131,7 +131,7 @@ public class LldbHooksTest extends AbstractLldbTraceRmiTest {
conn.execute("continue");
waitStopped(conn.conn);
waitForPass(() -> {
- TraceObject inf = tb.objAny("Processes[]");
+ TraceObject inf = tb.objAny0("Processes[]");
assertNotNull(inf);
assertEquals("STOPPED", tb.objValue(inf, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -283,7 +283,7 @@ public class LldbHooksTest extends AbstractLldbTraceRmiTest {
conn.execute("cont");
waitRunning(conn.conn);
- TraceObject proc = waitForValue(() -> tb.objAny("Processes[]"));
+ TraceObject proc = waitForValue(() -> tb.objAny0("Processes[]"));
waitForPass(() -> {
assertEquals("RUNNING", tb.objValue(proc, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -297,7 +297,7 @@ public class LldbHooksTest extends AbstractLldbTraceRmiTest {
try (LldbAndTrace conn = startAndSyncLldb()) {
start(conn, getSpecimenPrint());
- TraceObject inf = waitForValue(() -> tb.objAny("Processes[]"));
+ TraceObject inf = waitForValue(() -> tb.objAny0("Processes[]"));
waitForPass(() -> {
assertEquals("STOPPED", tb.objValue(inf, lastSnap(conn), "_state"));
}, RUN_TIMEOUT_MS, RETRY_MS);
@@ -318,7 +318,7 @@ public class LldbHooksTest extends AbstractLldbTraceRmiTest {
assertNotNull(snapshot);
assertEquals("Exited with code 72", snapshot.getDescription());
- TraceObject proc = tb.objAny("Processes[]");
+ TraceObject proc = tb.objAny0("Processes[]");
assertNotNull(proc);
Object val = tb.objValue(proc, lastSnap(conn), "_exit_code");
assertThat(val, instanceOf(Number.class));
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbMethodsTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbMethodsTest.java
index 7ea4ea4e47..c232d4b135 100644
--- a/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbMethodsTest.java
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test.slow/java/agent/lldb/rmi/LldbMethodsTest.java
@@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -79,7 +79,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
RemoteMethod refreshAvailable = conn.getMethod("refresh_available");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/noname")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject available = Objects.requireNonNull(tb.objAny("Available"));
+ TraceObject available = Objects.requireNonNull(tb.objAny0("Available"));
refreshAvailable.invoke(Map.of("node", available));
@@ -107,7 +107,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
conn.execute("breakpoint set --name main");
conn.execute("breakpoint set -H --name main");
txPut(conn, "breakpoints");
- TraceObject breakpoints = Objects.requireNonNull(tb.objAny("Breakpoints"));
+ TraceObject breakpoints = Objects.requireNonNull(tb.objAny0("Breakpoints"));
refreshBreakpoints.invoke(Map.of("node", breakpoints));
List<TraceObjectValue> procBreakLocVals = tb.trace.getObjectManager()
@@ -145,7 +145,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
waitStopped(conn);
TraceObject locations =
- Objects.requireNonNull(tb.objAny("Processes[].Breakpoints"));
+ Objects.requireNonNull(tb.objAny0("Processes[].Breakpoints"));
conn.execute("breakpoint set --name main");
conn.execute("breakpoint set -H --name main");
refreshProcBreakpoints.invoke(Map.of("node", locations));
@@ -183,7 +183,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
waitStopped(conn);
TraceObject locations =
- Objects.requireNonNull(tb.objAny("Processes[].Watchpoints"));
+ Objects.requireNonNull(tb.objAny0("Processes[].Watchpoints"));
conn.execute("watchpoint set expression -s 1 -- `(void(*)())main`");
conn.execute("watchpoint set expression -s 1 -w read -- `(void(*)())main`+-0x20");
conn.execute(
@@ -230,7 +230,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
RemoteMethod refreshProcesses = conn.getMethod("refresh_processes");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/noname")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject processes = Objects.requireNonNull(tb.objAny("Processes"));
+ TraceObject processes = Objects.requireNonNull(tb.objAny0("Processes"));
refreshProcesses.invoke(Map.of("node", processes));
@@ -254,7 +254,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
RemoteMethod refreshEnvironment = conn.getMethod("refresh_environment");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/expPrint")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject env = Objects.requireNonNull(tb.objAny(path));
+ TraceObject env = Objects.requireNonNull(tb.objAny0(path));
refreshEnvironment.invoke(Map.of("node", env));
@@ -276,7 +276,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
RemoteMethod refreshThreads = conn.getMethod("refresh_threads");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/expPrint")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject threads = Objects.requireNonNull(tb.objAny(path));
+ TraceObject threads = Objects.requireNonNull(tb.objAny0(path));
refreshThreads.invoke(Map.of("node", threads));
@@ -302,7 +302,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
waitTxDone();
txPut(conn, "frames");
- TraceObject stack = Objects.requireNonNull(tb.objAny(path));
+ TraceObject stack = Objects.requireNonNull(tb.objAny0(path));
refreshStack.invoke(Map.of("node", stack));
// Would be nice to control / validate the specifics
@@ -355,7 +355,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
RemoteMethod refreshMappings = conn.getMethod("refresh_mappings");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/expPrint")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject memory = Objects.requireNonNull(tb.objAny(path));
+ TraceObject memory = Objects.requireNonNull(tb.objAny0(path));
refreshMappings.invoke(Map.of("node", memory));
@@ -377,7 +377,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
RemoteMethod refreshModules = conn.getMethod("refresh_modules");
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/expPrint")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject modules = Objects.requireNonNull(tb.objAny(path));
+ TraceObject modules = Objects.requireNonNull(tb.objAny0(path));
refreshModules.invoke(Map.of("node", modules));
@@ -474,7 +474,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/expPrint")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc2 = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc2 = Objects.requireNonNull(tb.objAny0("Processes[]"));
removeProcess.invoke(Map.of("process", proc2));
String out = conn.executeCapture("target list");
@@ -545,7 +545,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/expPrint")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
detach.invoke(Map.of("process", proc));
String out = conn.executeCapture("target list");
@@ -565,7 +565,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/noname")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
launch.invoke(Map.ofEntries(
Map.entry("process", proc),
Map.entry("file", getSpecimenPrint())));
@@ -587,7 +587,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/noname")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
launch.invoke(Map.ofEntries(
Map.entry("process", proc),
Map.entry("file", getSpecimenRead())));
@@ -619,7 +619,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped(conn);
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
kill.invoke(Map.of("process", proc));
String out = conn.executeCapture("target list");
@@ -677,7 +677,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
txPut(conn, "threads");
conn.execute("script lldb.debugger.SetAsync(False)");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
stepToCall(conn, step_into, thread);
String dis2 = conn.executeCapture("dis -c2 -s '$pc'");
@@ -704,7 +704,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
txPut(conn, "threads");
conn.execute("script lldb.debugger.SetAsync(False)");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
stepToCall(conn, step_over, thread);
String dis2 = conn.executeCapture("dis -c2 -s '$pc'");
@@ -733,7 +733,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
txPut(conn, "threads");
conn.execute("script lldb.debugger.SetAsync(False)");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
String dis3 = conn.executeCapture("disassemble -c3 -s '$pc'");
// TODO: Examine for control transfer?
List<String> lines = List.of(dis3.split("\n"));
@@ -766,7 +766,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
txPut(conn, "threads");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
activate.invoke(Map.of("thread", thread));
int initDepth = getDepth(conn);
@@ -796,7 +796,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
txPut(conn, "threads");
- TraceObject thread = Objects.requireNonNull(tb.objAny("Processes[].Threads[]"));
+ TraceObject thread = Objects.requireNonNull(tb.objAny0("Processes[].Threads[]"));
activate.invoke(Map.of("thread", thread));
int initDepth = getDepth(conn);
@@ -819,7 +819,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
try (ManagedDomainObject mdo = openDomainObject("/New Traces/lldb/expPrint")) {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = Long.decode(conn.executeCapture("dis -c1 -n main").split("\\s+")[1]);
breakAddress.invoke(Map.of("process", proc, "address", tb.addr(address)));
@@ -861,7 +861,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped(conn);
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = Long.decode(conn.executeCapture("dis -c1 -n main").split("\\s+")[1]);
breakAddress.invoke(Map.of("process", proc, "address", tb.addr(address)));
@@ -903,7 +903,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped(conn);
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = Long.decode(conn.executeCapture("dis -c1 -n main").split("\\s+")[1]);
AddressRange range = tb.range(address, address + 0); // length 1
breakRange.invoke(Map.of("process", proc, "range", range));
@@ -949,7 +949,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped(conn);
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = Long.decode(conn.executeCapture("dis -c1 -n main").split("\\s+")[1]);
AddressRange range = tb.range(address, address + 0); // length 1
breakRange.invoke(Map.of("process", proc, "range", range));
@@ -995,7 +995,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
tb = new ToyDBTraceBuilder((Trace) mdo.get());
waitStopped(conn);
- TraceObject proc = Objects.requireNonNull(tb.objAny("Processes[]"));
+ TraceObject proc = Objects.requireNonNull(tb.objAny0("Processes[]"));
long address = Long.decode(conn.executeCapture("dis -c1 -n main").split("\\s+")[1]);
AddressRange range = tb.range(address, address + 0); // length 1
breakRange.invoke(Map.of("process", proc, "range", range));
@@ -1063,7 +1063,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
conn.execute("breakpoint set -n main");
txPut(conn, "breakpoints");
- TraceObject bpt = Objects.requireNonNull(tb.objAny("Breakpoints[]"));
+ TraceObject bpt = Objects.requireNonNull(tb.objAny0("Breakpoints[]"));
toggleBreakpoint.invoke(Map.of("breakpoint", bpt, "enabled", false));
@@ -1087,7 +1087,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
conn.execute("breakpoint set -n main");
txPut(conn, "breakpoints");
- TraceObject loc = Objects.requireNonNull(tb.objAny("Breakpoints[][]"));
+ TraceObject loc = Objects.requireNonNull(tb.objAny0("Breakpoints[][]"));
toggleBreakpointLocation.invoke(Map.of("location", loc, "enabled", false));
@@ -1110,7 +1110,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
conn.execute("breakpoint set -n main");
txPut(conn, "breakpoints");
- TraceObject bpt = Objects.requireNonNull(tb.objAny("Breakpoints[]"));
+ TraceObject bpt = Objects.requireNonNull(tb.objAny0("Breakpoints[]"));
deleteBreakpoint.invoke(Map.of("breakpoint", bpt));
@@ -1140,7 +1140,7 @@ public class LldbMethodsTest extends AbstractLldbTraceRmiTest {
assertThat(out, containsString(Long.toHexString(address)));
txPut(conn, "watchpoints");
- TraceObject wpt = Objects.requireNonNull(tb.objAny("Processes[].Watchpoints[]"));
+ TraceObject wpt = Objects.requireNonNull(tb.objAny0("Processes[].Watchpoints[]"));
deleteWatchpoint.invoke(Map.of("watchpoint", wpt));
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePluginTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePluginTest.java
index dbec222909..a0395303fb 100644
--- a/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePluginTest.java
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/tracermi/launcher/TraceRmiLauncherServicePluginTest.java
@@ -26,13 +26,22 @@ import org.junit.Before;
import org.junit.Test;
import db.Transaction;
+import generic.jar.ResourceFile;
+import ghidra.app.plugin.core.analysis.AnalysisBackgroundCommand;
+import ghidra.app.plugin.core.analysis.AutoAnalysisManager;
import ghidra.app.plugin.core.debug.gui.AbstractGhidraHeadedDebuggerTest;
import ghidra.app.services.TraceRmiLauncherService;
+import ghidra.app.util.importer.AutoImporter;
+import ghidra.app.util.importer.MessageLog;
+import ghidra.app.util.opinion.LoadResults;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.tracermi.TraceRmiLaunchOffer;
import ghidra.debug.api.tracermi.TraceRmiLaunchOffer.*;
+import ghidra.framework.Application;
import ghidra.framework.OperatingSystem;
+import ghidra.framework.cmd.Command;
import ghidra.framework.plugintool.AutoConfigState.PathIsFile;
+import ghidra.program.model.listing.Program;
import ghidra.util.task.ConsoleTaskMonitor;
public class TraceRmiLauncherServicePluginTest extends AbstractGhidraHeadedDebuggerTest {
@@ -68,6 +77,20 @@ public class TraceRmiLauncherServicePluginTest extends AbstractGhidraHeadedDebug
};
}
+ @Test
+ public void testGetClassName() throws Exception {
+ ResourceFile rf = Application.getModuleDataFile("TestResources", "HelloWorld.class");
+ LoadResults<Program> results = AutoImporter.importByUsingBestGuess(rf.getFile(false),
+ env.getProject(), "/", this, new MessageLog(), monitor);
+ program = results.getPrimaryDomainObject();
+ AutoAnalysisManager analyzer = AutoAnalysisManager.getAnalysisManager(program);
+ analyzer.reAnalyzeAll(null);
+ Command<Program> cmd = new AnalysisBackgroundCommand(analyzer, false);
+ tool.execute(cmd, program);
+ waitForBusyTool(tool);
+ assertEquals("HelloWorld", TraceRmiLauncherServicePlugin.tryProgramJvmClass(program));
+ }
+
// @Test // This is currently hanging the test machine. The gdb process is left running
public void testLaunchLocalGdb() throws Exception {
assumeTrue(OperatingSystem.CURRENT_OPERATING_SYSTEM == OperatingSystem.LINUX);