Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-5894: Add DebuggerVariableViewerPlugin to display variables with their values in a trace or live debugging session

ghidra_red548a9188d0b2
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineActions.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineActions.java
index 63a4892659..7a6a2333d8 100644
--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineActions.java
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineActions.java
@@ -15,13 +15,11 @@
*/
package ghidra.app.plugin.core.debug.gui.breakpoint.timeline;
+import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
-import javax.swing.JComponent;
-import javax.swing.JScrollPane;
-
import docking.*;
import docking.action.DockingAction;
import docking.action.MenuData;
@@ -44,7 +42,52 @@ import ghidra.trace.model.target.TraceObjectValue;
import ghidra.util.Msg;
public class BreakpointTimelineActions {
- protected record AddressSnap(Address address, Long snap) {}
+ private enum BreakType {
+ EXECUTE("Execution"), READ("Memory Read"), WRITE("Memory Write"), ACCESS("Memory Access");
+
+ final String menuName;
+
+ BreakType(String menuName) {
+ this.menuName = menuName;
+ }
+
+ String infoTitle() {
+ return switch (this) {
+ case EXECUTE -> "Execute search";
+ case READ -> "Read search";
+ case WRITE -> "Write search";
+ case ACCESS -> "Access search";
+ };
+ }
+
+ String plural() {
+ return switch (this) {
+ case EXECUTE -> "executions";
+ case READ -> "memory reads";
+ case WRITE -> "memory writes";
+ case ACCESS -> "memory accesses";
+ };
+ }
+ }
+
+ private enum SearchType {
+ FIRST("First...", "Go To First"),
+ PREVIOUS("Previous...", "Go To Previous"),
+ NEXT("Next." + "..", "Go To Next"),
+ FINAL("Final...", "Go To Final"),
+ ALL("Show All...", "Show All");
+
+ final String menuGroup;
+ final String actionName;
+
+ SearchType(String menuGroup, String actionName) {
+ this.menuGroup = menuGroup;
+ this.actionName = actionName;
+ }
+ }
+
+ protected record AddressSnap(Address address, Long snap) {
+ }
private class BreakpointTimelineActionProvider extends ComponentProvider {
private final JComponent component;
@@ -52,11 +95,11 @@ public class BreakpointTimelineActions {
public BreakpointTimelineActionProvider(Tool tool, String title,
List<AddressSnap> snapList) {
- super(tool, title, "BreakpointTimelineActions");
+ super(tool, title, BreakpointTimelineActions.this.name);
snaps = new ArrayList<>(snapList);
final AnyObjectTableModel<AddressSnap> model =
- new AnyObjectTableModel<>("AddressSnap", AddressSnap.class, "snap", "address");
+ new AnyObjectTableModel<>("AddressSnap", AddressSnap.class, "snap", "address");
model.setModelData(snaps);
final GTable table = new GTable(model);
@@ -85,59 +128,28 @@ public class BreakpointTimelineActions {
}
- private enum BreakType {
- EXECUTE("Execution"), READ("Memory Read"), WRITE("Memory Write"), ACCESS("Memory Access");
-
- String menuName;
-
- BreakType(String menuName) {
- this.menuName = menuName;
- }
-
- String plural() {
- return switch (this) {
- case EXECUTE -> "executions";
- case READ -> "memory reads";
- case WRITE -> "memory writes";
- case ACCESS -> "memory accesses";
- };
- }
- }
-
- private enum SearchType {
- FIRST("First..."),
- PREVIOUS("Previous..."),
- NEXT("Next..."),
- FINAL("Final..."),
- ALL("Show All...");
-
- String menuGroup;
-
- SearchType(String menuGroup) {
- this.menuGroup = menuGroup;
- }
- }
-
private class TimelineAction extends DockingAction {
private final BreakType breakType;
private final SearchType searchType;
private final PluginTool tool;
private TimelineAction(PluginTool tool, SearchType searchType, BreakType breakType) {
- super(breakType.menuName, "BreakpointTimelineHitAction");
+ super(searchType.actionName + " " + breakType.menuName,
+ BreakpointTimelineActions.this.name);
this.breakType = breakType;
this.tool = tool;
this.searchType = searchType;
if (searchType != SearchType.ALL) {
setPopupMenuData(new MenuData(
- new String[] { "Go to...", searchType.menuGroup, breakType.menuName }, null,
- "BreakpointTimelineActions"));
+ new String[] { "Go to...", searchType.menuGroup, breakType.menuName },
+ null,
+ BreakpointTimelineActions.this.name));
}
else {
setPopupMenuData(
- new MenuData(new String[] { searchType.menuGroup, breakType.menuName }, null,
- "BreakpointTimelineActions"));
+ new MenuData(new String[] { searchType.menuGroup, breakType.menuName },
+ null, BreakpointTimelineActions.this.name));
}
}
@@ -146,7 +158,11 @@ public class BreakpointTimelineActions {
final AddressSet addrRange = getAddessRangeFromContext(context);
final Lifespan lifespan = getLifespan();
final Trace currentTrace =
- tool.getService(DebuggerTraceManagerService.class).getCurrentTrace();
+ tool.getService(DebuggerTraceManagerService.class).getCurrentTrace();
+
+ if (addrRange == null) {
+ return;
+ }
switch (breakType) {
case EXECUTE -> handleExecutionAction(addrRange, lifespan, currentTrace);
@@ -156,102 +172,21 @@ public class BreakpointTimelineActions {
private AddressSet getAddessRangeFromContext(ActionContext context) {
return switch (context) {
- case final CodeViewerActionContext c -> getAddressRangeFromCodeViewerActionContext(
- c);
- case final DebuggerListingActionContext c -> getAddressRangeFromDebuggerListingActionContext(
- c);
- case final DebuggerRegisterActionContext c -> getAddressRangeFromDebuggerRegisterActionContext(
- c);
- case final ByteViewerActionContext c -> getAddressRangeFromByteViewerActionContext(
- c);
+ case final CodeViewerActionContext c ->
+ getAddressRangeFromCodeViewerActionContext(c);
+ case final DebuggerListingActionContext c ->
+ getAddressRangeFromDebuggerListingActionContext(c);
+ case final DebuggerRegisterActionContext c ->
+ getAddressRangeFromDebuggerRegisterActionContext(c);
+ case final ByteViewerActionContext c ->
+ getAddressRangeFromByteViewerActionContext(c);
default -> null;
};
}
- private AddressSet getAddressRangeFromByteViewerActionContext(ByteViewerActionContext c) {
- final AddressSet dynamicSet = new AddressSet();
-
- for (final AddressRange range : c.getSelection().getAddressRanges()) {
- dynamicSet.add(range.getMinAddress(), range.getMaxAddress());
- }
- return dynamicSet;
- }
-
- private AddressSet getAddressRangeFromCodeViewerActionContext(CodeViewerActionContext c) {
- final Trace trace =
- tool.getService(DebuggerTraceManagerService.class).getCurrentTrace();
- final DebuggerStaticMappingService staticMappingService =
- tool.getService(DebuggerStaticMappingService.class);
- final AddressSet dynamicSet = new AddressSet();
-
- if (c.getSelection().isEmpty()) {
- final ProgramLocation dynamicLocation =
- staticMappingService.getDynamicLocationFromStatic(trace.getProgramView(),
- new ProgramLocation(c.getProgram(), c.getAddress()));
- if (dynamicLocation == null) {
- Msg.showInfo(null, null, "No mapping", "No mapping for %s @ 0x%x"
- .formatted(c.getProgram(), c.getAddress().getOffset()));
- }
- else {
- dynamicSet.add(dynamicLocation.getAddress());
- }
- }
- else {
- for (final AddressRange range : c.getSelection().getAddressRanges()) {
- final ProgramLocation startDynamicLocation =
- staticMappingService.getDynamicLocationFromStatic(trace.getProgramView(),
- new ProgramLocation(c.getProgram(), range.getMinAddress()));
- if (startDynamicLocation == null) {
- Msg.showInfo(null, null, "No mapping", "No mapping for %s @ 0x%x"
- .formatted(c.getProgram(), range.getMinAddress().getOffset()));
- continue;
- }
- final ProgramLocation endDynamicLocation =
- staticMappingService.getDynamicLocationFromStatic(trace.getProgramView(),
- new ProgramLocation(c.getProgram(), range.getMaxAddress()));
- if (endDynamicLocation == null) {
- Msg.showInfo(null, null, "No mapping", "No mapping for %s @ 0x%x"
- .formatted(c.getProgram(), range.getMaxAddress().getOffset()));
- continue;
- }
- dynamicSet.add(startDynamicLocation.getAddress(),
- endDynamicLocation.getAddress());
- }
- }
- return dynamicSet;
- }
-
- private AddressSet getAddressRangeFromDebuggerListingActionContext(
- DebuggerListingActionContext c) {
- final AddressSet dynamicSet = new AddressSet();
- if (c.getSelection().isEmpty()) {
- dynamicSet.add(c.getAddress());
- }
- else {
- for (final AddressRange range : c.getSelection().getAddressRanges()) {
- dynamicSet.add(range.getMinAddress(), range.getMaxAddress());
- }
- }
- return dynamicSet;
- }
-
- private AddressSet getAddressRangeFromDebuggerRegisterActionContext(
- DebuggerRegisterActionContext c) {
- final AddressSpace addressSpace = tool.getService(DebuggerTraceManagerService.class)
- .getCurrentTrace()
- .getProgramView()
- .getAddressFactory()
- .getDefaultAddressSpace();
- final Long regValue = c.getSelected().getValue().longValue();
- final Address addr = addressSpace.getAddress(regValue);
- final AddressSet addressSet = new AddressSet();
- addressSet.add(addr);
- return addressSet;
- }
-
private Lifespan getLifespan() {
final long currentSnap =
- tool.getService(DebuggerTraceManagerService.class).getCurrentSnap();
+ tool.getService(DebuggerTraceManagerService.class).getCurrentSnap();
return switch (searchType) {
case ALL, FINAL, FIRST -> Lifespan.ALL;
case NEXT -> Lifespan.nowOn(currentSnap + 1);
@@ -275,14 +210,13 @@ public class BreakpointTimelineActions {
.sorted(Comparator.comparingLong(TraceObjectValue::getMinSnap))
.toList();
- if (hits.size() > 0) {
+ if (!hits.isEmpty()) {
if (searchType == SearchType.ALL) {
new BreakpointTimelineActionProvider(tool,
- "All executions in %s - %s".formatted(addrSet.getMinAddress(),
- addrSet.getMaxAddress()),
- hits.stream()
- .map(c -> new AddressSnap(c.castValue(), c.getMinSnap()))
- .toList());
+ "All executions in %s - %s".formatted(addrSet.getMinAddress(),
+ addrSet.getMaxAddress()), hits.stream()
+ .map(c -> new AddressSnap(c.castValue(), c.getMinSnap()))
+ .toList());
return;
}
final Long snap = switch (searchType) {
@@ -296,17 +230,18 @@ public class BreakpointTimelineActions {
tool.getService(DebuggerTraceManagerService.class).activateSnap(snap);
}
else if (searchType == SearchType.ALL) {
- Msg.showInfo(this, null, "%s search".formatted(breakType.name()),
- "There are no executions at this location".formatted(breakType.name()));
+ Msg.showInfo(this, null, breakType.infoTitle(),
+ "There are no executions at this location");
}
else {
- Msg.showInfo(this, null, "%s search".formatted(breakType.name()),
- "There is no %s execution at this location"
- .formatted(searchType.name().toLowerCase()));
+ Msg.showInfo(this, null, breakType.infoTitle(),
+ "There is no %s execution at this location".formatted(
+ searchType.name().toLowerCase()));
}
}
- private void handleMemoryAction(AddressSet addrSet, Lifespan lifespan, Trace currentTrace) {
+ private void handleMemoryAction(AddressSet addrSet, Lifespan lifespan,
+ Trace currentTrace) {
final List<? extends TraceReference> hits = addrSet.stream()
.flatMap(addrRange -> currentTrace.getReferenceManager()
.getReferencesToRange(lifespan, addrRange)
@@ -314,14 +249,14 @@ public class BreakpointTimelineActions {
.sorted(Comparator.comparingLong(TraceReference::getStartSnap))
.toList();
- if (hits.size() > 0) {
+ if (!hits.isEmpty()) {
if (searchType == SearchType.ALL) {
new BreakpointTimelineActionProvider(tool,
- "All %s in %s - %s".formatted(breakType.name(), addrSet.getMinAddress(),
- addrSet.getMaxAddress()),
- hits.stream()
- .map(c -> new AddressSnap(c.getFromAddress(), c.getStartSnap()))
- .toList());
+ "All %s in %s - %s".formatted(breakType.name(),
+ addrSet.getMinAddress(),
+ addrSet.getMaxAddress()), hits.stream()
+ .map(c -> new AddressSnap(c.getFromAddress(), c.getStartSnap()))
+ .toList());
return;
}
final Long snap = switch (searchType) {
@@ -335,26 +270,115 @@ public class BreakpointTimelineActions {
tool.getService(DebuggerTraceManagerService.class).activateSnap(snap);
}
else if (searchType == SearchType.ALL) {
- Msg.showInfo(this, null, "%s search".formatted(breakType.name()),
- "There are no %s to this location".formatted(breakType.plural()));
+ Msg.showInfo(this, null, breakType.infoTitle(),
+ "There are no %s to this location".formatted(breakType.plural()));
+ }
+ else {
+ Msg.showInfo(this, null, breakType.infoTitle(),
+ "There is no %s %s to this location".formatted(
+ searchType.name().toLowerCase(),
+ breakType.menuName.toLowerCase()));
+ }
+ }
+
+ private AddressSet getAddressRangeFromCodeViewerActionContext(CodeViewerActionContext c) {
+ final Trace trace =
+ tool.getService(DebuggerTraceManagerService.class).getCurrentTrace();
+ final DebuggerStaticMappingService staticMappingService =
+ tool.getService(DebuggerStaticMappingService.class);
+ final AddressSet dynamicSet = new AddressSet();
+ String noMapping = "No mapping";
+ String noMappingFormat = "No mapping for %s @ 0x%x";
+
+ if (c.getSelection().isEmpty()) {
+ final ProgramLocation dynamicLocation =
+ staticMappingService.getDynamicLocationFromStatic(trace.getProgramView(),
+ new ProgramLocation(c.getProgram(), c.getAddress()));
+ if (dynamicLocation == null) {
+ Msg.showInfo(null, null, noMapping,
+ noMappingFormat.formatted(c.getProgram(), c.getAddress().getOffset()));
+ }
+ else {
+ dynamicSet.add(dynamicLocation.getAddress());
+ }
}
else {
- Msg.showInfo(this, null, "%s search".formatted(breakType.name()),
- "There is no %s %s to this location".formatted(searchType.name().toLowerCase(),
- breakType.menuName.toLowerCase()));
+ for (final AddressRange range : c.getSelection().getAddressRanges()) {
+ final ProgramLocation startDynamicLocation =
+ staticMappingService.getDynamicLocationFromStatic(
+ trace.getProgramView(),
+ new ProgramLocation(c.getProgram(), range.getMinAddress()));
+ if (startDynamicLocation == null) {
+ Msg.showInfo(null, null, noMapping,
+ noMappingFormat.formatted(c.getProgram(),
+ range.getMinAddress().getOffset()));
+ continue;
+ }
+ final ProgramLocation endDynamicLocation =
+ staticMappingService.getDynamicLocationFromStatic(
+ trace.getProgramView(),
+ new ProgramLocation(c.getProgram(), range.getMaxAddress()));
+ if (endDynamicLocation == null) {
+ Msg.showInfo(null, null, noMapping,
+ noMappingFormat.formatted(c.getProgram(),
+ range.getMaxAddress().getOffset()));
+ continue;
+ }
+ dynamicSet.add(startDynamicLocation.getAddress(),
+ endDynamicLocation.getAddress());
+ }
+ }
+ return dynamicSet;
+ }
+
+ private AddressSet getAddressRangeFromDebuggerListingActionContext(
+ DebuggerListingActionContext c) {
+ final AddressSet dynamicSet = new AddressSet();
+ if (c.getSelection().isEmpty()) {
+ dynamicSet.add(c.getAddress());
+ }
+ else {
+ for (final AddressRange range : c.getSelection().getAddressRanges()) {
+ dynamicSet.add(range.getMinAddress(), range.getMaxAddress());
+ }
+ }
+ return dynamicSet;
+ }
+
+ private AddressSet getAddressRangeFromDebuggerRegisterActionContext(
+ DebuggerRegisterActionContext c) {
+ final AddressSpace addressSpace = tool.getService(DebuggerTraceManagerService.class)
+ .getCurrentTrace()
+ .getProgramView()
+ .getAddressFactory()
+ .getDefaultAddressSpace();
+ final long regValue = c.getSelected().getValue().longValue();
+ final Address addr = addressSpace.getAddress(regValue);
+ final AddressSet addressSet = new AddressSet();
+ addressSet.add(addr);
+ return addressSet;
+ }
+
+ private AddressSet getAddressRangeFromByteViewerActionContext(ByteViewerActionContext c) {
+ final AddressSet dynamicSet = new AddressSet();
+
+ for (final AddressRange range : c.getSelection().getAddressRanges()) {
+ dynamicSet.add(range.getMinAddress(), range.getMaxAddress());
}
+ return dynamicSet;
}
@Override
public boolean isEnabledForContext(ActionContext context) {
return ((context instanceof CodeViewerActionContext) ||
- (context instanceof DebuggerListingActionContext) ||
- (context instanceof DebuggerRegisterActionContext) ||
- (context instanceof ByteViewerActionContext));
+ (context instanceof DebuggerListingActionContext) ||
+ (context instanceof DebuggerRegisterActionContext) ||
+ (context instanceof ByteViewerActionContext));
}
}
private final PluginTool tool;
+ String name = this.getClass().getSimpleName();
List<TimelineAction> actions;
BreakpointTimelineActions(PluginTool tool) {
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelinePanel.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelinePanel.java
index 1d2383af0c..fe34ad7685 100644
--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelinePanel.java
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelinePanel.java
@@ -97,8 +97,8 @@ class BreakpointTimelinePanel extends JPanel {
}
}
- private static boolean singleColumn = false;
- private static boolean showGridOutline = true;
+ private boolean singleColumn = false;
+ private boolean showGridOutline = true;
private static final GColor BG_COLOR = Colors.BACKGROUND;
private static final GColor GRID_COLOR = Colors.FOREGROUND_DISABLED;
@@ -156,9 +156,8 @@ class BreakpointTimelinePanel extends JPanel {
private void click(Point p) {
final Optional<BreakpointTimelinePanel.CachedIndex> first =
cells.values().stream().filter(s -> s.getRect().contains(p)).findFirst();
- if (first.isPresent()) {
- getTraceManagerService().activateSnap(first.get().getMainSnap());
- }
+ first.ifPresent(
+ cachedIndex -> getTraceManagerService().activateSnap(cachedIndex.getMainSnap()));
}
void decreaseDefaultCellSize() {
@@ -179,7 +178,7 @@ class BreakpointTimelinePanel extends JPanel {
return;
}
- if (!BreakpointTimelinePanel.singleColumn) {
+ if (!singleColumn) {
final long potentialSideLength = getPotentialSideLength(width, height);
cellWidth = Math.max(defaultCellSize, potentialSideLength);
@@ -235,7 +234,7 @@ class BreakpointTimelinePanel extends JPanel {
double xSideLength;
double ySideLength;
- double xPixelsPerCell = Math.ceil(Math.sqrt((numCells * width) / height));
+ double xPixelsPerCell = Math.ceil(Math.sqrt((double) (numCells * width) / height));
if (xPixelsPerCell == 0) {
xPixelsPerCell = width;
}
@@ -246,7 +245,7 @@ class BreakpointTimelinePanel extends JPanel {
xSideLength = width / xPixelsPerCell;
}
- final double yPixelsPerCell = Math.ceil(Math.sqrt((numCells * height) / width));
+ final double yPixelsPerCell = Math.ceil(Math.sqrt((double) (numCells * height) / width));
if ((Math.floor((yPixelsPerCell * width) / height) * yPixelsPerCell) < numCells) {
ySideLength = (width / Math.ceil((width * yPixelsPerCell) / height));
}
@@ -305,8 +304,9 @@ class BreakpointTimelinePanel extends JPanel {
final Graphics2D g2d = (Graphics2D) g;
- for (final Long cellIndex : cells.keySet()) {
- final CachedIndex curSpan = cells.get(cellIndex);
+ for (final Map.Entry<Long, CachedIndex> entry : cells.entrySet()) {
+ long cellIndex = entry.getKey();
+ final CachedIndex curSpan = entry.getValue();
if ((startDragIndex != null) && (endDragIndex != null) &&
(cellIndex >= startDragIndex.getIndex()) &&
(cellIndex <= endDragIndex.getIndex())) {
@@ -324,7 +324,7 @@ class BreakpointTimelinePanel extends JPanel {
}
g2d.fillRect(curSpan.getRect().x, curSpan.getRect().y, curSpan.getRect().width,
curSpan.getRect().height);
- if (BreakpointTimelinePanel.showGridOutline) {
+ if (showGridOutline) {
g2d.setColor(BreakpointTimelinePanel.GRID_COLOR);
g2d.drawRect(curSpan.getRect().x, curSpan.getRect().y, curSpan.getRect().width,
curSpan.getRect().height);
@@ -399,7 +399,6 @@ class BreakpointTimelinePanel extends JPanel {
else {
getTraceManagerService()
.activateSnap(getTraceManagerService().getCurrentSnap() - 1);
-
}
repaint();
}
@@ -446,12 +445,12 @@ class BreakpointTimelinePanel extends JPanel {
}
void toggleGridOrColumn() {
- BreakpointTimelinePanel.singleColumn = !BreakpointTimelinePanel.singleColumn;
+ singleColumn = !singleColumn;
calculateGridAndBuildCache();
}
void toggleGridOutline() {
- BreakpointTimelinePanel.showGridOutline = !BreakpointTimelinePanel.showGridOutline;
+ showGridOutline = !showGridOutline;
repaint();
}
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineProvider.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineProvider.java
index df085a92ac..1193568997 100644
--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineProvider.java
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/breakpoint/timeline/BreakpointTimelineProvider.java
@@ -44,20 +44,15 @@ public class BreakpointTimelineProvider extends ComponentProvider {
private class BreakpointTimeOverviewEventListener extends TraceDomainObjectListener {
public BreakpointTimeOverviewEventListener() {
- listenFor(TraceEvents.BREAKPOINT_CHANGED, this::breakpointChanged);
- listenFor(TraceEvents.BREAKPOINT_DELETED, this::breakpointDeleted);
+ listenFor(TraceEvents.BREAKPOINT_CHANGED, this::breakpointEvent);
+ listenFor(TraceEvents.BREAKPOINT_DELETED, this::breakpointEvent);
listenFor(TraceEvents.SNAPSHOT_ADDED, this::snapshotEvent);
listenFor(TraceEvents.SNAPSHOT_DELETED, this::snapshotEvent);
listenFor(TraceEvents.SNAPSHOT_CHANGED, this::snapshotEvent);
listenForUntyped(DomainObjectEvent.RESTORED, e -> snapshotEvent());
}
- void breakpointChanged(TraceBreakpointLocation tb) {
- refreshBreakpointHits();
- breakpointTimelinePlugin.refreshAllProviders(null);
- }
-
- void breakpointDeleted(TraceBreakpointLocation tb) {
+ void breakpointEvent(TraceBreakpointLocation tb) {
refreshBreakpointHits();
breakpointTimelinePlugin.refreshAllProviders(null);
}
@@ -68,6 +63,7 @@ public class BreakpointTimelineProvider extends ComponentProvider {
.longValue();
if (newMaxSnap != curMaxSnap) {
+ refreshBreakpointHits();
breakpointTimelinePanel.setEventsAndVisibleRange(breakpointHits, 0, newMaxSnap);
curMaxSnap = newMaxSnap;
}
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/AbstractTraceCallTreeNode.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/AbstractTraceCallTreeNode.java
index 2e1e369edf..9a89eeae88 100644
--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/AbstractTraceCallTreeNode.java
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/AbstractTraceCallTreeNode.java
@@ -22,7 +22,7 @@ import ghidra.trace.model.time.TraceSnapshot;
import ghidra.util.NumericUtilities;
import resources.Icons;
-abstract class AbstractTraceCallTreeNode extends GTreeTableNode {
+public abstract class AbstractTraceCallTreeNode extends GTreeTableNode {
public record ParamNameToBytes(String name, byte[] bytes) {}
private final TraceSnapshot snap;
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/TraceCallTreeProvider.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/TraceCallTreeProvider.java
index 1659242b24..20fb5398aa 100644
--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/TraceCallTreeProvider.java
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/tracecalltree/TraceCallTreeProvider.java
@@ -50,6 +50,7 @@ import ghidra.program.model.address.Address;
import ghidra.program.model.lang.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.FlowType;
+import ghidra.program.model.symbol.RefType;
import ghidra.program.util.AddressEvaluator;
import ghidra.program.util.ProgramLocation;
import ghidra.trace.model.*;
@@ -68,7 +69,7 @@ import resources.Icons;
import static ghidra.program.util.ProgramEvent.*;
-class TraceCallTreeProvider extends ComponentProviderAdapter
+public class TraceCallTreeProvider extends ComponentProviderAdapter
implements DebuggerProvider, PopupActionProvider {
private class ClearLogAction extends DockingAction {
@@ -76,8 +77,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
ClearLogAction(ComponentProvider provider) {
super("Clear log", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.CLEAR_ICON;
- setToolBarData(new ToolBarData(ICON, "log"));
+ Icon icon = Icons.CLEAR_ICON;
+ setToolBarData(new ToolBarData(icon, "log"));
}
@Override
@@ -91,8 +92,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
FoldRecursiveAction(ComponentProvider provider) {
super("Collapse from selected cell recursively", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.COLLAPSE_ALL_ICON;
- setToolBarData(new ToolBarData(ICON, "expand"));
+ Icon icon = Icons.COLLAPSE_ALL_ICON;
+ setToolBarData(new ToolBarData(icon, "expand"));
}
@Override
@@ -111,8 +112,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
JumpToCurrentAction(ComponentProvider provider) {
super("Jump to current node", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.HOME_ICON;
- setToolBarData(new ToolBarData(ICON, "jump"));
+ Icon icon = Icons.HOME_ICON;
+ setToolBarData(new ToolBarData(icon, "jump"));
}
@Override
@@ -131,8 +132,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
RebuildCallTreeAction(ComponentProvider provider) {
super("Rebuild Call Tree", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.REFRESH_ICON;
- setToolBarData(new ToolBarData(ICON, "refresh"));
+ Icon icon = Icons.REFRESH_ICON;
+ setToolBarData(new ToolBarData(icon, "refresh"));
}
@Override
@@ -154,8 +155,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
ShowLogWindowAction(ComponentProvider provider) {
super("Show/hide log window", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.WARNING_ICON;
- setToolBarData(new ToolBarData(ICON, "log"));
+ Icon icon = Icons.WARNING_ICON;
+ setToolBarData(new ToolBarData(icon, "log"));
setSelected(showLogWindow);
}
@@ -185,8 +186,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
ShowReturnsToggleAction(ComponentProvider provider) {
super("Show/hide returns", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.ARROW_UP_LEFT_ICON;
- setToolBarData(new ToolBarData(ICON, "show"));
+ Icon icon = Icons.ARROW_UP_LEFT_ICON;
+ setToolBarData(new ToolBarData(icon, "show"));
setSelected(showReturns);
}
@@ -209,8 +210,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
ShowTailCallsToggleAction(ComponentProvider provider) {
super("Show/hide tail calls", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.NAVIGATE_ON_INCOMING_EVENT_ICON;
- setToolBarData(new ToolBarData(ICON, "show"));
+ Icon icon = Icons.NAVIGATE_ON_INCOMING_EVENT_ICON;
+ setToolBarData(new ToolBarData(icon, "show"));
setSelected(showTailCalls);
}
@@ -283,8 +284,8 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
UnfoldRecursiveAction(ComponentProvider provider) {
super("Expand from selected cell recursively", provider.getOwner());
setEnabled(true);
- Icon ICON = Icons.EXPAND_ALL_ICON;
- setToolBarData(new ToolBarData(ICON, "expand"));
+ Icon icon = Icons.EXPAND_ALL_ICON;
+ setToolBarData(new ToolBarData(icon, "expand"));
}
@Override
@@ -474,7 +475,7 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
final Instruction inst) throws CancelledException {
monitor.checkCancelled();
- if (inst.getFlowType().equals(FlowType.UNCONDITIONAL_CALL) &&
+ if (inst.getFlowType().equals(RefType.UNCONDITIONAL_CALL) &&
(inst.getFlows().length == 1)) {
if (inst.getDefaultFallThrough() == null) {
treeLogModel.log(trace,
@@ -673,6 +674,7 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
final ProgramLocation loc =
new ProgramLocation(currentCoords.getView(), address);
listingService.goTo(loc, true);
+ listingService.requestFocus();
})
.build());
@@ -694,6 +696,7 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
final ProgramLocation loc =
new ProgramLocation(currentCoords.getView(), address);
dl.goTo(loc);
+ dl.requestFocus();
})
.build());
}
@@ -713,6 +716,7 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
final ProgramLocation loc =
new ProgramLocation(currentCoords.getView(), address);
dl.goTo(loc);
+ dl.requestFocus();
})
.build());
}
@@ -1215,9 +1219,9 @@ class TraceCallTreeProvider extends ComponentProviderAdapter
return;
}
final List<GTreeTableNode> list = currentRootNode.find(n -> {
- if (n instanceof final AbstractTraceCallTreeNode TraceCallTreeNode) {
- return TraceCallTreeNode.getName().equals(func.getName()) &&
- (coords.getSnap() >= TraceCallTreeNode.getSnapshotKey());
+ if (n instanceof final AbstractTraceCallTreeNode traceCallTreeNode) {
+ return traceCallTreeNode.getName().equals(func.getName()) &&
+ (coords.getSnap() >= traceCallTreeNode.getSnapshotKey());
}
treeTable.setStatusMessage("Can't find node for current location, check debug console");
return false;
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/AbstractDebuggerVariableViewerVarValue.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/AbstractDebuggerVariableViewerVarValue.java
new file mode 100644
index 0000000000..6a50b01925
--- /dev/null
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/AbstractDebuggerVariableViewerVarValue.java
@@ -0,0 +1,214 @@
+/* ###
+ * 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.variable;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Objects;
+
+import ghidra.app.services.DebuggerControlService;
+import ghidra.pcode.utils.Utils;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.DataType;
+import ghidra.program.model.data.DataTypeEncodeException;
+import ghidra.program.model.lang.Language;
+import ghidra.program.model.mem.ByteMemBufferImpl;
+import ghidra.trace.model.memory.TraceMemoryState;
+import ghidra.util.Msg;
+import ghidra.util.NumericUtilities;
+
+import static ghidra.docking.settings.SettingsImpl.NO_SETTINGS;
+
+public abstract class AbstractDebuggerVariableViewerVarValue {
+ byte[] oldValue;
+ TraceMemoryState state;
+ String repr;
+ Language language;
+ byte[] value;
+ Address address;
+ DebuggerVariableViewerProvider provider;
+ String error;
+
+ AbstractDebuggerVariableViewerVarValue(byte[] value, Address address, String repr,
+ DebuggerVariableViewerProvider provider, String error, TraceMemoryState state) {
+ this.value = value;
+ this.oldValue = value;
+ this.address = Objects.requireNonNull(address);
+ this.provider = Objects.requireNonNull(provider);
+ this.repr = Objects.requireNonNullElse(repr, "");
+ this.error = error;
+ language = provider.currentCoordinates.getLanguage();
+ this.state = state;
+ }
+
+ public void setOldValue(byte[] oldValue) {
+ this.oldValue = oldValue;
+ }
+
+ public boolean isKnown() {
+ return state == TraceMemoryState.KNOWN;
+ }
+
+ public boolean canEdit() {
+ if (this.language == null) {
+ return false;
+ }
+ if (this.value == null) {
+ return false;
+ }
+ if (this.error != null) {
+ return false;
+ }
+ if (address == Address.NO_ADDRESS) {
+ return false;
+ }
+
+ DebuggerControlService controlService = provider.controlService;
+ if (controlService == null) {
+ return false;
+ }
+ DebuggerControlService.StateEditor editor =
+ controlService.createStateEditor(provider.currentCoordinates);
+ return editor.isVariableEditable(address, value.length);
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public String getRepr() {
+ return repr;
+ }
+
+ public void setRepr(String reprValue) {
+ if ((getDataType() == null) || (value == null)) {
+ Msg.error(this, "No value or no data type");
+ return;
+ }
+ try {
+ final byte[] encoded = getDataType().encodeRepresentation(reprValue,
+ new ByteMemBufferImpl(address, value, language.isBigEndian()), NO_SETTINGS,
+ value.length);
+ setRawValueBytes(encoded);
+ }
+ catch (final DataTypeEncodeException e) {
+ Msg.error(this, e.getMessage());
+ }
+ }
+
+ abstract DataType getDataType();
+
+ abstract void setDataType(DataType dataType);
+
+ private void setRawValueBytes(byte[] bytes) {
+ if (address == null) {
+ throw new IllegalStateException("Cannot write to variable without an address");
+ }
+ if (bytes.length > value.length) {
+ throw new IllegalArgumentException("Byte arrays cannot exceed length of variable");
+ }
+ if (bytes.length < value.length) {
+ final byte[] fillOld = Arrays.copyOf(value, value.length);
+ System.arraycopy(bytes, 0, fillOld, 0, bytes.length);
+ bytes = fillOld;
+ }
+ final DebuggerControlService controlService = provider.controlService;
+ if (controlService == null) {
+ throw new AssertionError("No control service");
+ }
+ final DebuggerControlService.StateEditor editor =
+ controlService.createStateEditor(provider.currentCoordinates);
+ editor.setVariable(address, bytes).exceptionally(ex -> {
+ Msg.showError(this, null, "Write Failed", "Could not modify value (on target)", ex);
+ return null;
+ });
+
+ }
+
+ abstract String getSource();
+
+ abstract String getSymbol();
+
+ abstract void setSymbol(String symbol);
+
+ public String getValue() {
+ if ((value == null) || (language == null)) {
+ return "??";
+ }
+ if (value.length <= address.getPointerSize() || !address.isMemoryAddress()) {
+ final BigInteger asBigInt =
+ Utils.bytesToBigInteger(value, value.length, language.isBigEndian(), false);
+ return "0x" + asBigInt.toString(16);
+ }
+ else if (value.length > 64) {
+ // TODO: I'd like this not to affect the actual value, just the display esp., since
+ // this will be the "value" when starting to edit.
+ return "{ " + NumericUtilities.convertBytesToString(value, 0, 64, " ") + " ... }";
+ }
+ return "{ " + NumericUtilities.convertBytesToString(value, " ") + " }";
+ }
+
+ public void setValue(String valueString) {
+ if ((value == null) || (language == null)) {
+ throw new AssertionError("Value and language cannot be null");
+ }
+ if ((getDataType() == null) || (value == null)) {
+ // isValueEditable should have been false
+ Msg.error(this, "No value or no data type");
+ return;
+ }
+
+ valueString = valueString.trim();
+ if (valueString.startsWith("{")) {
+ if (!valueString.endsWith("}")) {
+ throw new NumberFormatException("Byte array values must be hex enclosed in {}");
+ }
+
+ setRawValueBytesString(valueString.substring(1, valueString.length() - 1));
+ return;
+ }
+
+ setRawValueIntString(valueString);
+ }
+
+ private void setRawValueBytesString(String bytesString) {
+ setRawValueBytes(NumericUtilities.convertStringToBytes(bytesString));
+ }
+
+ private void setRawValueIntString(String intString) {
+ intString = intString.trim();
+ final BigInteger val;
+ if (intString.startsWith("0x")) {
+ val = new BigInteger(intString.substring(2), 16);
+ }
+ else {
+ val = new BigInteger(intString, 10);
+ }
+ setRawValueBytes(Utils.bigIntegerToBytes(val, value.length, language.isBigEndian()));
+ }
+
+ public String getError() {
+ return error;
+ }
+
+ public boolean isChanged() {
+ return !Arrays.equals(value, oldValue);
+ }
+
+ public Language getLanguage() {
+ return this.language;
+ }
+}
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerHighVarValue.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerHighVarValue.java
new file mode 100644
index 0000000000..291cdd668e
--- /dev/null
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerHighVarValue.java
@@ -0,0 +1,82 @@
+/* ###
+ * 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.variable;
+
+import db.Transaction;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.DataType;
+import ghidra.program.model.pcode.HighFunctionDBUtil;
+import ghidra.program.model.pcode.HighSymbol;
+import ghidra.program.model.symbol.SourceType;
+import ghidra.trace.model.memory.TraceMemoryState;
+import ghidra.util.Msg;
+import ghidra.util.exception.DuplicateNameException;
+import ghidra.util.exception.InvalidInputException;
+
+public class DebuggerVariableViewerHighVarValue extends AbstractDebuggerVariableViewerVarValue {
+ HighSymbol variable;
+
+ public DebuggerVariableViewerHighVarValue(HighSymbol variable, byte[] value, Address address,
+ String repr, DebuggerVariableViewerProvider provider, String error,
+ TraceMemoryState state) {
+ super(value, address, repr, provider, error, state);
+ this.variable = variable;
+ }
+
+ @Override
+ public DataType getDataType() {
+ return variable.getDataType();
+ }
+
+ @Override
+ public void setDataType(DataType dataType) {
+ try (Transaction ignored = variable.getProgram().openTransaction("Set DataType")) {
+ HighFunctionDBUtil.updateDBVariable(variable, null, dataType, SourceType.USER_DEFINED);
+ }
+ catch (final DuplicateNameException e) {
+ Msg.showError(this, null, "Duplicate Name", e.getMessage());
+ }
+ catch (final InvalidInputException e) {
+ Msg.showError(this, null, "Invalid Input", e.getMessage());
+ }
+ }
+
+ @Override
+ public String getSource() {
+ return "Decompiler";
+ }
+
+ @Override
+ public String getSymbol() {
+ if (variable.getSymbol() == null) {
+ return variable.getName();
+ }
+ return variable.getSymbol().getName();
+ }
+
+ @Override
+ public void setSymbol(String symbol) {
+ try (Transaction ignored = variable.getProgram().openTransaction("Rename Symbol")) {
+ HighFunctionDBUtil.updateDBVariable(variable, symbol, null, SourceType.USER_DEFINED);
+ }
+ catch (final DuplicateNameException e) {
+ Msg.showError(this, null, "Duplicate Name", e.getMessage());
+ }
+ catch (final InvalidInputException e) {
+ Msg.showError(this, null, "Invalid Input", e.getMessage());
+ }
+ }
+}
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerModel.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerModel.java
new file mode 100644
index 0000000000..eed148aaf7
--- /dev/null
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerModel.java
@@ -0,0 +1,392 @@
+/* ###
+ * 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.variable;
+
+import javax.swing.*;
+import javax.swing.table.TableCellEditor;
+import javax.swing.table.TableModel;
+import java.awt.*;
+import java.awt.event.MouseEvent;
+import java.util.*;
+import java.util.List;
+import java.util.function.*;
+import java.util.stream.Collectors;
+
+import db.Transaction;
+import docking.Tool;
+import docking.widgets.table.*;
+import docking.widgets.table.threaded.ThreadedTableModelStub;
+import generic.theme.GColor;
+import ghidra.app.services.DataTypeManagerService;
+import ghidra.base.widgets.table.AbstractDataTypeTableCellEditor;
+import ghidra.docking.settings.Settings;
+import ghidra.framework.plugintool.ServiceProvider;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.DataType;
+import ghidra.program.model.lang.Register;
+import ghidra.trace.model.Trace;
+import ghidra.util.datastruct.Accumulator;
+import ghidra.util.table.column.GColumnRenderer;
+import ghidra.util.task.TaskMonitor;
+
+import static docking.widgets.table.CustomToStringCellRenderer.CustomFont.MONOSPACED;
+
+public class DebuggerVariableViewerModel
+ extends ThreadedTableModelStub<AbstractDebuggerVariableViewerVarValue> {
+ private static class DataTypeEditor extends AbstractDataTypeTableCellEditor {
+ @Override
+ protected DataTypeManagerService getService(TableModel model) {
+ if (!(model instanceof final DebuggerVariableViewerModel dvvModel)) {
+ return null;
+ }
+ return dvvModel.tool.getService(DataTypeManagerService.class);
+ }
+
+ @Override
+ protected DataType resolveSelection(DataType dataType, TableModel model) {
+ if ((dataType == null) ||
+ !(model instanceof final DebuggerVariableViewerModel dvvModel)) {
+ return null;
+ }
+ final Trace trace = dvvModel.trace;
+ if (trace == null) {
+ return dataType;
+ }
+ try (Transaction ignored = trace.openTransaction("Resolve DataType")) {
+ return trace.getDataTypeManager().resolve(dataType, null);
+ }
+ }
+ }
+
+ private static class VariableValueOrReprCellEditor<T> extends AbstractCellEditor
+ implements TableCellEditor {
+ private final Function<AbstractDebuggerVariableViewerVarValue, T> getter;
+ private final JTextField jTextField;
+
+ public VariableValueOrReprCellEditor(
+ Function<AbstractDebuggerVariableViewerVarValue, T> getter) {
+ this.getter = getter;
+ jTextField = new JTextField();
+ }
+
+ @Override
+ public Object getCellEditorValue() {
+ return jTextField.getText();
+ }
+
+ @Override
+ public boolean isCellEditable(EventObject e) {
+ if (e instanceof MouseEvent me) {
+ return me.getClickCount() >= 2;
+ }
+ return true;
+ }
+
+ @Override
+ public Component getTableCellEditorComponent(final JTable table, Object value,
+ boolean isSelected, int row, int column) {
+ AbstractDebuggerVariableViewerVarValue rowData =
+ (AbstractDebuggerVariableViewerVarValue) value;
+ jTextField.setText(getter.apply(rowData).toString());
+ return jTextField;
+ }
+ }
+
+ private static class VariableMemoryStateCellRenderer
+ extends CustomToStringCellRenderer<AbstractDebuggerVariableViewerVarValue> {
+ private static final Color COLOR_FOREGROUND_STALE =
+ new GColor("color.debugger.plugin.resources.watch.stale");
+ private static final Color COLOR_FOREGROUND_STALE_SEL =
+ new GColor("color.debugger.plugin.resources.watch.stale.selected");
+ private static final Color COLOR_FOREGROUND_CHANGED =
+ new GColor("color.debugger.plugin.resources.watch.changed");
+ private static final Color COLOR_FOREGROUND_CHANGED_SEL =
+ new GColor("color.debugger.plugin.resources.watch.changed.selected");
+
+ public VariableMemoryStateCellRenderer(
+ BiFunction<AbstractDebuggerVariableViewerVarValue, Settings, String> toString) {
+ super(MONOSPACED, AbstractDebuggerVariableViewerVarValue.class, toString, false);
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(GTableCellRenderingData data) {
+ super.getTableCellRendererComponent(data);
+ AbstractDebuggerVariableViewerVarValue row =
+ (AbstractDebuggerVariableViewerVarValue) data.getRowObject();
+ if (!row.isKnown()) {
+ if (data.isSelected()) {
+ setForeground(COLOR_FOREGROUND_STALE_SEL);
+ }
+ else {
+ setForeground(COLOR_FOREGROUND_STALE);
+ }
+ }
+ else if (row.isChanged()) {
+ if (data.isSelected()) {
+ setForeground(COLOR_FOREGROUND_CHANGED_SEL);
+ }
+ else {
+ setForeground(COLOR_FOREGROUND_CHANGED);
+ }
+ }
+ return this;
+ }
+ }
+
+ private static class AbstractDebuggerVariableColumn<T, V>
+ extends AbstractDynamicTableColumn<AbstractDebuggerVariableViewerVarValue, T, Object> {
+ private final Function<AbstractDebuggerVariableViewerVarValue, T> getter;
+ private final BiConsumer<AbstractDebuggerVariableViewerVarValue, V> setter;
+ private final Class<V> clazz;
+ private final String columnName;
+
+ AbstractDebuggerVariableColumn(String columnName,
+ Function<AbstractDebuggerVariableViewerVarValue, T> getter,
+ BiConsumer<AbstractDebuggerVariableViewerVarValue, V> setter, Class<V> clazz) {
+ this.columnName = columnName;
+ this.getter = getter;
+ this.setter = setter;
+ this.clazz = clazz;
+ }
+
+ @Override
+ public String getColumnName() {
+ return columnName;
+ }
+
+ @Override
+ public T getValue(AbstractDebuggerVariableViewerVarValue rowObject, Settings settings,
+ Object data, ServiceProvider services) throws IllegalArgumentException {
+ return getter.apply(rowObject);
+ }
+
+ public void setValue(AbstractDebuggerVariableViewerVarValue rowObject, Object data) {
+ setter.accept(rowObject, clazz.cast(data));
+ }
+
+ public boolean isEditable() {
+ return true;
+ }
+ }
+
+ private static class AbstractDebuggerVariableColumnNoSetter<T>
+ extends AbstractDebuggerVariableColumn<T, Void> {
+ AbstractDebuggerVariableColumnNoSetter(String columnName,
+ Function<AbstractDebuggerVariableViewerVarValue, T> getter) {
+ super(columnName, getter, null, null);
+ }
+
+ @Override
+ public void setValue(AbstractDebuggerVariableViewerVarValue rowObject, Object data) {
+ // Ignore set value as there is no setter
+ }
+
+ @Override
+ public boolean isEditable() {
+ return false;
+ }
+ }
+
+ private static class VariableValueOrReprColumn
+ extends AbstractDebuggerVariableColumn<AbstractDebuggerVariableViewerVarValue,
+ String> {
+
+ private final VariableMemoryStateCellRenderer cellRenderer;
+ private final VariableValueOrReprCellEditor<String> cellEditor;
+
+ VariableValueOrReprColumn(String columnName,
+ Function<AbstractDebuggerVariableViewerVarValue, String> getter,
+ BiConsumer<AbstractDebuggerVariableViewerVarValue, String> setter) {
+ super(columnName, v -> v, setter, String.class);
+ cellRenderer = new VariableMemoryStateCellRenderer((v, s) -> getter.apply(v));
+ cellEditor = new VariableValueOrReprCellEditor<>(getter);
+ }
+
+ @Override
+ public GColumnRenderer<AbstractDebuggerVariableViewerVarValue> getColumnRenderer() {
+ return cellRenderer;
+ }
+
+ @Override
+ public TableCellEditor getColumnEditor() {
+ return cellEditor;
+ }
+
+ }
+
+ private static class SourceColumn extends AbstractDebuggerVariableColumnNoSetter<String> {
+ SourceColumn() {
+ super("Source", AbstractDebuggerVariableViewerVarValue::getSource);
+ }
+ }
+
+ private static class StorageColumn
+ extends AbstractDebuggerVariableColumnNoSetter<AbstractDebuggerVariableViewerVarValue> {
+
+ private static final CustomToStringCellRenderer<AbstractDebuggerVariableViewerVarValue>
+ ADDRESS_RENDERER = new CustomToStringCellRenderer<>(MONOSPACED,
+ AbstractDebuggerVariableViewerVarValue.class, (v, s) -> {
+ if (v.getAddress() == Address.NO_ADDRESS) {
+ return "??";
+ }
+ else if (v.getAddress().isRegisterAddress()) {
+ Register register = v.getLanguage().getRegister(v.getAddress(), v.value.length);
+ if (register != null) {
+ return register.getName();
+ }
+ }
+ return v.getAddress().toString();
+ }, false);
+
+ StorageColumn() {
+ super("Storage", v -> v);
+ }
+
+ @Override
+ public GColumnRenderer<AbstractDebuggerVariableViewerVarValue> getColumnRenderer() {
+ return ADDRESS_RENDERER;
+ }
+
+ }
+
+ private static class ReprColumn extends VariableValueOrReprColumn {
+ ReprColumn() {
+ super("Repr", AbstractDebuggerVariableViewerVarValue::getRepr,
+ AbstractDebuggerVariableViewerVarValue::setRepr);
+ }
+ }
+
+ private static class SymbolColumn extends AbstractDebuggerVariableColumn<String, String> {
+ SymbolColumn() {
+ super("Symbol", AbstractDebuggerVariableViewerVarValue::getSymbol,
+ AbstractDebuggerVariableViewerVarValue::setSymbol, String.class);
+ }
+ }
+
+ private static class TypeColumn extends AbstractDebuggerVariableColumn<DataType, DataType> {
+ private static final DataTypeEditor TYPE_EDITOR = new DataTypeEditor();
+
+ TypeColumn() {
+ super("Type", AbstractDebuggerVariableViewerVarValue::getDataType,
+ AbstractDebuggerVariableViewerVarValue::setDataType, DataType.class);
+ }
+
+ @Override
+ public TableCellEditor getColumnEditor() {
+ return TYPE_EDITOR;
+ }
+ }
+
+ private static class ValueColumn extends VariableValueOrReprColumn {
+ ValueColumn() {
+ super("Value", AbstractDebuggerVariableViewerVarValue::getValue,
+ AbstractDebuggerVariableViewerVarValue::setValue);
+ }
+ }
+
+ private static class ErrorColumn extends AbstractDebuggerVariableColumnNoSetter<String> {
+ ErrorColumn() {
+ super("Error", AbstractDebuggerVariableViewerVarValue::getError);
+ }
+ }
+
+ private final List<AbstractDebuggerVariableViewerVarValue> vars;
+ private final Tool tool;
+ private final DebuggerVariableViewerProvider provider;
+ private Trace trace;
+
+ public DebuggerVariableViewerModel(Tool tool, DebuggerVariableViewerProvider provider) {
+ super("Variable Model", null);
+ vars = new LinkedList<>();
+ this.tool = tool;
+ this.provider = provider;
+ }
+
+ @Override
+ protected TableColumnDescriptor<AbstractDebuggerVariableViewerVarValue> createTableColumnDescriptor() {
+ final TableColumnDescriptor<AbstractDebuggerVariableViewerVarValue> descriptor =
+ new TableColumnDescriptor<>();
+ descriptor.addHiddenColumn(new SourceColumn());
+ descriptor.addVisibleColumn(new StorageColumn());
+ descriptor.addVisibleColumn(new SymbolColumn());
+ descriptor.addVisibleColumn(new ValueColumn());
+ descriptor.addVisibleColumn(new TypeColumn());
+ descriptor.addVisibleColumn(new ReprColumn());
+ descriptor.addVisibleColumn(new ErrorColumn());
+
+ return descriptor;
+ }
+
+ @Override
+ protected void doLoad(Accumulator<AbstractDebuggerVariableViewerVarValue> accumulator,
+ TaskMonitor monitor) {
+
+ if (provider != null) {
+ Map<String, AbstractDebuggerVariableViewerVarValue> varValueMap = vars.stream()
+ .sorted(Comparator.comparing(AbstractDebuggerVariableViewerVarValue::getSource))
+ .filter(v -> switch (provider.actionShowVariables.getCurrentState()
+ .getUserData()) {
+ case LISTING -> v instanceof DebuggerVariableViewerVarValue;
+ case DECOMPILER -> v instanceof DebuggerVariableViewerHighVarValue;
+ case BOTH -> true;
+ })
+ .collect(Collectors.toMap(AbstractDebuggerVariableViewerVarValue::getSymbol,
+ Function.identity(), (existing, replacement) -> existing));
+
+ for (AbstractDebuggerVariableViewerVarValue varValue : varValueMap.values()) {
+ accumulator.add(varValue);
+ }
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ if (getColumn(
+ columnIndex) instanceof AbstractDebuggerVariableColumn<?, ?> abstractDebuggerVariableColumn) {
+ return provider.actionEnableEdits.isSelected() &&
+ abstractDebuggerVariableColumn.isEditable() && getRowObject(rowIndex).canEdit();
+ }
+ return false;
+ }
+
+ @Override
+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
+ final AbstractDebuggerVariableViewerVarValue value = getRowObject(rowIndex);
+ if (getColumn(columnIndex) instanceof final AbstractDebuggerVariableColumn<?, ?> advCol) {
+ advCol.setValue(value, aValue);
+ provider.rebuildTable();
+ }
+ }
+
+ public void setModelData(List<AbstractDebuggerVariableViewerVarValue> result) {
+ for (AbstractDebuggerVariableViewerVarValue newValue : result) {
+ for (AbstractDebuggerVariableViewerVarValue oldValue : vars) {
+ if (oldValue.getAddress().equals(newValue.getAddress()) &&
+ Objects.equals(oldValue.getSymbol(), newValue.getSymbol()) &&
+ oldValue.getDataType().equals(newValue.getDataType())) {
+ newValue.setOldValue(oldValue.value);
+ }
+ }
+ }
+ vars.clear();
+ vars.addAll(result);
+ reload();
+ }
+
+ public void setTrace(Trace trace) {
+ this.trace = trace;
+ }
+}
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerPlugin.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerPlugin.java
new file mode 100644
index 0000000000..77ac89fc2d
--- /dev/null
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerPlugin.java
@@ -0,0 +1,66 @@
+/* ###
+ * 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.variable;
+
+import java.util.Objects;
+
+import ghidra.app.plugin.PluginCategoryNames;
+import ghidra.app.plugin.core.debug.AbstractDebuggerPlugin;
+import ghidra.app.plugin.core.debug.DebuggerPluginPackage;
+import ghidra.app.plugin.core.debug.event.TraceActivatedPluginEvent;
+import ghidra.app.services.*;
+import ghidra.debug.api.tracemgr.DebuggerCoordinates;
+import ghidra.framework.plugintool.*;
+import ghidra.framework.plugintool.util.PluginStatus;
+
+@PluginInfo(
+ shortDescription = "Variable Viewer For Traces",
+ description = "Displays a table of variables at the current snap for a trace",
+ category = PluginCategoryNames.DEBUGGER,
+ packageName = DebuggerPluginPackage.NAME,
+ status = PluginStatus.UNSTABLE,
+ servicesRequired = { DebuggerStaticMappingService.class, DebuggerListingService.class,
+ ProgressService.class, DebuggerControlService.class },
+ eventsConsumed = { TraceActivatedPluginEvent.class }
+)
+public class DebuggerVariableViewerPlugin extends AbstractDebuggerPlugin {
+ DebuggerVariableViewerProvider provider;
+
+ public DebuggerVariableViewerPlugin(PluginTool tool) {
+ super(tool);
+ }
+
+ @Override
+ protected void init() {
+ super.init();
+ provider = new DebuggerVariableViewerProvider(this);
+ }
+
+ @Override
+ public void processEvent(PluginEvent event) {
+ super.processEvent(event);
+ if (Objects.requireNonNull(event) instanceof TraceActivatedPluginEvent evt) {
+ DebuggerCoordinates current = evt.getActiveCoordinates();
+ provider.setCoordinates(current);
+ }
+ }
+
+ @Override
+ protected void dispose() {
+ tool.removeComponentProvider(provider);
+ super.dispose();
+ }
+}
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerProvider.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerProvider.java
new file mode 100644
index 0000000000..a741546a11
--- /dev/null
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerProvider.java
@@ -0,0 +1,454 @@
+/* ###
+ * 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.variable;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.MouseEvent;
+import java.util.*;
+import java.util.List;
+import java.util.concurrent.*;
+
+import docking.*;
+import docking.action.DockingActionIf;
+import docking.action.ToggleDockingAction;
+import docking.action.builder.ActionBuilder;
+import docking.action.builder.MultiStateActionBuilder;
+import docking.actions.PopupActionProvider;
+import docking.menu.MultiStateDockingAction;
+import docking.util.MessageOverlay;
+import docking.widgets.table.GTable;
+import docking.widgets.table.GTableFilterPanel;
+import generic.theme.GIcon;
+import ghidra.app.decompiler.DecompInterface;
+import ghidra.app.decompiler.DecompileResults;
+import ghidra.app.plugin.core.debug.gui.DebuggerProvider;
+import ghidra.app.plugin.core.debug.gui.DebuggerResources;
+import ghidra.app.plugin.core.debug.gui.action.NoneLocationTrackingSpec;
+import ghidra.app.plugin.core.debug.gui.stack.vars.VariableValueUtils;
+import ghidra.app.plugin.core.debug.service.modules.DebuggerStaticMappingUtils;
+import ghidra.app.plugin.core.debug.stack.StackUnwindWarningSet;
+import ghidra.app.plugin.core.debug.stack.UnwoundFrame;
+import ghidra.app.services.*;
+import ghidra.debug.api.listing.DebuggerListing;
+import ghidra.debug.api.tracemgr.DebuggerCoordinates;
+import ghidra.framework.model.DomainObjectListener;
+import ghidra.framework.model.DomainObjectListenerBuilder;
+import ghidra.framework.plugintool.*;
+import ghidra.framework.plugintool.annotation.AutoServiceConsumed;
+import ghidra.pcode.exec.DebuggerPcodeUtils;
+import ghidra.pcode.exec.PcodeExecutionException;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.lang.Register;
+import ghidra.program.model.lang.RegisterValue;
+import ghidra.program.model.listing.*;
+import ghidra.program.model.pcode.HighFunction;
+import ghidra.program.model.pcode.HighSymbol;
+import ghidra.program.util.ProgramLocation;
+import ghidra.trace.model.*;
+import ghidra.trace.model.memory.TraceMemorySpace;
+import ghidra.trace.model.thread.TraceThread;
+import ghidra.util.HelpLocation;
+import ghidra.util.Msg;
+import ghidra.util.task.TaskMonitor;
+import resources.Icons;
+
+import static ghidra.framework.model.DomainObjectEvent.RESTORED;
+import static ghidra.program.util.ProgramEvent.*;
+import static ghidra.trace.util.TraceEvents.BYTES_CHANGED;
+import static ghidra.trace.util.TraceEvents.BYTES_STATE_CHANGED;
+
+public class DebuggerVariableViewerProvider extends ComponentProviderAdapter
+ implements DebuggerProvider, PopupActionProvider {
+ enum VariableViewerStates {
+ LISTING, DECOMPILER, BOTH
+ }
+
+ interface DebuggerVariableViewerPopupAction {
+ String NAME = "Debugger variable viewer Popup Actions";
+ String DESCRIPTION = "Popup actions for debugger variable viewer";
+ String HELP_ANCHOR = "";
+ String GROUP1 = "z";
+ String GROUP2 = "zz";
+
+ static ActionBuilder builder(ComponentProvider owner, String subgroup, String... path) {
+ final String ownerName = owner.getName();
+ return new ActionBuilder(NAME, ownerName).description(DESCRIPTION)
+ .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR))
+ .popupMenuGroup(GROUP1, subgroup)
+ .popupMenuPath(path)
+ .popupWhen(c -> true)
+ .enabledWhen(c -> true);
+ }
+ }
+
+ static class DebuggerVariableActionContext extends DefaultActionContext {
+ private final List<AbstractDebuggerVariableViewerVarValue> selected;
+
+ public DebuggerVariableActionContext(DebuggerVariableViewerProvider provider,
+ List<AbstractDebuggerVariableViewerVarValue> selected, GTable source) {
+ super(provider, selected, source);
+ this.selected = selected;
+ }
+
+ public List<AbstractDebuggerVariableViewerVarValue> getSelected() {
+ return selected;
+ }
+ }
+
+ private final JComponent component;
+ private final DebuggerVariableViewerModel model;
+ private final MessageOverlay msgOverlay;
+ private final PluginTool pluginTool;
+ DebuggerCoordinates currentCoordinates;
+ private Set<Program> mappedPrograms;
+ private CompletableFuture<List<AbstractDebuggerVariableViewerVarValue>> currentFuture;
+ private DebuggerVariableActionContext myActionContext;
+
+ ToggleDockingAction actionEnableEdits;
+ MultiStateDockingAction<VariableViewerStates> actionShowVariables;
+
+ @SuppressWarnings("unused")
+ private final AutoService.Wiring autoServiceWiring;
+ @AutoServiceConsumed
+ DebuggerControlService controlService;
+ @AutoServiceConsumed
+ private ProgressService progressService;
+ @AutoServiceConsumed
+ private DebuggerStaticMappingService mappingService;
+ @AutoServiceConsumed
+ private DebuggerListingService listingService;
+
+ private final DomainObjectListener listener =
+ new DomainObjectListenerBuilder(this).ignoreWhen(() -> !isVisible())
+ .any(FUNCTION_ADDED, FUNCTION_REMOVED, FUNCTION_CHANGED, SYMBOL_ADDED,
+ SYMBOL_PRIMARY_STATE_CHANGED, SYMBOL_RENAMED, SYMBOL_DATA_CHANGED,
+ RESTORED, BYTES_CHANGED, BYTES_STATE_CHANGED)
+ .call(e -> rebuildTable())
+ .build();
+
+ public DebuggerVariableViewerProvider(DebuggerVariableViewerPlugin plugin) {
+ super(plugin.getTool(), "Variable Viewer", plugin.getName());
+ autoServiceWiring = AutoService.wireServicesConsumed(plugin, this);
+ pluginTool = plugin.getTool();
+ model = new DebuggerVariableViewerModel(plugin.getTool(), this);
+ final GTable table = new GTable(model);
+ GTableFilterPanel<AbstractDebuggerVariableViewerVarValue> filterPanel =
+ new GTableFilterPanel<>(table, model);
+
+ table.getSelectionModel().addListSelectionListener(evt -> {
+ if (evt.getValueIsAdjusting()) {
+ return;
+ }
+ myActionContext =
+ new DebuggerVariableActionContext(this, filterPanel.getSelectedItems(), table);
+ contextChanged();
+ });
+
+ final JScrollPane pane = new JScrollPane(table);
+
+ msgOverlay = new MessageOverlay();
+ JLayer<JComponent> jLayer = new JLayer<>(pane, msgOverlay);
+
+ final JPanel panel = new JPanel(new BorderLayout());
+ panel.add(jLayer);
+ panel.add(filterPanel, BorderLayout.SOUTH);
+
+ component = panel;
+
+ actionEnableEdits = DebuggerResources.EnableEditsAction.builder(plugin)
+ .enabledWhen(
+ c -> currentCoordinates != null && currentCoordinates.getTrace() != null)
+ .onAction(c -> {
+ })
+ .buildAndInstallLocal(this);
+
+ actionShowVariables =
+ new MultiStateActionBuilder<VariableViewerStates>("Show/hide variables",
+ this.getName()).onActionStateChanged((a, e) -> model.reload())
+ .addState("Show Variables From Both", Icons.CONFIGURE_FILTER_ICON,
+ VariableViewerStates.BOTH)
+ .addState("Show Listing Variables Only",
+ new GIcon("icon.plugin.codebrowser.provider"),
+ VariableViewerStates.LISTING)
+ .addState("Show Decompiler Variables Only",
+ new GIcon("icon.decompiler.action.provider"),
+ VariableViewerStates.DECOMPILER)
+ .toolBarGroup("z")
+ .buildAndInstallLocal(this);
+
+ setVisible(true);
+ pluginTool.addPopupActionProvider(this);
+ }
+
+ @Override
+ public JComponent getComponent() {
+ return component;
+ }
+
+ @Override
+ public ActionContext getActionContext(MouseEvent event) {
+ if (myActionContext == null) {
+ return super.getActionContext(event);
+ }
+ return myActionContext;
+ }
+
+ public void setCoordinates(DebuggerCoordinates coordinates) {
+ currentCoordinates = coordinates;
+ setupListeners(coordinates);
+ model.setTrace(coordinates.getTrace());
+ if (coordinates == DebuggerCoordinates.NOWHERE) {
+ model.setModelData(List.of());
+ model.fireTableDataChanged();
+ return;
+ }
+ rebuildTable();
+ }
+
+ private void setupListeners(DebuggerCoordinates coordinates) {
+ // Remove old listeners
+ if (mappedPrograms != null) {
+ for (Program program : mappedPrograms) {
+ program.removeListener(listener);
+ }
+ }
+
+ // Add listeners
+ mappedPrograms = mappingService.getOpenMappedProgramsAtSnap(coordinates.getTrace(),
+ coordinates.getSnap());
+ if (mappedPrograms != null) {
+ for (Program program : mappedPrograms) {
+ program.addListener(listener);
+ }
+ }
+ }
+
+ public void rebuildTable() {
+ if (currentFuture != null) {
+ currentFuture.cancel(true);
+ }
+ msgOverlay.setMessage("Loading...");
+ component.repaint();
+ currentFuture = progressService.execute(true, true, true,
+ m -> gatherVariables(m, currentCoordinates));
+ currentFuture.whenComplete((result, ex) -> {
+ if (ex != null && !(ex instanceof CancellationException)) {
+ Throwable actual = (ex instanceof CompletionException) ? ex.getCause() : ex;
+ result = List.of();
+ msgOverlay.setMessage(actual.getMessage());
+ }
+ else {
+ msgOverlay.setMessage(null);
+ }
+ model.setModelData(result);
+ model.fireTableDataChanged();
+ component.repaint();
+ });
+ }
+
+ private CompletableFuture<List<AbstractDebuggerVariableViewerVarValue>> gatherVariables(
+ TaskMonitor monitor, DebuggerCoordinates coordinates) {
+ return CompletableFuture.supplyAsync(() -> {
+ final List<AbstractDebuggerVariableViewerVarValue> varValues = new LinkedList<>();
+
+ final TraceThread thread = coordinates.getThread();
+ final Trace trace = coordinates.getTrace();
+ final long snap = coordinates.getSnap();
+
+ if (thread == null) {
+ return varValues;
+ }
+ final TraceMemorySpace regs =
+ trace.getMemoryManager().getMemoryRegisterSpace(thread, coordinates.getFrame(), false);
+ final Register programCounter = trace.getBaseLanguage().getProgramCounter();
+
+ final RegisterValue pcRegVal = regs.getValue(snap, programCounter);
+
+ if (pcRegVal == null) {
+ Msg.error(this, "Snapshot %d: PC =<unavailable>".formatted(snap));
+ return varValues;
+ }
+
+ final Address dynamicPC = trace.getBaseAddressFactory()
+ .getDefaultAddressSpace()
+ .getAddress(pcRegVal.getUnsignedValue().longValue());
+
+ final TraceLocation dynamicLoc =
+ new DefaultTraceLocation(trace, null, Lifespan.at(snap), dynamicPC);
+ final ProgramLocation staticLoc = mappingService.getOpenMappedLocation(dynamicLoc);
+
+ if (staticLoc == null) {
+ Msg.error(this, "Snap %d: Can't map 0x%x".formatted(snap, dynamicPC.getOffset()));
+ return varValues;
+ }
+
+ final Address pc = staticLoc.getAddress();
+ final Program program = staticLoc.getProgram();
+
+ final Function func =
+ DebuggerStaticMappingUtils.getFunction(dynamicPC, trace, snap, pluginTool);
+ if (func == null) {
+ Msg.error(this,
+ "Snap %d @ 0x%x : 0x%x in %s is not part of a function".formatted(snap,
+ dynamicPC.getOffset(), pc.getOffset(), program.getName()));
+ return varValues;
+ }
+
+ final VariableValueUtils.VariableEvaluator evaluator =
+ new VariableValueUtils.VariableEvaluator(pluginTool, coordinates);
+ final StackUnwindWarningSet warnings = new StackUnwindWarningSet();
+ final UnwoundFrame<DebuggerPcodeUtils.WatchValue> frame =
+ evaluator.getStackFrame(func, warnings, monitor, true);
+
+ gatherListingVariables(func, frame, varValues, evaluator);
+ gatherDecompilerVariables(monitor, program, func, varValues, frame, evaluator);
+
+ return varValues;
+ });
+ }
+
+ private void gatherListingVariables(Function func,
+ UnwoundFrame<DebuggerPcodeUtils.WatchValue> frame,
+ List<AbstractDebuggerVariableViewerVarValue> varValues,
+ VariableValueUtils.VariableEvaluator evaluator) {
+ for (final Variable variable : func.getAllVariables()) {
+ try {
+ final DebuggerPcodeUtils.WatchValue value = frame.getValue(variable);
+ varValues.add(new DebuggerVariableViewerVarValue(variable, value.bytes().bytes(),
+ value.address(), evaluator.getRepresentation(frame, value.address(), value,
+ variable.getDataType()), this, null, value.state()));
+ }
+ catch (PcodeExecutionException e) {
+ varValues.add(
+ new DebuggerVariableViewerVarValue(variable, null, Address.NO_ADDRESS, "",
+ this, e.getMessage(), null));
+ }
+ }
+ }
+
+ private void gatherDecompilerVariables(TaskMonitor monitor, Program program, Function func,
+ List<AbstractDebuggerVariableViewerVarValue> varValues,
+ UnwoundFrame<DebuggerPcodeUtils.WatchValue> frame,
+ VariableValueUtils.VariableEvaluator evaluator) {
+ final DecompInterface decompInterface = new DecompInterface();
+ decompInterface.openProgram(program);
+ final DecompileResults res = decompInterface.decompileFunction(func, 0, monitor);
+ if (!res.decompileCompleted()) {
+ return;
+ }
+
+ final HighFunction highFunction = res.getHighFunction();
+ final Iterator<HighSymbol> symbols = highFunction.getLocalSymbolMap().getSymbols();
+ while (symbols.hasNext()) {
+ final HighSymbol sym = symbols.next();
+ try {
+ final DebuggerPcodeUtils.WatchValue value =
+ frame.getValue(program, sym.getStorage());
+ varValues.add(new DebuggerVariableViewerHighVarValue(sym, value.bytes().bytes(),
+ value.address(), evaluator.getRepresentation(frame, value.address(), value,
+ sym.getDataType()), this, null, value.state()));
+ }
+ catch (PcodeExecutionException e) {
+ varValues.add(
+ new DebuggerVariableViewerHighVarValue(sym, null, Address.NO_ADDRESS, "",
+ this, e.getMessage(), null));
+ }
+ }
+ }
+
+ @Override
+ public List<DockingActionIf> getPopupActions(Tool t, ActionContext context) {
+ if ((context != myActionContext) || (context == null)) {
+ return List.of();
+ }
+ final List<DockingActionIf> result = new ArrayList<>();
+
+ final List<AbstractDebuggerVariableViewerVarValue> selected =
+ myActionContext.getSelected();
+ final boolean multipleSelected = selected.size() > 1;
+ if (multipleSelected) {
+ return List.of();
+ }
+
+ Address address = selected.getFirst().getAddress();
+ if (address != null && !address.isRegisterAddress()) {
+ addActions(result, "View %s @ 0x%x in...".formatted(selected.getFirst().getSymbol(),
+ address.getOffset()), address);
+ }
+
+ address = currentCoordinates.getLanguage()
+ .getAddressFactory()
+ .getAddress(selected.getFirst().getValue());
+ if (address != null) {
+ addActions(result, "View *%s @ 0x%x in...".formatted(selected.getFirst().getSymbol(),
+ address.getOffset()), address);
+ }
+ return result;
+ }
+
+ private void addActions(List<DockingActionIf> result, String name, Address address) {
+ // Add action for each additional debugger listing window
+ int i = 0;
+ result.add(DebuggerVariableViewerPopupAction.builder(this, Integer.toString(i), name,
+ "Main Listing").onAction(ctx -> {
+ if (listingService == null) {
+ return;
+ }
+ final ProgramLocation loc = new ProgramLocation(currentCoordinates.getView(), address);
+ listingService.goTo(loc, true);
+ listingService.requestFocus();
+ }).build());
+
+ pluginTool.setMenuGroup(new String[] { name }, DebuggerVariableViewerPopupAction.GROUP1);
+ i++;
+ for (final DebuggerListing dl : listingService.getAllListings()) {
+ if (dl.isMainListing()) {
+ continue;
+ }
+
+ result.add(DebuggerVariableViewerPopupAction.builder(this, Integer.toString(i), name,
+ dl.getTitle()).onAction(ctx -> {
+ if (listingService == null) {
+ return;
+ }
+ final ProgramLocation loc =
+ new ProgramLocation(currentCoordinates.getView(), address);
+ dl.goTo(loc);
+ dl.requestFocus();
+ }).build());
+ i++;
+ }
+
+ result.add(DebuggerVariableViewerPopupAction.builder(this, Integer.toString(i), name,
+ "New Listing")
+ .popupMenuGroup(DebuggerVariableViewerPopupAction.GROUP2)
+ .onAction(ctx -> {
+ if (listingService == null) {
+ return;
+ }
+ final DebuggerListing dl = listingService.createNewListing();
+ dl.setCustomTitle(listingService.findNextCustomTitle());
+ dl.setTrackingSpec(NoneLocationTrackingSpec.INSTANCE);
+ dl.setFollowsCurrentThread(true);
+ final ProgramLocation loc =
+ new ProgramLocation(currentCoordinates.getView(), address);
+ dl.goTo(loc);
+ dl.requestFocus();
+ })
+ .build());
+ }
+}
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerVarValue.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerVarValue.java
new file mode 100644
index 0000000000..43bad2974b
--- /dev/null
+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/variable/DebuggerVariableViewerVarValue.java
@@ -0,0 +1,78 @@
+/* ###
+ * 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.variable;
+
+import db.Transaction;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.DataType;
+import ghidra.program.model.listing.Variable;
+import ghidra.program.model.symbol.SourceType;
+import ghidra.trace.model.memory.TraceMemoryState;
+import ghidra.util.Msg;
+import ghidra.util.exception.DuplicateNameException;
+import ghidra.util.exception.InvalidInputException;
+
+public class DebuggerVariableViewerVarValue extends AbstractDebuggerVariableViewerVarValue {
+ Variable variable;
+
+ public DebuggerVariableViewerVarValue(Variable variable, byte[] value, Address address,
+ String repr, DebuggerVariableViewerProvider provider, String error,
+ TraceMemoryState state) {
+ super(value, address, repr, provider, error, state);
+ this.variable = variable;
+ }
+
+ @Override
+ public DataType getDataType() {
+ return variable.getDataType();
+ }
+
+ @Override
+ public void setDataType(DataType dataType) {
+ try (Transaction ignored = variable.getProgram().openTransaction("Set DataType")) {
+ variable.setDataType(dataType, SourceType.USER_DEFINED);
+ }
+ catch (final InvalidInputException e) {
+ Msg.showError(this, null, "Invalid Input", e.getMessage());
+ }
+ }
+
+ @Override
+ public String getSource() {
+ return "Listing";
+ }
+
+ @Override
+ public String getSymbol() {
+ if (variable.getSymbol() == null) {
+ return variable.getName();
+ }
+ return variable.getSymbol().getName();
+ }
+
+ @Override
+ public void setSymbol(String symbol) {
+ try (Transaction tx = variable.getProgram().openTransaction("Rename Symbol")) {
+ variable.setName(symbol, SourceType.USER_DEFINED);
+ }
+ catch (final DuplicateNameException e) {
+ Msg.showError(this, null, "Duplicate Name", e.getMessage());
+ }
+ catch (final InvalidInputException e) {
+ Msg.showError(this, null, "Invalid Input", e.getMessage());
+ }
+ }
+}