Ghidra is a software reverse engineering (SRE) framework
GP-5548: Factor listing synchronization into plugin.
Dan31f447e8c790
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerOpenProgramActionContext.java b/Ghidra/Debug/Debugger-api/src/main/java/ghidra/debug/api/modules/DebuggerOpenProgramActionContext.javasimilarity index 95%rename from Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerOpenProgramActionContext.javarename to Ghidra/Debug/Debugger-api/src/main/java/ghidra/debug/api/modules/DebuggerOpenProgramActionContext.javaindex 3583cfb8a6..183cfc3e04 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerOpenProgramActionContext.java+++ b/Ghidra/Debug/Debugger-api/src/main/java/ghidra/debug/api/modules/DebuggerOpenProgramActionContext.java@@ -4,16 +4,16 @@* 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.listing;+package ghidra.debug.api.modules;import java.util.Objects;diff --git a/Ghidra/Debug/Debugger/certification.manifest b/Ghidra/Debug/Debugger/certification.manifestindex b87686864a..96169f2e80 100644--- a/Ghidra/Debug/Debugger/certification.manifest+++ b/Ghidra/Debug/Debugger/certification.manifest@@ -65,6 +65,7 @@ src/main/help/help/topics/DebuggerTraceViewDiffPlugin/images/DebuggerTimeSelectisrc/main/help/help/topics/DebuggerTraceViewDiffPlugin/images/DebuggerTraceViewDiffPlugin.png||GHIDRA||||END|src/main/help/help/topics/DebuggerWatchesPlugin/DebuggerWatchesPlugin.html||GHIDRA||||END|src/main/help/help/topics/DebuggerWatchesPlugin/images/DebuggerWatchesPlugin.png||GHIDRA||||END|+src/main/help/help/topics/DynamicStaticSynchronizationPlugin/DynamicStaticSynchronizationPlugin.html||GHIDRA||||END|src/main/help/help/topics/VariableValueHoverPlugin/VariableValueHoverPlugin.html||GHIDRA||||END|src/main/help/help/topics/VariableValueHoverPlugin/images/VariableValueHoverPluginBrowser.png||GHIDRA||||END|src/main/help/help/topics/VariableValueHoverPlugin/images/VariableValueHoverPluginDecompiler.png||GHIDRA||||END|diff --git a/Ghidra/Debug/Debugger/src/main/help/help/TOC_Source.xml b/Ghidra/Debug/Debugger/src/main/help/help/TOC_Source.xmlindex d4f279d256..3b751e1cf5 100644--- a/Ghidra/Debug/Debugger/src/main/help/help/TOC_Source.xml+++ b/Ghidra/Debug/Debugger/src/main/help/help/TOC_Source.xml@@ -15,24 +15,24 @@</tocdef><tocdef id="DebuggerTroubleshooting" text="Troubleshooting"- sortgroup="b"- target="help/topics/Debugger/Troubleshooting.html" />+ sortgroup="b"+ target="help/topics/Debugger/Troubleshooting.html" /><tocdef id="DebuggerConsolePlugin" text="Debug Console"- sortgroup="c"- target="help/topics/DebuggerConsolePlugin/DebuggerConsolePlugin.html" />+ sortgroup="c"+ target="help/topics/DebuggerConsolePlugin/DebuggerConsolePlugin.html" /><tocdef id="DebuggerCopyActionsPlugin" text="Copy Actions"- sortgroup="d"- target="help/topics/DebuggerCopyActionsPlugin/DebuggerCopyActionsPlugin.html" />+ sortgroup="d"+ target="help/topics/DebuggerCopyActionsPlugin/DebuggerCopyActionsPlugin.html" /><tocdef id="DebuggerModelPlugin" text="Model"- sortgroup="e"- target="help/topics/DebuggerModelPlugin/DebuggerModelPlugin.html" />+ sortgroup="e"+ target="help/topics/DebuggerModelPlugin/DebuggerModelPlugin.html" />- <tocdef id="DebuggerThreadsPlugin" text="Threads"- sortgroup="f"- target="help/topics/DebuggerThreadsPlugin/DebuggerThreadsPlugin.html" />+ <tocdef id="DebuggerThreadsPlugin" text="Threads"+ sortgroup="f"+ target="help/topics/DebuggerThreadsPlugin/DebuggerThreadsPlugin.html" /><tocdef id="DebuggerTraceManagerServicePlugin"text="Trace Management"@@ -40,32 +40,33 @@target="help/topics/DebuggerTraceManagerServicePlugin/DebuggerTraceManagerServicePlugin.html" /><tocdef id="DebuggerEmulationServicePlugin" text="Emulation"- sortgroup="h"- target="help/topics/DebuggerEmulationServicePlugin/DebuggerEmulationServicePlugin.html" />+ sortgroup="h"+ target="help/topics/DebuggerEmulationServicePlugin/DebuggerEmulationServicePlugin.html" />- <tocdef id="DebuggerMemoryBytesPlugin" text="Memory"- sortgroup="i"- target="help/topics/DebuggerMemoryBytesPlugin/DebuggerMemoryBytesPlugin.html" />+ <tocdef id="DebuggerMemoryBytesPlugin" text="Memory"+ sortgroup="i"+ target="help/topics/DebuggerMemoryBytesPlugin/DebuggerMemoryBytesPlugin.html" />- <tocdef id="DebuggerRegistersPlugin" text="Registers"- sortgroup="j"- target="help/topics/DebuggerRegistersPlugin/DebuggerRegistersPlugin.html" />+ <tocdef id="DebuggerRegistersPlugin" text="Registers"+ sortgroup="j"+ target="help/topics/DebuggerRegistersPlugin/DebuggerRegistersPlugin.html" />- <tocdef id="DebuggerListingPlugin" text="Dynamic Listing"- sortgroup="k"- target="help/topics/DebuggerListingPlugin/DebuggerListingPlugin.html" />+ <tocdef id="DebuggerListingPlugin" text="Dynamic Listing"+ sortgroup="k"+ target="help/topics/DebuggerListingPlugin/DebuggerListingPlugin.html" />- <tocdef id="DebuggerDisassemblerPlugin" text="Disassembly and Assembly"- sortgroup="l"- target="help/topics/DebuggerDisassemblerPlugin/DebuggerDisassemblerPlugin.html" />+ <tocdef id="DebuggerDisassemblerPlugin"+ text="Disassembly and Assembly"+ sortgroup="l"+ target="help/topics/DebuggerDisassemblerPlugin/DebuggerDisassemblerPlugin.html" /><tocdef id="DebuggerStackPlugin" text="Stack"sortgroup="m"target="help/topics/DebuggerStackPlugin/DebuggerStackPlugin.html" />- <tocdef id="DebuggerBreakpointsPlugin" text="Breakpoints"- sortgroup="n"- target="help/topics/DebuggerBreakpointsPlugin/DebuggerBreakpointsPlugin.html" >+ <tocdef id="DebuggerBreakpointsPlugin" text="Breakpoints"+ sortgroup="n"+ target="help/topics/DebuggerBreakpointsPlugin/DebuggerBreakpointsPlugin.html"><tocdef id="DebuggerBreakpointMarkerPlugin"text="In the Listings"@@ -73,54 +74,58 @@target="help/topics/DebuggerBreakpointMarkerPlugin/DebuggerBreakpointMarkerPlugin.html" /></tocdef>- <tocdef id="DebuggerRegionsPlugin" text="Memory Regions"- sortgroup="o"- target="help/topics/DebuggerRegionsPlugin/DebuggerRegionsPlugin.html" />+ <tocdef id="DebuggerRegionsPlugin" text="Memory Regions"+ sortgroup="o"+ target="help/topics/DebuggerRegionsPlugin/DebuggerRegionsPlugin.html" />- <tocdef id="DebuggerTimePlugin" text="Time"- sortgroup="p"- target="help/topics/DebuggerTimePlugin/DebuggerTimePlugin.html" />+ <tocdef id="DebuggerTimePlugin" text="Time"+ sortgroup="p"+ target="help/topics/DebuggerTimePlugin/DebuggerTimePlugin.html" />- <tocdef id="DebuggerModulesPlugin" text="Modules and Sections"- sortgroup="q"- target="help/topics/DebuggerModulesPlugin/DebuggerModulesPlugin.html" >+ <tocdef id="DebuggerModulesPlugin" text="Modules and Sections"+ sortgroup="q"+ target="help/topics/DebuggerModulesPlugin/DebuggerModulesPlugin.html"><tocdef id="DebuggerStaticMappingPlugin" text="Static Mappings"sortgroup="a"target="help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html" />++ <tocdef id="DynamicStaticSynchronizationPlugin" text="Static Synchronization"+ sortgroup="b"+ target="help/topics/DynamicStaticSynchronizationPlugin/DynamicStaticSynchronizationPlugin.html" /></tocdef><tocdef id="DebuggerWatchesPlugin" text="Watches"- sortgroup="r"- target="help/topics/DebuggerWatchesPlugin/DebuggerWatchesPlugin.html" />+ sortgroup="r"+ target="help/topics/DebuggerWatchesPlugin/DebuggerWatchesPlugin.html" /><tocdef id="VariableValueHoverPlugin" text="Variable Hovers"- sortgroup="s"- target="help/topics/VariableValueHoverPlugin/VariableValueHoverPlugin.html" />+ sortgroup="s"+ target="help/topics/VariableValueHoverPlugin/VariableValueHoverPlugin.html" /><tocdef id="DebuggerControlPlugin" text="Control and Machine State"- sortgroup="t"- target="help/topics/DebuggerControlPlugin/DebuggerControlPlugin.html" />+ sortgroup="t"+ target="help/topics/DebuggerControlPlugin/DebuggerControlPlugin.html" /><tocdef id="DebuggerMemviewPlugin" text="Memview Plot"- sortgroup="u"- target="help/topics/DebuggerMemviewPlugin/DebuggerMemviewPlugin.html" />+ sortgroup="u"+ target="help/topics/DebuggerMemviewPlugin/DebuggerMemviewPlugin.html" /><tocdef id="DebuggerTimeOverviewPlugin" text="Time Overview Sidebar"- sortgroup="v"- target="help/topics/DebuggerTimeOverviewPlugin/DebuggerTimeOverviewPlugin.html" />+ sortgroup="v"+ target="help/topics/DebuggerTimeOverviewPlugin/DebuggerTimeOverviewPlugin.html" /><tocdef id="DebuggerPcodeStepperPlugin" text="P-code Stepper"- sortgroup="w"- target="help/topics/DebuggerPcodeStepperPlugin/DebuggerPcodeStepperPlugin.html" />+ sortgroup="w"+ target="help/topics/DebuggerPcodeStepperPlugin/DebuggerPcodeStepperPlugin.html" /><tocdef id="DebuggerTraceDiffPlugin" text="Comparing Times"- sortgroup="x"- target="help/topics/DebuggerTraceViewDiffPlugin/DebuggerTraceViewDiffPlugin.html" />-+ sortgroup="x"+ target="help/topics/DebuggerTraceViewDiffPlugin/DebuggerTraceViewDiffPlugin.html" />+<tocdef id="DebuggerPlatformPlugin" text="Platform Selection"- sortgroup="y"- target="help/topics/DebuggerPlatformPlugin/DebuggerPlatformPlugin.html" />+ sortgroup="y"+ target="help/topics/DebuggerPlatformPlugin/DebuggerPlatformPlugin.html" /></tocdef></tocref></tocroot>diff --git a/Ghidra/Debug/Debugger/src/main/help/help/topics/DebuggerListingPlugin/DebuggerListingPlugin.html b/Ghidra/Debug/Debugger/src/main/help/help/topics/DebuggerListingPlugin/DebuggerListingPlugin.htmlindex a5509bfc6f..be738abb7d 100644--- a/Ghidra/Debug/Debugger/src/main/help/help/topics/DebuggerListingPlugin/DebuggerListingPlugin.html+++ b/Ghidra/Debug/Debugger/src/main/help/help/topics/DebuggerListingPlugin/DebuggerListingPlugin.html@@ -191,60 +191,6 @@manually using the <A href="help/topics/DisassemblerPlugin/Disassembly.htm#Disassemble">Disassemble</A> command.</P>- <H3><A name="auto_sync_cursor_static"></A>Auto-Sync Cursor with Static Listing</H3>-- <P>This action is always available, but only on the primary dynamic listing. It configures- location synchronization with the (primary) static listing. When enabled, navigation in either- listing — including automatic navigation — automatically navigates to the- corresponding location, if applicable, in the other. In general, "corresponding location" is- computed using information about loaded modules reported by the debugger. For the finer- details, see the <A href=- "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>- window. When you navigate to a location contained by a module, but there is no corresponding- static location, the listing logs a "missing module" to the console, offering either to import- the module or map it to an existing program. If the cursor cannot be mapped, the other- listing's location is left unchanged. If this does not seem correct. Check your module list and- static mappings.</P>-- <H3><A name="auto_sync_selection_static"></A>Auto-Sync Selection with Static Listing</H3>-- <P>This action is always available, but only on the primary dynamic listing. It configures- selection synchronization with the (primary) static listing. When enabled, selection in either- listing automatically selects the corresponding ranges, if applicable, in the other. In- general, "corresponding ranges" are computed using information about loaded modules reported by- the debugger. For the finer details, see the <A href=- "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>- window. Portions of the selection which cannot be mapped are omitted.</P>-- <H3><A name="sync_selection_into_static"></A>Sync Selection Here into Static Listing</H3>-- <P>This action is available whenever the current context is dynamic and has a selection. It- maps the current dynamic selection to corresponding static ranges and selects those in the- static listing. In general, "corresponding ranges" are computed using information about loaded- modules reported by the debugger. For the finer details, see the <A href=- "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>- window. Portions of the selection which cannot be mapped are omitted. If no part of the- selection is mappable, an error is displayed in the status bar. This can happen if the module- list is missing, or Ghidra could not find the program for the current module.</P>-- <H3><A name="sync_selection_from_static"></A>Sync Selection Here from Static Listing</H3>-- <P>This action is available whenever the current context is static and has a selection. It maps- the current static selection to corresponding dynamic ranges and selects those in the dynamic- listing. In general, "corresponding ranges" are computed using information about loaded modules- reported by the debugger. For the finer details, see the <A href=- "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>- window. Portions of the selection which cannot be mapped are omitted. If no part of the- selection is mappable, an error is displayed in the status bar. This can happen if the module- list is missing, or Ghidra could not find the program for the current module.</P>-- <H3><A name="open_program"></A>Open Program</H3>-- <P>This action is offered as a resolution whenever a module cannot be automatically opened.- This typically happens when the module's program database has crash data that can be recovered- and/or needs a version upgrade. It will attempt to open the program, allowing Ghidra to prompt- you about the situation.</P>-<H3><A name="read_memory"></A>Read Memory</H3><P>This action is available when the current trace is "at the present" with a live target. Itdiff --git a/Ghidra/Debug/Debugger/src/main/help/help/topics/DynamicStaticSynchronizationPlugin/DynamicStaticSynchronizationPlugin.html b/Ghidra/Debug/Debugger/src/main/help/help/topics/DynamicStaticSynchronizationPlugin/DynamicStaticSynchronizationPlugin.htmlnew file mode 100644index 0000000000..13532ce35a--- /dev/null+++ b/Ghidra/Debug/Debugger/src/main/help/help/topics/DynamicStaticSynchronizationPlugin/DynamicStaticSynchronizationPlugin.html@@ -0,0 +1,77 @@+<!DOCTYPE doctype PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">++<HTML>+ <HEAD>+ <META name="generator" content=+ "HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net">++ <TITLE>Debugger: Static Synchronization</TITLE>+ <META http-equiv="Content-Type" content="text/html; charset=windows-1252">+ <LINK rel="stylesheet" type="text/css" href="help/shared/DefaultStyle.css">+ </HEAD>++ <BODY lang="EN-US">+ <H1><A name="plugin"></A>Debugger: Static Synchronization</H1>++ <P>This plugin ensures the static and dynamic listings, byte viewers, etc., all remain+ synchronized.</P>++ <H2>Actions</H2>++ <P>The plugin places a few actions in the <B>Debugger → Synchronization</B> menu to toggle+ synchronization, and to transfer locations and selections on demand.</P>++ <H3><A name="sync_locations"></A>Synchronize Static and Dynamic Locations</H3>++ <P>This action is always available. When selected, navigation in either listing —+ including automatic navigation — automatically navigates to the corresponding location,+ if applicable, in the other. In general, "corresponding location" is computed using information+ about loaded modules reported by the debugger. For the finer details, see the <A href=+ "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>+ window. When you navigate to a location contained by a module, but there is no corresponding+ static location, a "missing module" appears in the console, offering either to import the+ module or map it to an existing program. If the cursor cannot be mapped, the other listing's+ location is left unchanged. If this does not seem correct. Check your module list and static+ mappings.</P>++ <H3><A name="sync_selections"></A>Synchronize Static and Dynamic Selections</H3>++ <P>This action is always available. When selected, selection in either listing automatically+ selects the corresponding ranges, if applicable, in the other. In general, "corresponding+ ranges" are computed using information about loaded modules reported by the debugger. For the+ finer details, see the <A href=+ "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>+ window. Portions of the selection which cannot be mapped are omitted.</P>++ <H3><A name="transfer_selection_dynamic_to_static">Transfer Dynamic Selection to+ Static</A></H3>++ <P>This action is available when the dynamic listing has a selection. It maps the current+ dynamic selection to corresponding static ranges and selects those in the static listing. In+ general, "corresponding ranges" are computed using information about loaded modules reported by+ the debugger. For the finer details, see the <A href=+ "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>+ window. Portions of the selection which cannot be mapped are omitted. If no part of the+ selection is mappable, an error is displayed in the status bar. This can happen if the module+ list is missing, or Ghidra could not find the program for the current module.</P>++ <H3><A name="transfer_selection_static_to_dynamic">Transfer Static Selection to+ Dynamic</A></H3>++ <P>This action is available when the static listing has a selection. It maps the current static+ selection to corresponding dynamic ranges and selects those in the dynamic listing. In general,+ "corresponding ranges" are computed using information about loaded modules reported by the+ debugger. For the finer details, see the <A href=+ "help/topics/DebuggerStaticMappingPlugin/DebuggerStaticMappingPlugin.html">Static Mappings</A>+ window. Portions of the selection which cannot be mapped are omitted. If no part of the+ selection is mappable, an error is displayed in the status bar. This can happen if the module+ list is missing, or Ghidra could not find the program for the current module.</P>++ <H3><A name="open_program"></A>Open Program</H3>++ <P>This action is offered as a resolution whenever a module cannot be automatically opened.+ This typically happens when the module's program database has crash data that can be recovered+ and/or needs a version upgrade. It will attempt to open the program, allowing Ghidra to prompt+ you about the situation.</P>+ </BODY>+</HTML>diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/DebuggerResources.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/DebuggerResources.javaindex c13c786297..1755ee9c86 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/DebuggerResources.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/DebuggerResources.java@@ -724,65 +724,6 @@ public interface DebuggerResources {}}- interface AutoSyncCursorWithStaticListingAction {- String NAME = "Auto-Sync Cursor with Static Listing";- String DESCRIPTION = "Automatically synchronize the static and dynamic listings' cursors";- String HELP_ANCHOR = "auto_sync_cursor_static";-- static ToggleActionBuilder builder(Plugin owner) {- String ownerName = owner.getName();- return new ToggleActionBuilder(NAME, ownerName)- .description(DESCRIPTION)- .menuPath(NAME)- .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));- }- }-- interface AutoSyncSelectionWithStaticListingAction {- String NAME = "Auto-Sync Selection with Static Listing";- String DESCRIPTION =- "Automatically synchronize the static and dynamic listings' selections";- String HELP_ANCHOR = "auto_sync_selection_static";-- static ToggleActionBuilder builder(Plugin owner) {- String ownerName = owner.getName();- return new ToggleActionBuilder(NAME, ownerName)- .description(DESCRIPTION)- .menuPath(NAME)- .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));- }- }-- interface SyncSelectionIntoStaticListingAction {- String NAME = "Sync Selection into Static Listing";- String DESCRIPTION =- "Change the static listing's selection to synchronize with this component's selection";- String HELP_ANCHOR = "sync_selection_into_static";-- static ActionBuilder builder(Plugin owner) {- String ownerName = owner.getName();- return new ActionBuilder(NAME, ownerName)- .description(DESCRIPTION)- .menuPath(NAME)- .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));- }- }-- interface SyncSelectionFromStaticListingAction {- String NAME = "Sync Selection from Static Listing";- String DESCRIPTION =- "Change this component's selection to synchronize with the static listing's selection";- String HELP_ANCHOR = "sync_selection_from_static";-- static ActionBuilder builder(Plugin owner) {- String ownerName = owner.getName();- return new ActionBuilder(NAME, ownerName)- .description(DESCRIPTION)- .menuPath(NAME)- .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));- }- }-interface FollowsCurrentThreadAction {String NAME = "Follows Selected Thread";String DESCRIPTION = "Register tracking follows selected thread (and contents" +@@ -1038,21 +979,6 @@ public interface DebuggerResources {}}- interface OpenProgramAction {- String NAME = "Open Program";- Icon ICON = ICON_PROGRAM;- String DESCRIPTION = "Open the program";- String HELP_ANCHOR = "open_program";-- static ActionBuilder builder(Plugin owner) {- String ownerName = owner.getName();- return new ActionBuilder(NAME, ownerName)- .description(DESCRIPTION)- .toolBarIcon(ICON)- .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));- }- }-abstract class AbstractSetBreakpointAction extends DockingAction {public static final String NAME = "Set Breakpoint";public static final Icon ICON = ICON_SET_BREAKPOINT;diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/action/DebuggerStaticSyncTrait.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/action/DebuggerStaticSyncTrait.javadeleted file mode 100644index af52f25d48..0000000000--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/action/DebuggerStaticSyncTrait.java+++ /dev/null@@ -1,401 +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.gui.action;--import java.lang.invoke.MethodHandles;-import java.util.Collection;-import java.util.Set;--import docking.ActionContext;-import docking.ComponentProvider;-import docking.action.DockingAction;-import docking.action.ToggleDockingAction;-import docking.widgets.EventTrigger;-import ghidra.app.context.ProgramLocationActionContext;-import ghidra.app.plugin.core.debug.gui.DebuggerResources.*;-import ghidra.app.services.DebuggerStaticMappingService;-import ghidra.app.services.DebuggerStaticMappingService.MappedAddressRange;-import ghidra.debug.api.modules.DebuggerStaticMappingChangeListener;-import ghidra.debug.api.tracemgr.DebuggerCoordinates;-import ghidra.framework.options.SaveState;-import ghidra.framework.plugintool.*;-import ghidra.framework.plugintool.annotation.AutoConfigStateField;-import ghidra.framework.plugintool.annotation.AutoServiceConsumed;-import ghidra.program.model.address.AddressCollectors;-import ghidra.program.model.address.AddressSet;-import ghidra.program.model.listing.Program;-import ghidra.program.util.ProgramLocation;-import ghidra.program.util.ProgramSelection;-import ghidra.trace.model.Trace;-import ghidra.trace.model.program.TraceProgramView;-import ghidra.util.Msg;-import ghidra.util.Swing;--public class DebuggerStaticSyncTrait {- protected static final AutoConfigState.ClassHandler<DebuggerStaticSyncTrait> CONFIG_STATE_HANDLER =- AutoConfigState.wireHandler(DebuggerStaticSyncTrait.class, MethodHandles.lookup());-- private static boolean dynamicHasSelection(ProgramLocationActionContext ctx) {- if (ctx == null) {- return false;- }- ProgramSelection sel = ctx.getSelection();- if (sel == null || sel.isEmpty()) {- return false;- }- return true;- }-- protected class ForStaticSyncMappingChangeListener- implements DebuggerStaticMappingChangeListener {- @Override- public void mappingsChanged(Set<Trace> affectedTraces, Set<Program> affectedPrograms) {- Swing.runIfSwingOrRunLater(() -> {- if (current.getView() == null) {- return;- }- if (!affectedTraces.contains(current.getTrace())) {- return;- }- doAutoSyncCursorIntoStatic(currentDynamicLocation);- // TODO: Remember last sync direction, or just always take dyn->static- doAutoSyncSelectionIntoStatic(current.getView(), currentDynamicSelection);- });-- /**- * TODO: Remove "missing" entry in modules dialog, if present? There's some nuance here,- * because the trace presenting the mapping may not be the same as the trace that missed- * the module originally. I'm tempted to just leave it and let the user remove it.- */- }- }-- protected ToggleDockingAction actionAutoSyncCursorWithStaticListing;- protected ToggleDockingAction actionAutoSyncSelectionWithStaticListing;- protected DockingAction actionSyncSelectionIntoStaticListing;- protected DockingAction actionSyncSelectionFromStaticListing;-- @AutoConfigStateField- private boolean autoSyncCursorWithStaticListing;- @AutoConfigStateField- private boolean autoSyncSelectionWithStaticListing;-- private final PluginTool tool;- private final Plugin plugin;- private final ComponentProvider provider;- private final boolean isAutoSyncAllowed;-- //@AutoServiceConsumed via method- private DebuggerStaticMappingService mappingService;- @SuppressWarnings("unused")- private final AutoService.Wiring autoServiceWiring;-- private DebuggerCoordinates current = DebuggerCoordinates.NOWHERE;- private ProgramLocation currentDynamicLocation;- private ProgramSelection currentDynamicSelection;-- private Program currentStaticProgram;- private ProgramLocation currentStaticLocation;- private ProgramSelection currentStaticSelection;-- protected final ForStaticSyncMappingChangeListener mappingChangeListener =- new ForStaticSyncMappingChangeListener();-- public DebuggerStaticSyncTrait(PluginTool tool, Plugin plugin, ComponentProvider provider,- boolean isAutoSyncAllowed) {- this.tool = tool;- this.plugin = plugin;- this.provider = provider;- this.isAutoSyncAllowed = isAutoSyncAllowed;-- this.autoServiceWiring = AutoService.wireServicesConsumed(plugin, this);-- this.autoSyncCursorWithStaticListing = isAutoSyncAllowed;- this.autoSyncSelectionWithStaticListing = isAutoSyncAllowed;- }-- @AutoServiceConsumed- private void setMappingService(DebuggerStaticMappingService mappingService) {- if (this.mappingService != null) {- this.mappingService.removeChangeListener(mappingChangeListener);- }- this.mappingService = mappingService;- if (this.mappingService != null) {- this.mappingService.addChangeListener(mappingChangeListener);- doAutoSyncCursorIntoStatic(currentDynamicLocation);- }- }-- public ToggleDockingAction installAutoSyncCursorWithStaticListingAction() {- return actionAutoSyncCursorWithStaticListing = AutoSyncCursorWithStaticListingAction- .builder(plugin)- .enabled(true)- .selected(true)- .onAction(ctx -> doSetAutoSyncCursorWithStaticListing(- actionAutoSyncCursorWithStaticListing.isSelected()))- .buildAndInstallLocal(provider);- }-- public ToggleDockingAction installAutoSyncSelectionWithStaticListingAction() {- return actionAutoSyncSelectionWithStaticListing = AutoSyncSelectionWithStaticListingAction- .builder(plugin)- .enabled(true)- .selected(true)- .onAction(ctx -> doSetAutoSyncSelectionWithStaticListing(- actionAutoSyncSelectionWithStaticListing.isSelected()))- .buildAndInstallLocal(provider);- }-- public DockingAction installSyncSelectionIntoStaticListingAction() {- return actionSyncSelectionIntoStaticListing = SyncSelectionIntoStaticListingAction- .builder(plugin)- .withContext(ProgramLocationActionContext.class)- .enabledWhen(ctx -> dynamicHasSelection(ctx))- .onAction(this::activatedSyncSelectionIntoStatic)- .buildAndInstallLocal(provider);- }-- public DockingAction installSyncSelectionFromStaticListingAction() {- return actionSyncSelectionFromStaticListing = SyncSelectionFromStaticListingAction- .builder(plugin)- .withContext(ProgramLocationActionContext.class)- .enabledWhen(ctx -> staticHasSelection(ctx))- .onAction(this::activatedSyncSelectionFromStatic)- .buildAndInstallLocal(provider);- }-- private boolean staticHasSelection(ActionContext ctx) {- return currentStaticSelection != null && !currentStaticSelection.isEmpty();- }-- protected void activatedSyncSelectionIntoStatic(ProgramLocationActionContext ctx) {- ProgramSelection result = doSyncSelectionIntoStatic(ctx.getProgram(), ctx.getSelection());- if (result != null && result.isEmpty()) {- displayMapError("the dynamic view", "the static listing");- }- }-- protected void activatedSyncSelectionFromStatic(ActionContext ctx) {- ProgramSelection result = doSyncSelectionFromStatic();- if (result != null && result.isEmpty()) {- displayMapError("the static listing", "the dynamic view");- }- }-- protected void doSyncCursorIntoStatic(ProgramLocation location) {- if (location == null || mappingService == null) {- return;- }- ProgramLocation staticLoc = mappingService.getStaticLocationFromDynamic(location);- if (staticLoc == null) {- return;- }- staticGoTo(staticLoc);- }-- protected void doSyncCursorFromStatic() {- TraceProgramView view = current.getView(); // NB. Used for snap (don't want emuSnap)- if (currentStaticLocation == null || view == null || mappingService == null) {- return;- }- ProgramLocation dynamicLoc =- mappingService.getDynamicLocationFromStatic(view, currentStaticLocation);- if (dynamicLoc == null) {- return;- }- dynamicGoTo(dynamicLoc);- }-- public void doAutoSyncCursorIntoStatic(ProgramLocation location) {- if (!isAutoSyncCursorWithStaticListing()) {- return;- }- doSyncCursorIntoStatic(location);- }-- public void doAutoSyncCursorFromStatic() {- if (!isAutoSyncCursorWithStaticListing()) {- return;- }- doSyncCursorFromStatic();- }-- protected void doSetAutoSyncCursorWithStaticListing(boolean sync) {- this.autoSyncCursorWithStaticListing = sync;- provider.contextChanged();- doAutoSyncCursorIntoStatic(currentDynamicLocation);- }-- protected void doSetAutoSyncSelectionWithStaticListing(boolean sync) {- this.autoSyncSelectionWithStaticListing = sync;- provider.contextChanged();- doAutoSyncSelectionIntoStatic(current.getView(), currentDynamicSelection);- }-- protected ProgramSelection doSyncSelectionIntoStatic(Program program, ProgramSelection sel) {- if (program == null || sel == null || currentStaticProgram == null ||- mappingService == null) {- return null;- }- TraceProgramView view = (TraceProgramView) program;- Collection<MappedAddressRange> ranges =- mappingService.getOpenMappedViews(view.getTrace(), sel, view.getSnap())- .get(currentStaticProgram);- AddressSet mapped;- if (ranges == null) {- mapped = new AddressSet();- }- else {- mapped = ranges.stream()- .map(r -> r.getDestinationAddressRange())- .collect(AddressCollectors.toAddressSet());- }- ProgramSelection result = new ProgramSelection(mapped);- staticSelect(currentStaticProgram, result);- return result;- }-- protected ProgramSelection doSyncSelectionFromStatic() {- TraceProgramView view = current.getView();- if (view == null || currentStaticProgram == null || currentStaticSelection == null ||- mappingService == null) {- return null;- }- AddressSet mapped =- mappingService.getOpenMappedViews(currentStaticProgram, currentStaticSelection)- .entrySet()- .stream()- .filter(e -> e.getKey().getTrace() == current.getTrace())- .filter(e -> e.getKey().getSpan().contains(current.getSnap()))- .flatMap(e -> e.getValue().stream())- .map(r -> r.getDestinationAddressRange())- .collect(AddressCollectors.toAddressSet());- ProgramSelection result = new ProgramSelection(mapped);- dynamicSelect(view, result);- return result;- }-- protected void doAutoSyncSelectionIntoStatic(Program program, ProgramSelection selection) {- if (isAutoSyncSelectionWithStaticListing()) {- doSyncSelectionIntoStatic(program, selection);- }- }-- protected void doAutoSyncSelectionFromStatic() {- if (isAutoSyncSelectionWithStaticListing()) {- doSyncSelectionFromStatic();- }- }-- protected void displayMapError(String from, String to) {- tool.setStatusInfo("No selected addresses in " + from + " are mappable to " + to +- ". Check your module list and static mappings.", true);- }-- public void goToCoordinates(DebuggerCoordinates coordinates) {- this.current = coordinates;- }-- public void dynamicProgramLocationChanged(ProgramLocation location, EventTrigger trigger) {- currentDynamicLocation = location;- if (trigger != EventTrigger.GUI_ACTION) {- return;- }- doAutoSyncCursorIntoStatic(location);- }-- public void dynamicSelectionChanged(Program program, ProgramSelection selection,- EventTrigger trigger) {- currentDynamicSelection = selection;- provider.contextChanged();- if (trigger != EventTrigger.GUI_ACTION) {- return;- }- doAutoSyncSelectionIntoStatic(program, selection);- }-- public void staticProgramActivated(Program program) {- currentStaticProgram = program;- }-- public void staticProgramLocationChanged(ProgramLocation location) {- currentStaticLocation = location;- doAutoSyncCursorFromStatic();- }-- public void staticProgramSelectionChanged(Program program, ProgramSelection selection) {- if (program != currentStaticProgram) {- Msg.warn(this, "Got selection change for not the current static program");- return;- }- currentStaticProgram = program;- currentStaticSelection = selection;- provider.contextChanged();- doAutoSyncSelectionFromStatic();- }-- public void setAutoSyncCursorWithStaticListing(boolean sync) {- actionAutoSyncCursorWithStaticListing.setSelected(sync);- doSetAutoSyncCursorWithStaticListing(sync);- }-- public boolean isAutoSyncCursorWithStaticListing() {- return autoSyncCursorWithStaticListing;- }-- public void setAutoSyncSelectionWithStaticListing(boolean sync) {- actionAutoSyncSelectionWithStaticListing.setSelected(sync);- doSetAutoSyncSelectionWithStaticListing(sync);- }-- public boolean isAutoSyncSelectionWithStaticListing() {- return autoSyncSelectionWithStaticListing;- }-- public void readConfigState(SaveState saveState) {- CONFIG_STATE_HANDLER.readConfigState(this, saveState);-- if (isAutoSyncAllowed) {- if (actionAutoSyncCursorWithStaticListing != null) {- actionAutoSyncCursorWithStaticListing.setSelected(autoSyncCursorWithStaticListing);- }- if (actionAutoSyncSelectionWithStaticListing != null) {- actionAutoSyncSelectionWithStaticListing- .setSelected(autoSyncSelectionWithStaticListing);- }- }- else {- autoSyncCursorWithStaticListing = false;- autoSyncSelectionWithStaticListing = false;- }- }-- protected void staticGoTo(ProgramLocation location) {- // listener method- }-- protected void staticSelect(Program program, ProgramSelection selection) {- // listener method- }-- protected void dynamicGoTo(ProgramLocation location) {- // listener method- }-- protected void dynamicSelect(Program program, ProgramSelection selection) {- // listener method- }-}diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsolePlugin.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsolePlugin.javaindex cc219d9900..bd59b6a8d8 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsolePlugin.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsolePlugin.java@@ -166,4 +166,11 @@ public class DebuggerConsolePlugin extends Plugin implements DebuggerConsoleServpublic LogRow<?> getLogRow(ActionContext ctx) {return provider.getLogRow(ctx);}++ /**+ * Clear the console+ */+ public void clear() {+ provider.clear();+ }}diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsoleProvider.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsoleProvider.javaindex ee68fd9c60..a174b75f85 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsoleProvider.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/console/DebuggerConsoleProvider.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.@@ -400,9 +400,9 @@ public class DebuggerConsoleProvider extends ComponentProviderAdapterprivate final AutoService.Wiring autoServiceWiring;@AutoOptionDefined(- name = DebuggerResources.OPTION_NAME_LOG_BUFFER_LIMIT,- description = "The maximum number of entries in the console log (0 or less for unlimited)",- help = @HelpInfo(anchor = "buffer_limit"))+ name = DebuggerResources.OPTION_NAME_LOG_BUFFER_LIMIT,+ description = "The maximum number of entries in the console log (0 or less for unlimited)",+ help = @HelpInfo(anchor = "buffer_limit"))private int logBufferLimit = DebuggerResources.DEFAULT_LOG_BUFFER_LIMIT;@SuppressWarnings("unused")private final AutoOptions.Wiring autoOptionsWiring;@@ -517,13 +517,17 @@ public class DebuggerConsoleProvider extends ComponentProviderAdapter.buildAndInstallLocal(this);}- private void activatedClear(ActionContext ctx) {+ public void clear() {synchronized (buffer) {logTableModel.deleteItemsWith(r -> !(r instanceof MonitorLogRow));buffer.removeIf(r -> !(r instanceof MonitorLogRow));}}+ private void activatedClear(ActionContext ctx) {+ clear();+ }+private void activatedSelectNone(ActionContext ctx) {logTable.clearSelection();}diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingPlugin.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingPlugin.javaindex 307131ffe4..66417daea8 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingPlugin.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingPlugin.java@@ -45,13 +45,9 @@ import ghidra.framework.plugintool.*;import ghidra.framework.plugintool.annotation.AutoServiceConsumed;import ghidra.framework.plugintool.util.PluginStatus;import ghidra.program.model.address.*;-import ghidra.program.model.listing.Program;import ghidra.program.util.ProgramLocation;import ghidra.program.util.ProgramSelection;import ghidra.trace.model.program.TraceProgramView;-import ghidra.util.Swing;-import utilities.util.SuppressableCallback;-import utilities.util.SuppressableCallback.Suppression;@PluginInfo(shortDescription = "View and annotate listings of trace (possibly live) memory",@@ -62,11 +58,7 @@ import utilities.util.SuppressableCallback.Suppression;packageName = DebuggerPluginPackage.NAME,status = PluginStatus.RELEASED,eventsConsumed = {- ProgramOpenedPluginEvent.class, // For auto-open log cleanupProgramClosedPluginEvent.class, // For marker set cleanup- ProgramActivatedPluginEvent.class, // To track the static program for sync- ProgramLocationPluginEvent.class, // For static listing sync- ProgramSelectionPluginEvent.class, // For static listing syncTraceActivatedPluginEvent.class, // Trace/thread activation and register trackingTraceClosedPluginEvent.class,TraceLocationPluginEvent.class,@@ -75,8 +67,6 @@ import utilities.util.SuppressableCallback.Suppression;TrackingChangedPluginEvent.class,},eventsProduced = {- ProgramLocationPluginEvent.class,- ProgramSelectionPluginEvent.class,TraceLocationPluginEvent.class,TraceSelectionPluginEvent.class,TraceHighlightPluginEvent.class,@@ -130,10 +120,6 @@ public class DebuggerListingPlugin extends AbstractCodeBrowserPlugin<DebuggerLis@SuppressWarnings("unused")private AutoService.Wiring autoServiceWiring;- private final SuppressableCallback<Void> cbProgramLocationEvents = new SuppressableCallback<>();- private final SuppressableCallback<Void> cbProgramSelectionEvents =- new SuppressableCallback<>();-private DebuggerCoordinates current = DebuggerCoordinates.NOWHERE;public DebuggerListingPlugin(PluginTool tool) {@@ -277,21 +263,7 @@ public class DebuggerListingPlugin extends AbstractCodeBrowserPlugin<DebuggerLis@Overridepublic void processEvent(PluginEvent event) {switch (event) {- case ProgramLocationPluginEvent ev -> cbProgramLocationEvents.invoke(() -> {- if (heedLocationEvent(ev)) {- connectedProvider.staticProgramLocationChanged(ev.getLocation());- }- });- case ProgramSelectionPluginEvent ev -> cbProgramSelectionEvents.invoke(() -> {- if (heedSelectionEvent(ev)) {- connectedProvider.staticProgramSelectionChanged(ev.getProgram(),- ev.getSelection());- }- });- case ProgramOpenedPluginEvent ev -> allProviders(p -> p.programOpened(ev.getProgram()));case ProgramClosedPluginEvent ev -> allProviders(p -> p.programClosed(ev.getProgram()));- case ProgramActivatedPluginEvent ev -> allProviders(- p -> p.staticProgramActivated(ev.getActiveProgram()));case TraceActivatedPluginEvent ev -> {current = ev.getActiveCoordinates();allProviders(p -> p.coordinatesActivated(current));@@ -323,24 +295,6 @@ public class DebuggerListingPlugin extends AbstractCodeBrowserPlugin<DebuggerLis}}- void fireStaticLocationEvent(ProgramLocation staticLoc) {- assert Swing.isSwingThread();- try (Suppression supp = cbProgramLocationEvents.suppress(null)) {- // Use this instead of GoToService to avoid event loopback- programManager.setCurrentProgram(staticLoc.getProgram());- tool.firePluginEvent(new ProgramLocationPluginEvent(getName(), staticLoc,- staticLoc.getProgram()));- //goToService.goTo(staticLoc);- }- }-- void fireStaticSelectionEvent(Program staticProg, ProgramSelection staticSel) {- assert Swing.isSwingThread();- try (Suppression supp = cbProgramSelectionEvents.suppress(null)) {- tool.firePluginEvent(new ProgramSelectionPluginEvent(getName(), staticSel, staticProg));- }- }-protected void allProviders(Consumer<DebuggerListingProvider> action) {action.accept(connectedProvider);for (DebuggerListingProvider provider : disconnectedProviders) {@@ -382,18 +336,6 @@ public class DebuggerListingPlugin extends AbstractCodeBrowserPlugin<DebuggerLisconnectedProvider.setSelection(selection);}- @Override- public boolean goTo(ProgramLocation location, boolean centerOnScreen) {- boolean result = super.goTo(location, centerOnScreen);- if (!result) {- return false;- }- DebuggerListingProvider provider = connectedProvider;- provider.doAutoSyncCursorIntoStatic(location);- provider.doCheckCurrentModuleMissing();- return true;- }-@Overridepublic boolean goTo(Address address, boolean centerOnScreen) {TraceProgramView view = connectedProvider.current.getView();diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProvider.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProvider.javaindex a559cd96b0..f933ae4298 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProvider.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProvider.java@@ -25,8 +25,6 @@ import java.awt.event.MouseEvent;import java.lang.invoke.MethodHandles;import java.util.*;import java.util.concurrent.CompletableFuture;-import java.util.stream.Collectors;-import java.util.stream.Stream;import javax.swing.*;import javax.swing.event.ChangeEvent;@@ -55,12 +53,10 @@ import ghidra.app.plugin.core.debug.disassemble.DebuggerDisassemblerPlugin;import ghidra.app.plugin.core.debug.event.TrackingChangedPluginEvent;import ghidra.app.plugin.core.debug.gui.*;import ghidra.app.plugin.core.debug.gui.DebuggerResources.FollowsCurrentThreadAction;-import ghidra.app.plugin.core.debug.gui.DebuggerResources.OpenProgramAction;import ghidra.app.plugin.core.debug.gui.action.*;import ghidra.app.plugin.core.debug.gui.thread.DebuggerTraceFileActionContext;import ghidra.app.plugin.core.debug.gui.trace.DebuggerTraceTabPanel;import ghidra.app.plugin.core.debug.utils.ProgramLocationUtils;-import ghidra.app.plugin.core.debug.utils.ProgramURLUtils;import ghidra.app.plugin.core.marker.MarkerMarginProvider;import ghidra.app.plugin.core.marker.MarkerOverviewProvider;import ghidra.app.services.*;@@ -74,30 +70,25 @@ import ghidra.debug.api.action.GoToInput;import ghidra.debug.api.action.LocationTrackingSpec;import ghidra.debug.api.control.ControlMode;import ghidra.debug.api.listing.MultiBlendedListingBackgroundColorModel;-import ghidra.debug.api.modules.DebuggerMissingModuleActionContext;import ghidra.debug.api.modules.DebuggerStaticMappingChangeListener;import ghidra.debug.api.tracemgr.DebuggerCoordinates;import ghidra.features.base.memsearch.bytesource.AddressableByteSource;import ghidra.features.base.memsearch.bytesource.EmptyByteSource;-import ghidra.framework.model.DomainFile;import ghidra.framework.options.SaveState;import ghidra.framework.plugintool.*;import ghidra.framework.plugintool.annotation.AutoConfigStateField;import ghidra.framework.plugintool.annotation.AutoServiceConsumed;-import ghidra.program.model.address.*;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSetView;import ghidra.program.model.listing.Instruction;import ghidra.program.model.listing.Program;import ghidra.program.util.ProgramLocation;import ghidra.program.util.ProgramSelection;import ghidra.trace.model.Trace;-import ghidra.trace.model.modules.*;import ghidra.trace.model.program.TraceProgramView;import ghidra.trace.model.time.TraceSnapshot;import ghidra.util.*;import ghidra.util.datastruct.ListenerSet;-import ghidra.util.exception.CancelledException;-import ghidra.util.exception.VersionException;-import ghidra.util.task.*;import utilities.util.SuppressableCallback;import utilities.util.SuppressableCallback.Suppression;@@ -159,54 +150,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {return;}doMarkTrackedLocation();- cleanMissingModuleMessages(affectedTraces);- });- }- }-- protected class ForListingSyncTrait extends DebuggerStaticSyncTrait {- public ForListingSyncTrait() {- super(DebuggerListingProvider.this.tool, DebuggerListingProvider.this.plugin,- DebuggerListingProvider.this, isMainListing());- }-- @Override- protected void staticGoTo(ProgramLocation location) {- Swing.runIfSwingOrRunLater(() -> plugin.fireStaticLocationEvent(location));- }-- @Override- protected void staticSelect(Program program, ProgramSelection selection) {- Swing.runIfSwingOrRunLater(() -> plugin.fireStaticSelectionEvent(program, selection));- if (selection.isEmpty()) {- return;- }- Optional<CodeViewerService> codeViewer =- Stream.of(tool.getServices(CodeViewerService.class))- .filter(cv -> cv != plugin)- .findFirst();- if (codeViewer.isEmpty()) {- return;- }- ListingPanel listingPanel = codeViewer.get().getListingPanel();- Swing.runIfSwingOrRunLater(() -> {- listingPanel.scrollTo(new ProgramLocation(program, selection.getMinAddress()));- });- }-- @Override- protected void dynamicGoTo(ProgramLocation location) {- Swing.runIfSwingOrRunLater(() -> goTo(location.getProgram(), location));- }-- @Override- protected void dynamicSelect(Program program, ProgramSelection selection) {- Swing.runIfSwingOrRunLater(() -> {- setSelection(selection);- if (!selection.isEmpty()) {- getListingPanel()- .scrollTo(new ProgramLocation(program, selection.getMinAddress()));- }});}}@@ -224,9 +167,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {@Overrideprotected boolean goToAddress(Address address) {- if (syncTrait.isAutoSyncCursorWithStaticListing()) {- syncTrait.doAutoSyncCursorIntoStatic(new ProgramLocation(getProgram(), address));- }return getListingPanel().goTo(address);}}@@ -348,7 +288,7 @@ public class DebuggerListingProvider extends CodeViewerProvider {private final DebuggerListingPlugin plugin;- //@AutoServiceConsumed via method+ @AutoServiceConsumedprivate DebuggerTraceManagerService traceManager;//@AutoServiceConsumed via methodprivate DebuggerStaticMappingService mappingService;@@ -356,10 +296,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {private DebuggerConsoleService consoleService;//@AutoServiceConsumed via methodprivate DebuggerControlService controlService;- @AutoServiceConsumed- private ProgramManager programManager;- @AutoServiceConsumed- private FileImporterService importerService;//@AutoServiceConsumed via methodprivate MarkerService markerService;@SuppressWarnings("unused")@@ -374,24 +310,17 @@ public class DebuggerListingProvider extends CodeViewerProvider {protected MarkerSet trackingMarker;protected DockingAction actionGoTo;- protected ToggleDockingAction actionAutoSyncCursorWithStaticListing;- protected ToggleDockingAction actionAutoSyncSelectionWithStaticListing;- protected DockingAction actionSyncSelectionIntoStaticListing;- protected DockingAction actionSyncSelectionFromStaticListing;protected ToggleDockingAction actionFollowsCurrentThread;protected ToggleDockingAction actionAutoDisassemble;protected MultiStateDockingAction<AutoReadMemorySpec> actionAutoReadMemory;protected DockingAction actionRefreshSelectedMemory;- protected DockingAction actionOpenProgram;protected MultiStateDockingAction<LocationTrackingSpec> actionTrackLocation;@AutoConfigStateFieldprotected boolean followsCurrentThread = true;- // TODO: followsCurrentSnap?@AutoConfigStateFieldprotected boolean autoDisassemble = true;- protected final ForListingSyncTrait syncTrait;protected final ForListingGoToTrait goToTrait;protected final ForListingTrackingTrait trackingTrait;protected final ForListingReadsMemoryTrait readsMemTrait;@@ -433,9 +362,8 @@ public class DebuggerListingProvider extends CodeViewerProvider {this.plugin = plugin;this.isMainListing = isConnected;- // TODO: An icon to distinguish dynamic from static+ // LATER: Consider an icon to distinguish dynamic from static- syncTrait = new ForListingSyncTrait();goToTrait = new ForListingGoToTrait();trackingTrait = new ForListingTrackingTrait();readsMemTrait = new ForListingReadsMemoryTrait();@@ -583,7 +511,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {}CONFIG_STATE_HANDLER.readConfigState(this, saveState);- syncTrait.readConfigState(saveState);trackingTrait.readConfigState(saveState);readsMemTrait.readConfigState(saveState);@@ -599,9 +526,10 @@ public class DebuggerListingProvider extends CodeViewerProvider {@Overridepublic void addToTool() {- //TODO: This is lame. AddToTool executes the window placement- // logic but is called by the CodeViewer constructor, so we have- // no efficient path in+ /**+ * NOTE: This isn't great. addToTool executes the window placement logic but is called by+ * the CodeViewer constructor, so we have no efficient path in+ */setIntraGroupPosition(WindowPosition.STACK);setDefaultWindowPosition(WindowPosition.STACK);super.addToTool();@@ -615,11 +543,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {}}- @AutoServiceConsumed- private void setTraceManager(DebuggerTraceManagerService traceManager) {- this.traceManager = traceManager;- }-@AutoServiceConsumedprivate void setMappingService(DebuggerStaticMappingService mappingService) {if (this.mappingService != null) {@@ -686,15 +609,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {}}- @AutoServiceConsumed- private void setConsoleService(DebuggerConsoleService consoleService) {- if (consoleService != null) {- if (actionOpenProgram != null) {- consoleService.addResolutionAction(actionOpenProgram);- }- }- }-protected void markTrackedStaticLocation(ProgramLocation location) {Swing.runIfSwingOrRunLater(() -> {if (location == null) {@@ -716,17 +630,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {});}- public void programOpened(Program program) {- if (!isMainListing()) {- return;- }- DomainFile df = program.getDomainFile();- DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);- if (consoleService != null) {- consoleService.removeFromLog(ctx);- }- }-public void programClosed(Program program) {if (program == markedProgram) {removeOldStaticTrackingMarker();@@ -735,10 +638,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {}}- public void staticProgramActivated(Program program) {- syncTrait.staticProgramActivated(program);- }-@Overrideprotected void doSetProgram(Program newProgram) {// E.g., The "Navigate Previous" could cause a change in trace@@ -833,13 +732,7 @@ public class DebuggerListingProvider extends CodeViewerProvider {}protected void createActions() {- if (isMainListing()) {- actionAutoSyncCursorWithStaticListing =- syncTrait.installAutoSyncCursorWithStaticListingAction();- actionAutoSyncSelectionWithStaticListing =- syncTrait.installAutoSyncSelectionWithStaticListingAction();- }- else {+ if (!isMainListing()) {actionFollowsCurrentThread = FollowsCurrentThreadAction.builder(plugin).enabled(true).selected(true)@@ -854,29 +747,14 @@ public class DebuggerListingProvider extends CodeViewerProvider {.onAction(ctx -> doSetAutoDisassemble(actionAutoDisassemble.isSelected())).buildAndInstallLocal(this);- actionSyncSelectionIntoStaticListing =- syncTrait.installSyncSelectionIntoStaticListingAction();- actionSyncSelectionFromStaticListing =- syncTrait.installSyncSelectionFromStaticListingAction();-actionGoTo = goToTrait.installAction();actionTrackLocation = trackingTrait.installAction();actionAutoReadMemory = readsMemTrait.installAutoReadAction();actionRefreshSelectedMemory = readsMemTrait.installRefreshSelectedAction();- actionOpenProgram = OpenProgramAction.builder(plugin)- .withContext(DebuggerOpenProgramActionContext.class)- .onAction(this::activatedOpenProgram)- .build();-contextChanged();}- private void activatedOpenProgram(DebuggerOpenProgramActionContext context) {- programManager.openProgram(context.getDomainFile(), DomainFile.DEFAULT_VERSION,- ProgramManager.OPEN_CURRENT);- }-protected boolean isEffectivelyDifferent(ProgramLocation cur, ProgramLocation dest) {if (Objects.equals(cur, dest)) {return false;@@ -969,10 +847,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {location = ProgramLocationUtils.fixLocation(location, false);}super.programLocationChanged(location, trigger);- syncTrait.dynamicProgramLocationChanged(location, trigger);- if (trigger == EventTrigger.GUI_ACTION) {- doCheckCurrentModuleMissing();- }}@Override@@ -989,174 +863,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {return locationLabel.getActionContext(this, event);}- @Override- public void programSelectionChanged(ProgramSelection selection, EventTrigger trigger) {- super.programSelectionChanged(selection, trigger);- syncTrait.dynamicSelectionChanged(getProgram(), selection, trigger);- }-- protected void doTryOpenProgram(DomainFile df, int version, int state) {- DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);- if (consoleService != null && consoleService.logContains(ctx)) {- return;- }- if (df.canRecover()) {- if (consoleService != null) {- consoleService.log(DebuggerResources.ICON_MODULES, "<html>Program <b>" +- HTMLUtilities.escapeHTML(df.getPathname()) +- "</b> has recovery data. It must be opened manually.</html>", ctx);- }- return;- }- new TaskLauncher(new Task("Open " + df, true, false, false) {- @Override- public void run(TaskMonitor monitor) throws CancelledException {- Program program = null;- try {- program = (Program) df.getDomainObject(this, false, false, monitor);- programManager.openProgram(program, state);- }- catch (VersionException e) {- if (consoleService != null) {- consoleService.log(DebuggerResources.ICON_MODULES, "<html>Program <b>" +- HTMLUtilities.escapeHTML(df.getPathname()) +- "</b> was created with a different version of Ghidra." +- " It must be opened manually.</html>", ctx);- }- return;- }- catch (Exception e) {- if (consoleService != null) {- consoleService.log(DebuggerResources.ICON_LOG_ERROR, "<html>Program <b>" +- HTMLUtilities.escapeHTML(df.getPathname()) +- "</b> could not be opened: " + e + ". Try opening it manually.</html>",- ctx);- }- return;- }- finally {- if (program != null) {- program.release(this);- }- }- }- }, tool.getToolFrame());- }-- protected void doCheckCurrentModuleMissing() {- // Is there any reason to try to open the module if we're not syncing listings?- // I don't think so.- if (!syncTrait.isAutoSyncCursorWithStaticListing()) {- return;- }- Trace trace = current.getTrace();- if (trace == null) {- return;- }- ProgramLocation loc = getLocation();- if (loc == null) { // Redundant?- return;- }- AddressSpace space = loc.getAddress().getAddressSpace();- if (space == null) {- return; // Is this NO_ADDRESS or something?- }- if (mappingService == null) {- return;- }- ProgramLocation mapped = mappingService.getStaticLocationFromDynamic(loc);- if (mapped != null) {- // No need to import what is already mapped and open- return;- }-- long snap = current.getSnap();- Address address = loc.getAddress();- TraceStaticMapping mapping = trace.getStaticMappingManager().findContaining(address, snap);- if (mapping != null) {- DomainFile df = ProgramURLUtils.getDomainFileFromOpenProject(tool.getProject(),- mapping.getStaticProgramURL());- if (df != null) {- doTryOpenProgram(df, DomainFile.DEFAULT_VERSION, ProgramManager.OPEN_CURRENT);- }- }-- Set<TraceModule> missing = new HashSet<>();- Set<DomainFile> toOpen = new HashSet<>();- TraceModuleManager modMan = trace.getModuleManager();- Collection<TraceModule> modules = Stream.concat(- modMan.getModulesAt(snap, address).stream().filter(m -> m.getSections(snap).isEmpty()),- modMan.getSectionsAt(snap, address).stream().map(s -> s.getModule()))- .collect(Collectors.toSet());-- // Attempt to open probable matches. All others, list to import- for (TraceModule mod : modules) {- DomainFile match = mappingService.findBestModuleProgram(space, mod, snap);- if (match == null) {- missing.add(mod);- }- else {- toOpen.add(match);- }- }- if (programManager != null && !toOpen.isEmpty()) {- for (DomainFile df : toOpen) {- // Do not presume a goTo is about to happen. There are no mappings, yet.- doTryOpenProgram(df, DomainFile.DEFAULT_VERSION, ProgramManager.OPEN_VISIBLE);- }- }-- if (importerService == null || consoleService == null) {- return;- }-- for (TraceModule mod : missing) {- consoleService.log(DebuggerResources.ICON_LOG_ERROR,- "<html>The module <b><tt>" + HTMLUtilities.escapeHTML(mod.getName(snap)) +- "</tt></b> was not found in the project</html>",- new DebuggerMissingModuleActionContext(mod));- }- /**- * Once the programs are opened, including those which are successfully imported, the- * automatic mapper should take effect, eventually invoking callbacks to our mapping change- * listener.- */- }-- protected boolean isMapped(AddressRange range) {- if (range == null) {- return false;- }- return mappingService.getStaticLocationFromDynamic(- new ProgramLocation(getProgram(), range.getMinAddress())) != null;- }-- protected void cleanMissingModuleMessages(Set<Trace> affectedTraces) {- if (consoleService == null) {- return;- }- nextCtx: for (ActionContext ctx : consoleService.getActionContexts()) {- if (!(ctx instanceof DebuggerMissingModuleActionContext mmCtx)) {- continue;- }- TraceModule module = mmCtx.getModule();- if (!affectedTraces.contains(module.getTrace())) {- continue;- }- long snap = traceManager.getCurrentFor(module.getTrace()).getSnap();- if (isMapped(module.getRange(snap))) {- consoleService.removeFromLog(mmCtx);- continue;- }- for (TraceSection section : module.getSections(snap)) {- if (isMapped(section.getRange(snap))) {- consoleService.removeFromLog(mmCtx);- continue nextCtx;- }- }- }- }-public void setTrackingSpec(LocationTrackingSpec spec) {trackingTrait.setSpec(spec);}@@ -1173,22 +879,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {trackingSpecChangeListeners.remove(listener);}- public void setAutoSyncCursorWithStaticListing(boolean sync) {- if (!isMainListing()) {- throw new IllegalStateException(- "Only the main dynamic listing can be synced to the main static listing");- }- syncTrait.setAutoSyncCursorWithStaticListing(sync);- }-- public void setAutoSyncSelectionWithStaticListing(boolean sync) {- if (!isMainListing()) {- throw new IllegalStateException(- "Only the main dynamic listing can be synced to the main static listing");- }- syncTrait.setAutoSyncSelectionWithStaticListing(sync);- }-public void setFollowsCurrentThread(boolean follows) {if (isMainListing()) {throw new IllegalStateException(@@ -1241,10 +931,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {return readsMemTrait.getLastRead();}- public void doAutoSyncCursorIntoStatic(ProgramLocation location) {- syncTrait.doAutoSyncCursorIntoStatic(location);- }-protected ProgramLocation doMarkTrackedLocation() {ProgramLocation trackedLocation = trackingTrait.getTrackedLocation();if (trackedLocation == null) {@@ -1272,28 +958,16 @@ public class DebuggerListingProvider extends CodeViewerProvider {protected void doGoToTracked() {Swing.runIfSwingOrRunLater(() -> {ProgramLocation loc = trackingTrait.getTrackedLocation();- ProgramLocation trackedStatic = doMarkTrackedLocation();+ doMarkTrackedLocation();if (loc == null) {return;}TraceProgramView curView = current.getView();- if (!syncTrait.isAutoSyncCursorWithStaticListing() || trackedStatic == null) {- if (curView != current.getView()) {- // Trace changed before Swing scheduled us- return;- }- goToAndUpdateTrackingLabel(curView, loc);- doCheckCurrentModuleMissing();- }- else {- if (curView != current.getView()) {- // Trace changed before Swing scheduled us- return;- }- goToAndUpdateTrackingLabel(curView, loc);- doCheckCurrentModuleMissing();- plugin.fireStaticLocationEvent(trackedStatic);+ if (curView != current.getView()) {+ // Trace changed before Swing scheduled us+ return;}+ goToAndUpdateTrackingLabel(curView, loc);});}@@ -1328,11 +1002,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {@Overridepublic void dispose() {super.dispose();- if (consoleService != null) {- if (actionOpenProgram != null) {- consoleService.removeResolutionAction(actionOpenProgram);- }- }removeOldStaticTrackingMarker();}@@ -1352,7 +1021,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {}current = coordinates;doSetProgram(current.getView());- syncTrait.goToCoordinates(coordinates);goToTrait.goToCoordinates(coordinates);trackingTrait.goToCoordinates(coordinates);readsMemTrait.goToCoordinates(coordinates);@@ -1376,14 +1044,6 @@ public class DebuggerListingProvider extends CodeViewerProvider {}}- public void staticProgramLocationChanged(ProgramLocation location) {- syncTrait.staticProgramLocationChanged(location);- }-- public void staticProgramSelectionChanged(Program program, ProgramSelection selection) {- syncTrait.staticProgramSelectionChanged(program, selection);- }-@Overridepublic void cloneWindow() {final DebuggerListingProvider newProvider = plugin.createNewDisconnectedProvider();diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/breakpoint/DebuggerLogicalBreakpointServicePlugin.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/breakpoint/DebuggerLogicalBreakpointServicePlugin.javaindex edd7302648..e2479c484e 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/breakpoint/DebuggerLogicalBreakpointServicePlugin.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/breakpoint/DebuggerLogicalBreakpointServicePlugin.java@@ -64,12 +64,21 @@ import ghidra.util.datastruct.ListenerSet;category = PluginCategoryNames.DEBUGGER,packageName = DebuggerPluginPackage.NAME,status = PluginStatus.RELEASED,- eventsConsumed = { ProgramOpenedPluginEvent.class, ProgramClosedPluginEvent.class,- TraceOpenedPluginEvent.class, TraceActivatedPluginEvent.class,- TraceInactiveCoordinatesPluginEvent.class, TraceClosedPluginEvent.class, },- servicesRequired = { DebuggerTraceManagerService.class,- DebuggerStaticMappingService.class, },- servicesProvided = { DebuggerLogicalBreakpointService.class, })+ eventsConsumed = {+ ProgramOpenedPluginEvent.class,+ ProgramClosedPluginEvent.class,+ TraceOpenedPluginEvent.class,+ TraceActivatedPluginEvent.class,+ TraceInactiveCoordinatesPluginEvent.class,+ TraceClosedPluginEvent.class,+ },+ servicesRequired = {+ DebuggerTraceManagerService.class,+ DebuggerStaticMappingService.class,+ },+ servicesProvided = {+ DebuggerLogicalBreakpointService.class,+ })public class DebuggerLogicalBreakpointServicePlugin extends Pluginimplements DebuggerLogicalBreakpointService {diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/modules/DynamicStaticSynchronizationPlugin.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/modules/DynamicStaticSynchronizationPlugin.javanew file mode 100644index 0000000000..2f00042a13--- /dev/null+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/modules/DynamicStaticSynchronizationPlugin.java@@ -0,0 +1,707 @@+/* ###+ * 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.service.modules;++import java.lang.invoke.MethodHandles;+import java.util.*;+import java.util.stream.Collectors;+import java.util.stream.Stream;++import javax.swing.Icon;++import docking.ActionContext;+import docking.action.DockingAction;+import docking.action.ToggleDockingAction;+import docking.action.builder.ActionBuilder;+import docking.action.builder.ToggleActionBuilder;+import ghidra.app.context.ProgramLocationActionContext;+import ghidra.app.events.*;+import ghidra.app.plugin.PluginCategoryNames;+import ghidra.app.plugin.core.debug.DebuggerPluginPackage;+import ghidra.app.plugin.core.debug.event.*;+import ghidra.app.plugin.core.debug.gui.DebuggerResources;+import ghidra.app.plugin.core.debug.utils.ProgramURLUtils;+import ghidra.app.services.*;+import ghidra.app.services.DebuggerStaticMappingService.MappedAddressRange;+import ghidra.debug.api.modules.*;+import ghidra.debug.api.tracemgr.DebuggerCoordinates;+import ghidra.framework.model.DomainFile;+import ghidra.framework.options.SaveState;+import ghidra.framework.plugintool.*;+import ghidra.framework.plugintool.annotation.AutoConfigStateField;+import ghidra.framework.plugintool.annotation.AutoServiceConsumed;+import ghidra.framework.plugintool.util.PluginStatus;+import ghidra.program.model.address.*;+import ghidra.program.model.listing.Program;+import ghidra.program.util.ProgramLocation;+import ghidra.program.util.ProgramSelection;+import ghidra.trace.model.Trace;+import ghidra.trace.model.modules.*;+import ghidra.trace.model.program.TraceProgramView;+import ghidra.util.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.VersionException;+import ghidra.util.task.*;++@PluginInfo(+ shortDescription = "Debugger static synchronization",+ description = """+ Synchronizes the static and dynamic listings (and other components) where the module \+ map is known""",+ category = PluginCategoryNames.DEBUGGER,+ packageName = DebuggerPluginPackage.NAME,+ status = PluginStatus.RELEASED,+ eventsConsumed = {+ ProgramOpenedPluginEvent.class, // For auto-open log cleanup+ ProgramActivatedPluginEvent.class,+ ProgramLocationPluginEvent.class,+ ProgramSelectionPluginEvent.class,+ // NOTE: Don't sync highlight+ TraceActivatedPluginEvent.class,+ TraceLocationPluginEvent.class,+ TraceSelectionPluginEvent.class,+ },+ eventsProduced = {+ ProgramLocationPluginEvent.class,+ ProgramSelectionPluginEvent.class,+ TraceLocationPluginEvent.class,+ TraceSelectionPluginEvent.class,+ },+ servicesRequired = {+ DebuggerStaticMappingService.class,+ })+public class DynamicStaticSynchronizationPlugin extends Plugin {++ interface SyncLocationsAction {+ String NAME = "Synchronize Static and Dynamic Locations";+ String DESCRIPTION = "Automatically synchronize the static and dynamic listings' cursors";+ String HELP_ANCHOR = "sync_locations";++ static ToggleActionBuilder builder(Plugin owner) {+ String ownerName = owner.getName();+ return new ToggleActionBuilder(NAME, ownerName)+ .description(DESCRIPTION)+ .menuPath(DebuggerPluginPackage.NAME, "Synchronization", NAME)+ .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));+ }+ }++ interface SyncSelectionsAction {+ String NAME = "Synchronize Static and Dynamic Selections";+ String DESCRIPTION =+ "Automatically synchronize the static and dynamic listings' selections";+ String HELP_ANCHOR = "sync_selections";++ static ToggleActionBuilder builder(Plugin owner) {+ String ownerName = owner.getName();+ return new ToggleActionBuilder(NAME, ownerName)+ .description(DESCRIPTION)+ .menuPath(DebuggerPluginPackage.NAME, "Synchronization", NAME)+ .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));+ }+ }++ interface TransferSelectionDynamicToStaticAction {+ String NAME = "Transfer Dynamic Selection to Static";+ String DESCRIPTION = "Change the static selection to match the dynamic selection";+ String HELP_ANCHOR = "transfer_selection_dynamic_to_static";++ static ActionBuilder builder(Plugin owner) {+ String ownerName = owner.getName();+ return new ActionBuilder(NAME, ownerName)+ .description(DESCRIPTION)+ .menuPath(DebuggerPluginPackage.NAME, "Synchronization", NAME)+ .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));+ }+ }++ interface TransferSelectionStaticToDynamicAction {+ String NAME = "Transfer Static Selection to Dynamic";+ String DESCRIPTION = "Change the dynamic seleciton to mathc the static selection";+ String HELP_ANCHOR = "transfer_selection_static_to_dynamic";++ static ActionBuilder builder(Plugin owner) {+ String ownerName = owner.getName();+ return new ActionBuilder(NAME, ownerName)+ .description(DESCRIPTION)+ .menuPath(DebuggerPluginPackage.NAME, "Synchronization", NAME)+ .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));+ }+ }++ interface OpenProgramAction {+ String NAME = "Open Program";+ Icon ICON = DebuggerResources.ICON_PROGRAM;+ String DESCRIPTION = "Open the program";+ String HELP_ANCHOR = "open_program";++ static ActionBuilder builder(Plugin owner) {+ String ownerName = owner.getName();+ return new ActionBuilder(NAME, ownerName)+ .description(DESCRIPTION)+ .toolBarIcon(ICON)+ .helpLocation(new HelpLocation(ownerName, HELP_ANCHOR));+ }+ }++ protected static final AutoConfigState.ClassHandler<DynamicStaticSynchronizationPlugin> CONFIG_STATE_HANDLER =+ AutoConfigState.wireHandler(DynamicStaticSynchronizationPlugin.class,+ MethodHandles.lookup());++ /**+ * NOTE: We thought about having this respect the current (possible disconnected) provider, but+ * whatever we send will get reflected back into the connected provider, anyway. Not sure which+ * will be more confusing, so we'll just go with "only the main/connected" viewers for now.+ *+ * @param ctx the context, ignored+ * @return true if a static selection is present+ */+ private boolean hasDynamicSelection(ProgramLocationActionContext ctx) {+ return currentDynamicSelection != null && !currentDynamicSelection.isEmpty();+ }++ private boolean hasStaticSelection(ProgramLocationActionContext ctx) {+ return currentStaticSelection != null && !currentStaticSelection.isEmpty();+ }++ protected class ForStaticSyncMappingChangeListener+ implements DebuggerStaticMappingChangeListener {+ @Override+ public void mappingsChanged(Set<Trace> affectedTraces, Set<Program> affectedPrograms) {+ Swing.runIfSwingOrRunLater(() -> {+ if (currentDynamic.getView() == null) {+ return;+ }+ if (!affectedTraces.contains(currentDynamic.getTrace())) {+ return;+ }+ cleanMissingModuleMessages(affectedTraces);+ if (isSyncLocations()) {+ doSendLocationFromStable();+ }+ if (isSyncSelections()) {+ doSendSelectionFromStable();+ }+ });++ /**+ * TODO: Remove "missing" entry in modules dialog, if present? There's some nuance here,+ * because the trace presenting the mapping may not be the same as the trace that missed+ * the module originally. I'm tempted to just leave it and let the user remove it.+ */+ }+ }++ protected ToggleDockingAction actionSyncLocations;+ protected ToggleDockingAction actionSyncSelections;+ protected DockingAction actionTransferSelectionDynamicToStatic;+ protected DockingAction actionTransferSelectionStaticToDynamic;++ protected DockingAction actionOpenProgram;++ @AutoConfigStateField+ private boolean syncLocations = true;+ @AutoConfigStateField+ private boolean syncSelections = true;++ // @AutoServiceConsumed via method+ private DebuggerStaticMappingService mappingService;+ @AutoServiceConsumed+ private DebuggerTraceManagerService traceManager;+ @AutoServiceConsumed+ private DebuggerConsoleService consoleService;+ @AutoServiceConsumed+ private ProgramManager programManager;+ @AutoServiceConsumed+ private FileImporterService importerService;+ @SuppressWarnings("unused")+ private final AutoService.Wiring autoServiceWiring;++ protected final ForStaticSyncMappingChangeListener mappingChangeListener =+ new ForStaticSyncMappingChangeListener();++ enum StablePoint {+ STATIC, DYNAMIC;+ }++ private StablePoint stablePoint;+ private DebuggerCoordinates currentDynamic = DebuggerCoordinates.NOWHERE;+ private ProgramLocation currentDynamicLocation;+ private ProgramSelection currentDynamicSelection;+ private Program currentStatic;+ private ProgramLocation currentStaticLocation;+ private ProgramSelection currentStaticSelection;++ public DynamicStaticSynchronizationPlugin(PluginTool tool) {+ super(tool);+ this.autoServiceWiring = AutoService.wireServicesProvidedAndConsumed(this);++ createActions();+ }++ @Override+ protected void dispose() {+ super.dispose();+ if (consoleService != null) {+ if (actionOpenProgram != null) {+ consoleService.removeResolutionAction(actionOpenProgram);+ }+ }+ }++ @AutoServiceConsumed+ private void setMappingService(DebuggerStaticMappingService mappingService) {+ if (this.mappingService != null) {+ this.mappingService.removeChangeListener(mappingChangeListener);+ }+ this.mappingService = mappingService;+ if (this.mappingService != null) {+ this.mappingService.addChangeListener(mappingChangeListener);+ if (isSyncLocations()) {+ doSendLocationFromStable();+ }+ if (isSyncSelections()) {+ doSendSelectionFromStable();+ }+ }+ }++ @AutoServiceConsumed+ private void setConsoleService(DebuggerConsoleService consoleService) {+ if (consoleService != null) {+ if (actionOpenProgram != null) {+ consoleService.addResolutionAction(actionOpenProgram);+ }+ }+ }++ protected void createActions() {+ actionSyncLocations = SyncLocationsAction+ .builder(this)+ .enabled(true)+ .selected(true)+ .onAction(ctx -> doSetSyncLocations(actionSyncLocations.isSelected()))+ .buildAndInstall(tool);+ actionSyncSelections = SyncSelectionsAction+ .builder(this)+ .enabled(true)+ .selected(true)+ .onAction(ctx -> doSetSyncSelections(actionSyncSelections.isSelected()))+ .buildAndInstall(tool);+ actionTransferSelectionDynamicToStatic = TransferSelectionDynamicToStaticAction+ .builder(this)+ .withContext(ProgramLocationActionContext.class)+ .enabledWhen(this::hasDynamicSelection)+ .onAction(this::activatedTransferSelectionDynamicToStatic)+ .buildAndInstall(tool);+ actionTransferSelectionStaticToDynamic = TransferSelectionStaticToDynamicAction+ .builder(this)+ .withContext(ProgramLocationActionContext.class)+ .enabledWhen(this::hasStaticSelection)+ .onAction(this::activatedTransferSelectionStaticToDynamic)+ .buildAndInstall(tool);++ actionOpenProgram = OpenProgramAction.builder(this)+ .withContext(DebuggerOpenProgramActionContext.class)+ .onAction(this::activatedOpenProgram)+ .build();+ }++ protected void doSetSyncLocations(boolean sync) {+ this.syncLocations = sync;+ if (isSyncLocations()) {+ doSendLocationFromStable();+ }+ }++ protected void doSetSyncSelections(boolean sync) {+ this.syncSelections = sync;+ if (isSyncSelections()) {+ doSendSelectionFromStable();+ }+ }++ protected void displayMapError(String from, String to) {+ tool.setStatusInfo("No selected addresses in " + from + " are mappable to " + to ++ ". Check your module list and static mappings.", true);+ }++ private void activatedTransferSelectionDynamicToStatic(ActionContext ctx) {+ stablePoint = StablePoint.DYNAMIC;+ ProgramSelection result = doSendSelectionDynamicToStatic();+ if (result != null && result.isEmpty()) {+ displayMapError("the dynamic view", "the static listing");+ }+ }++ private void activatedTransferSelectionStaticToDynamic(ActionContext ctx) {+ stablePoint = StablePoint.STATIC;+ ProgramSelection result = doSendSelectionStaticToDynamic();+ if (result != null && result.isEmpty()) {+ displayMapError("the static listing", "the dynamic view");+ }+ }++ private void activatedOpenProgram(DebuggerOpenProgramActionContext context) {+ programManager.openProgram(context.getDomainFile(), DomainFile.DEFAULT_VERSION,+ ProgramManager.OPEN_CURRENT);+ }++ private void doSendLocationFromStable() {+ switch (stablePoint) {+ case null -> {+ }+ case STATIC -> doSendLocationStaticToDynamic();+ case DYNAMIC -> doSendLocationDynamicToStatic();+ }+ }++ private void doSendSelectionFromStable() {+ switch (stablePoint) {+ case null -> {+ }+ case STATIC -> doSendSelectionStaticToDynamic();+ case DYNAMIC -> doSendSelectionDynamicToStatic();+ }+ }++ private void doSendLocationStaticToDynamic() {+ if (mappingService == null || currentStaticLocation == null) {+ return;+ }+ TraceProgramView view = currentDynamic.getView(); // NB. Used for snap (don't want emuSnap)+ if (view == null) {+ return;+ }+ ProgramLocation dynamicLoc =+ mappingService.getDynamicLocationFromStatic(view, currentStaticLocation);+ if (dynamicLoc == null) {+ return;+ }+ firePluginEvent(new TraceLocationPluginEvent(getName(), dynamicLoc));+ }++ private void doSendLocationDynamicToStatic() {+ if (mappingService == null || currentDynamicLocation == null) {+ return;+ }+ /**+ * Is there any reason to try to open the module if we're not syncing listings? I don't+ * think so.+ */+ doCheckCurrentModuleMissing();+ TraceProgramView view = currentDynamic.getView();+ if (view == null) {+ return;+ }+ ProgramLocation staticLoc =+ mappingService.getStaticLocationFromDynamic(currentDynamicLocation);+ if (staticLoc == null) {+ return;+ }+ firePluginEvent(+ new ProgramLocationPluginEvent(getName(), staticLoc, staticLoc.getProgram()));+ }++ private ProgramSelection doSendSelectionStaticToDynamic() {+ if (mappingService == null || currentStatic == null || currentStaticSelection == null) {+ return null;+ }+ TraceProgramView view = currentDynamic.getView();+ if (view == null) {+ return null;+ }+ AddressSet dynamicAddrs =+ mappingService.getOpenMappedViews(currentStatic, currentStaticSelection)+ .entrySet()+ .stream()+ .filter(e -> e.getKey().getTrace() == view.getTrace())+ .filter(e -> e.getKey().getSpan().contains(currentDynamic.getSnap()))+ .flatMap(e -> e.getValue().stream())+ .map(r -> r.getDestinationAddressRange())+ .collect(AddressCollectors.toAddressSet());+ ProgramSelection dynamicSel = new ProgramSelection(dynamicAddrs);+ firePluginEvent(new TraceSelectionPluginEvent(getName(), dynamicSel, view));+ return dynamicSel;+ }++ private ProgramSelection doSendSelectionDynamicToStatic() {+ if (mappingService == null || currentStatic == null || currentDynamicSelection == null) {+ return null;+ }+ TraceProgramView view = currentDynamic.getView();+ if (view == null) {+ return null;+ }+ Collection<MappedAddressRange> ranges = mappingService+ .getOpenMappedViews(view.getTrace(), currentDynamicSelection,+ currentDynamic.getSnap())+ .get(currentStatic);+ AddressSet staticAddrs = ranges == null+ ? null+ : ranges.stream()+ .map(r -> r.getDestinationAddressRange())+ .collect(AddressCollectors.toAddressSet());+ ProgramSelection staticSel = new ProgramSelection(staticAddrs);+ firePluginEvent(new ProgramSelectionPluginEvent(getName(), staticSel, currentStatic));+ return staticSel;+ }++ @Override+ public void processEvent(PluginEvent event) {+ switch (event) {+ case ProgramOpenedPluginEvent ev -> programOpened(ev);+ case ProgramActivatedPluginEvent ev -> programActivated(ev);+ case ProgramLocationPluginEvent ev -> staticLocationChanged(ev);+ case ProgramSelectionPluginEvent ev -> staticSelectionChanged(ev);+ case TraceActivatedPluginEvent ev -> coordinatesActivated(ev);+ case TraceLocationPluginEvent ev -> dynamicLocationChanged(ev);+ case TraceSelectionPluginEvent ev -> dynamicSelectionChanged(ev);+ default -> {+ }+ }+ }++ private void programOpened(ProgramOpenedPluginEvent event) {+ DomainFile df = event.getProgram().getDomainFile();+ DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);+ if (consoleService != null) {+ consoleService.removeFromLog(ctx);+ }+ }++ private void programActivated(ProgramActivatedPluginEvent event) {+ currentStatic = event.getActiveProgram();+ }++ private void staticLocationChanged(ProgramLocationPluginEvent event) {+ currentStaticLocation = event.getLocation();+ stablePoint = StablePoint.STATIC;+ if (isSyncLocations()) {+ doSendLocationStaticToDynamic();+ }+ }++ private void staticSelectionChanged(ProgramSelectionPluginEvent event) {+ currentStaticSelection = event.getSelection();+ stablePoint = StablePoint.STATIC;+ if (isSyncSelections()) {+ doSendSelectionStaticToDynamic();+ }+ }++ private void coordinatesActivated(TraceActivatedPluginEvent event) {+ currentDynamic = event.getActiveCoordinates();+ }++ private void dynamicLocationChanged(TraceLocationPluginEvent event) {+ currentDynamicLocation = event.getLocation();+ stablePoint = StablePoint.DYNAMIC;+ if (isSyncLocations()) {+ doSendLocationDynamicToStatic();+ }+ }++ private void dynamicSelectionChanged(TraceSelectionPluginEvent event) {+ currentDynamicSelection = event.getSelection();+ stablePoint = StablePoint.DYNAMIC;+ if (isSyncSelections()) {+ doSendSelectionDynamicToStatic();+ }+ }++ public void setSyncLocations(boolean sync) {+ actionSyncLocations.setSelected(sync);+ doSetSyncLocations(sync);+ }++ public boolean isSyncLocations() {+ return syncLocations;+ }++ public void setSyncSelections(boolean sync) {+ actionSyncSelections.setSelected(sync);+ doSetSyncSelections(sync);+ }++ public boolean isSyncSelections() {+ return syncSelections;+ }++ @Override+ public void readConfigState(SaveState saveState) {+ CONFIG_STATE_HANDLER.readConfigState(this, saveState);+ actionSyncLocations.setSelected(syncLocations);+ actionSyncSelections.setSelected(syncSelections);+ }++ protected void doTryOpenProgram(DomainFile df, int version, int state) {+ DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);+ if (consoleService != null && consoleService.logContains(ctx)) {+ return;+ }+ if (df.canRecover()) {+ if (consoleService != null) {+ consoleService.log(DebuggerResources.ICON_MODULES, "<html>Program <b>" ++ HTMLUtilities.escapeHTML(df.getPathname()) ++ "</b> has recovery data. It must be opened manually.</html>", ctx);+ }+ return;+ }+ new TaskLauncher(new Task("Open " + df, true, false, false) {+ @Override+ public void run(TaskMonitor monitor) throws CancelledException {+ Program program = null;+ try {+ program = (Program) df.getDomainObject(this, false, false, monitor);+ programManager.openProgram(program, state);+ }+ catch (VersionException e) {+ if (consoleService != null) {+ consoleService.log(DebuggerResources.ICON_MODULES, "<html>Program <b>" ++ HTMLUtilities.escapeHTML(df.getPathname()) ++ "</b> was created with a different version of Ghidra." ++ " It must be opened manually.</html>", ctx);+ }+ return;+ }+ catch (Exception e) {+ if (consoleService != null) {+ consoleService.log(DebuggerResources.ICON_LOG_ERROR, "<html>Program <b>" ++ HTMLUtilities.escapeHTML(df.getPathname()) ++ "</b> could not be opened: " + e + ". Try opening it manually.</html>",+ ctx);+ }+ return;+ }+ finally {+ if (program != null) {+ program.release(this);+ }+ }+ }+ }, tool.getToolFrame());+ }++ protected boolean isMapped(AddressRange range) {+ if (range == null) {+ return false;+ }+ return mappingService.getStaticLocationFromDynamic(+ new ProgramLocation(currentDynamic.getView(), range.getMinAddress())) != null;+ }++ protected void cleanMissingModuleMessages(Set<Trace> affectedTraces) {+ if (consoleService == null) {+ return;+ }+ nextCtx: for (ActionContext ctx : consoleService.getActionContexts()) {+ if (!(ctx instanceof DebuggerMissingModuleActionContext mmCtx)) {+ continue;+ }+ TraceModule module = mmCtx.getModule();+ if (!affectedTraces.contains(module.getTrace())) {+ continue;+ }+ long snap = traceManager.getCurrentFor(module.getTrace()).getSnap();+ if (isMapped(module.getRange(snap))) {+ consoleService.removeFromLog(mmCtx);+ continue;+ }+ for (TraceSection section : module.getSections(snap)) {+ if (isMapped(section.getRange(snap))) {+ consoleService.removeFromLog(mmCtx);+ continue nextCtx;+ }+ }+ }+ }++ protected void doCheckCurrentModuleMissing() {+ Trace trace = currentDynamic.getTrace();+ if (trace == null) {+ return;+ }+ ProgramLocation loc = currentDynamicLocation;+ if (loc == null) { // Redundant?+ return;+ }+ AddressSpace space = loc.getAddress().getAddressSpace();+ if (space == null) {+ return; // Is this NO_ADDRESS or something?+ }+ if (mappingService == null) {+ return;+ }+ ProgramLocation mapped = mappingService.getStaticLocationFromDynamic(loc);+ if (mapped != null) {+ // No need to import what is already mapped and open+ return;+ }++ long snap = currentDynamic.getSnap();+ Address address = loc.getAddress();+ TraceStaticMapping mapping = trace.getStaticMappingManager().findContaining(address, snap);+ if (mapping != null) {+ DomainFile df = ProgramURLUtils.getDomainFileFromOpenProject(tool.getProject(),+ mapping.getStaticProgramURL());+ if (df != null) {+ doTryOpenProgram(df, DomainFile.DEFAULT_VERSION, ProgramManager.OPEN_CURRENT);+ }+ }++ Set<TraceModule> missing = new HashSet<>();+ Set<DomainFile> toOpen = new HashSet<>();+ TraceModuleManager modMan = trace.getModuleManager();+ Collection<TraceModule> modules = Stream.concat(+ modMan.getModulesAt(snap, address).stream().filter(m -> m.getSections(snap).isEmpty()),+ modMan.getSectionsAt(snap, address).stream().map(s -> s.getModule()))+ .collect(Collectors.toSet());++ // Attempt to open probable matches. All others, list to import+ for (TraceModule mod : modules) {+ DomainFile match = mappingService.findBestModuleProgram(space, mod, snap);+ if (match == null) {+ missing.add(mod);+ }+ else {+ toOpen.add(match);+ }+ }+ if (programManager != null && !toOpen.isEmpty()) {+ for (DomainFile df : toOpen) {+ // Do not presume a goTo is about to happen. There are no mappings, yet.+ doTryOpenProgram(df, DomainFile.DEFAULT_VERSION, ProgramManager.OPEN_VISIBLE);+ }+ }++ if (importerService == null || consoleService == null) {+ return;+ }++ for (TraceModule mod : missing) {+ consoleService.log(DebuggerResources.ICON_LOG_ERROR,+ "<html>The module <b><tt>" + HTMLUtilities.escapeHTML(mod.getName(snap)) ++ "</tt></b> was not found in the project</html>",+ new DebuggerMissingModuleActionContext(mod));+ }+ /**+ * Once the programs are opened, including those which are successfully imported, the+ * automatic mapper should take effect, eventually invoking callbacks to our mapping change+ * listener.+ */+ }+}diff --git a/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/disassemble/DebuggerDisassemblyTest.java b/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/disassemble/DebuggerDisassemblyTest.javaindex 11630e17f8..d00e26071c 100644--- a/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/disassemble/DebuggerDisassemblyTest.java+++ b/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/disassemble/DebuggerDisassemblyTest.java@@ -38,6 +38,7 @@ import ghidra.app.plugin.core.debug.gui.listing.*;import ghidra.app.plugin.core.debug.service.control.DebuggerControlServicePlugin;import ghidra.app.plugin.core.debug.service.emulation.DebuggerEmulationServicePlugin;import ghidra.app.plugin.core.debug.service.emulation.ProgramEmulationUtils;+import ghidra.app.plugin.core.debug.service.modules.DebuggerStaticMappingServicePlugin;import ghidra.app.plugin.core.debug.service.platform.DebuggerPlatformServicePlugin;import ghidra.app.services.*;import ghidra.debug.api.control.ControlMode;@@ -345,6 +346,7 @@ public class DebuggerDisassemblyTest extends AbstractGhidraHeadedDebuggerTest {@Testpublic void testAutoDisassembleReDisassembleX8664OffcutByProgEmu() throws Throwable {+ addPlugin(tool, DebuggerStaticMappingServicePlugin.class);DebuggerEmulationService emuService = addPlugin(tool, DebuggerEmulationServicePlugin.class);createProgram(getSLEIGH_X86_64_LANGUAGE());@@ -361,6 +363,7 @@ public class DebuggerDisassemblyTest extends AbstractGhidraHeadedDebuggerTest {tb.trace.release(this);TraceThread thread = Unique.assertOne(tb.trace.getThreadManager().getAllThreads());+ programManager.openProgram(program);traceManager.openTrace(tb.trace);traceManager.activateThread(thread);diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProviderTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProviderTest.javaindex 71092e1673..f8180980be 100644--- a/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProviderTest.java+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/gui/listing/DebuggerListingProviderTest.java@@ -20,7 +20,6 @@ import static org.junit.Assert.*;import java.awt.Component;import java.awt.Point;import java.awt.event.MouseEvent;-import java.io.IOException;import java.math.BigInteger;import java.nio.ByteBuffer;import java.util.Set;@@ -44,20 +43,15 @@ import ghidra.app.plugin.core.debug.gui.AbstractGhidraHeadedDebuggerIntegrationTimport ghidra.app.plugin.core.debug.gui.DebuggerResources;import ghidra.app.plugin.core.debug.gui.DebuggerResources.FollowsCurrentThreadAction;import ghidra.app.plugin.core.debug.gui.action.*;-import ghidra.app.plugin.core.debug.gui.console.DebuggerConsolePlugin;-import ghidra.app.plugin.core.debug.gui.console.DebuggerConsoleProvider.BoundAction;-import ghidra.app.plugin.core.debug.gui.console.DebuggerConsoleProvider.LogRow;import ghidra.app.plugin.core.debug.service.control.DebuggerControlServicePlugin;import ghidra.app.plugin.core.debug.service.modules.DebuggerStaticMappingUtils;import ghidra.app.plugin.core.debug.service.progress.ProgressServicePlugin;-import ghidra.app.services.*;+import ghidra.app.services.DebuggerControlService;+import ghidra.app.services.DebuggerStaticMappingService;import ghidra.app.util.viewer.listingpanel.ListingPanel;import ghidra.async.SwingExecutorService;import ghidra.debug.api.control.ControlMode;-import ghidra.debug.api.modules.DebuggerMissingModuleActionContext;import ghidra.debug.api.tracemgr.DebuggerCoordinates;-import ghidra.framework.model.*;-import ghidra.plugin.importer.ImporterPlugin;import ghidra.program.model.address.*;import ghidra.program.model.data.PointerDataType;import ghidra.program.model.lang.Register;@@ -65,7 +59,8 @@ import ghidra.program.model.lang.RegisterValue;import ghidra.program.model.listing.*;import ghidra.program.model.symbol.RefType;import ghidra.program.model.symbol.SourceType;-import ghidra.program.util.*;+import ghidra.program.util.OperandFieldLocation;+import ghidra.program.util.ProgramLocation;import ghidra.trace.database.ToyDBTraceBuilder;import ghidra.trace.database.memory.DBTraceMemoryManager;import ghidra.trace.database.stack.DBTraceStackManager;@@ -76,19 +71,16 @@ import ghidra.trace.model.modules.TraceModule;import ghidra.trace.model.stack.TraceStack;import ghidra.trace.model.target.TraceObject;import ghidra.trace.model.thread.TraceThread;-import ghidra.util.exception.CancelledException;-import ghidra.util.exception.VersionException;-import ghidra.util.task.TaskMonitor;@Category(NightlyCategory.class)public class DebuggerListingProviderTest extends AbstractGhidraHeadedDebuggerIntegrationTest {+ protected CodeBrowserPlugin codePlugin;+ protected CodeViewerProvider codeProvider;protected DebuggerListingPlugin listingPlugin;protected DebuggerListingProvider listingProvider;protected DebuggerStaticMappingService mappingService;- protected CodeBrowserPlugin codePlugin;- protected CodeViewerProvider codeProvider;@Beforepublic void setUpListingProviderTest() throws Exception {@@ -464,122 +456,6 @@ public class DebuggerListingProviderTest extends AbstractGhidraHeadedDebuggerInt}}- @Test- public void testSyncCursorToStaticListingStaticToDynamicOnGoto() throws Exception {- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- ProgramLocation loc;-- goTo(tool, program, ss.getAddress(0x00601234));- waitForSwing();-- loc = listingProvider.getLocation();- assertEquals(tb.trace.getProgramView(), loc.getProgram());- assertEquals(tb.addr(0x00401234), loc.getAddress());-- goTo(tool, program, ss.getAddress(0x00608765));- waitForSwing();-- loc = listingProvider.getLocation();- assertEquals(tb.trace.getProgramView(), loc.getProgram());- assertEquals(tb.addr(0x00401234), loc.getAddress());-- goTo(tool, program, ss.getAddress(0x00607fff));- waitForSwing();-- loc = listingProvider.getLocation();- assertEquals(tb.trace.getProgramView(), loc.getProgram());- assertEquals(tb.addr(0x00407fff), loc.getAddress());- }-- @Test- public void testSyncCursorToStaticListingDynamicToStaticOnSnapChange() throws Exception {- createAndOpenTrace();- createAndOpenProgramFromTrace();- intoProject(tb.trace);- intoProject(program);-- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();- try (Transaction tx = program.openTransaction("Add block")) {- program.getMemory()- .createInitializedBlock(".text", ss.getAddress(0x00600000), 0x10000, (byte) 0,- monitor, false);- }- TraceThread thread;- try (Transaction tx = tb.startTransaction()) {- DBTraceMemoryManager memory = tb.trace.getMemoryManager();- memory.addRegion("exe:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0040ffff),- TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);- TraceLocation from =- new DefaultTraceLocation(tb.trace, null, Lifespan.nowOn(0), tb.addr(0x00400000));- ProgramLocation to = new ProgramLocation(program, ss.getAddress(0x00600000));- DebuggerStaticMappingUtils.addMapping(from, to, 0x8000, false);-- thread = tb.getOrAddThread("Thread1", 0);- Register pc = tb.trace.getBaseLanguage().getProgramCounter();- TraceMemorySpace regs = memory.getMemoryRegisterSpace(thread, true);- regs.setValue(1, new RegisterValue(pc, BigInteger.valueOf(0x00401234)));- }- waitForProgram(program);- waitForDomainObject(tb.trace);- traceManager.activateThread(thread);- waitForSwing();-- traceManager.activateSnap(1);- waitForSwing();-- ProgramLocation loc = codePlugin.getCurrentLocation();- assertEquals(program, loc.getProgram());- assertEquals(ss.getAddress(0x00601234), loc.getAddress());- }-- @Test- public void testSyncCursorToStaticListingDynamicToStaticOnLocationChange() throws Exception {- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- listingProvider.getListingPanel()- .setCursorPosition(- new ProgramLocation(tb.trace.getProgramView(), tb.addr(0x00401234)),- EventTrigger.GUI_ACTION);- waitForSwing();-- ProgramLocation loc = codePlugin.getCurrentLocation();- assertEquals(program, loc.getProgram());- assertEquals(ss.getAddress(0x00601234), loc.getAddress());- }-- @Test- public void testSyncSelectionToStaticListingDynamicToStaticOnSelectionChange()- throws Exception {- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- runSwing(() -> listingProvider.getListingPanel()- .setSelection(new ProgramSelection(tb.addr(0x00401234), tb.addr(0x00404321)),- EventTrigger.GUI_ACTION));- waitForSwing();-- assertEquals(tb.set(tb.range(ss, 0x00601234, 0x00604321)),- codePlugin.getCurrentSelection());- }-- @Test- public void testSyncSelectionToStaticListingStaticToDynamicOnSelectionChange()- throws Exception {- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- runSwing(() -> codePlugin.getListingPanel()- .setSelection(- new ProgramSelection(tb.addr(ss, 0x00601234), tb.addr(ss, 0x00604321)),- EventTrigger.GUI_ACTION));- waitForSwing();-- assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());- }-@Testpublic void testDynamicListingMarksTrackedRegister() throws Exception {createAndOpenTrace();@@ -607,7 +483,7 @@ public class DebuggerListingProviderTest extends AbstractGhidraHeadedDebuggerInt}@Test- public void testSyncCursorToStaticListingMarksMappedTrackedRegister() throws Exception {+ public void testStaticListingMarksMappedTrackedRegister() throws Exception {createAndOpenTrace();createAndOpenProgramFromTrace();intoProject(tb.trace);@@ -967,98 +843,6 @@ public class DebuggerListingProviderTest extends AbstractGhidraHeadedDebuggerInt() -> assertEquals(tb.addr(0x0040f234), listingProvider.getLocation().getAddress()));}- @Test- public void testActionSyncCursorToStaticListing() throws Exception {- assertTrue(listingProvider.actionAutoSyncCursorWithStaticListing.isEnabled());-- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- // Check default is on- assertTrue(listingProvider.actionAutoSyncCursorWithStaticListing.isSelected());- goTo(tool, program, ss.getAddress(0x00601234));- waitForSwing();- assertEquals(tb.addr(0x00401234), listingProvider.getLocation().getAddress());-- performAction(listingProvider.actionAutoSyncCursorWithStaticListing);- assertFalse(listingProvider.actionAutoSyncCursorWithStaticListing.isSelected());- goTo(tool, program, ss.getAddress(0x00608765));- waitForSwing();- // Verify the goTo was effective, but no change to dynamic listing location- assertEquals(ss.getAddress(0x00608765), codePlugin.getCurrentLocation().getAddress());- assertEquals(tb.addr(0x00401234), listingProvider.getLocation().getAddress());-- listingProvider.setAutoSyncCursorWithStaticListing(true);- // NOTE: Toggling adjusts the static listing, not the dynamic- waitForSwing();- assertTrue(listingProvider.actionAutoSyncCursorWithStaticListing.isSelected());- assertEquals(ss.getAddress(0x00601234), codePlugin.getCurrentLocation().getAddress());- }-- @Test- public void testActionSyncSelectionToStaticListing() throws Exception {- assertTrue(listingProvider.actionAutoSyncCursorWithStaticListing.isEnabled());-- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- // Check default is on- assertTrue(listingProvider.actionAutoSyncSelectionWithStaticListing.isSelected());- makeSelection(tool, program, tb.range(ss, 0x00601234, 0x00604321));- goTo(tool, program, ss.getAddress(0x00601234));- waitForSwing();- assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());-- performAction(listingProvider.actionAutoSyncSelectionWithStaticListing);- assertFalse(listingProvider.actionAutoSyncSelectionWithStaticListing.isSelected());- goTo(tool, program, ss.getAddress(0x00608765));- makeSelection(tool, program, tb.range(ss, 0x00605678, 0x00608765));- waitForSwing();- // Verify the makeSelection was effective, but no change to dynamic listing location- assertEquals(tb.set(tb.range(ss, 0x00605678, 0x00608765)),- codePlugin.getCurrentSelection());- assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());-- listingProvider.setAutoSyncSelectionWithStaticListing(true);- // NOTE: Toggling adjusts the static listing, not the dynamic- waitForSwing();- assertTrue(listingProvider.actionAutoSyncSelectionWithStaticListing.isSelected());- assertEquals(tb.set(tb.range(ss, 0x00601234, 0x00604321)),- codePlugin.getCurrentSelection());- assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());- }-- @Test- public void testActionMapAddressesToStatic() throws Exception {- listingProvider.setAutoSyncSelectionWithStaticListing(false);- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- listingProvider.getListingPanel()- .setSelection(new ProgramSelection(tb.set(tb.range(0x00401234, 0x00404321))),- EventTrigger.GUI_ACTION);- assertTrue(codePlugin.getCurrentSelection().isEmpty());-- performAction(listingProvider.actionSyncSelectionIntoStaticListing,- listingProvider.getActionContext(null), true);- assertEquals(tb.set(tb.range(ss, 0x00601234, 0x00604321)),- codePlugin.getCurrentSelection());- }-- @Test- public void testActionMapAddressesToDynamic() throws Exception {- listingProvider.setAutoSyncSelectionWithStaticListing(false);- createMappedTraceAndProgram();- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();-- makeSelection(tool, program, tb.set(tb.range(ss, 0x00601234, 0x00604321)));- assertTrue(listingPlugin.getCurrentSelection().isEmpty());-- performAction(listingProvider.actionSyncSelectionFromStaticListing,- codeProvider.getActionContext(null), true);- assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());- }-@Testpublic void testActionFollowsCurrentThread() throws Exception {createAndOpenTrace();@@ -1179,62 +963,6 @@ public class DebuggerListingProviderTest extends AbstractGhidraHeadedDebuggerIntassertEquals(readNone, listingProvider.actionAutoReadMemory.getCurrentUserData());}- @Test- public void testPromptImportCurrentModuleWithSections() throws Exception {- addPlugin(tool, ImporterPlugin.class);- DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);-- createAndOpenTrace();- try (Transaction tx = tb.startTransaction()) {- tb.trace.getMemoryManager()- .addRegion("bash:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0041ffff),- Set.of(TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE));-- TraceModule bin = tb.trace.getModuleManager()- .addLoadedModule("/bin/bash", "/bin/bash", tb.range(0x00400000, 0x0041ffff), 0);- bin.addSection(0, "bash[.text]", tb.range(0x00400000, 0x0040ffff));- }- waitForDomainObject(tb.trace);- traceManager.activateTrace(tb.trace);- waitForSwing();-- // In the module, but not in its section- assertTrue(listingPlugin.goTo(tb.addr(0x00411234), true));- waitForSwing();- waitForPass(() -> assertEquals(0,- consolePlugin.getRowCount(DebuggerMissingModuleActionContext.class)));-- assertTrue(listingPlugin.goTo(tb.addr(0x00401234), true));- waitForSwing();- waitForPass(() -> assertEquals(1,- consolePlugin.getRowCount(DebuggerMissingModuleActionContext.class)));- }-- @Test- public void testPromptImportCurrentModuleWithoutSections() throws Exception {- addPlugin(tool, ImporterPlugin.class);- DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);-- createAndOpenTrace();- try (Transaction tx = tb.startTransaction()) {- tb.trace.getMemoryManager()- .addRegion("bash:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0041ffff),- Set.of(TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE));-- tb.trace.getModuleManager()- .addLoadedModule("/bin/bash", "/bin/bash", tb.range(0x00400000, 0x0041ffff), 0);- }- waitForDomainObject(tb.trace);- traceManager.activateTrace(tb.trace);- waitForSwing();-- // In the module, but not in its section- assertTrue(listingPlugin.goTo(tb.addr(0x00411234), true));- waitForSwing();- waitForPass(() -> assertEquals(1,- consolePlugin.getRowCount(DebuggerMissingModuleActionContext.class)));- }-@Testpublic void testLocationLabel() throws Exception {assertEquals("", listingProvider.locationLabel.getText());@@ -1503,131 +1231,6 @@ public class DebuggerListingProviderTest extends AbstractGhidraHeadedDebuggerIntassertEquals(tb.addr(0x00404321), listingProvider.getLocation().getAddress());}- @Test- public void testSyncCursorToStaticListingOpensModule() throws Exception {- DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);-- createAndOpenTrace();- createAndOpenProgramFromTrace();- intoProject(tb.trace);- intoProject(program);-- AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();- try (Transaction tx = program.openTransaction("Add block")) {- program.getMemory()- .createInitializedBlock(".text", ss.getAddress(0x00600000), 0x10000, (byte) 0,- monitor, false);- }- try (Transaction tx = tb.startTransaction()) {- DBTraceMemoryManager memory = tb.trace.getMemoryManager();- memory.addRegion("exe:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0040ffff),- TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);- TraceLocation from =- new DefaultTraceLocation(tb.trace, null, Lifespan.nowOn(0), tb.addr(0x00400000));- ProgramLocation to = new ProgramLocation(program, ss.getAddress(0x00600000));- mappingService.addMapping(from, to, 0x8000, false);- }- waitForProgram(program);- waitForDomainObject(tb.trace);-- programManager.closeAllPrograms(true);- waitForPass(() -> assertEquals(0, programManager.getAllOpenPrograms().length));-- traceManager.activateTrace(tb.trace);- waitForSwing();-- listingProvider.getListingPanel()- .setCursorPosition(- new ProgramLocation(tb.trace.getProgramView(), tb.addr(0x00401234)),- EventTrigger.GUI_ACTION);- waitForSwing();-- waitForPass(() -> assertEquals(1, programManager.getAllOpenPrograms().length));- assertTrue(java.util.List.of(programManager.getAllOpenPrograms()).contains(program));-- assertFalse(consolePlugin- .logContains(new DebuggerOpenProgramActionContext(program.getDomainFile())));- }-- @Test- public void testSyncCursorToStaticLogsRecoverableProgram() throws Exception {- DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);-- TestDummyDomainFolder root = new TestDummyDomainFolder(null, "root");- DomainFile df = new TestDummyDomainFile(root, "dummyFile") {- @Override- public boolean canRecover() {- return true;- }- };-- listingProvider.doTryOpenProgram(df, DomainFile.DEFAULT_VERSION,- ProgramManager.OPEN_CURRENT);- waitForSwing();-- DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);- waitForPass(() -> assertTrue(consolePlugin.logContains(ctx)));- assertTrue(consolePlugin.getLogRow(ctx).message() instanceof String message &&- message.contains("recovery"));- }-- @Test- public void testSyncCursorToStaticLogsUpgradeableProgram() throws Exception {- DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);-- TestDummyDomainFolder root = new TestDummyDomainFolder(null, "root");- DomainFile df = new TestDummyDomainFile(root, "dummyFile") {- @Override- public boolean canRecover() {- return false;- }-- @Override- public DomainObject getDomainObject(Object consumer, boolean okToUpgrade,- boolean okToRecover, TaskMonitor monitor)- throws VersionException, IOException, CancelledException {- throw new VersionException();- }- };-- listingProvider.doTryOpenProgram(df, DomainFile.DEFAULT_VERSION,- ProgramManager.OPEN_CURRENT);- waitForSwing();-- DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);- waitForPass(() -> assertTrue(consolePlugin.logContains(ctx)));- assertTrue(consolePlugin.getLogRow(ctx).message() instanceof String message &&- message.contains("version"));- }-- @Test- public void testActionOpenProgram() throws Exception {- DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);-- createProgram();- intoProject(program);-- assertEquals(0, programManager.getAllOpenPrograms().length);-- DebuggerOpenProgramActionContext ctx =- new DebuggerOpenProgramActionContext(program.getDomainFile());- consolePlugin.log(DebuggerResources.ICON_MODULES, "Test resolution", ctx);- waitForSwing();-- LogRow<?> row = consolePlugin.getLogRow(ctx);- assertEquals(1, row.actions().size());- BoundAction boundAction = row.actions().get(0);- assertEquals(listingProvider.actionOpenProgram, boundAction.action);-- boundAction.perform();- waitForSwing();-- waitForPass(() -> assertEquals(1, programManager.getAllOpenPrograms().length));- assertTrue(java.util.List.of(programManager.getAllOpenPrograms()).contains(program));- // TODO: Test this independent of this particular action?- assertNull(consolePlugin.getLogRow(ctx));- }-protected Instruction placeGuestInstruction(int guestRangeLength) throws Throwable {try (Transaction tx = tb.startTransaction()) {tb.trace.getMemoryManager()diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/service/modules/DynamicStaticSynchronizationPluginTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/service/modules/DynamicStaticSynchronizationPluginTest.javanew file mode 100644index 0000000000..49254531bb--- /dev/null+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/app/plugin/core/debug/service/modules/DynamicStaticSynchronizationPluginTest.java@@ -0,0 +1,512 @@+/* ###+ * 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.service.modules;++import static org.junit.Assert.*;++import java.io.IOException;+import java.math.BigInteger;+import java.util.Set;++import org.junit.Before;+import org.junit.Test;++import db.Transaction;+import docking.widgets.EventTrigger;+import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin;+import ghidra.app.plugin.core.codebrowser.CodeViewerProvider;+import ghidra.app.plugin.core.debug.gui.AbstractGhidraHeadedDebuggerIntegrationTest;+import ghidra.app.plugin.core.debug.gui.DebuggerResources;+import ghidra.app.plugin.core.debug.gui.console.DebuggerConsolePlugin;+import ghidra.app.plugin.core.debug.gui.console.DebuggerConsoleProvider.BoundAction;+import ghidra.app.plugin.core.debug.gui.console.DebuggerConsoleProvider.LogRow;+import ghidra.app.plugin.core.debug.gui.listing.DebuggerListingPlugin;+import ghidra.app.plugin.core.debug.gui.listing.DebuggerListingProvider;+import ghidra.app.services.DebuggerStaticMappingService;+import ghidra.app.services.ProgramManager;+import ghidra.debug.api.modules.DebuggerMissingModuleActionContext;+import ghidra.debug.api.modules.DebuggerOpenProgramActionContext;+import ghidra.framework.model.*;+import ghidra.plugin.importer.ImporterPlugin;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Register;+import ghidra.program.model.lang.RegisterValue;+import ghidra.program.util.ProgramLocation;+import ghidra.program.util.ProgramSelection;+import ghidra.trace.database.memory.DBTraceMemoryManager;+import ghidra.trace.model.*;+import ghidra.trace.model.memory.TraceMemoryFlag;+import ghidra.trace.model.memory.TraceMemorySpace;+import ghidra.trace.model.modules.TraceModule;+import ghidra.trace.model.thread.TraceThread;+import ghidra.util.Swing;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.VersionException;+import ghidra.util.task.TaskMonitor;++public class DynamicStaticSynchronizationPluginTest+ extends AbstractGhidraHeadedDebuggerIntegrationTest {++ protected DynamicStaticSynchronizationPlugin syncPlugin;++ protected CodeBrowserPlugin codePlugin;+ protected CodeViewerProvider codeProvider;+ protected DebuggerListingPlugin listingPlugin;+ protected DebuggerListingProvider listingProvider;++ protected DebuggerStaticMappingService mappingService;++ @Before+ public void setUpStaticSyncPluginTest() throws Exception {+ syncPlugin = addPlugin(tool, DynamicStaticSynchronizationPlugin.class);++ // Do before listingPlugin, since types collide+ codePlugin = addPlugin(tool, CodeBrowserPlugin.class);+ codeProvider = waitForComponentProvider(CodeViewerProvider.class);++ listingPlugin = addPlugin(tool, DebuggerListingPlugin.class);+ listingProvider = waitForComponentProvider(DebuggerListingProvider.class);++ // TODO: If a task crashes, the test framework hangs.+ listingProvider.setAutoDisassemble(false);++ mappingService = tool.getService(DebuggerStaticMappingService.class);+ }++ protected void createMappedTraceAndProgram() throws Exception {+ createAndOpenTrace();+ createAndOpenProgramFromTrace();+ intoProject(tb.trace);+ intoProject(program);++ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();+ try (Transaction tx = program.openTransaction("Add block")) {+ program.getMemory()+ .createInitializedBlock(".text", ss.getAddress(0x00600000), 0x10000, (byte) 0,+ monitor, false);+ }+ try (Transaction tx = tb.startTransaction()) {+ DBTraceMemoryManager memory = tb.trace.getMemoryManager();+ memory.addRegion("exe:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0040ffff),+ TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);+ TraceLocation from =+ new DefaultTraceLocation(tb.trace, null, Lifespan.nowOn(0), tb.addr(0x00400000));+ ProgramLocation to = new ProgramLocation(program, ss.getAddress(0x00600000));+ DebuggerStaticMappingUtils.addMapping(from, to, 0x8000, false);+ }+ waitForProgram(program);+ waitForDomainObject(tb.trace);+ traceManager.activateTrace(tb.trace);+ waitForSwing();+ }++ @Test+ public void testSyncLocationsStaticToDynamicOnGoto() throws Exception {+ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ ProgramLocation loc;++ goTo(tool, program, ss.getAddress(0x00601234));+ waitForSwing();++ loc = listingProvider.getLocation();+ assertEquals(tb.trace.getProgramView(), loc.getProgram());+ assertEquals(tb.addr(0x00401234), loc.getAddress());++ // Check no sync when out of bounds+ goTo(tool, program, ss.getAddress(0x00608765));+ waitForSwing();++ loc = listingProvider.getLocation();+ assertEquals(tb.trace.getProgramView(), loc.getProgram());+ assertEquals(tb.addr(0x00401234), loc.getAddress());++ goTo(tool, program, ss.getAddress(0x00607fff));+ waitForSwing();++ loc = listingProvider.getLocation();+ assertEquals(tb.trace.getProgramView(), loc.getProgram());+ assertEquals(tb.addr(0x00407fff), loc.getAddress());+ }++ @Test+ public void testSyncLocationsDynamicToStaticOnSnapChange() throws Exception {+ createAndOpenTrace();+ createAndOpenProgramFromTrace();+ intoProject(tb.trace);+ intoProject(program);++ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();+ try (Transaction tx = program.openTransaction("Add block")) {+ program.getMemory()+ .createInitializedBlock(".text", ss.getAddress(0x00600000), 0x10000, (byte) 0,+ monitor, false);+ }+ TraceThread thread;+ try (Transaction tx = tb.startTransaction()) {+ DBTraceMemoryManager memory = tb.trace.getMemoryManager();+ memory.addRegion("exe:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0040ffff),+ TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);+ TraceLocation from =+ new DefaultTraceLocation(tb.trace, null, Lifespan.nowOn(0), tb.addr(0x00400000));+ ProgramLocation to = new ProgramLocation(program, ss.getAddress(0x00600000));+ DebuggerStaticMappingUtils.addMapping(from, to, 0x8000, false);++ thread = tb.getOrAddThread("Thread1", 0);+ Register pc = tb.trace.getBaseLanguage().getProgramCounter();+ TraceMemorySpace regs = memory.getMemoryRegisterSpace(thread, true);+ regs.setValue(1, new RegisterValue(pc, BigInteger.valueOf(0x00401234)));+ }+ waitForProgram(program);+ waitForDomainObject(tb.trace);+ traceManager.activateThread(thread);+ waitForSwing();++ traceManager.activateSnap(1);+ waitForSwing();++ // Sanity check+ ProgramLocation dynamicLoc = listingPlugin.getCurrentLocation();+ assertEquals(tb.trace.getProgramView(), dynamicLoc.getProgram());+ assertEquals(tb.addr(0x00401234), dynamicLoc.getAddress());++ ProgramLocation staticLoc = codePlugin.getCurrentLocation();+ assertEquals(program, staticLoc.getProgram());+ assertEquals(ss.getAddress(0x00601234), staticLoc.getAddress());+ }++ @Test+ public void testSyncLocationsDynamicToStaticOnLocationChange() throws Exception {+ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ listingProvider.getListingPanel()+ .setCursorPosition(+ new ProgramLocation(tb.trace.getProgramView(), tb.addr(0x00401234)),+ EventTrigger.GUI_ACTION);+ waitForSwing();++ ProgramLocation loc = codePlugin.getCurrentLocation();+ assertEquals(program, loc.getProgram());+ assertEquals(ss.getAddress(0x00601234), loc.getAddress());+ }++ @Test+ public void testSyncSelectionsDynamicToStaticOnSelectionChange()+ throws Exception {+ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ runSwing(() -> listingProvider.getListingPanel()+ .setSelection(new ProgramSelection(tb.addr(0x00401234), tb.addr(0x00404321)),+ EventTrigger.GUI_ACTION));+ waitForSwing();++ assertEquals(tb.set(tb.range(ss, 0x00601234, 0x00604321)),+ codePlugin.getCurrentSelection());+ }++ @Test+ public void testSyncSelectionsStaticToDynamicOnSelectionChange()+ throws Exception {+ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ runSwing(() -> codePlugin.getListingPanel()+ .setSelection(+ new ProgramSelection(tb.addr(ss, 0x00601234), tb.addr(ss, 0x00604321)),+ EventTrigger.GUI_ACTION));+ waitForSwing();++ assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());+ }++ @Test+ public void testActionSyncLocations() throws Exception {+ assertTrue(syncPlugin.actionSyncLocations.isEnabled());++ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ // Check default is on+ assertTrue(syncPlugin.actionSyncLocations.isSelected());+ goTo(tool, program, ss.getAddress(0x00601234));+ waitForSwing();+ assertEquals(tb.addr(0x00401234), listingProvider.getLocation().getAddress());++ performAction(syncPlugin.actionSyncLocations);+ assertFalse(syncPlugin.actionSyncLocations.isSelected());+ // NOTE: address must be mapped, or else we're not really testing action selection+ goTo(tool, program, ss.getAddress(0x00607654));+ waitForSwing();+ // Verify the goTo was effective, but no change to dynamic listing location+ assertEquals(ss.getAddress(0x00607654), codePlugin.getCurrentLocation().getAddress());+ assertEquals(tb.addr(0x00401234), listingProvider.getLocation().getAddress());++ syncPlugin.setSyncLocations(true);+ // NOTE: Toggling adjusts the dynamic listing, because last goTo was static+ waitForSwing();+ assertTrue(syncPlugin.actionSyncLocations.isSelected());+ assertEquals(ss.getAddress(0x00607654), codePlugin.getCurrentLocation().getAddress());+ assertEquals(tb.addr(0x00407654), listingProvider.getLocation().getAddress());+ }++ @Test+ public void testActionSyncSelections() throws Exception {+ assertTrue(syncPlugin.actionSyncSelections.isEnabled());++ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ // Check default is on+ assertTrue(syncPlugin.actionSyncSelections.isSelected());+ makeSelection(tool, program, tb.range(ss, 0x00601234, 0x00604321));+ goTo(tool, program, ss.getAddress(0x00601234));+ waitForSwing();+ assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());++ performAction(syncPlugin.actionSyncSelections);+ assertFalse(syncPlugin.actionSyncSelections.isSelected());+ goTo(tool, program, ss.getAddress(0x00608765));+ makeSelection(tool, program, tb.range(ss, 0x00605678, 0x00608765));+ waitForSwing();+ // Verify the makeSelection was effective, but no change to dynamic listing location+ assertEquals(tb.set(tb.range(ss, 0x00605678, 0x00608765)),+ codePlugin.getCurrentSelection());+ assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());++ syncPlugin.setSyncSelections(true);+ // NOTE: Toggling adjusts the dynamic listing, because last selection was static+ waitForSwing();+ assertTrue(syncPlugin.actionSyncSelections.isSelected());+ assertEquals(tb.set(tb.range(ss, 0x00605678, 0x00608765)),+ codePlugin.getCurrentSelection());+ // Part of range is not mapped+ assertEquals(tb.set(tb.range(0x00405678, 0x00407fff)), listingPlugin.getCurrentSelection());+ }++ @Test+ public void testActionTransferSelectionDynamicToStatic() throws Exception {+ syncPlugin.setSyncSelections(false);+ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ listingProvider.getListingPanel()+ .setSelection(new ProgramSelection(tb.set(tb.range(0x00401234, 0x00404321))),+ EventTrigger.GUI_ACTION);+ assertTrue(codePlugin.getCurrentSelection().isEmpty());++ performAction(syncPlugin.actionTransferSelectionDynamicToStatic, true);+ assertEquals(tb.set(tb.range(ss, 0x00601234, 0x00604321)),+ codePlugin.getCurrentSelection());+ }++ @Test+ public void testActionTransferSelectionStaticToDynamic() throws Exception {+ syncPlugin.setSyncSelections(false);+ createMappedTraceAndProgram();+ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();++ makeSelection(tool, program, tb.set(tb.range(ss, 0x00601234, 0x00604321)));+ assertTrue(listingPlugin.getCurrentSelection().isEmpty());++ performAction(syncPlugin.actionTransferSelectionStaticToDynamic, true);+ assertEquals(tb.set(tb.range(0x00401234, 0x00404321)), listingPlugin.getCurrentSelection());+ }++ @Test+ public void testSyncLocationsOpensModule() throws Exception {+ DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);++ createAndOpenTrace();+ createAndOpenProgramFromTrace();+ intoProject(tb.trace);+ intoProject(program);++ AddressSpace ss = program.getAddressFactory().getDefaultAddressSpace();+ try (Transaction tx = program.openTransaction("Add block")) {+ program.getMemory()+ .createInitializedBlock(".text", ss.getAddress(0x00600000), 0x10000, (byte) 0,+ monitor, false);+ }+ try (Transaction tx = tb.startTransaction()) {+ DBTraceMemoryManager memory = tb.trace.getMemoryManager();+ memory.addRegion("exe:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0040ffff),+ TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);+ TraceLocation from =+ new DefaultTraceLocation(tb.trace, null, Lifespan.nowOn(0), tb.addr(0x00400000));+ ProgramLocation to = new ProgramLocation(program, ss.getAddress(0x00600000));+ mappingService.addMapping(from, to, 0x8000, false);+ }+ waitForProgram(program);+ waitForDomainObject(tb.trace);++ programManager.closeAllPrograms(true);+ waitForPass(() -> assertEquals(0, programManager.getAllOpenPrograms().length));++ traceManager.activateTrace(tb.trace);+ waitForSwing();++ listingProvider.getListingPanel()+ .setCursorPosition(+ new ProgramLocation(tb.trace.getProgramView(), tb.addr(0x00401234)),+ EventTrigger.GUI_ACTION);+ waitForSwing();++ waitForPass(() -> assertEquals(1, programManager.getAllOpenPrograms().length));+ assertTrue(java.util.List.of(programManager.getAllOpenPrograms()).contains(program));++ assertFalse(consolePlugin+ .logContains(new DebuggerOpenProgramActionContext(program.getDomainFile())));+ }++ @Test+ public void testSyncLocationsLogsRecoverableProgram() throws Exception {+ DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);++ TestDummyDomainFolder root = new TestDummyDomainFolder(null, "root");+ DomainFile df = new TestDummyDomainFile(root, "dummyFile") {+ @Override+ public boolean canRecover() {+ return true;+ }+ };++ syncPlugin.doTryOpenProgram(df, DomainFile.DEFAULT_VERSION,+ ProgramManager.OPEN_CURRENT);+ waitForSwing();++ DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);+ waitForPass(() -> assertTrue(consolePlugin.logContains(ctx)));+ assertTrue(consolePlugin.getLogRow(ctx).message() instanceof String message &&+ message.contains("recovery"));+ }++ @Test+ public void testSyncLocationsLogsUpgradeableProgram() throws Exception {+ DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);++ TestDummyDomainFolder root = new TestDummyDomainFolder(null, "root");+ DomainFile df = new TestDummyDomainFile(root, "dummyFile") {+ @Override+ public boolean canRecover() {+ return false;+ }++ @Override+ public DomainObject getDomainObject(Object consumer, boolean okToUpgrade,+ boolean okToRecover, TaskMonitor monitor)+ throws VersionException, IOException, CancelledException {+ throw new VersionException();+ }+ };++ syncPlugin.doTryOpenProgram(df, DomainFile.DEFAULT_VERSION,+ ProgramManager.OPEN_CURRENT);+ waitForSwing();++ DebuggerOpenProgramActionContext ctx = new DebuggerOpenProgramActionContext(df);+ waitForPass(() -> assertTrue(consolePlugin.logContains(ctx)));+ assertTrue(consolePlugin.getLogRow(ctx).message() instanceof String message &&+ message.contains("version"));+ }++ @Test+ public void testPromptImportCurrentModuleWithSections() throws Exception {+ addPlugin(tool, ImporterPlugin.class);+ DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);++ createAndOpenTrace();+ try (Transaction tx = tb.startTransaction()) {+ tb.trace.getMemoryManager()+ .addRegion("bash:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0041ffff),+ Set.of(TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE));++ TraceModule bin = tb.trace.getModuleManager()+ .addLoadedModule("/bin/bash", "/bin/bash", tb.range(0x00400000, 0x0041ffff), 0);+ bin.addSection(0, "bash[.text]", tb.range(0x00400000, 0x0040ffff));+ }+ waitForDomainObject(tb.trace);+ traceManager.activateTrace(tb.trace);+ waitForSwing();+ Swing.runNow(() -> consolePlugin.clear());++ // In the module, but not in its section+ assertTrue(listingPlugin.goTo(tb.addr(0x00411234), true));+ waitForSwing();+ waitForPass(() -> assertEquals(0,+ consolePlugin.getRowCount(DebuggerMissingModuleActionContext.class)));++ assertTrue(listingPlugin.goTo(tb.addr(0x00401234), true));+ waitForSwing();+ waitForPass(() -> assertEquals(1,+ consolePlugin.getRowCount(DebuggerMissingModuleActionContext.class)));+ }++ @Test+ public void testPromptImportCurrentModuleWithoutSections() throws Exception {+ addPlugin(tool, ImporterPlugin.class);+ DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);++ createAndOpenTrace();+ try (Transaction tx = tb.startTransaction()) {+ tb.trace.getMemoryManager()+ .addRegion("bash:.text", Lifespan.nowOn(0), tb.range(0x00400000, 0x0041ffff),+ Set.of(TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE));++ tb.trace.getModuleManager()+ .addLoadedModule("/bin/bash", "/bin/bash", tb.range(0x00400000, 0x0041ffff), 0);+ }+ waitForDomainObject(tb.trace);+ traceManager.activateTrace(tb.trace);+ waitForSwing();++ // In the module, but not in its section+ assertTrue(listingPlugin.goTo(tb.addr(0x00411234), true));+ waitForSwing();+ waitForPass(() -> assertEquals(1,+ consolePlugin.getRowCount(DebuggerMissingModuleActionContext.class)));+ }++ @Test+ public void testActionOpenProgram() throws Exception {+ DebuggerConsolePlugin consolePlugin = addPlugin(tool, DebuggerConsolePlugin.class);++ createProgram();+ intoProject(program);++ assertEquals(0, programManager.getAllOpenPrograms().length);++ DebuggerOpenProgramActionContext ctx =+ new DebuggerOpenProgramActionContext(program.getDomainFile());+ consolePlugin.log(DebuggerResources.ICON_MODULES, "Test resolution", ctx);+ waitForSwing();++ LogRow<?> row = consolePlugin.getLogRow(ctx);+ assertEquals(1, row.actions().size());+ BoundAction boundAction = row.actions().get(0);+ assertEquals(syncPlugin.actionOpenProgram, boundAction.action);++ boundAction.perform();+ waitForSwing();++ waitForPass(() -> assertEquals(1, programManager.getAllOpenPrograms().length));+ assertTrue(java.util.List.of(programManager.getAllOpenPrograms()).contains(program));+ // TODO: Test this independent of this particular action?+ assertNull(consolePlugin.getLogRow(ctx));+ }+}