From cde1f2b4af71ac74e54f4bfeac186348a5ffcbf3 Mon Sep 17 00:00:00 2001 From: Brett Cherrington Date: Tue, 10 Nov 2026 15:48:29 +0000 Subject: [PATCH 01/76] chore(ENG-2785): stop sending advanced_analysis --- .../analysiscreation/RevEngAIAnalysisOptionsDialog.java | 5 ++--- .../ghidra/core/services/api/AnalysisOptionsBuilder.java | 9 --------- src/test/java/ai/reveng/AnalysisOptionsDialogTest.java | 1 - 3 files changed, 2 insertions(+), 13 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java index 79a3b39c..c03a0e8d 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java @@ -169,10 +169,9 @@ private void buildInterface() { var options = AnalysisOptionsBuilder.forProgram(program, function -> includedEntryPoints.contains(function.getEntryPoint())); - // Capability generation and advanced analysis are not offered by this dialog and are - // always off for analyses the plugin creates. + // Capability generation is not offered by this dialog and is always off for analyses + // the plugin creates. options.skipCapabilities(true); - options.advancedAnalysis(false); if (privateScope.isSelected() && privateScope.isEnabled()) { options.scope(AnalysisScope.PRIVATE); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java index 2fcde831..01b49edc 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java @@ -40,11 +40,6 @@ public AnalysisOptionsBuilder hash(TypedApiInterface.BinaryHash hash) { return this; } - public AnalysisOptionsBuilder advancedAnalysis(boolean advanced) { - options.put("advanced_analysis", advanced); - return this; - } - public AnalysisOptionsBuilder fileName(String name) { options.put("file_name", name); return this; @@ -171,10 +166,6 @@ public AnalysisCreateRequest toAnalysisCreateRequest() { analysisConfig.setGenerateCapabilities(!options.getBoolean("skip_capabilities")); } - if (options.has("advanced_analysis")) { - analysisConfig.setAdvancedAnalysis(options.getBoolean("advanced_analysis")); - } - request.setAnalysisConfig(analysisConfig); var binaryConfig = new ai.reveng.model.BinaryConfig(); diff --git a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java index af3c4fda..87ae690a 100644 --- a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java +++ b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java @@ -100,7 +100,6 @@ public void testSubmittedAnalysisConfig() throws Exception { var analysisConfig = request.getAnalysisConfig(); assertNotNull("The request must always carry an analysis config", analysisConfig); assertEquals("Capabilities are never generated", Boolean.FALSE, analysisConfig.getGenerateCapabilities()); - assertEquals("Advanced analysis is never requested", Boolean.FALSE, analysisConfig.getAdvancedAnalysis()); assertNull("Third-party scraping is never requested", analysisConfig.getScrapeThirdPartyConfig()); assertNull("Sandbox execution is never requested", analysisConfig.getSandboxConfig()); From 74f570a6b898992b9820de2d907899a29c197a2d Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:20:07 +0000 Subject: [PATCH 02/76] feat(ENG-4410): align plugin design with Ghidra themes and RevEng.AI design system (#218) --- data/reveng.theme.properties | 38 +++++++++++++++ .../aidecompiler/AIDecompilationdWindow.java | 3 +- .../RevEngAIAnalysisOptionsDialog.java | 20 ++++---- .../ui/components/ItemSelectionPanel.java | 9 ++-- .../dialog/RevEngDialogComponentProvider.java | 45 +++++------------- .../AbstractFunctionMatchingDialog.java | 35 +++++++------- .../functionmatching/AssemblyDiffPanel.java | 20 ++++++-- .../BinaryLevelFunctionMatchingDialog.java | 3 +- .../binarysimilarity/ui/help/HelpDialog.java | 5 +- .../ghidra/chat/ui/AgentChatWindow.java | 3 +- .../ghidra/plugins/ReaiPluginPackage.java | 6 +-- .../java/docking/wizard/WizardManager.java | 35 ++------------ src/main/resources/images/icon.png | Bin 12305 -> 22581 bytes src/main/resources/images/icon_50.png | Bin 2391 -> 0 bytes src/main/resources/images/icon_dark.png | Bin 0 -> 22557 bytes src/main/resources/images/reveng_16.png | Bin 540 -> 493 bytes src/main/resources/images/reveng_16_dark.png | Bin 0 -> 493 bytes src/main/resources/images/reveng_24.png | Bin 0 -> 871 bytes src/main/resources/images/reveng_24_dark.png | Bin 0 -> 861 bytes src/main/resources/images/reveng_32.png | Bin 1604 -> 0 bytes .../RevEngMockableHeadedIntegrationTest.java | 21 ++++++++ 21 files changed, 139 insertions(+), 104 deletions(-) create mode 100644 data/reveng.theme.properties delete mode 100644 src/main/resources/images/icon_50.png create mode 100644 src/main/resources/images/icon_dark.png create mode 100644 src/main/resources/images/reveng_16_dark.png create mode 100644 src/main/resources/images/reveng_24.png create mode 100644 src/main/resources/images/reveng_24_dark.png delete mode 100644 src/main/resources/images/reveng_32.png diff --git a/data/reveng.theme.properties b/data/reveng.theme.properties new file mode 100644 index 00000000..b3c52318 --- /dev/null +++ b/data/reveng.theme.properties @@ -0,0 +1,38 @@ +[Defaults] + +color.bg.reveng.tag = rgba(14,169,104,.08) +color.border.reveng.tag = rgba(14,169,104,.35) +color.border.reveng.title = [color]laf.color.Separator.foreground + +color.fg.reveng.similarity.critical = #b31d1d +color.fg.reveng.similarity.high = #ac3f09 +color.fg.reveng.similarity.medium = #985a04 +color.fg.reveng.similarity.low = #137236 + +color.bg.reveng.diff.deleted = rgba(201,55,55,.15) +color.bg.reveng.diff.inserted = rgba(14,169,104,.15) +color.bg.reveng.diff.changed = rgba(184,108,0,.15) +color.bg.reveng.diff.placeholder = rgba(7,9,13,.04) + +icon.reveng.mark.16 = images/reveng_16.png +icon.reveng.mark.24 = images/reveng_24.png +icon.reveng.mark.large = images/icon.png + +[Dark Defaults] + +color.bg.reveng.tag = rgba(92,240,163,.06) +color.border.reveng.tag = rgba(92,240,163,.3) + +color.fg.reveng.similarity.critical = #f26d6d +color.fg.reveng.similarity.high = #f08b3c +color.fg.reveng.similarity.medium = #f5c04a +color.fg.reveng.similarity.low = #47d17a + +color.bg.reveng.diff.deleted = rgba(255,107,107,.15) +color.bg.reveng.diff.inserted = rgba(92,240,163,.15) +color.bg.reveng.diff.changed = rgba(255,180,84,.15) +color.bg.reveng.diff.placeholder = rgba(255,255,255,.03) + +icon.reveng.mark.16 = images/reveng_16_dark.png +icon.reveng.mark.24 = images/reveng_24_dark.png +icon.reveng.mark.large = images/icon_dark.png diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java index c1cbc082..71313737 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java @@ -27,6 +27,7 @@ import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RTextScrollPane; +import generic.theme.Gui; import javax.swing.*; import javax.swing.text.BadLocationException; @@ -179,7 +180,7 @@ private JComponent buildComponent() { descriptionArea.setContentType("text/html"); descriptionArea.setEditable(false); descriptionArea.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); - descriptionArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + descriptionArea.setFont(Gui.getFont("font.monospaced")); descriptionArea.setText("No function selected or binary not analysed yet with RevEng.AI"); headerPanel.add(descriptionArea); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java index 79a3b39c..a0fe922e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java @@ -13,6 +13,7 @@ import ghidra.program.model.listing.Program; import ghidra.util.Msg; import ghidra.util.Swing; +import generic.theme.GThemeDefaults.Colors.Messages; import javax.annotation.Nullable; import javax.swing.*; @@ -73,13 +74,9 @@ private void buildInterface() { var workPanel = new JPanel(); workPanel.setLayout(new BoxLayout(workPanel, BoxLayout.Y_AXIS)); - // Create title panel - JPanel titlePanel = createTitlePanel("Create new analysis for this binary"); - workPanel.add(titlePanel, BorderLayout.NORTH); - // File size warning label (hidden by default) fileSizeWarningLabel = new JLabel(); - fileSizeWarningLabel.setForeground(Color.RED); + fileSizeWarningLabel.setForeground(Messages.ERROR); fileSizeWarningLabel.setHorizontalAlignment(SwingConstants.CENTER); fileSizeWarningLabel.setAlignmentX(Component.CENTER_ALIGNMENT); fileSizeWarningLabel.setVisible(false); @@ -143,16 +140,23 @@ private void buildInterface() { // Loading indicator (shown while fetching config) loadingLabel = new JLabel("Checking file size limits..."); - loadingLabel.setForeground(Color.GRAY); + loadingLabel.setForeground(Messages.HINT); loadingLabel.setHorizontalAlignment(SwingConstants.CENTER); loadingLabel.setAlignmentX(Component.CENTER_ALIGNMENT); loadingLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); workPanel.add(loadingLabel); + var optionsColumn = new JPanel(new BorderLayout()); + optionsColumn.add(workPanel, BorderLayout.NORTH); + var contentPanel = new JPanel(new BorderLayout(12, 0)); - contentPanel.add(workPanel, BorderLayout.WEST); + contentPanel.add(optionsColumn, BorderLayout.WEST); contentPanel.add(buildFunctionSelectionPanel(), BorderLayout.CENTER); - addWorkPanel(contentPanel); + + var rootPanel = new JPanel(new BorderLayout()); + rootPanel.add(createTitlePanel("Create new analysis for this binary"), BorderLayout.NORTH); + rootPanel.add(contentPanel, BorderLayout.CENTER); + addWorkPanel(rootPanel); addCancelButton(); addOKButton(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java index 67343ce8..835080ea 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java @@ -1,5 +1,6 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.components; +import generic.theme.GColor; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; @@ -107,7 +108,7 @@ private void addSelectedItem() { private void addItemTag(SelectableItem item) { JPanel tagPanel = new JPanel(new BorderLayout()); tagPanel.setBorder(createTagBorder()); - tagPanel.setBackground(new Color(230, 240, 250)); + tagPanel.setBackground(new GColor("color.bg.reveng.tag")); JLabel label = new JLabel(item.getName()); // Display name to user label.setBorder(BorderFactory.createEmptyBorder(2, 6, 2, 6)); @@ -116,8 +117,8 @@ private void addItemTag(SelectableItem item) { removeButton.setPreferredSize(new Dimension(20, 20)); removeButton.setFont(removeButton.getFont().deriveFont(Font.BOLD, 12f)); removeButton.setMargin(new Insets(0, 0, 0, 0)); - removeButton.setBackground(Color.WHITE); - removeButton.setBorder(BorderFactory.createRaisedBevelBorder()); + removeButton.setBorder(BorderFactory.createEmptyBorder()); + removeButton.setContentAreaFilled(false); removeButton.addActionListener(e -> removeItem(item, tagPanel)); tagPanel.add(label, BorderLayout.CENTER); @@ -130,7 +131,7 @@ private void addItemTag(SelectableItem item) { private Border createTagBorder() { return BorderFactory.createCompoundBorder( - BorderFactory.createRaisedBevelBorder(), + BorderFactory.createLineBorder(new GColor("color.border.reveng.tag")), BorderFactory.createEmptyBorder(2, 2, 2, 2) ); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java index b3da6e7d..ac7582cd 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java @@ -2,7 +2,8 @@ import docking.DialogComponentProvider; import docking.widgets.label.GDLabel; -import resources.ResourceManager; +import generic.theme.GColor; +import generic.theme.GIcon; import javax.swing.*; import java.awt.*; @@ -13,39 +14,19 @@ public RevEngDialogComponentProvider(String title, boolean isModal) { } protected JPanel createTitlePanel(String title) { - // Load icon from resources - Icon dialogIcon = null; - try { - dialogIcon = ResourceManager.loadImage("images/icon_50.png"); - } catch (Exception e) { - // If loading fails, fall back to no icon - } + return createTitlePanel(new GDLabel(title)); + } - // Create title label - JLabel titleLabel = new GDLabel(title); - // Make the title text bold - Font currentFont = titleLabel.getFont(); - titleLabel.setFont(currentFont.deriveFont(Font.BOLD)); + public static JPanel createTitlePanel(JLabel titleLabel) { + titleLabel.setIcon(new GIcon("icon.reveng.mark.24")); + titleLabel.setIconTextGap(8); + titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD)); JPanel titlePanel = new JPanel(new BorderLayout()); - titlePanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), - BorderFactory.createEmptyBorder(5, 5, 5, 5))); - - // Add icon to the left if available - if (dialogIcon != null) { - JLabel iconLabel = new JLabel(dialogIcon); - titlePanel.add(iconLabel, BorderLayout.WEST); - } - - // Create a centered panel for the title text - JPanel centerPanel = new JPanel(); - centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS)); - centerPanel.add(Box.createHorizontalGlue()); - centerPanel.add(titleLabel); - centerPanel.add(Box.createHorizontalGlue()); - - titlePanel.add(centerPanel, BorderLayout.CENTER); - + titlePanel.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(0, 0, 1, 0, new GColor("color.border.reveng.title")), + BorderFactory.createEmptyBorder(8, 12, 8, 12))); + titlePanel.add(titleLabel, BorderLayout.CENTER); return titlePanel; } -} \ No newline at end of file +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 8f31caa8..6a28b86f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -18,6 +18,8 @@ import ghidra.util.task.TaskMonitorComponent; import ghidra.util.Msg; import resources.ResourceManager; +import generic.theme.GThemeDefaults.Colors.Messages; +import generic.theme.GColor; import javax.swing.*; import javax.swing.table.DefaultTableModel; @@ -354,7 +356,7 @@ public Component getTableCellRendererComponent(JTable table, Object value, if (!isSelected) { // Set text color based on percentage value - c.setForeground(textColor); + c.setForeground(textColor != null ? textColor : table.getForeground()); // Keep default background color c.setBackground(table.getBackground()); } else { @@ -367,36 +369,37 @@ public Component getTableCellRendererComponent(JTable table, Object value, return c; } + private static final Color SIMILARITY_CRITICAL = new GColor("color.fg.reveng.similarity.critical"); + private static final Color SIMILARITY_HIGH = new GColor("color.fg.reveng.similarity.high"); + private static final Color SIMILARITY_MEDIUM = new GColor("color.fg.reveng.similarity.medium"); + private static final Color SIMILARITY_LOW = new GColor("color.fg.reveng.similarity.low"); + /** - * Get the text color based on percentage value + * Get the text color based on percentage value, or null for the table's default */ private Color getColorForPercentage(String percentageStr) { try { // Remove the % symbol and parse as double String numStr = percentageStr.replace("%", "").trim(); if (numStr.equals("N/A")) { - return Color.BLACK; // Default color for N/A values + return null; } double percentage = Double.parseDouble(numStr); - if (percentage >= 0 && percentage <= 1) { - return new Color(255, 0, 0); // Red - } else if (percentage > 1 && percentage <= 50) { - return new Color(128, 0, 128); // Purple + if (percentage >= 0 && percentage <= 50) { + return SIMILARITY_CRITICAL; } else if (percentage > 50 && percentage <= 70) { - return new Color(255, 165, 0); // Orange + return SIMILARITY_HIGH; } else if (percentage > 70 && percentage <= 90) { - return new Color(200, 140, 0); // Darker yellow for better visibility - } else if (percentage > 90 && percentage <= 95) { - return new Color(34, 139, 34); // Forest Green - } else if (percentage > 95 && percentage <= 100) { - return new Color(0, 100, 0); // Dark Green + return SIMILARITY_MEDIUM; + } else if (percentage > 90 && percentage <= 100) { + return SIMILARITY_LOW; } else { - return Color.BLACK; // Default for out-of-range values + return null; } } catch (NumberFormatException e) { - return Color.BLACK; // Default color for unparseable values + return null; } } } @@ -518,7 +521,7 @@ protected JComponent buildMainPanel() { errorArea.setLineWrap(true); errorArea.setWrapStyleWord(true); errorArea.setEditable(false); - errorArea.setBackground(Color.PINK); + errorArea.setForeground(Messages.ERROR); errorArea.setBorder(BorderFactory.createTitledBorder("Error Details")); errorScrollPane = new JScrollPane(errorArea); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java index e0551ba3..396f5cfb 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java @@ -8,13 +8,17 @@ import com.github.difflib.patch.AbstractDelta; import com.github.difflib.patch.DeltaType; import com.github.difflib.patch.Patch; +import generic.theme.GColor; +import generic.theme.Gui; import ghidra.util.Msg; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; +import org.fife.ui.rsyntaxtextarea.Theme; import org.fife.ui.rtextarea.RTextScrollPane; import javax.swing.*; import java.awt.*; +import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -25,10 +29,10 @@ public class AssemblyDiffPanel extends JPanel { private static final String PLACEHOLDER_TEXT = "Select a row to view assembly comparison"; // Diff highlighting colors - private static final Color DIFF_COLOR_CHANGED = new Color(255, 255, 180); // Light yellow - private static final Color DIFF_COLOR_DELETED = new Color(255, 200, 200); // Light red - private static final Color DIFF_COLOR_INSERTED = new Color(200, 255, 200); // Light green - private static final Color DIFF_COLOR_PLACEHOLDER = new Color(240, 240, 240); // Light gray + private static final Color DIFF_COLOR_CHANGED = new GColor("color.bg.reveng.diff.changed"); + private static final Color DIFF_COLOR_DELETED = new GColor("color.bg.reveng.diff.deleted"); + private static final Color DIFF_COLOR_INSERTED = new GColor("color.bg.reveng.diff.inserted"); + private static final Color DIFF_COLOR_PLACEHOLDER = new GColor("color.bg.reveng.diff.placeholder"); private final RSyntaxTextArea localAssemblyTextArea; private final RSyntaxTextArea matchedAssemblyTextArea; @@ -76,6 +80,14 @@ private RSyntaxTextArea createAssemblyTextArea() { textArea.setEditable(false); textArea.setLineWrap(false); textArea.setHighlightCurrentLine(false); + if (Gui.isDarkTheme()) { + try (var in = RSyntaxTextArea.class.getResourceAsStream("themes/dark.xml")) { + Theme.load(in).apply(textArea); + } catch (IOException e) { + Msg.warn(this, "Failed to load dark editor theme", e); + } + } + textArea.setFont(Gui.getFont("font.monospaced")); textArea.setText(PLACEHOLDER_TEXT); return textArea; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java index 9c7a2f94..0721b759 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java @@ -6,6 +6,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; import ghidra.framework.plugintool.PluginTool; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; +import generic.theme.Gui; import javax.swing.*; import java.awt.*; @@ -101,7 +102,7 @@ protected void configureTableColumns() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - c.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + c.setFont(Gui.getFont("font.monospaced")); return c; } }); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java index 6770829d..f12f5083 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java @@ -4,6 +4,7 @@ import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import docking.widgets.label.GLabel; import ghidra.framework.plugintool.PluginTool; +import generic.theme.GThemeDefaults.Colors.Messages; import javax.swing.*; @@ -248,7 +249,7 @@ private JPanel createMenuItem(String name, String description, Integer leftPaddi JLabel descLabel = new JLabel(htmlDescription); descLabel.setFont(descLabel.getFont().deriveFont(Font.ITALIC)); - descLabel.setForeground(Color.GRAY); + descLabel.setForeground(Messages.HINT); descLabel.setAlignmentX(Component.LEFT_ALIGNMENT); descLabel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); @@ -266,7 +267,7 @@ private JLabel createDescription(String text, Integer leftPadding) { JLabel label = new JLabel(htmlText); label.setFont(label.getFont().deriveFont(Font.ITALIC)); - label.setForeground(Color.GRAY); + label.setForeground(Messages.HINT); label.setAlignmentX(Component.LEFT_ALIGNMENT); label.setBorder(BorderFactory.createEmptyBorder(0, paddingLeft, 5, 0)); return label; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java index 74761531..4c72652a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java @@ -25,6 +25,7 @@ import ghidra.util.exception.InvalidInputException; import ghidra.util.task.Task; import ghidra.util.task.TaskMonitor; +import generic.theme.GThemeDefaults.Colors.Messages; import javax.swing.*; import javax.swing.text.AttributeSet; @@ -105,7 +106,7 @@ private JComponent buildComponent() { top.add(header, BorderLayout.NORTH); contextLabel = new JLabel("No analysis attached"); - contextLabel.setForeground(Color.GRAY); + contextLabel.setForeground(Messages.HINT); top.add(contextLabel, BorderLayout.CENTER); historyModel = new DefaultListModel<>(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java index d83404bb..54dda60f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java @@ -1,7 +1,7 @@ package ai.reveng.toolkit.ghidra.plugins; +import generic.theme.GIcon; import ghidra.framework.plugintool.util.PluginPackage; -import resources.ResourceManager; import javax.swing.*; import java.nio.file.Path; @@ -32,13 +32,13 @@ public class ReaiPluginPackage extends PluginPackage { @Deprecated public static final Integer INVALID_ANALYSIS_ID = -1; - public static final Icon REVENG_16 = ResourceManager.loadImage("images/reveng_16.png"); + public static final Icon REVENG_16 = new GIcon("icon.reveng.mark.16"); /** * Create a Top Level Plugin Package that uses the RevEng.AI logo */ public ReaiPluginPackage() { - super(NAME, ResourceManager.loadImage("images/icon.png"), "AI Assisted Binary Analysis"); + super(NAME, new GIcon("icon.reveng.mark.large"), "AI Assisted Binary Analysis"); } } \ No newline at end of file diff --git a/src/main/java/docking/wizard/WizardManager.java b/src/main/java/docking/wizard/WizardManager.java index e53edad3..b5640158 100644 --- a/src/main/java/docking/wizard/WizardManager.java +++ b/src/main/java/docking/wizard/WizardManager.java @@ -23,6 +23,7 @@ import javax.swing.*; import javax.swing.border.TitledBorder; +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; import docking.DockingWindowManager; import docking.ReusableDialogComponentProvider; import docking.widgets.EmptyBorderButton; @@ -33,7 +34,6 @@ import help.Help; import help.HelpService; import resources.Icons; -import resources.ResourceManager; /** * A dialog that controls the panels for going to "Next" and "Previous" in some @@ -221,41 +221,12 @@ public void componentResized(ComponentEvent e) { } }); - // Load custom icon from resources if wizardIcon is null - if (wizardIcon == null) { - try { - wizardIcon = ResourceManager.loadImage("images/icon_50.png"); - } catch (Exception e) { - // If loading fails, fall back to no icon - wizardIcon = null; - } - } - - // Create title label without icon - icon will be handled separately titleLabel = new GDLabel(INIT_TITLE); - // Make the title text bold - Font currentFont = titleLabel.getFont(); - titleLabel.setFont(currentFont.deriveFont(Font.BOLD)); - - JPanel titlePanel = new JPanel(new BorderLayout()); - titlePanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), - BorderFactory.createEmptyBorder(5, 5, 5, 5))); - - // Add icon to the left if available + JPanel titlePanel = RevEngDialogComponentProvider.createTitlePanel(titleLabel); if (wizardIcon != null) { - JLabel iconLabel = new JLabel(wizardIcon); - titlePanel.add(iconLabel, BorderLayout.WEST); + titleLabel.setIcon(wizardIcon); } - // Create a centered panel for the title text - JPanel centerPanel = new JPanel(); - centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS)); - centerPanel.add(Box.createHorizontalGlue()); - centerPanel.add(titleLabel); - centerPanel.add(Box.createHorizontalGlue()); - - titlePanel.add(centerPanel, BorderLayout.CENTER); - mainJPanel = new JPanel(new BorderLayout()); mainJPanel.add(titlePanel, BorderLayout.NORTH); mainJPanel.add(scrollPane, BorderLayout.CENTER); diff --git a/src/main/resources/images/icon.png b/src/main/resources/images/icon.png index ae04979a0d966d7ecb6c11c079c1ee05b15a151e..ade1fefbeeeee5cb1cabfdc958e077340f1abf15 100644 GIT binary patch literal 22581 zcmb??`6E={8~>f%*p1!TvSeQ(OUM$k?_mlVTf}53Yql9mmXKW}DtRZ{43Q;_eJN3j zQOOh~5ff!!zPHc!`zL&Vnz=LQoO{l5p8MSAdA(jI&ED3Gjai5p001@%a}!4ZfP!D4 z0231Y_!IqZ7yLklTiBSQezGug2&4PD*Ch)RqjS+8e$7VR6LFp$`aS-6_K)u* zxA+ad>!>AW+0N9YR4&fHM*TQL1jY4_1LcvqgHiuFC&Z|P2Lf5@G$z_(%+1e?Rs}bH z+nLvDx?A?CBX(`I?3DVouC?jquH3TO&b^MU*Y`F`ov@*mCm-DX(tYZ|%5&mxY86$J z+Cp`qUZUdg+N$Ew`R)Ur_%cJ?2|hg+m;&h=6@%we>{EpWFG)A4 z3e*kiHEI*p8n5rtQs3v?R=hi6{{=2aa$b*x#zJ%fEOZQKsxtG=Xe;l~X2m3tJsKH( zLc8U~Clv)j&LzrQv2^DZH@w!FkAM@IIg!<6gyW3Xne$V~XFv#G2it;i;759Lw>kdv zI9^o<*ahvi3WTBVQo={QbDnb-?$&24q%M#fy!z+Jqw)W~Af`+28 z(J(<=A`3c~s!OGDHPkCq8|r+1n}y{gYim7-?6rptC}HL}CK}dxw=1Bpommtbj9l%% zz@qcepwh%Jz1BL01`wbtw+b?1y~lO~cm5c&FvLTpLnR}VpKX?+i*BV!1AexDGKtmH zG}>%}&%*}m##(OOH)}vWbQQ^GmS~tp4bV>t~TDFo*@*%1~J7gHgEhynoJ0OwTNJqR0k>|RjC+GA#dvJBr4iRap zRPnaMpEL&~f~zF%7T%1o07mbv=mMU77-A2)+rm*%geE)V2~0!kzG&sc%|-i1`ye#K zMRiitgLKcpN%l|7`#`JAZszs;TL-p)x6Gb6U6MLYiP@8gZ^pDjx4AU^sxmN;k%wwp zXPk&CFd6)EQR<)fdh{ad&O3@mg(uo@<;EPat;q;G>1X=WAIb1g6#P-5|3u2LQObp{ zkobtS<^{WN`tt#-m9L{GL0OMh-bfz*UoYOE#@V^Qx>7fvLA5!8*l@z4=P=^uITcvU z@M8y_{d{WN)zAG&P2|hThI21_^`!v{_hBgAozN_wBju6CTiG1bgGL>FWcEjJO||lg7L&2$9g5p6)Ki+FX=T0l;-^d0fhX%l;cSR5 zZoT$PA2n`2N%-pV-pSEhW`BsHo2WFeplpqdgdZBK9>-6Fb-cO$t*?F_!_hz5Ye8M3 z99WyYok~@zHsIV=nb7|cuj}f;=TZRl+iuSjJ$*VH(pno&L@q{Pr+BKQ3^Du)EJJv| zFMA$C(iauHV$GlVl-5U_bK~3mfB;v-LH#a~6>*SmO5E~-*>~hRM4-$qODJ8_)%7s0 z9=?0KLW~iHp@yGVHfUya3nbyDMogOTz;9|crSpv`hFgvU1)CdcKV#bH%@lc2lvnhJ z68cFbCtZO49}Uwjaef1>xOWBG3^hM6eO-;wOrpqu0{Z*E* z+3_{UyUAm?Yt!P>4jF$Yt7#)DZ~05{>J`tL8y05MXx<64`MMMi$mef57jkrHtXK}< z39n(`rh`O>ZTbT3EEWAbS^9^IDtix~li-hkZFW>!R8!0wB>cWqnIP@bc&K6UNnGEC zURTL`QEHbQ{4L}ea3$c>*vSa*kutkw9l~vC$lNuN)P+$LX-s5jBBda&tbUF)JKQ_= zG*1}iKPAfVc>WZWP=(vnUXVl$N;=@!)X6=}Pfsf+T}`D0*X`!~rAgfMlrXWdntyX` zrt*%&H@Y_cI9(*m_&T390+$|~|MqRlm9>52^qu>2%))H70f~MPo1DA^wa@@dqi2wD zm`ZDcmfkb;;j9B8dF6Gt%hWRf z-LV%EE>dQGX7gAv=E)3z;m7V54Qk7Bxw4B3%yS+Gmc3a1OXYcQ@~k4`Pp~IGcUjy7 z^XzmFFs%xqas9d~JrE^66Y!yc5ZM1ZM}qwjgU*x|pbH%bV!fTjOwtMbNgcWoFmpj} z(yTk`SZ>m64~A&eTD~fgo5Du^u9Bmi;~VNm(9Ab~bA{u!qL*&fl`lF%IXtW;BlYK6 z6k3Fyf`7mX_Pu92>leX4@>gzqW{6uvSn|XkJ~w|SfN#P?Zh7|mahQ(I2><$}yeyO! znZ=XH3aPq*Ca$LT^Dje|JJ`>t`9n(%We#N_rA6i;e+_aJ1C9&)czhSYoI)M6QU85Il zsH)ROsg*Vb-P`79qKU@CLi^u$Fu-pINu4dfI*cXLfU!K>v_FdNi6RfjQYF7wL_52o z+GFk?p&~cTKjZ_cscSmK$o~z2CZ?udxY=)P37D9e=vBfEO-%kjT{PD8L;#NNmcYK# znVae6qCa#BOynSpao`*|b%9jxWRZ^nj!r&EGL_=6d~&-GzO=BOjRA7v1c)9D5^45O zdieuc239wEDanAF6jVV)uV>^;$`v5)_h?5G5mI<$c@xAU%B*!k==UO zov)5iI%!zKaQ=-B*rE|~fyEH>5KdLeo3JE;*P@mmq>q6EH_Gk4GF|u86KYjJJNVIy z?hR0H=x>lg2;~m(UPoCai+1IDSQADLagMwmy0Ij_r>l59gQf zSUkGf8{RL~w@&_D{xP5l-rd^~Y9E>dy~>SGT8>tG2yx@~5^p*6ma~E@h%1OGp$ZlN zyFe<)F$)S6mi2_l$(f(!Er^%Y9F8z&2ng$y;68qsNsDj!MO$oB)SjC7n5X+pNt3(c zeT2B9A~UxBNr@Be@s>)_Yj*rP!a>6 zp~O1c*~N`ZNS!|!dRK6c3?ze*LB-TVZfcg)j4t8P?@!-q-G1yhqkS*0a*iGQ59W`bmwq4Cs?Q0WxU9b zsndlnLbRae#s!I|u-cX z+b3c~(d{S^pAm-RHptlV?fL9PDZvGmiTGY?yh<3tSS-0g>Pw3$)rNlQc3_=W`hv^rp0-GTW zi=?X^=8LJVU=+`HkRQ>Xu0ujwNExISH}Tr z@BR^54#u8$3$xVl+KKE+EYJ2+7?C?q_O6?my3P95AH!457LIZNRbYa z_S8fqWZPf~H{$r#bBe8K6+>3!_bZi0Sx|j}gq)!b<3=O2p;13GsgE@8F(ehQDTL)_ z_$B!TZ=4%0vM@4#fexUuZ9JiZ^}Ysi8PVvB1*xc)DhBaz zcd>;x#s`~g%0Y(PXr_sJQ*-hICz#w6{|hqo=VRGbYqIOgZuU06+Iwxj>ERu3%Nr%%e9te{D`9bHr1@X^WwBhT1<)03???;FFr|&MjxsNk45dH+(xBE1F zIpM?f@7VbcCo-uhx$j?AC*ciIxLM_nr>xM_&x$RyoQS7ElrYN)qwaz3=C%>Z&{>)Q=A>q zT0Mp7@5{R92BH2wy8Vykuj<=U!B^|%!Hg8dhW3H0oBEpD(1KWNg*Hsluq)^54%nhb zI_Z9hAmpNBbJit{C<6($eHQ?!SW9X(b-<*M)deH&Uim#m{b$SdPzk8KA z^iFbjhZy7Xw93Wne-j9$OZ6souQG2&gA*RiZ`1C(sjnE|lr&+Z3`;D+9J*n>;*T=xJ)gZJh-*ei zbJRNjzKR#DRZ6}9LIOHxEpjdZ!t#0X4YzE*v_Y`cN28ukn-O5)ka7L<`+@t*+%%VG zxt?yYMIWDZ_G7eQp?4B=Y%@?<+dI%K8p^6!5#&03!ZJ7>UMjtAa%Q}nE$5fN^fVGM z!`EnCMD4S;a^TnkxfnMwM4od`{$R-+EsrSr??oIkZvPoa;xI8f6Ek}87rI#(w6;Bi zfWGR7f}{uyQ8ZYOB3ij|tg{A*(y)O?aPecOPd>`*o4RHo6qN9BIHJ~3b_kkSaaad@ z1jHf_zDk{tBym93K%Af+5{$f$y5KddW`j05l!N?uB(yt%^p*^bLVixpq<(Wn*4ewuY3+sa=IQDjae|EFd@Vx)iaq+R*c5`FD; z-|qcOtqHK7Pq;dwODOsWa#VI)`C%k2?vPZU%%k!my;-@FDPHBaBx3(KRS8#AuzeY= z*|&hEJJ3(jBj{J~r+R3lByG`cg((}ifcgtSinnCpV(y$4Xm)dTVYl0UdM(FyO=|BZ zN|ne<2NRNhaU|N7-CsL+vc5HIP8aE!_r*(-IXmu_V)yqn3uSAeI_{`XX1}Pb^~vTL zHGBY<#ndCJ7d7rlC$IR`Ed%COE+r!+M{S`9Wk+jWV6DDyV})hq>+V3R`N3t*iUkK$ zOVW&Y?M#>#v?6o>k{2M{J^-@iX*BKBU*s9Bj}WZmex+UIaZ5m|W(wbAatQmBGG=q%SXHL& ztVqvVvv(ar1<>-UgO%cKz6}9u4{z%x1_wAyKK$a=Rk}CbpC%GhBxSJpZNB0IsM zRGsvaJbqnX^NxK#3mcfGb@5cFsa#ITW-Ib&-d=LJOr~gN_wS_*-{z%+{ zC_E)V1a34B3Ofu5Ttsz|ei_a2iN2ax{FG`FvyYk5s91H7dy(>eY0~8ZP|mpN+$+j+wD)jNJb7cxnzb02a}<^{pQxkH_DqlLen z+@**&SCFhEZSw>N_^6X*K14`vaBn!zWX@U+R7{zB;IW;2f9*} zjPLOqR|l6)Mon~&CbBVLS1;}qrNweFlxp4R&eN2%cRh`mNbihylan-R!$zv&Z0U4* z#hLwSc!P>v(3I}w9zLljdoHoC!rmoARfZb z;Tu!oStrr(h+CV#buz+QgT}W!-{5+p0mCl^u6l1g~SNBrY~VsO(tOd{_o1S0Ie|80hK zOB=xYB3Hh}KGxS;#L$c2*uCgKGsy*Ii{3%*0hY}Rrn-#l#lXAvqZacYYdGjcfeBwH zRCfLpq1{K6kbLDYRtvyNPVi6P8E@v=t$o!>GyoPmvaBjCYl!Ei@$5TGeffkoY|!B| z-EQuLMdxo~v2}^ai&sUQcr_t|`KR=mX|){V&pEe6dUC(&#~)IrKc-}&+TKQ3OE}}0 zUnzUR?w;hd57dBd>$SWry}TAGl4qq(arkmx3xZ`ezucMgW`23{`QM|E{<8xaHr0oi zmLrmR;TY_DA=w(-_&4VDFEV+jKOD}o$rPhi_dm@)QU^49kmxDz zQ=x+QKOfxkZrIbHvjiLgBQ4YDDM-N3)Gxm3!9e;RHR21zljTtDzRX_Gpq67o=|?%5 zHu1tItlkUPOJzirM|UB)9_qxY(Ec@boP_w>(m9yN<1+c9;58#uC?aQuQ&8jasL$yo zDw3$2-HG~~-idOBELL1~Zd|&I)BU!HcqT>uv+6?dDR;4d;MoJCKB`atF>p4#9IXn_ zS_c=4)5P%FRuP4+}`Iy`1K$CKL{EaUL6p^A)A_cxvj`U@kax{_o;NqwBvHFpx z6q+^hL5~kcwJT*V1W_M#AaT{3Pg9g`Gfhf`-|t0UjdJ_Dd=Z>#{uZ{@j@$m5r^P~i zjA(R!gx+a^TT1TXR*Y@+W*f*oh~C1ksqgs}p*HMCsmsmFttRC5E|GQ_faAe;kMq+u z)NzWD=hOX~rgXwqwiZMevc@XfVgHep*ugZ)T*gr_@VV3gniwXM7aejUN4eT@L8=U` zx1^&pl0Qw+e|57SHu9iD?mP8^1`TQMc+-5Row-zh4>wnCQ#p5Ennr2z`+0Nr0^s5e zi#4G#?}~9<9-W%KxF)gohK1)^eCCXAN37(_i-@jdHXh!vFOd?9o^gu}iQKI0oNFGL zb?e9{>ubq;>1|Rg^KjUQaNBb-oBFfFE5cH_Estr%<;v1OB9rtp#(em?J5#O@8lmSV zw)#5ZFBkZRI|KF@B?EjJyNE#3oIj^62`!#45O`h&M-s&I>tl8TggXe-j${iKm~C)M&J5 z`pbK5CIY8bYA$r~@v9Fa9w0nC(f;)5fB6s3XKC0eLwVOD$VtOrEf5T0GBtuThOe#a z0?88^(w1fMB2=lRB)_~o#7N1k>Zk2;}JF&mVD zt||hJ|3auEq^dGG`;zWx(+1#=ILGLd2EC!@~z6aGy z7QOq#{Ape%^JRRipr`;ZeVgUIiJaxff+y0){QVGdFbu!s~CqH z)kGD?7p9r_(%pksx>hE*Ko%#gv=V0E;x1?qBlx=e-rT#eBIn4WG|l5qOx59$ z@9fP?ey-|U-4NFsp6A*rH8d#a&P`3lya|BfeI1Eid(d&DlTlZfv-o|(nRZ6P(Vx=u z@Is2m&o2&i)VULnYCwd4qLfUPTi&|EneCJasDh?6- zxI}Cfq!>I_wxFJpI4c~p7u#l=Wn*FPS~W2wZw-E2MHI>h;-goCq!~&CSI>&A8=cd9 zL>l)#+qS6DWYWTCy;>H-+-ByF!10F9XVMbACHz(tp46D`R&$vQZbO3Z*ox43T*kla*_jCzaT@1fp=>sV#R5)D<+2?494Z_lzXNs1a?9hhWD9K<% zR$pP$IZrSBT5;T=tK*w9`a^EDy}A4rW-OLKWn(Fc12TORwVPMGbqXT8ajP7q&wekH z`L-Soq8KG|!>llG{I{Bd{muL;=Y#LPHaG z*K*$Bc}qSNRJp9T2{W#)&s@!M4YK!Eo;}Tc4<1)GoaFxZNA7YIloN?@Qvj(47!A0& zv()A4`1t)o)Vb@Tb;rxmR5ijgO68-nICj2*T{otEVeJxHaL!+$Y^Nf4#Tol+#1MFo z=S}9E+9i{DjkoX4>T?qx2fS%`w$%Q|O<`&%QIT>wdRK?mklTJ7@FJer@*d-t@eblq z=om}EpyLi59b|S^tUOaRtgLi|CL)$DQMOc*RHj z$CFdD<|iSk-FM6-$k0}{R*_<;Fq1HP1zCGbBiW)c1@g!p_2sUfGQ5&&X-O!n{-s1L zOEkO#eW=Bdpuly<5YHVgfUhcwxlG|u6-2fbX^hxOUL|=@3Q3ppIi~M5Zx9q!-$rmcYFQDdNkhaA(jKu$P95>lRPbIP)PD8m*<6wfy^S6w z7kP|;B%lZ!1T+DD8+8^)_89QwgpsHCEygVsm&TmV)HF*ta>}8!21m6Wt&2(s>qpi^#Zh8w1%l)t1hkD)w>F)6J+`H9Q@mt)p4K<7vwR?Pj=m~YehkdvD9b+2hsv^U$1 z74VG7{(9ul;HjPZG`zU4=;*fIWV+Lmz}d*X_-v-HFP$2t_@SU- z%h{&0nbgfyDW{vqy(2A&|q z*|0v?s*wxlJH6!dYhA5PbN-%5)MK1as&%Ua(njX_Ud3c+@q16xWQcVj9(w2i4xxAQ zK$PW$*8Uj_;+=zQElit$ZJ3A&vU*t#VF|pYl&tVq^$|lJmI<0-crEJ9pmWD*dB*K; z{!H@7Ld?w+b_5PO6Kg%gubmN-0bM zO7+PM5{4MAc+9ioX(o_>yeA-Pj}d>XMG0C2=unU;Y*i!hl4%i~`on)O0;k?$^ro(X z?llPQ9&EuKN=|U``Cce@tBmr?{Vqw`AlkSO6^6YeUx}3V3WS&sITE^myby%#GjHp( z81q+50Xd)h>vPW1ed*rkc3kJLJTr~?-^L+SKSprIpA_C!4n3CBTNAT;QW`4Z*I%DO zp=J~3?mSWo7AZ|eLaP3)S%+BUfqKJ{Nn0T%0%lw@Gav$*DwoHz#^%m`&$JR@b6q2E zpS9$*Mkd63oQ1YOrPmPF$->~LJJQ`(&Y1eZ`u+WK>1b*-ZT&-x&{iJrcn3R`AKZ@( z=u~aNR<*$xO$UPVft6JG#7A1f`xX4;54~ttKX?M0S4BK+>)`jViQG`h2c&Aj9Ma3^ zx4b4h-fjBC`w>lC_xCiaDfKV)%#Vwz@`86Bf~1KUU=3r3Bipi041I^FkVdmkf?GQd zr3GpLUf3&-f=)Cd!#-cx78^om|wQ5e;T_VD~3x8eh(gLPrm=?Km)&>`Djvh$2sI{=GgXZdjN+1Z;1?O}`q1yJGsLn=B=mXWD57zII zcj_cPP`P)I1ka5+ijh5sw+Ac=KX$#29NhEthGApHEkUJBn)2PX-b+0%SlCvrdM)Xq z(?;7SXhUX+dEh>as6H#F5Sy?NsG#D2J@?_?W|gptmp{hIfBkN+4l9kd!-a$Ouq|}Xf zi;!g^GlP?Dmh!?srLjTZHQ&cb14|uf?aX~U)Jly5t)k~NaUAc&b*Vm%f&L+0^u98@3VUg>1C|eJ@Pwp zxNiocZa*)4ip5|7S-H`Tr{Qhfa`Y<5;-jtZ3uQEsGb~fysvK6x@9^vx+*`8j_T6u^ zLzX()=dV|2inp`qZSFH{Sk#GLFV^M&l>QAR$S+4UHg!66wv3~<>JwYv=a+A2C41cD z)vCYAi89_%yOPP}&PVZ)@rZ4-te{=q1>jRF#7!_XXqvQO0-GY}@+i=rXT*1N*Zgqx zN$a&#M5h|KG-{r}k))9|$!6G*<4hu;FwSr~#J z7;RBsaXTuSal}|YmNVyoD7R~XOt-T4nzh4h&R6o%JE&3aLy{6-X(}Xj!>FUnPJ=72 zJt;lG5)xe{F!%2|OrCO(&_&bmuNkRx%4XM&%0NeJ#BooHQ4Sy`CUNTAAI)pI-|ep@ zVSwis`y$^3fkKQ_^K=~&3%O_FYbpjndEZ@~BbI`3QX==EE``q?yi2_-Bvk5ZuL|Oj z{|ZS?A_13L5EGItpIDR+`1Zwv_25lc6O;56J%Sxim^GScOnJ2>@u{KpxI}JcB4qI) zDe-Q_O`@83qxM80m6w`T?}Op0ZW5%1(b|um?yDOr0W)eaZSLro5#kaO5zjcc)r`KW z%v8X|VcvHc-J}LD-Op*M3$yZsnT^C0RQOgo+uzT0BlI%=vL(f;ihOEPVK@4*7s z$3;MH$g#=_Z$@}i;X|H*N=RJB!Q46aIit0A*_;n|9>B$KjXpyPXDA(e(X>o6sbt(o zCZMfRg||@7zZbJH#C!6SLaOL(sZcf5nTR+EN9}7wD@vJ_XGQ`@r|SPB>eSMx?9~6r zMoA!JC?nCfr5VZ_dW?blgMGTaVe^ko#E>uyb~+C|0Ho5lO{AjuK$TuMO0@s%UX;VP z@wdOkOB)h&;qV;o;(A)U~Fh| zCWz=yRG@r6x|l?uzC^u%dFwS26$>(dU2^6>_;5QgG!fvu$XctG)Tv1#SYt8_N{dHONJhtEwovBcQ@ zTh2=?pfp2GUJ8a+M-9T9$cS5!y}8MmB#NvYr$ygYLfHLj^6b`q;6C&s@;mqPI7ju{ zB5i5lZH*`x04+hn)P{UYb2ikH@fS|Of3ZLL%f6B?i2Qxml;*LoSesN1d2vHyZTvrL zg9LNlE|9t;zN;;|0n{$z1zdKr5u5PWkh85>9#SY5h$m{bfAtT)7jJy5U3Vq3XW(PF z;m?Ofm3S;c{H^wMSo#9hk#1P4(yi#c>BwR8Pcf0oXUrPPd zco$Pw0B58Lm4-;X52V)LJu5MGSWvGejeP6+6MEiDy6Y zn~p)HFBPm&nd{FC7@$9HZVBMU(kXvKWTwPEq}NrpNUY;T^<0ogEyyEJk)1NlDVOlF z=KU{1UrXWlpsbMxmzGL?xtDP^?Q-&XLmF9jD&_hCC$%(h{Ru&w6Rf8HZNlKX9 z7a!lyxM;>kGA8wTDxX&=(j!wE-p~&!fDI{25^_&K*#);|>Y6q^p6ar&{Q9X#&9fqW zZ0R`cJM>yo;$llp^x&$J+Eyxmv3LP~bQkK;0}7 zNOj)r1B01xOY%1<{8dIVk1#e<8Y92ezT7W=v`ku}O41@GP16idES-@pR^vUw6U66+ zh{hv_vk5XSJU`y{p%RG*mNY@encX%KajxgbYS04-B#>W+XU)s{@4zsm#1b5ULCqPrlUq z)Z(Qh`Hv(bhjw^cm_`+Amty>y?ef3%%5BGic}KZi^AeeS$_^C2&&Bx4`-4ZQUUJm1IVzQ9oYFv*7 z-!`0a9xpjfK@>vl04<*=_Hpkts!p7&VLq^6%z-viC$nf0H<|EO`@&kP{M#a-MvNon zu6vTE58>keqdfL&kS@dv>{huyYN{wv62ufS=V$(o#49L*{p~nLs42Lu4`^E8-SdH0 ztX{&X9OR(RpfV=0@jSh29$w~b-iWsWAk;IGSUW%Q-6v}IIU@V~Z!tzE9!!Blz-pL_ zb{01T8S-gjjeDEajNE6%_W7Vr8@R56`KoO{b43{_UA{HHsqW6Y4{K$@zM2+2g76|i z=|$K%b7Uk`pUqm@pgg4W6FQEqRpq+DW@^QGO#;F!`%I;ME2BaySx5XdYFBXb zPWYDw@SXBI-vTZ~xtaI67s#1!DYkJb;E^y-i1Of-Z$}cE zG)6Sxy8ZJE5B?Y14`1zk&Qf})&Z`Y`8y@AydOIPy&3r%j8t{kZ-T?3WMD5_f0M?bA zc{cI^TdQ!iL5sHebg%f+?E!zk*GGKxY1&1s)}4m;@_RnAQ@o*~EqSsPQsOVcjL3c^ zX@(OUuyOuVoox$e2iXpCpM~S;SN`)gul_P*Lori+&p$=P$z2BYnfG(dtsdtR369V^ zCnzj_>U0b}nceuh;I>#T;$aP^(}0TO#gz}Z8-FtsvuH1Nl5|x`llFR(7OLQ%zfFW=GUKx_zDOP`8P5ja(gD9VvvzzK+0Z zRAW2G!*!&Gbf@d2=Kq4n-Nk#UH$z(=!Ks}Gl&-|0Lzp{n!h?>)9N&R@iWN!5V<^8d z8!!X2@+eC{IMw%sB)P0_P@C0Xqow7@5nOw2;c)Zj@k02vueQr(CITD_RPxn53e%kv zqkGX^rbBL|F4hk=Ad;vq%z8aw0S_9n(Y#8RZ~LSwHO$-hg9?h5xT|4C0(wS}uVpf|ve-c@07JTp*_K@eDp^SzP#(fb_lUQ75l_w;WyS7}3LH zh`ZR1{5!kyQv5XJ-4i$~LgQssz^R^gVbKqwG@T z!2qZgyW#Hw196y8-;pwiVa54Cv(#as4fAW2dT%Y@cFMea5jPBwHGE zzWR2YDuy-?!O0bPXy?kUi4+exo7X_fh?yqMO@C*nYJ>X%A|=-~rQF7>aGi%V@BR$LN;_RHu#|MYa73asRygXd@WjGxgsobzvpcy(-K<=$1WG zT!2Y-1azDGbt5iLfuehlHVEQ7wdO+)28eIpnW%2`I+6CyR}S| z@~i(rZeM);4-*6Q0zcTe`?3xrX|o=mSqCpR zN62dbo^q!XTXhC}oU<-9PVegq*gUs*$=RrdtmMn{K+$u4xufntU~jZj&;3Kc!+@;*(;X(8s0oL zQR)Dn<>0pagDsZgw~{&Pr{)3d0 zB+zNS6KNRWlO#=geB_egX0`5WC*S7WxUE zRL@!_7NLRICNGPtRf*uhXIboI8+*ltQ!3%#VG6^Wk>s_(L8$wZ&Yh%x2Pq=dSWCx3 zii=j1z6-R{g??FON`dgCXS-!Vja0|p7_r*m>$Al1e{NW#s@T!;9V zLL#2mWCGPHY`Axz1TWb3D=XH5QW!Zq5CI^XP8R~^Q6RIK2l1^bXy;ZKcS{~hANKJJ zt>u=V_BpTMr0(FbX}`qL?=o1zN=We=Eyc&yWcO*#2&On+gpoBWo5Fi<2qg(L3Amj@ zF=FU17=}}}G`-Y&J=}O0BC&Xu8-xeWO`q_ym&qAD>7zq|KhA8n z0P!lI81@4BLRjx2>bsYc(DHDv#zHNk;>_c@8*C{vTr?Q=UJIfn|7U2UC+WKfT3e(Q zQT#=x7)m2~vjVI(JxG{-HQ&PoU4g#`u5S&yhQ`9Z(|Yvi()2LJm;~YCn`6w&E~xhQ zLPtAb^xS?XuBXu;(qRQuV3u$%5Asoqz=JM98}K-z)9(;?98kK~uHHU5{_p|yInj)Gw?26!Z+NE*p?Rk|V3V4=^&CV!`6+4) zfPM`GgBFi_|E2GNSU@)_yGXp#M4Y0#3YH8~bV=Hi=_{CcXGfJHpu7j!@r1X6IcMWA zobEpTTM922D%BHiSjOF%agTf1r!MfrAG6WB=zYXCHwD{JS>I%`E8|m;sLrsUpQR5y zSs%~iCS|91E=1VY!(bHMP6?r`I>BSkshPV+%un|pH;xfQd?LQ_6Hk26D*4aOs&cE@0f?QKocPQ zFzp-Wr#;rzp9iB270GX?S`-NTt-Kz@t;)bWN?~alh<4^2P@3h_1I-9rSm_(Q{hy0G zNKJ1pSvqziYlZK!gZk%m?2|PO*CMz$--IpBU~q=VAHp-&i47_dVv_&!GVO&-GI6Ut zOUCQb1mD~DCBQzsl>NA4jRS7_O*rAg3Hxqk(my&gX&cZS{>F6jaYKMUj6M?0!96`cY<>6!RC_zeW&FO^HmXaToHYBaIvF%I7rN>Ht{uVp2R)+f?vNh)#l5G zDewqKv=~CUza2^Z(9rW#VU@-m!nDu6Eq0PN?)sm1&8!BIIdLVJHl+W1o)H(;Fx+M! zT-q2B`cI~ETnv6_?z`flY4KhIs7Af9iZe6#p7XGyEX-{r%>H2#Notn9CAkvNM z2?p+^G&A!aZm2XJj+`S*c!Ee^e-O%R@yl>v;)5Z$cw}xl^4`iWujTPyslV{=n<2J2 z3M5*PZh`swJcWbnya@S8dE!b08=#*(8&kKaqsc|Ee(j1zN^V7pxCm4E_XZ@%-{QfA zM&w>@B43(Nc!bJ$=0{j*r(r*mjc<0hiMg?bv-2!pyA`3o=RgxE9{;jP;~1&`Mw2*q z#4q|JT*+n9vzdz#e{RQW?YIxj#K3GqnDu5SRu~q?;e6;2>jnGrw0&3!LWQl;;ss!uaN${TR-V6$H`RShme~ z&`?%}==2+_)n9;n3U7tSy!rZ7SAmRcD)i@1)*A-(X(h+7H&E-0yF=atfE`ued&#hR zz39bE+3?lbFi;aEA#;SI>k#sr%uk0ypL@d=S2GhNYobypqj)hwC#+m^ulm+9aok(o zgh)vE?3bH|rtx%-S9sV;&)x5-`tdqtb=vbWA5oI>%Bb?95Yd=?`Py7BGfq6#2R7P& zO?zskVYEBa%*)59{j8M#Qj;>b9U82_mXCCv?n@uFz_OIKGV4M0N(!H=4-7EPy(-oc z_@0ecOHx)|mV&|J=Y_XT}O#xB7!m(GMbykvk5v9r^+TB~CFoTkelT zaj~-nRsj1ThUir2YOZl5rHU#*De(TCdyeh#E;}E)tqNa zkX5SfJ6)2N`~f~uKApLsM}Tm zhTZoa0^cV|$GUozZ!H_fmK~i{*DOkms{J~La{Kz?fq|WTuCXUP0Rhf$?WzzZ$-bbw zb?Qc)cq^~w(XJBRl%Vr6gO=a8NYbJ__MblY`yPw}splq+Q3`&3Mz6qcM;#=cp1M88 zqm7AX!`6nYFti!+WKNvXxP=kABSS39#_OU=v~_QLSPQ5Y4tw&Jzgr|JVxs{XkoxH$ z7WrJ~4f>l2dOP%58t{jhbxl0wAfF1Fv%=lA_*kH>rG?Dc+~vvYmEUe71PgJM8l zV;d%UsLKYu7FnmTy?Hw-X+BC7J35Og@h9r#e|t@Ah1g{JL@HCtkUKJ#zGl9{G$Pyh zHoizo*cq!A1=p(1tgA=PO?(z`fLT4Qrq&AZG{Ldp{x|macdXGd8! z3*UDuovC=+4zj#^nAh`|qVo1sme(Qf4)U<|wwHLAEXFidFmpF`F7T&*+M@q%{HmrS zq|FA_U5NAT3WxhC| zl~Rjjy7c?3%_*^AY9}g8<*@vmB%5Pg;VjB&!sxf4A-u*pVW2*NF1S;hljPrbnRs@5 zT8eFmIudt#B$D_wOq%Eye#Xx)VuYEW+cEpRlzp*QWI87V9Hee?Bs?}wI0B4k#%}q? zqe~y8DjKCzkW4{#P>{^iSlE?zicOU}FHF*73iK33gYiB*8dAs1_tER}@fsMfperBvP~0c2X|=}XBY32uHc@opi=M(s#HsTNxBU;QM62)(!wu@RStxeV z=8usCqn-dG|8w^;t^msAZ$*?O`Dbt0|XO zST+C)T=_^Oe%(Ww-}xT$CJlt%f-7rg1vt4St;DSDHYRoJXK>DbA+WOAa>Lp7Fs!1O zSlO5i$!O_@J=?n!|Nc!LAij5M{ToOA%CI!S#xsOHdrJ%6TwKNk2wt%Z^F|k5QBB-; zt^-p?s`7W6Ns5=1lV1&Foww6$&Ok3#xJg|3r0KxhlwI9Ul~QzHb9i?NN75_yC(N`L z2^ETNv_*N*Oq^X4AjBXX7x05iM>X5J($>B}-FdE^&oTMXTPOx9c0ays0t0MTn-X62 zn7;gIrmdW)3GY^>O@b{;PRtX*Zc-LHvYa0FO7 ze4BnFSXsqaW)aKT#=!$y-IB zkjx-&TdYAsr<-}Xclni{!h4OjH};-GBxL;L;xJ2lxZ!AXKB7*c(%(}k`n`|b7J^v| zaE}WN6z{U{Kk*rmOh}DokCfGT+`0Q2VVvImhHJs`gi+cXISZj>AWd+6G zNsg;~X@q52a{R?_tu(d*6Gwn*{@T^{t7Y&r?r_5QD3W%ue~*S$4xBaIx|sck4T@Nx zT%dTc_NQMk=&fHUhRZqk4_zJ29#?M{jHDprkW%Luv0B7K(xR6Go=bb7%1``4;)2=MT3g}6fgx4$+}T1TAQVa zVs;pG765>TeIj1gd{)Zyodw?5*-ZuXMwT%kSzAy|l5tGyGAX7_=COO0motm?p-+iW zE{lsA-gGbn(V3QlvM@Qqz8p2-A>N!rfW%sn6ruHRkG#lfQBulbD&Q!)xKLr2fviYz z6m(-=B>afNy}3OcS(a9pUkF((IT82)D8EcGK9()w(G;#9zhgs2W^LGrphkYaKlvm6 z0;W9U4^^2{a~cjST^)h(Xv_tkLa6w7*H5Nb?{MqCxfn>|XL4QaQk!|XpU?S{_KOk# zo2BpklxtZs3rO%^C7zWz^t~6-+_Qt8%N!mHV2>T7-91jR@di}j5=1cvo6R)UE2@~R zhACFBWF79lKVkbQ&QdjQyFTCHATaPP43w6QAT*U58u`6AL;=c9b=KyS&VPkSPAJRL z7OROXx;Ula<%B5#%=#kc0{DAhypVWq zx`BOV@@ks?Efr^^^-$SitJqw(&w}|N556J(Y27Hh%lwzYNyJ3XeTn!@fx$JJmwE{KD9MriX;h4yyY@$h^ zvEEl#8esODSGdSn+|>|jIa0TrnuuK8c{&BR)SD4MgiQzWwR`$O$BLVNAi8n=Ibz3C%|whE~;zty-Gu@&tBUuIjAN}0LoBu8cJ2O#;N z+-OW5g+GR)0Q0JH!*72r(T=HgG$zaT%swE%@W`Ez$d_fdbBWSwd=Z95#|wB%@}r^* zf7+JKJDKhq!>T>%$9Yn|q*t`Oo?`c(RysCFvTdEIU}4&gM{~gkdJcV4x}lFbC&Ufp zbTFH%{UoWiK!n1-BbbywDn#+@NM>~D9rryy3coCDsH9q zI8c5NtAd4fz}<( zKsQi^(7cSLC7G6AnHkNUqMR^}GU+l?pMCJ4FDob+s7SE?g>jSsyjTF=kn`+b3G;1i zT63AtjccY3k=>a$m_L~#grvy5AOWRPG@E=F%mfAq&S#3`M5?#f%{1?iHFc(^JHM&V zFt0v{4HpVmp@YMDlMGvG$F%Xt?J48zm;Y7wuWX-Pya$`z`Ye5?8ryPw<9q;yBFahO z%*PQ!h(1Jfq6!fMf)}5W$7IOLPCyRhUjbrcWmIqd!D#eQZtIR%$yj7T|1u&v*Ziu^ z@8=c$bKZ+)8Om@q#w)5~$B;Ndj4k4Th=$-_W0LyVyV{}pybruW6t>|J!s7Dc&boJD za@rz0lJ)l+zz;FHis7DJ(E@nwP>H(TJ)TT2q9Q&eR931k)V*{x282cNB)cyk*y>(=nlDR8?JtEQokS6cA&AIVO0%Z-9xXMW+~ja^2R&{(*ix|6o|x+ zHI=?wd5{uzI?aqfc;%_J;iU_c}ZFz$o#}=3Gh$0?QHC{O3&V$wAp$RHZOtt8@ znaBE*@!{zy-85yPqs_Po_?uG!71M5itm540kw;Tbsn;glmBOT|_Y%GB3RPhstwH=P z0B>l9?g-w|HY_b3q;-@82J&!ueMKp@%jKm`n8%Xu z%)zjH>Wl<^t&*3hhq6%qy>rWM-v8{rAELf2$8w$jQYBbDb9@^e5Uly^{%e_&m=|JT| zNlF#8B*Y!_E#j7)&FVdnbnn$Fc3^6fe=N;bWT(ZqhwzcxR82{83^ee*N19#~YvzaL}T0dY7`U@s>!Anmy#DO$8YbCfJ#0a5b=X(ePV!zA<BRIAO+EnEEW+#d0t2qFm_Ypa3PTlzea zPH8cJ9w*Q&sO|Tr^pl5PX;tAW&D~zg0HPq+Zb(6QE}dQ-H6Tk>f0eL1>VV9fGZvw4 z*MOcmRNwC7uZhQ7y_7-Oml?Tj=*Z+v7z@8GtUvnCt`O5=Yi(Q5r(0 zwxoD6PH91P`<|AKWvcY9X?`=CHHJ{PH@m`4wFw?h-##47*}v5iGpIT^kl2cNz;!#M zA?O4Nr6!~)9EbviSa+w$P*@;Ol9q&HqHrY6KigP+X(b#xb)@*dzysX0>0MT?ToG;r zQf}i{@pKS)P1EQxgGpxq#Hu}gVj*814PQuaq= zSGzVeR{n_4ZQnRVtmwadt?7(H$r{K?<4qf7%fBgCiJ>rUq1Bq{GAm4^*~uU7m+A$d zOCOQS9($2Xq=)1|B4Gx;Dy_DC?_gnIOC9f2U|)w&ADn$1miqB@C=7xZ-9 zl3?EN`L1^3pYzaO6UK^EL=zbuDNwxKXlk@w2TsMF5ZOQj?INJ0HA)evP8Ki!I|TXY zV7+5A-4g|2x(CHr?92H?`3;0j8Ws%0!6I$-BSM3j$-sZ{* z=H-r9byM*i-)HAD_jT`+CQWU8%;;1)jf;5~q2tK>3lN&lS{Rn!CaI zYiO-h$9&a?<5T@mYU(kLd5)Z2+?ZH?Y9@8Ep1r!4YTB5uGwm6P1Nd2je)xf${b}Qa zd}s_Hlts+#=41kwr>+_iu%85n&!yT+C45mNzL+kvUZ2Eqj=#)rw0a_C64B7(TcQ*lK-Fz;2mREYpccMR(`N5(Ba4A*u1TG86ZH_+7 z0MKy>UyVvZU}Y~L@jqH6!7XR=Rd@L)d_tn|99H(}wh&~qfoboti)=rXMJ0bavF{0i zX2$YWXjT~O5@b!yo|(PKbB{G@Q9<(;C^cG-G+9W?0j0zIlV-q za--GJWsUXVhbEbAr!*38HoHD}EhY?lK+yEhh3f3Jq6;;UdrWB*#?C<&-u;vK9MyYV=Z!aKUY`%leeOx+czyB%P1xU9iS&&Oqynw+&beo!SX>0 zZdi_Xb%0F{jB9hmw9s!=?Y^bPzfykf<%V(&V;8EyRXFEm*CFx>(cti0q(Z^=E;B-6 zqWi)|+`t3^(sg(7_vr<{m6+va+oS4G%~y|Vo50InX`PT(lVri2I$j8NHrzZC5o(10 zG%la?KE9a$?Q|=K>@riLBz9SFRWBHQ>tj{h_Z7bBYJG@-JwUgG7{BPy5CKC;!)-fe zj1RmmvSFmGR^tetlztpj9Ku1#PphDDzNi5C^eBn6#S*j};gUq%n1B5~4FJeGcip~v zi1HVG9y-_FDFSdX&ANAM0)*DY+)LS4qZ}X*L3uj*(1F3Kr9|y;Ly$P;LnKDbWsmym-N85BJgO78KUy+Uk@55K^dE6gVRyqRF}PDF zhH~F-!~5+GQPQ<3Pl_5N3YPBXsZr@9kQuPz#cNhw@wcoaC-RV!Q%3p?rONOg(cQO7QLXjksj7_=k^JGo%a#@2NAoTT-_FnrAy@q z&s;Cskn>##(vQH$7g?wc*|cu|Bz@^XPFr`U(+^e>zcr<3@@Mv4$Lto{05gy^{LN2y z=%g`{Z5Zp=NlQW!e0#4))r)qXmYrh^5)yfG>?6Go+rA1^UZ1(nPwKLkkdUx@&xfB^ XXb5mrF46@$zz{oYC#&j%#H9ZN(VfHhS>+JxUZ1gSbzsZ!%R3<#6!=b1f&^x(h1Z%fwcpD7*?a5gh7xZj2t z@&t~gRjE<#5W9!m92{+q@`(hPX4;$1q-2wx*V)~iTY3mc1`qNLLPT3WME2ZT-QK*` zI~Kie2J!U`V&wlcU2vOU2GO{FW5SsxLq%`aq#SRDD*Qft!=aD5Yv~jVHKHhL_?T2f zU-{mA8|w)=;!0u4tRy!3ypOG*6RHjIY)J8S&$9i^_vPar-_)Z%mBTKr(q4VH!va=$ z$eEV>+p#m$&zUadRo(g4v*p%Egq6{TGQ{5WbaDGtZ26SfMQo@_3};^?t)SXD*NV*1 z_4n5I|J8}e+P6s;q1m7O*i;OnXHyTdV1Jfi}zmdaEKke%&mVlMhw;|=!4U2hbN&#5)u{V!*?Rsfy6(dGJa}@2=`$?02x^Mj@pY;dLi`MV0 zU7s|CgliWTTdPip*KKXH3_?8KtrBi5p7SSBQ1UgZv`;Rs5ZX^HYPnkdO5}xaxwYFx zGx9Yj6`1t=p}Oa|XE#I_ZfjQ>WS!e8^<-+DD7(gnAfE5h++ITmnz8GH$B=rUpHHFp zyRO6}=}zh$bZo7kH&<6@RpQ^~T=`5U<}9im^u1jcX{n-CDgSTGV&an4*t*8~z)-PT zKXixM?!t?trdZU{_^F|R9dr42c zZ1rMD)M#5k9x70RXDInl%*KV~vJd)`KP@Wl$r~#z%HZbH(K6rCs*a5MI&VB^sicm> z-@zvH7@m90NWt51-!Xx>#P;584MeuzmqhN_+W-W6Hoa1U@+{3(*m>5kuh+JXj}ftD zu#%Qi2tg{FiWFMU%4m0#Az?6kc-8dl!d_dkPe+|!sd=xcm%HF9i&;ybn>>pd6=p7? zo;?VG&vsUoKwa?AZW>kg$b`B5C41v8Hx zi_-0t#F98D7IKix&zkf?@#2Cbn_`8kR_=))dh4qS`&;GAiQ`5v^&Xc z4JAba$>DB34$6hOJ*}YOtm>;c7xudj-3q);NZ{UpSJM)T1%@dcpLtPJaCu1<2l)bf zL+j*1Mmn6u3ulBD&dj@#IR1mk;b-~259;EMBNTKeoF`DlN0GDLK}vp>E9AH{6iU3X z_n!q6N{y5Rfz&B6AkgC%g#@4+!vEh!M|43j9tdy+!8r1=9R&J_FV6yM^6Z31x&p5F zywi<@|Bp+KIS)ahgp?RZwyCgv!7#cRDhy~WPNQ7Pg=1<`E}tAk!ZtOz&woM+LOvGY zg*3dTLzP=t8O8p^TX{J3-vz7rFZ};gOp>JJmuE4e!d&PT5v=^XBq;&IuN_1}J;oD> z{wtyv34X%6?FqgD<+){iu!)t?@%PU39~SDZht-UE!DKW2P0Mku^dG*7?HzZoSXbM4 zn?GKB8nXx^G@fp`X$Dyl)3Qy$bMen?Gg77tf^PM#jD|xjo->-!oKkE=F5@&Hn%l%x z7wpsXv-Yl5s;k15L|3BcSw9)&EyWl=yfVAf5pnw+viBB(`|`0NsUuq;W^rh7P|?ar zfn=|3{b1vxpJAQ~*$gG7Y22j2^O5X(BG+Sinf(F#-C0?Z=nLb!Z$K%LE)Lw z%bF%Bt#lNjmEr1^?56cfs|*p6^A#_pg+^QKj~0iYFK5kfu|TCN!*pjIzg*k_f825k z{`h-A?IZ4jZI9(rt3g>D_)f6~?^dTO6mo{n4rW_Q?b1tpi$;d?Dk@^rSl42lSPC9a zourL@BpMw`Zl7#`7Pb^LBU1`8ofvV0Dzjj?k_}(0>b0cePd>2>XG}cMRnF$UsxOEB zDPAmLxxjc;o~v14uxDr{&j55J zrT5_!-Nyn1V_1U{!wxk%kYcd2b8(U^0Y-_D973NOuoqjW%&O-!3$K^LnPYSlG7Qvx znzyNxD#d!nRz_ZmNw02;6QUqO3@Qcs6Wr*#T2@RN6;};wW~-D)L|)!&TV~4wVN%KKJ$X@Z0(qyVBeh@6VYQ9;b>&ih@u2DA8&pW!rF` z3X+8=#1_XD+Z4wH*oSe(=Pmg4tON-Sx!o3|Gd>f1qAGGa#WgnRy|8}PbhQw>712c~ z6)F0fLmrCnPV?+i9h?}kFlGYKvw+v==WlxeKqa|#wEzG~sTWG)@#+g4!U~3M78G7CkHX?%t=?5NsaI+9 zDNR!=H?lSLnQ4bjdPP!Puh=FHCEtjNn}~W>59t=iZY zYnLscRw3@0c<@&)DeJqiDg3DRkV}B~XfP<*Ho+Np|21ov?9JZs?X~9hL(r#7S-@?N z0rQV_!?)|opnr9b5g~$lKzw7p|RMLt)?76WsJ9enPz_; zQ5Q-;i2*N^5#lmMPAOcQ(rpDo+e+7GWE>BM_>|0PTXXGx4n7lIqL9a({Ng*;G>@Ad zP@M8UmljwP<~qiEQOF^3qW|^xlNt}(#JG$0kh@Y0Vi0x1lBdg&+g|k-UTJ=Djl9TK=+ehO2*FxSBr0}PgCTDnwugNjy^=N*{)mKSLo|yZ)C}%6Mb?1RNa>UX+UeQ8@`7cd7Gd(orn!)g+^BVx!C@h67 z+T383#=rK>U1}Lu5bQ@|{mzWk;gI=G>SrX*_s{(UxB2~5Ecfi@-#$QZ2C_pLGUSMp zObW=eHDR}#-_UUi&?o9WN0-lprHmpC7VArnzbcJ05ni3A4=mjKarLy7BvcY9X;ISr zhggW2nLSM820 z5cF>*mGW6-w(S)BS$-e^c+I-nZ*q%C5 z^@HT3)$%wnmNsOD{!>M$TzXb@2G(zGUr#}7hyPgyrG`Sgx5dIwe?(D{m|dn%FYb3G zk=a6xd03^-ba%2Hpq@tHkn=1XL?O z=LcOCXV`|N3)ieI!#`)5uXc^Bl1I?SM=q}YUF0;Il;J6;5r2ky>o@bkFO0VXOf6k5 zuJO=_rMPHsw1sfjlBm_tZdP5H>L8S6)l4X9CnfaN5~o1Ph32J#LXeuku$!F;fbfr? zY37pI5b-J3qa}9;T3(FFiI=OVjwA8AeEF1&jp?acunhCr(gas68->h{cw~9YS(d0m zCcpnw54Dkl$~NU41%anRZSmx-eb`Oi1nUWktFs>Qi%t<4$_g|>b}m(vHmjBKp}DM1 zCbqt|?4gvE2w0sp%8`_ub5Q2|rlY`kY4Sw3Kwjf-)CpQ;(x^4X;U$qu_R<#7E_ig0 z1TKZX4(Bx|tqrK#6E)pA-iEc$AleYjRW6U(rt{i}^OHs2*#je>l8#}#Hm zy_56f#;}t`*vx+6~qVdX9Z>1maX`?ou=B1NroWF_yNFxgHzG+bKw9t^)KD8sOHUrl^Nv^cEO!F16Xa z7(2M`;u6zGWnYcqPN!t$tbPH=-Mc1uWfi}$2UL4H%Dz2@lPJ=6|4e^Ezq<1}m$B=< z=G&8Zd#p}eytma1=(J(o(O}{T273Y5n?^a!he00S%pdF*d^zymcJ1z8*xSyN3I_1E z=BZS${pB9O@5q0bWNm!A{{w<~9xzTHV5+s|lO}8&LJyEb!d>Q*!2Zz?9BtIRB=$+n zv-4g6Cs%!bmQOo@Tk1~pJ{3A`P`$NCNTIF#kBR|Sm%pB2e`t<)C!ly}n6h@ywK3Be zqqQ*%1OX;IxC9rA)mK(V*Heqal$32DO$!?JP{R$&jGC2v{a4&c&1s5$PuYb((=4YN zY%VsQih&7Z_p)U)B#dy9$m?qn}gYO8dEx3mc=deg7KtdDlIv zi91LIhyy?jsH_&xoIxyz&W10Ohh-56_oPbv_6V#~?ztaahZ`d$hcx}0R`4#%CGzgJ zQDFqzJUDr+6Qm!vZ+`wM1}r2Jo#Yw(0wsE(_A+c#$R_j7J)I>FuFbzSLuBHgr5^~# zw^?eszWD-%|9B%Mvi>=SMLd4UC%eXbUYnV7{Q(MV6x)lV+UW?(8@%QXYcsA@N$&~Q z^?UqJI6$lGSb>oTB(-L1Yu9)?`23H+hW7xBYBvBw)tG`2Q@&MC`4@FG8sx2T!^GO@@s`G{?WeAzhXYuT$1N;EM_9T%$Wr_<%4Gs$xMT!6Rd&nJ;1 zkFP07Bn3J}uRd@H9xV{aFSIs(!+AY|?auBnBz#FtoEcIm(~N+nG^{!}k-k$Zl&XJ> zV02%jFipNT{uxBsv5lAUabW&!WV^TEV1MBh)cRWn>koA%LK-aVVRcgqnV6ksp~8+0 z!S_$hTAGG#y-?S8tjH!-?{%H?lP+~;4%pc+spSU z`ni1^Cg{=L->abjbrlC2tG-Y+T(~X{sf)ALJH{SXn{mw~;h6V-R}dW=A^0}bHyPMG z^y4TPW%*Q&V2*z}Xcry8V0g$-qSL2=uM5lS!7}T%N&U*S-f7a_y(y6Te$J8L)kw-c zBEu#XWRvXVFNL55+nP_Vgx3lz#~b^^#fY7U(?3XdNY5GiDl|Pvi3?@|6bl32oJuG2 zJ0y3z7!zL~oqb0Jaq)tyC3n_08=JVVPE5`DO>f)C_q=)b9?w@VHNQeOy_!W{jAORz z4=$enZ1-(m6+j$U+KJYmTyjtZl23)Tkg%6c!ZGw6KV*Y%uF__tu&FLWYO`#h-628= z->l5>hj!dqo5iVjACt5XnP90OtUE%OaO2qrnsb68sMN*iu@)ebkG` zhA;Nvn~Dxh4t&xf=t(Zenfid9t!b%C_=|Tp9-9Gf!iZfEiLkz}w5J!p%Q=UK?5oux za4eyGAP<#`vtEL8iG$93HF6^3gibovZJ!TUmjZD#2yFqdWXx04;y}{DUWMQ+(9_4XxGK z=gB_B@g-&Yy-#mV7E7q>QZ*k_&8~9>_#~>|q&eVoaLPp;$fG(RDPg%w#W6+K2RxxS zVe2!o2jS$jj3sR=3B5otvWXg?&^0P)u%JICYC20_;F}0a%m5`8bjmhF$1#=k*@JaJ zGoWW4k1rpZO0|KY!jSY0I>kUyI1v2ma#@v3^z;g6MoLe;v z`PNUiZ-yW%F$G7>CW{|8?Xx93m?dFOp9XhoY|WgNc)UU(FIU{AYG-oUaK3EX5LlG1 zZ}l5`0e;q0KQQR@+4gq<<*UC$db=K66oqNh;?wO}lSj2LTc1CjZuUYp$y0B@&ZE~A z>o%TcHT{e~HQ3tzg^5w5-6+{$w1`ttr^c)}@Qs$f%Zj;4 zVVX43ZQMQ-Jt56`LHN4ub6R6*)q6j$cFWlicUZMUD^hq`eQ~IQVZ+vz2lr&9oFECY zc3AxkwvhQChRv&`MwMm!;N zwxuFVW4IBKvVeS!B*Ff*hS=RC;bgTBURaRIL*>H^!%BM6O&IYNwRonT0~{b49R;;t zMrcU@g6*Q^F(MIUMM18J3sl4}8F9B|jz6hj8oMr6=}@pJPs{qj-s z3Um8;B|w8uD5-B8f6JA>8Mct~J^q_L8_lEFi4$C91 z`9b7jv!i#LIujC1iNO=ra0j|L?J<5(a^*5}M!lh$X?hB<4R)p1I$K%VN}p1uEs_Zy zS|brTYlFgj{`bp^Ms7uD>`c1uUfFTI=Z~?Httwu)cTKeu#xX^}X>Pd)Z#kM4D;h}~ zCwE~t3{;2he%C^L6upc0aEgHARdPVDu&euhC3jUg`3^U1_Z>3)T9d~&94d!I$T5a3 zt|J=~fJN;t_8$l@5mFW`zq&&hm;*3Qed5!6p>pA}cQ&G=}JPN$MMT$iG&c3aK!*$Qz-bRMrvKFbCF*Men~ITFzeP_~0qQI@9a zws;-XB&Q+NO<8;SPZfH>C*=K{i2^L`u~aqlc$a{OJb!r#{*lsbHmMZ)m2C5ue75`t zD$w7)lgrcwLn2hxXe;=8$Bn%XX+bJB%2%7n^1b|8S2P&47}jGtY?(f>OYSeEwd3CQ~d^Lrp5h`H#=o(4=;BRc23xP%w`B|b_Ur^s5PrhwX zC)?CD>B``+&HWAz26LUQ!kJj7RwiVVN|?bGuU!j_tU2ub)1R(mI@tCN6(;!o{#yE< zImqd@7oD=Y{@c{=X1G{goZ_i6glJ#Ca3YMnkKen9p<18?*!E<*Kz1!mPel3T9_#;k z&7UYLfPBNn0N7v5&qW)NT1FL1zTTPqO4}Zi@pOd>g$?tOZKYVw=L6tfQIso%i~K?Y zZOZ3ouSYn5l5SHr1RubC1Nys9V8cz^0EUQt!tP_BADq{;MdONRAM(8r+2!K%nc_c5Tt!`z(XrkERWN~lER2VIA`V?@$(oFY; zLoN58RVgge0E5k!DIa>53j?4dyXfb)MU`Z@2nCn6LnN^Z@Vgw3U1N3Ex|l>7+^8`B z!Q9bDG~Y5}8dtb{=KqB;j!A<^fa^to=J*9P|dRJoI%VTWx;^k2S*0JAUsLP^}n%1GE2hXpPLB4T*Nz3P7wNcBBh`D$=dqck1} zULgZyWUo~U+eTuY+6D78t53RaLvw4kCxxX{w}E=cc6crE=*Mq66r^wy+Y;M{VRM&? z5-*cBZQ)OKs&A>$oq}OLnZRoz?$JAz49wx}f~&{xg=Kx$=&vPC^t3E{cyJ%nTK%X3 z1fuxyUoJqL;BAGey3(w{$8sA!%E<8tp|K^bstDEq!Jagm`H*I?-zKV!eTb@_Boe`_ z2?MpQ%81X!zPaPv64^Yd3#bndh3}9Y`Hzu>fX=@;vB>{>8=9OK`QiB%5Ew6K+I)Md zEx#bWGRQcrBi*RHrH?SK%-*Q7@0m9L2#FKuY}fS}wprm$jN=dNERAfEuDY?tw>TcU zUv1!Y>6rCSj{XYrEPjOFQ5@Od!&<%}U`h)2_SS&+(v(16GM?Ll6 z|N7tj-lc3^B7ub8ZHh#J@=x}}qE|Xka>&Wy=Yu!vFSYcqInyqFHPRAbc}|=xjc|f~ zV415xmr7Pz%*0cPR7erFV1Lumgem6+SdrGntRzMK)`FtpUFjG#&m>kRC`uAD} z<^>jQsI9xl;qxqOsA=uhZs>)Z|8Mq0vO3Ce;r?Z#(+J4|iq{k;og)&zD`?ZXho46< zI^rl}O6mi<_wK=eH^t}k&24IuKOSp}zfR98HZI*WWx-FoCvBfBg)ib*leyET9yIXa zA-T1kbMYTutE~7X;(dMjTsJ!8PWoArC`Fj0^CYYRe%kC)5wtnkO*J%hHqI_As_?6H z)5r~&B^U@}QLvrCX4J1&AHMxK0U$z>k-det{}_f0LlJ<2sn(ooW+@iXjBZs8x2lJC#9m>kU{onNb<+e1$ z#sxh9dy7f#rhPhf;gjWi`A+%PR5k<#onp{Yq)(oBDtRP?iWkIN|-X1N~-^zZN+X`95QELr&8V2lxehS!;hwWrTK}@*;^O~}# z?_u>hh2)DuKeZkiF6w=SG!fMk!oT%eb{D^rjNG3rRK4Um&|9n&kBmbI*Wjq3kXD znu`cIoteqc+hR;Juv`UdY|wc)e(xWVqt^TLrkmo?Pw+1Qyof4+I_lh!L_r=O-AO9W zEWX=2M>jvdM-^soM?Eh$Xy%pi>s~$$hCR{NGpK3R6KUD0m0#Yq38*@HnF_i^y>eL{ z#Dr4hwY&`^Cuc!l7Nv7eEs8ii4mo8$mWx_vua{#@&To?~x*dXSo-x;>^b?RIzLV3+ zmAUUlVH>d}z0q>LqN59YI}Z1$NPL_ARgt2~X~NX$b$>KCWzSBZBy{XNlB{yga4~z_r9kdLF7;Ti%A;Z5e2CySOFfVQGVXx(+OAfw=r2W_ zN_u?QCfx?Z*VkzI<87w9HvPq>o6L8P$hW~KB7)6EkxbbOb9%9!e$x zIWUJCNa)P{>SKV^zh*&Y0VGW@2ZQ>7`pt+QhJNV|SAXXnpyFZ|$SA0$k!1(9wzpA9 z&xQ}=ycABY*4@q1hgA74@NiZ9B$0>WS^E6_nf@A_&APBZbC8LoK}u4VkFv)#4>+GQ zcWB^M-a(Ng`(ty7e-JmfeE$lvx*JLchOCl?~?7cAN&P@Ty~gAOGZ`c8gk>{K`+ z_G#7Z5}=3%u3!3BP>#i^v+Va8RE9W_9dm8P-zFBb?0-;a@z~qq^U<>0brmW075?Ow zZu{Hxtb#F$DM@m9MBVQFtGxSYt;0ouH8a6aFQ+MvGU zxdP>$yuWKG7gEwXK>}^VRnt)whHNG|bp*&}?^-^lSdA zpPVvn@-v97{n;rwbF?n;AK?XzAN4=)G;jn>f7e*umCb*=&oc3|`yu_$iTbr0hTnwNEg-suUDe;z31qMH`yHCj+%C{%Q`K?+ z4I4|pD(5j$7^*-m`t8J#l2b4>rvK-psw|Mi$z3_|GwuKW4YEt^8vJE?`<^ZmAWI7L z2n+{-zOYT_sisV)c89uZy9Sa_Kw5pmvx{bOoGX2 zo^))dh&x6%(pO}y&{IGTNPhdO8)>Iu2hHWe;d@8rOnc*`bSlPTgbYeovqFv9c}@VX zq}}vDNP(Tv<3E!!Z~x&Y{J+FJhn|9%=kqjU=>Ig{P31^Y+=p+yO*SoTxL;!BcfSOT zc<{g-p06i%-=`HC+px{&uaW;PPnACA0b|0FIe7iGSf8A~%p4#xn;$!gcU@a-Siyf0 zy}j|*Awm-H;9t59b)ZLr+`DOnFMv37Ds+EpeuTw?eLn}TC6^%khGzmF%_dl_Z_!o3 z9+0?>FS7e4p3L6%j%Lfgx}pH)6ZagijFV!Y3u#~{ab!I}+|a}>dUjH>3;Q|L-c--> zp18a`B>42;=*5a$1)~xhHB;cDSMMcZT2Wt2XF6?kn31RCpPGt(ytn*Oq(53XL&aX~ z!~7wTxaxQMIFPlOW%XN~s_O9%XdV7#U+YmC>3h|;i}1W-K>kcDFxGZgKqnvbb%sB& zFXOgHTHmMX}RUhy9hR@;1(Qb31;Ls7hHm>LNm5j*d`S zHmmcim?^3l92_XUd@gp$kS&h?#;%#-OwQWe%E*qcJCL6b|Bdg!&W`{IDc+MEKQU=% z398S5P3kLSQ7?I^D20EN!SQOurfObw%H*2g4KopnCr?>hWE9eSfaibrSm95z5i0At zX`Gw+EIfW%Onh*5`O7?vAe@DTiS^H79XVX+yZK!fMr!o_dux?mU@2Sdj3j3PVum|{ zY;)sb2}3@S?$kRw;>1hwcaKYlcW_#V)smytLn4(aZ>Ky;Aqw`d{Cv0sO4@1zO7X*; zRfrM3inz-}hPa}*L@U_UC?#g(Y_=ccMbvm9So~%UG zsdaEiB2KrJS^F3JeY84>yyZw&Q^EJU@9{MysdX6LeZUL!VKKn1hlWqP5|A#rezE%l z55oFS8eYWfkg8m??1d&Pn3A5DSsBr!JyoBMuQ!^Q6wYsEsX`5RQDO5#tJ)N25ry{c zCB8?5fwtEak)n1Ax&7rwVPRuxU+sTh6R_U*HBmeGw?k;ajj~F_7Co^%oC_6UM7;L#^H>Ov2wG0%(Udzqb6zvT1brB`?J z>T@#9#;)1Cz?UK8WeCr@z{VXjVxDh(V;qRno^6r&LA@p%&U~hYAN-i<_n3FlsF>*; z(d}Zf>O@_4C&DYa;M5n4^uiw|rK8jLvuc>h9CQ!@mlLO!x@(H|hV+7#L;){>pjtc2 zW}B%+K$b8_%!qoX2eyja;0n&WOT3dPx^MBPQ}a*9QO}+uMYG@~ diff --git a/src/main/resources/images/icon_50.png b/src/main/resources/images/icon_50.png deleted file mode 100644 index d4baed0476fc4401929c59d9b885b4ca5edb72b1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2391 zcmeAS@N?(olHy`uVBq!ia0vp^Mj*_=3?wxlRx|@Cg=CK)Uj~LMH3o);76yi2K%s^g z3=E|P3=FRl7#OT(FffQ0%-I!a!@$6_Ccr1eRdvE^pc)`Kibg|VFo(eZ|Nn1g*8CLxpNaN?{V%c)N;*YT27pS{je-M?D;I!{z^Ebi@2*~us@a^|E=7o&8f)-$KW-f2z>R$6;n7cL7~ zY_R2uk+0(0v}sH4zAybZ>0IvnbGysG{QUCg)4b<4=fB?plFwNkI(ma0)jo1|mNPOW zsW^H~idxKjv-D*7at4JZuN3u--%V6D<~7=!7baz}YD?SAkaxbv=St2@WNWaD4DjK& z>3d?$T<%8+Wq$8$lqx@;wD@ULB;UgN%qeTXJ@f7E1}?Gb3|g6DM&Fs_Dj5!4vPrAI z&~=uT;ZTxvDWj%H=hKNsEmMrESsk@fPdGJ6{AUmPD&QzKF?0em+k?a>pHGxMz@-fo@= zaVMuNQ@wIfS8?^HELO)4Cg~po<6;AMy9GsEo0iVy6#6h(QN{N3)1s}nT$8qLKb!k~ z(fac*1>VZ`>!&~7vc}o&o?F+79~&PE`!8ahpcAow;nAL3($=mT)73U~hOcc+x#+LB z{p`Qxp1ZTXSst-QTl#+Hv6G(CU8wPQ*JKaroZEWtWes!Bw{0~lo3(qM^QkwLZ{C!j z=D7Zu;mt?y+bPielDdG7TKcYm!?y)H4W{_5#~|BCJ>6W8Q8yj9-u)$8qt zz^YTT!d1Tq%<7+T;ahdMyiHn6iA?@~m*1V&w~76{p~t4J68c78|*7qtVug*LxRQiPXG) zJLjVY$E#D8cO!nDJJNM0aN#Q+r*mOfds3=?-8;H;z0pTofmD6#$q!F0yjKu&Ztn88 z+-oaJZ=as(aXpfwzxCA-ohM)ZS!hejPvDwkvCg4LOL5PMBA%L#ns0GQr&5J2Q~9^E zYkhsO#xAMjH^)Bl#XLKm4!z%fDmDCi%I7Orj$fbfaF@gN)Y*+SUiJ&Sers61`r==` zY?+<(iUUWU$D6b%Ey!Aadw=8fMfuB=>rOtk+w*fOdu)mQ^~b-Z*dI)qrNO&n&-Z)3 z+~gu&Gk(y$GP~(ug3Vil(pmZO8izX<3ooqtwC(db-)TlCPP&+-vXog&v$wQ~xj*NY zZ;m7H-*t|gf18-}`!?G;Pj8?6ZGzSZ*$W3l%{D#zyxr?3tHkXk%QDUP=02XiF|5lg zzD%$CW>g=?yjcRyZ;jhCTQYsWwF>am&KGd2^U&5zIxBy6)2Z`{h6|1<3C{k-FeAa* zKf=cLQt8}ZFMRFK9{K+7RLv(B>AGpQo);$+d)Fr}Jzn-$Nvo-?_oBczrT<jx9< zMLW1lT*^#2Y&NYmEjqIQ!2RY=>mGUjJb%@5_ZgiyXZw`a#t*#$rvGC?{~Vf|H&ISu zZ{lB$AL0v^DY?FFVp{+#pHxd+BT7;dOH!?pi&B9UgOP!esjh*guAyOwp^24|iIs_| zwt<0_fkD>or`9MMa`RI%(<*UmkZy}@2WrrO+fb63n_66wm|FnXV`Lg)Xli9*Ze?l= Vv1C`+H!GkX22WQ%mvv4FO#tyiZ>9hM diff --git a/src/main/resources/images/icon_dark.png b/src/main/resources/images/icon_dark.png new file mode 100644 index 0000000000000000000000000000000000000000..b95f8cff94055f1461f4e711a59994ad0144e1ce GIT binary patch literal 22557 zcmb??`9GBJ7xz6gX6(jJ_I=5ktl1_@2$4!t3}Y)XqOub+WDlW8$`Xn!%}BC@v6Dgy zQ?^l-7|SI4`rM!I^Ljmh!SmBFbKmFM&ULPH-tYI7WPibeokfTR004F?OEU)mfP#NQ z0VV|au@U-x5By*Zw6Zm4Tw-NGikv?6Le~NSu70&LJ9|0w=gMTrbI~i4J%0zMCO4)C zoJ_4W06h zqfY1j=xc7;UY*K4eR^R(s(DrE$B)UTg(>}e1O69wUm!$I=tgPw7~FSj@PC58NWMX? zBL|a5$@63;ti+H~=ws(6t>mA0{zARbN{A!0pU_1%!K$h=KIIGh44Gn&s;(N&a@7jV zq>agEUgHt4U0t$3U^l4o-ts7{+TS6c>u;&TYTgbLEkw_vN0 zgdpU9COq&~WJQW#w&nMexJ0TC^&C#aO&<=;ya~R1k<3UsbH@(%+*M{Nh z%HI0@6}+Bxhl`Hg5Z)|9Mu-5N7q*PZX4E`N&(uK2MkUc-!2gFo)>e4iB5j{xKUhorRAXwtR)=|Tj^)yW3bHbTx#bIV57ru z?e8oNYoR)BI+RNtv4-WWO`>2+JCj7!ahP+fse`2wK7}-eH=j8Rhh)M@jRBmalgE6@ z8M&6t%}mc@RfHKDT?K-b{%gqsD&Y3xjalYKNafx8rws}vP|nFCal%mJj>d!cC3cyb z;yc>fw;Bzb1FAONzCcjR4~)5*{)zwIo8c9FFS>X z90=~{O+Ht~TzV{|KV#R{=ryuq{cI||Dt%JUz`hG{QYwf~e?gm3)ikxWq{5iqO#RyO zvwD!ew2CUDYCRD%IQCee9rcfOU&L5Un1!!kOo&}l$&yORFJ@C4s~Z^)H!c-YQJ^1dq5zXw@x%Ys4Rkl}lzd){`q$@lAf)}x~E=Uh=2 z%TS#0uI~ zDTmnmq&fA}LKk4MrMKZ5es0USHz?Q4M;*Gu|AGx3I0_>g(~YZL36?s~V}b}t-#aA9 zH!%VxCBjq4+MDoXMu;dB->buj&3Y5xpxSJy!`AKye~8$GTCPYfd=6N4cEBivU52&* zHf0-M?xvaisFIo9k{pgLl|a4W)4zJbWc;~xi(j0|6U3SP=~4|wMvqC%ednC(B?%XL zE<|Ol3Z_@#heum7L*(814$dfqxQin`4hG#aU&7wQ83ACo%YVoxEuT@$^vDC`yOG(2 zrd<@I^{e6W|DKuULA$eMsG2Xee@V2-=T^k0b18eU5B>|)t}rAVIw)8w5gEq2?H4t_ zeT#>O7|jJycv+!Q)JBO+C2@FNfOGtf%6#0t!yBO`?Blee#J>Ex_WA8YRf8cw^yQQ* zPoLQ1LO6PCxxzbA#a4w<^T>7P>d9{lq@t=H_J=M%e&tvi>T=hMhNl0P0yi8&*<9!R zty>7AhhCA&zapXp0@#S|ZKwT*c=Z;0APKK8C*GjSQoY93;uE@mPm6ZdQLf*%g+B5T zVOpMTy6cj0u)_N) zm9cbq!QJI@tir7&LizY$@=)N^N|B|WQ(^O@*L~BWfs9}2QRD~ez>sLhjynu%Iu`fn z^NG~#<0RwrWPaJ<{v-KJcr3GA_$^ty*#LorR>LQ%$vqyby!zMLKX9Obue*pD|10Ot z%t?T&0Jq!-Wa=#)2~0m!gqUJ-Ok}(~oCQ!C7D`2(I;Q8##;p%dL;WIUX`0xD2Z?rj zkBO%)auu+hi-7i?vGs-)hL)L;wvG4|UyEPgJ4w@oz?=n4Wc+*%x-3`#nKxXU50Vpj zfy8v7uMKLn$Mz@%F$Y-%sTN;UP*JF*eDhA(mmrADrJs1mu{chvJSf2R7o#-vtC3Uc z)+Inf>ZOb1-$&q=TwF*+fRl^s|Ia@e%RT`ZKv5MA94Qu^HBMX!Am#963S|tg)-MNuS|C}? z3WlmhcD4Wv(|?_bQiODXlV|p3SQx&XDFJ?Q%LHuIWkagorDyrW3tEjOL=m7{yJG7> zN3*;lgwFsHrViN0yfUDmy&OmxBTB}uyIvK~n*#+}*-Sl>rNU~8Xi&>L;AlI|IgcNyW|iuC36RD03scQa zeiLZKk4!MqIVs$MFcBe%Qy9hat!ZGn)RADa2n*#4HQWhzqyM96U1niwe4T}8?QA6d z{X%R|$%DJ5bF}CH`_2)UcHglZkHN{K)vo^Xb)9msfx8$^MSgJcD4>^Wc&ZaaMDt&t zU}c$tx&UH~Vz5{45D2ka@{)x83l{ccd#o@PiM7KJLikosmmkSNGfvqyGl4D}xhDdIgWT!65ryfP%I|wjhQ=s_i zYg@>vgb0j)S+Y3 zHQI9Wmpf03+<{5B-Y0(T+a&dTM}$I%z~6v8-O?PYiC^Hh?H zY)0cnz}}v;dfe=sWAQT;xX=M5h;w^}!S+8Vi!eP7yDtn(!*6%RTc2xC^@!hurb(cy z(X;=|hKqs1owSZsF&QUqhL+SXNL_xX4i4UTchj3+fwd0Kr4u={d#$P%FA5&O$)*q# z#QfyAErgx_#&`r?iNK0KHPa>qhmgiJxObQXw3c$;jGQCCW?ov6dLjKQ9*U1iy26r0 zeE%)e4+iGIV_4b*!TmCwG)82lU!^+Z-aq)h%A*jFc?Rsg^El)+81lc*qNvw#6hvV%4P&Rns z3> z;yu%$cxd9}ofj!y`B?|FSol3xNygKy(q6tm3lLd=t-Q{ChdW!3t9PqG@<$0EvEVLn z$V>^X;I$A}zII{%!GN;khL>Z(0Vl2N(d>hT?uZW9H3J=)CSG6`z3e{CdZp1^3)nf8 zEiK;bXfCeQ&qdz#&UL-s4HawO?{5M9Rb4^kP!=@u|sZZ7UQ{w*D^xN*ENZgf_u(5tCBndenXzk|w{W-N9)0J!rPlv$9wI zF?a%v#CzH?>x$MtwETpHL%2%;iDGvFA0F-Qa1~-Yt;XurbA-q*>e?zYa$qwhNAD$Gd!>6GlKBq6qf=h01L|LU*81kx)$aHzXd{e8GMhV647RCM|Fl0x@2rx8dt&f| z#eD?sB0$3Q)5NAYYyx4g0}bOIqfZpgJ#B8O3O%UhdZ`S^@J{gXj>-#_s1W$BG(QeQ`edvo#_(2vE42969_ zP2RuVC%FmeUY6UN0-W0KDQOcdQd=+kT2sHx2yA|=NHH8Mr#RMTx{d=m*n7zw(v;gm z-=(R-n?Olrd)IqNfUi?|9xs%RScO(Y zS7H2Tdj?(GP=6HwOH27lZ)sBGY7chOKd)Z3g7?!MazRSy(V+7F^it zvih~>-f(WKZJk3@QXt9lxL#-~#?zm4+r zhyiPXvx$zt8Akh$#qp|rBy6fSLnq%pl;%4KrCz}Gov;b{mLfqahr83BSb{^mK4uz&mYQC!TlxGzgBTmd}wvj`?heX;M!PUIBwH}XGnV5J+AaNK)zhwBAqUrt8sJuU5y zRiEu{xm#(nt@kdT;i=XQtImE7WUL-Dlg}zATRlyPx3Belyb%X6K&gG8w0}r{oivmQ5wG(6pXH4EQ783e=sv zDX;uA%$O+3f-nQ~z2g_L`r#(Sa08T(5@G_xhEn9`uCUD-Y( zFa7C8GG6QfYIKX`e=e6-6B_@W=ox+e7JdVf?nL4{vyWxY;^>KiajD(n!+Ul$k&W^F zB>ncy?y4+HRR_6TD}O4MT0xm~pGrXRyH!BM;;N@RdiP1J!4^gu1P$A^;NpGxw%dV4 zkBvNtZbhP`5~~98utG{`X;Ki6kC`)?V}il?p_YSacUabd0>4poA+h;Gr`xv* z{W*{~{@lCWnQaioCoD8XFXMIT=rqr|TEu)Rv-$&J8k;xzIXy~RNw3p`y;Ga~7CijY z=iy$_h?A{78Dk&W1CVuZQHBQWkzAqb;p(gfLAfZ23DLC*GJkcyd}axEhPShfTNPP_ zav{-Jc6bK_F&*TD9(adIxwO}{H@5{fG~VK^n9`ZHxwMW4&?Z2+zwPcl(k}WgEphjt_rE1K`8}CmgCO^5u5r7D2 zrQHqcxQ*uTtbPatzwMZgV9rD9Xc;`}7>wZ4zV%lZXUvcxbq(`!t3+688|acUc_Kg;k>WSCP@{#sm= zO7)$ANA0vGeR{c&QC|xwx{@oz_pE!o5~)xw_PSPZbemrEWS^ zJSbMV`jM&sPLb?Lrhp1L&kZOn#SdemJD~V2iJCv`s1uh6O3q-j<4E4&)%{`|FQB2Oe*OH0W<=8duy5 z)IWayTST6p3~hm;JcK~n9 z`0(M){?Kw-E@sS8X)j zb3BhB47g7GI4L!Ph8=L$>lsjeyIi}iJ&kWhO3!_0c!B={E9)|C>xl4LXLz3Ch_DQ{ zm8P%)RJbxH=i(=E!gQQ#+21v~SS@sn>l%B;MV>bXqq&Ya=$~~;1htA15nvc#^yaE; zUVcK5b(G6FMM9}>2xNgv#^_?H>u9l=c3WSW?Voz?LIL8f)WK7t`r?$oK576 zR+h9J^qp#xX;F!iiXn5-+(#3#UEY!4cHnZ31DsJ?46 zr8g;;5{dr+7H~3j5$%j7)6usH_UEyRYdVyta)sTknZ5h#-1HLKdZ4>ZcKx3L>Z#nH z*}w&uSjeGNjdF0R0p2gOwmYc7j9AwKKZ5|$i&rt%rdP;uloB_~gF!rGQZ3oMZLzLt^iv%Zhh1FEHi@Vb1hD)*+qx46kO*G)3Bf zPI~W4Vt-V^lCc-WR~H$4e!IZ7q{l^uLiz_5@n<%G%1*hhMEsQvW69wsRZY#+=2OKv ziZ`NCuX#paAm`g&UyCP1T>7vPu%4lx~9yv z(1q7(`ckLkepdwG2sxH`N|$x<>EeFsZDcuUXhD)2Rke6`Oq)@mzNQc>EU(}042S%L z4LjtDH^Q9erK1`PdZ)G;_upb>4fD*^XI@F%;QG#fM$JbcV(@l%{13BXI>PI2NG&5k zI#1hslkbpxLvPfuf%9_TSR0E}Ult4Yr22G_!8 z@grl?>Nxvrazp%!H;;pO zB9O<(IoAwNXDfN@3uCMxRWM(G?{RL0T1}irFI_Kh)#CNI@+C0&)Z+~EL2QM;+0tSd zHItrlmk?2&BL6hDG!`?z_r&t$ZQ0)Kw@poEyl#qAC0@1ij7u55e(ZF+$I<3XH~9jL zFl@hb*a7!cvI=>w+BH??#;Iq!1+|M5cNKlX2-l#xGC8X$Z+-U zmSVQ$RC*;q+!X^?=N+jj0G%NJd8DJR*RzIR+ArU$WC7ZZ1@8#ZPbt4B?PmGs20y#!YSqQPt~c$@$N$mt zOm-oFI@tu<(G9p4S}0El`vAjhMDNH_FOkE_+IwU9$alx$=)HH>^;~bjeI5}%u zfg8N)%sX-!51cmzGii4KPJWqeC2BAT`!mFaEw)^BDAk$`aSRu$k}QCbHE?yLlH$0? z3;a*^oB(Gg5mVfU-taFy<<@|Gk^MV@KRm8g?26R2Z}IcKCFQx12*CQ{@Y~wO#*J|w z+{0sC_Xv7mNR6v(5IfKg?KXH2>AW^`8n@JgdB=)iQKK?hM18Bip#SB8Q#k|hSAd_H;V1rT zY!4qO7MP;Y$+yviWGpYIj2l3dq%0IE`}Z~Y{3)S7AN25e)}yiTg9)2RGqIdhMoclh z0+0X__V(fp=DL(Kx+6g01Zye-tb$P9_M2tdgd#!_qd+Ju6b3;!8+5PnWc1mM_Hb7j zLnTt7jvb`xu6c=s1M+tAh<~Q|mr84@CNl56F}rp8F;rc&f3kJT{uxbJZGqi84qM1> z9jY!Ks;oOI+@yXEkS2U>J5GT2?0cL&3;Xc~J5Ida>_M7(sQjZX2x9P#yMjRogq{## zB6Yp*R!G!|n@U8h->iKun5kr~EhQ2nT5`00u;XV%$fEmVCGDK?r!at%FWN&20-*@+ z-KO`BYu7osRfyN{1IrJBbms5e4;RzQYSo(Zm2`UINYHXKEogCyUD4csOpEz$n*H{L z4IH?GX}&`OB>UUlQYwFFgc=lu0p)1(qZ{9q2v^&sHYxFB)$0B%$RXhr80xDG#`1DG zfX2)O9i#es#;h;5o82f6`sJMkI(dBiT!BIv)Z!0V-ok8?TujoVu(IF(Y)-r$K80US z+ZW?|tY&9;GVIBRZsWIJ1I65Ryk}B$SZ*m5IWv{p1CP?CJhz*tc=}r<`g~Ev9jgMusK0C3;E@Qdgu&PD;Y~iknX! zUt|Fs3IPexYtaS955pnDL+4wdfISi=q}`=$lND4G-f>ysn*Y;eDcX}G1u84U#Sh^S z?yMe_r~e$MoD(q~uc71hs#!Z05Y(CVq0I;pI)Tm#hnQ>){*a>Z=za;3)UY(QQ~a;H zTAr;MqClkZ%4dblGRpu%h8@+me34;7cEKwY__kwK`j6=*H$Derdo{devw3wng4$2c zsP2D!*3TQ6d>KT6dNkI*m1;5TW?{M0Vt|ajM2vL-FkliCpjU-9x^MOLLQ7y^qn=s! z2DAnKTtv*CQ)2iu$@h;s6 zkQ}H7CP%5m5t8C8(9YN}#VTQu&5+LS4EmQe-qpiN`S^r4yOPG-0{`Om+`?UNsyp^0 zt;TCY1DA)fdKwN4lX%C~&iKc}TA?jTD?{)y9aM=D$+v_{7hcZ>rgotMei!pu;J_jp z^7$?%@wO0Cr1*|##wTBpX<`A9;Y5spG`;|6m9%i0IHN6W3$=-Z;sa};ZyQw2kecol zup>z1quzmd7O0s`Zegf6RfsAgW#~Ozx;T4tII#K_2P)j9d-TJ+Ue9JV`3jkjY)*+w zo<}4Oeqv}VCVV4p{0w`xoyDitpo&)mCt<;>(n)E}IvU{-2Ic6I)5N5t{!rxPeEay; z4v03^wz4g+G)C&Z=YG1>$k_reAh9C;0*g|z4lxWEZ&1DT0+*8No6m3{Ru4x5qDtrB zFb7ROp`%#*Ae0dXa^Ruocd!}(r!$z-m-rq@ zm8p+;$pkQEYtn!i-k-zLmk4^*tTU|OEZu^LA&ll5C78Y2e!WpYaP%;Fb3|ciu_d01 zx{0;GvSN9KzJ<8S22_AuIR`=Qy~3WJM+Rdau_?Imttu!>0C|9>xRaH-XsGN?2txZY z5nyF=yyO*N&kpBY9nq`s6ko26Qpk=85mATu&dOs`j}??h-q&v{YeVcE9xqe|Ht>{F zjaZ#yrjC8yyM-`W6UAa1(CX^?p`W{A;^W!|m3y{a(WxscQxB`!z1j2opG=a%IAcY! zi}+Q@JtW>C)hEQH&{WD~m^iL)5?F2)iJzMgPi5Ef6FksIG<_52KB(+odq?vn52D&a zpM8f>yQ|PQ$bQZOGV(&i+v7**u9o}D`+jKCRs<`rqx)IZ0Vy+x(8i*yj^;6VW~Ght zhHJyZo1#wp4&nXW^y7PvkU^2Fe~NiO>fHZB>D}%y+J>~X!eWmTT(?sW(u8&*pFt-6 zG;$gZi+X>OY6hkmTNWA(q@>agxpi3sw+pn*Kd(Bc+6MD*{T%_3G0-=jK!FgKv+^y8 zJ1au9Thk}tfMQC}ox>C3;wZCDoo}Sn&Y!5sV^swpz!ymI=ktgCPHtdGZS{E(Y1K`QkGPXlTc+YAW2lt7uSm-6kX&_!{=x3!K=fLv9ql)$HxxN+*guL1bP zS<};WUuvGW>ZMm8)6#N<97Y~v(zuzF==t59+SDl&J$ZODYaQ@J%NV2nSW;gr*x?gB z2d&W^(b8vMii2J80(mM4ekL4&oi$SA&m4$i{c7f?B9;fDeM0ToqyOWjlF*z(NZk{{ z{DN!${akg8Vm4=7q;`-Ztoyt$`A@h9oFZ(-)1gWCS zuXL!o%5ik?2$z$J+cwC4J$oG+_Mhn^1)#TFqZ#5su!Fq@emm#bf#M|X0C?TKMNpyl zeP@?}cz8uW%Wqd0UWEJgm zQ2Q4sv&i;{wXlb$-uQ@pIm&l9X1+VFFQg(w;Je$uSLY2xH| zJ|rLJ0-NU&9z>RZ&C!Je!=)FXP~y30UTqs9ylx`EgudyGb9albUA8ab_a&|F#ZfQ^ zHkE_|#K+{IwZY=gx>1(wErI3`{P)TfJb?Ry1x9z$fi36&BcegI$&#ZI+QK}MFuADK zDYTb85M{;Q@*R|td^Z<3+g3+0D*-bU#Y~trA(lissQFH@Hq->qS64SiT<;ybOt#D;v zV+V0-Vr^Rp^aJCu>xpAYI4sH@unz$93=*ZTwFkQI@USX+ocMQW1TFWTFQaFjO48T~ z38EisWlZ0?fiWF(>=&;tiu53S!?#pVSDtK!MzRQ7SBGG}a)xQTTW1Q#T8I~h(EW{- zpKJiQTN79;leU^{BpY)Yk}aym4mzjuGLG`|{aDfcQ9l^ADrXD< z>9>8tuBtHpB+rE_!wAl4(k{V9$L7|wG|$(hPy0A;0h|1X<)tEjS^Bx zSnLNXiM=kRbnTkMRVWgO?wn^);8XzRPH@f&`ZN3?Ud=t^0Op*dc0(&z{#co=FgmHr z-t^9O@`u`d!!Q^>T=)oQqm?BnCz|57+QL~Qr@HQHjq(JXqWf!V+ADxTztSeIPC7tN zd%(CeXjh8g<3zt0IT#+v-$e7T-e5JaK!eBEC2&isV;L*uSL~J5dwuM#4`;)U8KTT_ zIqfg=g^j=*_7W-Cmm%OJ9ggK0^I}zo;8j0Grz+!Z&nMlm7lFN5kfpC1ns5=IM;?zUK~xf zdE7W)jC?ByiXWWfuvpGIuF)Pm5Ah1Z=vvGs;y@&?1NP_oAV_%XaaG`h5m9U+N#lb7 zTy!LLo8sA$y@M>%P-g*>i%rytr|Ejs(Di@2qy6{EI{1WQ#-IUD@JxA_az&e+e1~jD z)cRaq*|oY8O|V_2spr}W9PNRJgDeHwC0!^x+f6a6MHN&l6-ZKc`&+h#sAnaick4Aa^@I+?m zTD5}+MZ^KL7{j#k}Rch#(tlb78_Pdrq$ zJD3~J%ix&{CMn4nbzu)4zZQJcvL`E%bzc+v-}&C!d&a9e;Wgfh@@Vqz*qpT$jBZ68 zGz&k;$KVMbzYmiz3VE;`n0OGnWDI}Y7B2Bq>6F%i)Ld6}Y8-{KBal>;r&ceGZw1B^ zK)K0(sv9=NZ#&1#c{a13PLs`Ww#J1`Q5imubAvovW zfqA%GF#DmfZXQd72k&<`if1pR&;?&<4^Yv|COew+6A4|{;%w24^8d4J)mG;roWYpD*Cjc7aL=D4ro8 zAAl254+>g@waLMwLcfV@gOCM}TTvrBDKav5{Z!xs9dCC5Q__PQc@3(GU`8v)y{nC# zbYBZXKYx#QIo5gJq9}Eg3v~vIMaA(Gx;YZ0+;9k(a#5!s6iTc0F{B#VIyBj8S>rxN z;Um8T%leum@QmUDFbdDqWm}6v&W+q%l-;jSawH)Y#b*7pedm{zXLYqn)+mfxz- zsvHH&KqM%Nj4VyjH_u=SVamSQ`t?pmKEeeudH7n!KjeFJz_jUHmg3I)Yxdq!>O$XH zA8EsZ+amb=rf7Tu{s}m)jE|ESx8ZwW?f%s~W~~9uNzHqK?*L&si?BBjlV38^)|Y7Y zBEEQeOzVmK#n^q9g6kWyy_2ft-d%&fHC(!4+d(fwz(L6jzke@#`@=4~3g8liVH(_! zb%mhBaShoe3+CAOG!tDSk|^yhC}GP242LigGiWBjJ)){b>ao1C_I7b!P?*mUYyTBV z<`n1H(|>()$U^~CCa|JO1)+saNqrB@JAxP3+uVz@v}e9%_kiI#01cK#X(Gwcfy;B{ z8lS3qMXB@T+tvL%Pc4Xl(@SoE9$R*i`44g_+xF|-n2#c2KOq!EU`r_|XKdUeucSp^ zOd+aR$r^?=<=qCln^Yg%90jaFL?y$G;tW`UF*I<+I(X{eTs14T$Y7vsdIALUz9koA z0jB$zZT+z_IY6Ti~73Ool|Sq|L*^s;1XQ?zko!3YM*1s z8>9U|b~&el==Xas@5$P-?;J*b7|VLb_{gBZuJ&^0=yB7;mX50b@2_DxiCEgV=O+?} zA+O6BHi9us2?#D5hR3stAU>h(S)rtr4n8!R7pYw$eNm%OQ;VzeBmFXrSOr$qCJu9E)a}ndyKkuV+@(NE`lG;&w)m9DI`}iDrz~2);vZHV==`UO=}i@<{G@vqh}NK> zxa5{Zc&pAi!^i(a>T{dB^f?AsM3zteQ*=kSIn9=bjUtpG~Swm6NmNoBl#i~Cvm(Lq* zr&yZsN7%5+r=&V?ZA#@~R!m8gA7ri-_icAppDlZ>z|L5BMh`3+;b(pfXUuKya@Oda zC3)A$k1wFE#&ZYSR=h52ky=|okRvcT@}@PR9hX7<(Bt(IP|ACT#7NXCyK85ebdXNd z=A&wPPEP$XO#5{A#Wg{2Ykai{w)^vy%mreySXkeJHu;Xv^Ce~OfE+wBYt8LtxbGbd zApRf5C{!a103z0p!mOKtARVE8zx)uVnQhe|tDpS3-$6L@MimXZ^FP26R#naVHEELA z0655JpnOiRzko^9DxN)$U2H%X-iLmw6C6QQ24a~0XO_E0^y?Plf-IU=<$`bgnH_l> zCZh8Ut6;idfw2XQW*Rw9e1j^38(bW$A5ib_x-5Q%IX+rh!6G~7p$C&eXIcKcI#HGd zq4>n_V+3T@+=G7f&4v^tmQ+Hg2nVD4SJ_|8HZoo5a|Z0^7^j4NZT2n1nn`mwTTfqR zD*rP~p2U-`YdsZkZxwu}c0r;Dex7fJ+vES28wSo$~8 z=3zcd($F16JQ*idj+EzmE9l?ai15fIbwlzzGS)+J{+k&TIei$hyFwt_^o+H+{t{n-ky9m7MzW zR9hJZrs|wThNsBSh#SCLc)AXu0iE6*UK7BsM}w3N{n2sDatnrTb;`Z=ODc5`wcHXO z`ltlC2@QdMa~6071eXZ%0H!>|KK$UDgt8tEbC2UEnvd4PPWz#;>H?rlT!=Nl0CB^; zqWw%Qp}M;CJIG|QM@u`BMDQ5iCXciDQBXH7OTR*8C0_@L>l&Rdmg^SSdqN<+{>UKt z`~70PKi2T6g8@5waN|bXZ~Mv~thPFQM+cO9X|&DK=@XVs)wU{t!Z&(4S?KULSOK3i z<}u}Nw<2T6LD+&9G5BZfZQ-Qk5{UKHh*Db2tZn7dK9pEM)3AE;j99dM2fV;#m4<|l zd2~Dwl{0*GWm--Q08v;Sh*3<{{Ym)b;?0ZERDE(5IdCklFRORAMOHhb+RGY?CdcZzaP0e7aZty8#Bbmdw*e(|uGaT!9(WLvD3xP=Jom3SsO7*4dgPkQ z1PWO){vFv+rNHx$tU>jTnZuuvZ{*jL*X|4-sa;Hed|I@gWrvj{{I;a}omscMN9r+_ z`i<;Iw!8SdKwchFz}DJJd*;j-?hz7huF2VdLh?%Dm%U>lpM%nxFN8IBzquU3%#4m4 z=xCOQPGdl!jpR108lu{EW6Qb)44cp`7Ni1GnezG+E^Va-eVLKRGxhN&_pwj%L}AH{ zY8?9kbcZoOFeA8eYSVubibuD_L#DgsbVaNXJRDXd-EM|D9w0nu!9l)zg?Hovnp+tD zfUk2ZXA=K!=*D@6W<;e}13xHuP8Kd()4G}iNH`Y0Al-TRPvHWTcUm+t$aWKPWpB=G zD$9t>=$s?(X8M(XctnW(fX#_R&Y_}+GW7L5rN+H5$`oqI0(|2AB~6jZDIUsfd8x;z zt8!p+7G>VRxaYo=w@<;Jz5_uOp=9M|2&*>yfw^9z_82ab?b{xE@hulWA zK%L`NqBDOj!XndqTjt*E^zTVT;qscKpAFUJQ?&lxk~;g&5}DdD|LuNCZ-9f{(#&l* zKr+?^XsgGHqZr99EukGfqV0cKXu>v@EufONUQ&V#Flajvd%;L+X0*UU?un1hWtyD8 zZ=S@UN}5+zH?Q6UIQLCs@&5?->`la7mmk0(MiX2NbZh(sx9_TYzaT0#b^4f_eB>^U%VdG~#IWeg@f}=oKXuODHI`A&9rH zZPfFSQky?=>yO!i1W`xPukI*vDSFMo9)p>f>k|sgJVI}0tG#<(dWMHMQ@B;-f1e5J ze)@Q@bIpn<47rJIHi2F94>q(g#49iNj0 z_PdIS8!a8qt!MgbbJ03~ri&R?Fou4_8R6v3hK}%pLwg*@XMw-> zRueqO?kY2n9LF)9#H5Toyy^!%;M6)Aet(C;@KudFkkQm_4UqsdMx{o7pQ4!6zgaa} zm)W{5hs~-UI0pj1g8(i!IH%&?r!Bzj!qz!z4tl%Q^1UNO0Cvo(%z~UhOj8fW9B}T$ z(=@z>G?Wil-p>#WqF23Qp2iZDaZL@Xd6ojz?bTf)_D5%y-!M`+sh(qRP42!{qhG<@ zUmBfh3tz#`nN&{5zbvfJ3{W{(ogu_T&fh2HSGB(Ec3qz-4kS58H;dtWt&9bQ`>!~# zE+#GD{h=SAelu+blYHGmF|j1(^#Ay`-(pZX$hQty*zV_k2IV~W-7)!J+djy?f*vCK zr}_51G3-r4pa;4Zf(h?y79}W=SZeQ!S-GsTc+5=*@2L13RFKrNPkR>AQDR2_&?kiP z(gYfb&)(-i)_+SPvs%B}6p5Oh6^Beb{BoDSJVBePiu*NT`qkfab3lDma5-g8pML9I zL3sU%9cY~iL+|_oMo#xcs>+B4$ga5M4GW?QPM@ z7Bcn+&?D3h45(0*HE567SS`WuRU#l+!yc>hzcHA{!5NNE7UP=i9y9biXJ2 z`dGIO;WT5K8(Q`FG~Vxdi>Xu}n)Nw@GvgB&9h<0f^>iESd~McFpQ|H@ulz9ui9Q0xpvB<>sO#rtQ@tta3g80wk(%eI+FZW5NW zrxCuhIvw%4#%Z>zm$i-mwuw|G9ETBUN@74HcOJ1=MWw6s233n1r7ZCx1`g||9fa&b zoZPZnjACR%7e|V3KEAHf7Sl{44er|(mJURFsMlpjBP(a71+4E(4Q0vm^%cDZWjw6F z%MiU(w0T*#tFv#r2Gi}-s@5pRP`J~;I!j&2vMkk4d2{*a$^3UZ+HFCaM0j@jYBPC& ztT3iV@rWfofm*;$6Z_61A$Bl-fECXdD8~Dk*tA2SaL=>H^q_HqH}#iKizf-)|2ytR zQ9nM3kMEs4mZLnKU>K9-T{K~(tBxws`PGqm7DORd#C2kFi%xKku?RTyPNDc2Z+F*G zmH$)2mB&Nbwc%%GjC~#3TfAhlq=qRnEy@;U-nUdnKSe%E8dO)L3mi;p=!RxZZ>Bh{g8i9 z_d1EaZ#3N4RM=mXqHzjNinWO3E?#E4S2ER@l1HM6kx~uRbfY!otuAspvbC(jI3F8oM};S{y7I~ zvuEfj1}{nBFr)as9`1?+rrDCQy(i^;Qz`qC%#pVQ0)&e=bTiz$Qvora7~gX4^moVG zn0o@4^eYYU{D9(9xB9YOgGals1dD&ffJM?1zY=y(@r{iBOIKn`SU3LB*!ClDQw(pw z=o$$P?|p`xv30}{=G(mxOE6z-&P2|RWPk8iV0d=Z5D(s@7!mda>lXZ-phcaR@79rL zzU{~=b}8eCNv3%u+{a>xgNlXkTz}Lj>n-h}@Hd!OGSml#R@tAFpy0HYyk7TV#S#zd za(g$+w6u+dd%7Y3SSJm9`UC|`gM4Stk+K;>RY$|~y%)ZlDlE`ACKl>d#K_-v2nj-3 ztxx;>Ec4QG=jDn{m6&yBRsUU#p#y57Q1yvd59><%gp~Ekt^|k0Ai5znuX6|zAm+V~ z5Xnd@`8uHU&ZlMf*29Px%c)7fPVD)X?VHT$k}2JvVhvN4_?P=_SjeXP9F(jL7oLXX zv!X74ymfND^Jm5!W62mpOfz?65Yl6ZF9nCwjhM(g{Z)P=Ys{1G+nzX1YHvL!W?diC zoG%O^`G7DlUvCLoJn_{r4!mQ@nRk<8bW0=ve*U&B4 z-IFn)_0n6gk+1TjQ3Sj+ju^6&S^CSS?6;T=;v=F0Zi~n`v94nt+uhzCH9kpvRXc!i z@#+RU-q&<3Je_Hq-spB5aq=Fe-n-&I92N^BK{b7Kpz`b@|VqF{B>n5oOm zhUSH@s^uCg>&@)@t9K`1tBhA@rArko5&`^J!`)^{}5$lu>%qoqd&8U7-n+S-8(t zo0;0-@LE+jr5E1n6Tg9k_pE%mQjA&*(H!k~@>R&xDcBJhfEZ|#m`GrE%t zclZ?^n>EoR2J)K`+f7s$Ft=^h{*g>~r;h;bT;9s|W+mwR_T=}}Jo=3akv)2K%Bwon zHduf`()s~{B;KYy`-Upwn_Ycravz2;`$3pZWF}|dtG}tW{Q0WkGqW+&mqLTPe)6k} z^h5Y+EV)LG5n|(=zUB7^QeBsWPdzM+bF6a|8j`XP+Z9nf#_vU%TTnwS;}%TC47Wt9 z|1R_Q+!N6~CIbq{*w+9Hy+{?=MEOk{n2|IRw)I{{Nc|br2e6gIrjVCnTyeYaSr-#` z=pr`kE4Dd8y5Kv_I#Y9tpTSsI3}IDV@DR`Seu)?p$VuEDKm7pJ%ce;>y4m?fB13>; zIB!8b)b~K#PpL#7L`T7C_SB`umr3S#FRl1WQuTq*M%Zg&U*b~Zz_8l!xJjE}og)99 z`=)&foOxfG6_DVX?oPZ+H>00roV<|sCym8R=1#7enF}!C5`a-81FGtYX~R;O7M!RDk67H*faj;*o0r*XxQ+|G z#*tT<8|Bwl%Pn|T7eB3ugxVrB7H)G)Ql(!caHcQ&q$*Gb)V__5^|l&5+X*TrGPSyR zQLfT5eD%kf8Qrv>7I&m~h)g2fuKE6$_nqNQ&=K44A-W~i>%{H#CjE3XK#wGhfBdj_ zn$dtyIsRYyE?M}BRK!$KJ+vA1cMUb8CsKbQkt6?|`kFqL6d%5V4SxjDCAQEkVb}Ul z#7HhzUjEO>An+8Z*_ZwWcM7PDwrki0)<-N-bQIcA0*PPx>EJjb}Z|N?UdM zG9v0jxJpSbC^>kQNafzhxhOlbOqX7c>wAA_f3|;$d`aaK`;{hDQy9rt$*8mT`b-Er zQZ;f#nN~o!sAAE!Gtl$2MJkZNA3@Y}Xp)(!d&~pwuLjYTdn^0)V+0=ao&`|JOPJ2{ z2RzIhHd}%-b|E^3H{Ly1v}8Llv0o4uNz+C1@fIl{1_tH>Fu-RoPP5%ujyIU)Q?i=D=5uXEt?GSLI2ILSg+@-mhV=cshGf z5RM;hi-^j)QYSk!v&}p*6F+<2J6VTMohXK5CcZdPFiXQY+5?ICt2;%V_%MzhzySP0 zb&nnSeZUQF2tByC@mQwoY~ozOkjH*MjSf&2D0B%F+|iSR7*q3%X=xI^l2p{3NyDed zGSF!NJuiG6=u}jH7NL#q`#v8Q8#Q}=Oc+@C7IjoBpxtQ|6A z-4MR$Oj&J_NZ{0i{HRvBkDLk$GY~LmKyC^a2z5zFoTmP|m3>A?j*p8HJCNp|0~&)p zlG9fTkr+W<<4gPMQ>;+>N^hkT+1e4rJi16pX*xEZ_r1NzWSiSb2kwe^Y%ArJ+8x7&b^wzu&5tm80sfO z%BhSKa8UMiYSoy5E!ZK}hP~ZkT#nyIC?rBtwIf|Y6cU8 z1t?IUzB-*R##OMIT8F6KqgMh~I~zvL&(n9aacm`mGREkz;$Ks=GVyHEaWF>xK%Ga~ z1v8CL4H=B_T!=~|NEhBdFBb2WY{d3q8xX7jT?C>i?0p-4+37LI8TACB8$QQpQibb2 z$BWk}gP&v__k}CxSI0l_!OQ8L&EvP|IC>m?6YPKSMTML&4eMi2CSX@=ev%~3RWdAB zb`QR0;WyFj5VlLO#gHz`do%dM?0CiTrl3zNyHKKKt(iM*n!^Nxq2P2RTp#WUD(HKI zQN)+qw}S0HBFSE0xES0^C>;#pPl2~kwI>06q-wUH!3ED{kVlKrW)IEr+7@ z=xufR*`>OdCVP8tmdZRxE`JyZU^XH>5OWY<(ZU&G?a{(({Dwm*NEs_i&%8J0b`Y{r zEO=@y{KPK%yRE<`!wy0F?0&QRps(X(%qPn?kLQ91*cv-G8;`>iaTv&xziW0vleT6Z zgD4E&ID8TqhkOIZAtxf`{!wy1yrLhnH1NKTIT#=*B>s>lJP}Q9XmPWB7gtFHh5DzdMe8$6B6F`edHyfu$8t+eZe)Gi!u z<~}+ErpLdzfQNdrYRT&FXB`zNRjpHqk6aH*!Al_?ay0Z@Xw;FMjA6pM;c@``ER_ zYvyPf_v@*tQRZMqr>0&5_xHbl{LiQ6l0oWS-v59F7|)PKxg6#JmS>$uvicgP^$#JV zD^8(Fm9h^$qxqP#JgV3Ho`OBPaa>WUH6O3(2NQh6%U0fz&eu6Ai5(S0sF!~@>)6DNu7W7UQkULtEvo`<6 z=tyd2mePF_TtPwJ>yH9YEoM41tDace3o0x9#R3pJx=O!Drt>Jhg{M_o+|T3NruKjG zV$*&kL_rIf&^nIe_5KcFwjJNIih&KRcUr;DZu+Uf@m-o3p43asIZMi@MLd$y8g5}W z!?tCg1NUG!`mfa|yfDos?6Aa+cw)Zq?!}}nD$eCS?Pvl{?mh0A5fw>ORrn}auzC1cjHp$4baH_fu2M?KWUOBVgYc08A32hh{Mf(pD5d~>DO6HOltnoUs2wm}-*x=Z-gY~ECUVd@P*$0;ai~kcgvMr}&mc1r>g9*s% zNNW+mto7}ad?E3U_^Mn29NvDpDgba?G5A{?Ky6%jvbB78K?bTkRbK-31e}5tQ||}q zCiD;#?9xiKg1J3vf!rX6Wl5vi5{aLU4ae*g&G9!K*Vq{5S*=6^2~ZIACr#K*D(Rxz&oZbf+G zG)vrBf5P>euNwaFiDi{T5JP`@oj6YL6=<)Ci!8B!0B;l-KJGvA8hkMmA1k;JH{1TB z0T61FfA7GJ`VJi4ssOfWq)LsAP1YI-Nza|}PuI#zTuWGvk=y=lU@%pjN^ z4g1KS0j<%r3nxB0;n9uxf??~&VrN=te2{(h0Rk4|(Ef=fnP47pkD6B6^iIbXkWhIT zb%}K>OZlL1zVd=Wa0SUcV3Kg=Bet!5V`$)oL7686QQ9;l{D1luZa>;De-O0_rzrR8 z*REKGojrtmuq+>35KmmnKf9_1)E4k0YKd{-+Z1boI_*dPAJMbwKm7cL?3i^1WkHbS z^UywJSV1BZzLB+Bm#I+BlKUJ9i+}gq5_4;lv^`EUQzzWdkRZW6Saz-e+E3Gda&TEY zLV8JK_VLq0Yu&0dt)_62eO^`^#MoFCVgs;5b*s_eQa49$&H>2g3<&(xzX$pktjO8V zq?>1&Hz=chu_PP&^Utsz)OvNmDJ0}YNS|Llmc|bi>uAIZu}}v^^{2;@7+rEUx_g!N zYn25yZ`hp9v+(!xH3v+s5)(jKZim+q4p_#(J&DpUVrsQt_1h@mvbG%9r-LgO^M5H@ zKC-n|g9Kd;POpQV9{Fb+tHV%S0rynXsrcY0uorAEKaKcI-QUmy!xFRHaVT5nwmROAK6Klr%{hT&u1nH?Qn!S(C z!0(`lMEpK~v;5IO*Wl7?*bC~uwNh4f?;=GoLN3CwM{sjXJmTRS=V%?!M|L<$lr(TF zi8=~8dfa?cQBLM&J3OhG6&mEL$oQq?nUp@&lsv+BRQ8BZ`^@|5RqRtA87V1pKi5z? XKEDZhc>62h_X}B=*_u|E5EB0bMF~@N literal 0 HcmV?d00001 diff --git a/src/main/resources/images/reveng_16.png b/src/main/resources/images/reveng_16.png index d822d7b2772b465bd01ecfd4df0bca1fd4a1907d..b58f038bbe7b792d2fd4be66aef67a0425757539 100644 GIT binary patch delta 478 zcmV<40U`dJ1nmQm8Gi-<001BJ|6u?C0kla(K~y-)b<;a*R8bTK;O|Zb@x>H^U?RT2 z#z=}Z2COU;>=Z2RRB#X*9}$Jvh@wIe5rjmsun`9R6ACIu6kk{f5#N$v5)6V#%)?^V z$W?F`_nf=$+Iz3N);UG3Q6I!E{KO)3;55#nO*7__JA&^huzwaei&~@p6+QTZPCUma ztnqhz!y(+kQanIc1ylHpSxf}H99v4oJy?b@%;N{9p&HuV7{{3u%;FL1sNia7_hB?c zm&nHsJjO8g;u==sJOz^BBeC;(G^ten0nA6p9oUy#FSg zMXgb9?Yl7)yJkZBLy8{;^ESWNg;y;Rdvl2H#nxj1@6Ng>>;4qO{Rn@&s5R;n@p}{} zBGAiB8O?#2#zs7eYqPk8_9`ZGJm+G~aEitIqGajOFjs|-tp=6+_auHrq_Hr08t_mG z%K}zgkJXwNV;YOoa4N+`z|S;q;cd-}R>h`PgBv(d>b!s}*|%(-!)5eiRS7%z8=nAj UB+sgb&;S4c07*qoM6N<$f-lqJe*gdg literal 540 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbL!Lb6AYF9SoB8UsT^3j@P1pisjL z28L1t28LG&3=CE?7#PG0=Ijcz0ZRA<_=LCuY1f7CR42SfMjNmH0CJaH_#U(71CU`n z{muXX|F6IPz2N*ehk5V(mcB3F_4(6}f9tOO*nRis$tS;_eEK`-#Mjn?Uw%H&UIR3d zt0c%Tm?3LIg293hKO27B6FC0>D9V`R?e4<+ZA;=;Acwug)7O>#C8Ip2wHUwA`%<9L zL{AsT5Q)pa{eeP<6nI>e1CHn%+!l7_cl;HdT=$=+_IS$eE(#1~`6ynqD)7n~2BsfN zEF6S9Gt_q^A2ZR7kZ1X@{ibpJ+Ts?Ggojseuy>sfddqjFYH8M=>Bo(VCNSTrYXAC{ zC3D$hS9brHSBK2QvP(U#-eT{XGkw>#_@I`Czpw0n-CMfpZCqcj;zY(7{#=ib=nHpq zHed4>`UiBJYKdz^NlIc#s#S7PDv)9@GB7gLH89jQHViSav@*4{GBnXPFt9Q(h&L~q zgrXrgKP5A*5>11Nxs`z>L_#<^29 ztarocEM6x!jQ2QM!3C_tRxE3I?+kcN1U=M}+m5w3U(_1)wg@wy>HYp6!?E*vG^ten z0nA0nZP=4sFE-;6ri1wtMXgaU_uUwbUDKicA;k}ad7Izs!mCom-W;NPvGr)cJG1V} zx;MpeKf)g?YK{7M{2sya2=p>jMsi@LupUq1+6-=?y^4t(&)HZrlw$F|XtDH2n8L@h zK_&k^fnO16G)$fbJea~(0juR>rRK$$!ooD1OmPwLGtFCgTl1n-v7u~m1N&M!&*Mt= jrOmUrjEh*&f*tq`QY3aXgdBpQ00000NkvXXu0mjfC9&x- literal 0 HcmV?d00001 diff --git a/src/main/resources/images/reveng_24.png b/src/main/resources/images/reveng_24.png new file mode 100644 index 0000000000000000000000000000000000000000..781deae0d2e6427fa15b71b12ae040981e513fb9 GIT binary patch literal 871 zcmV-t1DO1YP)6 zTZola6bJC%IdgO-qCqDpl5RxMU{}fRW)ww1MA(ISDCwb>A<&9&OrqDql!$H=6jU!U zA_)~;p$LkkhoK0hGRGRVP_o1e%{VjX^zi+6^Ld&UZ2sT3_gPG+Q@Ih?HC>G=ID6Ws84{-bcIQRrN<0159eiDyh zDfYB55aVyvyq}E?`Cf_zm_?(urw5l}Ctm4_{?6!~+04Y^;3>g@+UDtuc5SX5htued z<35~}_1@rYad0enB)F_>!1>9=dUP^2U`GO3k`qsc-VzjO1qX3qPH-7E)@b+*mt_2u zNT0&tTEy?;ar_xar)Iv<=pP+!cX3Uav(~3gNHXe;?N5zlraoTWo1%p^@r#{zQfCf}I`1Ber zTY{ZX*lC%o??%S6_yrGRB`)Yn+%j`zT)6)lFJWtJv`fG(^Ggr*V>5omK|F@b@hU!5 z)&B}ruj=6Ve1_^2QB}~RImI=}N0B??;Nv6^UWnt(xG}oVB|zwurZsD>Jns+Zr4&!j z{At0nf{TLR)`A!c7MtxR&PYUilhDB!9m%FrEf+`m+Tfw!lQjodtIBw1627FT_ul1S zE+J?WP#tk3FIMoCLJ8(LXxe!P@ZI2o>+tBCX5k zF>piI{6;*HWVi7lZd2=~B`FIN$-4X>cVe4<8P9hapHMZr**I6jPOEF8;GsmbP<8!x zs2-)QSs%eYxKdTZLT{0On`dz_87%#Lsy=DKC4rdYn$sve6 zTZola6bJC%Idhzuh(aeYk}gs`40gZYED3^wh;Rz#p^+YX3$!8}ljt>=l!$H=6jbvN zi6~Tbg?cHHprHt)GDn&;P_ho0G~--O58r<`pT}vz=Kpt?eSajE|xo$ zzQcMPKobk$m+#eh50@^Xdk`BMBkl2{*n@Yl0{=vDOALL0yZ^_*C%6L-qbK}nJc>2= zwS|Egf2-#Gd~D748Z5&+8a0_7T!DRfr7QY-qjzpIj1|E%f&(?-*{p>cZy^q6(HF=4 zI4%2q!TI9gc<@;8sv>}kQ;RL=WNpRX1hOh8o=$p8P@okY#3ebwl^Cm~;Wu2K^;05! z8h_OyejiWZk2pFj{6=G>J-*PD+d{u%7@y%myn!!p1l!UWoAHdLX%4L>Cb~A}gBxNT z-b_l?Vt7vslktt-Hr7vOvOnn z$J&D%@DN_FMOGT&&)R=KHs-&H@1t96X=S64?tmQ;dM!DgjImp?Kbn9BR5$qST3U7l zJ4s=uG149{n~mD$5FWv8OBJq*H-oS65_WdkIYqco4-R8He!)>Zj%)BLK2`PqTGg!T z;KWjf>M5e?pvUkmZc050-4h2Nr-1N69B;?%(S0rfLZ=L^d5i5ilAM=TJU#rC!SjO4 zgWuMI7!DSj3r(Dphz_QpgE2Z9q0%jvMfv7nJNQ)1!Hudm-j{-}YN@XI)vEsOuN`kp z)hWAF<9B5WI+Rp=6XWY5e^@mtdT{|R!s^CId%S~9$!8;mcGV)S)90z#x-R}0o=mY9 z@FDI}o2Dh|-bAuF|0kS0reDVMUB;(WgKj>~)v(j*ViasAnqJlQ->Z6*c4mJR_v3n1 z3sa4XLjMiV;$S*h=J`xb=n$^$Qrwnx$l}PJtvQ(McCb_{kI?a&-Z52k?8orGuvXvZt2elu00000NkvXXu0mjfcn+n- literal 0 HcmV?d00001 diff --git a/src/main/resources/images/reveng_32.png b/src/main/resources/images/reveng_32.png deleted file mode 100644 index 0f6aca5ff7bb894c03c3419b74910d5f89ed26d8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1604 zcmV-K2D|x*P)$YB z7sa@K(U`b=AP|kR#JJX7WJv_6vIIz=VAm;yQaUqb+Rl6P-tohm&fa$1{z=oxIrpA( z-aY?&?m3ExkRu9#24Dp+AD9aGV!8m(0-OYX2EGPvEfA|HrISaQb=5qV!k zs>iZFn$ja8uZoENHyo!UA|fw~NZ#KKpjt#u{tL(H_(Mdhat&afh+O^;oe!f+MCPXZ zQzVsyWx#JeVXN|`gJC*?W(r?Q@>RCgd#I~$X5~|p-{9S*L9P#2De_96gJ+j{nUJq` z0k;Ef!@A@EoWKvjvh9ui3`T{8lM;>&w(1=B8x*+}4s9Ke$El<^>5mA@cV6fAn_S#H zQH#qPFGM)k6J>pkn>W`K0yF`O0Uba~vhf124B*oBC>!VG@nD@NuIwAMIPNzHMud)_ z$;=7KTcJH@(jO6)Ryw(RUS3?@+#BUwPn71~_-QT#o&a6}P-DWWz*Curnm{O$NLAR# z)DIfAKBVVVSDpq+k^^`WaF4Y5hAtfIOnBYAH^4pnf?OZ8xHe$1X-|MH`-1@d(xMZ! zMzR!#4|oP_4&(usNmMl&J__J`f>k0w*>b#35zU`;E*G$g2ZL?4%4Mo5mDt2v8!M1u2 zMebCVubb&&ZkbIyO@&31om}p>m|o(DuW6`pGp96_oB%~`g+~_VXUKt-8c>@qt*dZy z=%Mkn1x)lPY}y;3BV=J(;D~*QFHed6PkdP@B3z5r0EYs5H~Y|3nCf$6T-z9K(SWLK z8jq$hD|XcuR5)q!8?4^l$D+wjiaiRyciE);wmHK2Yf-L+EsnGs@cEhPjj*TwtULG8F^1f-Kty<*;?meMu~%-0pYvm2*HR@;8busvL1P+Z6L%LC$PP-AD>6%t+j=5S$n|b za2wQ?Ypj`JmyoS>9#-$}W9NxMF7!s(c~{X`{(~xZCzAoggwBvjYry2V-#|+{&8x9g zTun-es@UWMINE8@7BKOL%+U(dpBiwA*c&j6GgqQK{6&b~q*v{m3lTQVa8ejhoG}SM7lX9yWdw;Ox~XM>`U4!ip*v5fk>G9g52~ z%yRSk>I7GQ>ohps9i{t5MjnE|k18+(e3-0Bf6s=$JQ?%LH6E+a=keR}nOBxL+Qm~` z>5j761a<*K!_;~Mh-BS497NLZJ)3;&-Rz^(t5RN|^69-kc5k#9ujF?727%Wh(U7zO zuK~{wulV6oB&8)g*`0WpyjeOjZ>-erKRZN|Kar->SE8AV?PjDiIRJncfhEB5>BSBj zn9P0^N)jJM_X%D16 zsS^uS9=$c6+VboL^p7rs_nHPX%JsDI4xU}=rP!mk0`)*oT$!aUpCclz|3h2eA|kWX z{f#u3Oc0R+|Dp3EA~G?XuhB*`w}|Wzd%XIm2#LsZBH|j!PcFl0m5972_Q07d`bFez z5h)wXemV(9LjkZBScyHJSCKiMpTHi^8-Z{xM*jkxT7mQ&*W~U10000 diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index 9f25a0fb..40e0397f 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -3,6 +3,10 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.plugins.LoggingPlugin; +import generic.jar.ResourceFile; +import ghidra.GhidraTestApplicationLayout; +import utility.application.ApplicationLayout; +import ghidra.framework.GModule; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.mgr.ServiceManager; import ghidra.framework.plugintool.util.PluginException; @@ -12,12 +16,29 @@ import org.junit.After; import org.junit.Before; +import java.io.File; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; /// Base class abstract class RevEngMockableHeadedIntegrationTest extends AbstractGhidraHeadedIntegrationTest { protected TestEnv env; + /// Registers this project as a module so its data/*.theme.properties load, as for an installed extension. + @Override + protected ApplicationLayout createApplicationLayout() throws IOException { + return new GhidraTestApplicationLayout(new File(getTestDirectoryPath())) { + @Override + protected Map findGhidraModules() throws IOException { + var modules = new HashMap<>(super.findGhidraModules()); + var root = new ResourceFile(new File("").getAbsoluteFile()); + modules.put(root.getName(), new GModule(applicationRootDirs, root)); + return modules; + } + }; + } + @Before public void setup() throws IOException, PluginException { // For most tests we want to fail if a user visible error would show up. From 9a7b420bb144db32863584ed6c605da9ff23fffc Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:31:40 +0000 Subject: [PATCH 03/76] fix(ENG-4233): open portal links via OS launcher; right-click to open, double-click to pick (#220) --- .../recentanalyses/RecentAnalysisDialog.java | 63 +++++++++++-------- .../ghidra/chat/ui/AgentChatWindow.java | 4 +- .../services/api/GhidraRevengService.java | 22 +------ .../toolkit/ghidra/core/ui/WebBrowser.java | 36 +++++++++++ .../ai/reveng/RecentAnalysisDialogTest.java | 47 ++++++++++++++ .../ghidra/core/ui/WebBrowserTest.java | 34 ++++++++++ 6 files changed, 159 insertions(+), 47 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowser.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowserTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java index 0696a885..f7c91c0a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java @@ -31,6 +31,7 @@ public class RecentAnalysisDialog extends RevEngDialogComponentProvider { private final PluginTool tool; private final Program program; private final GhidraRevengService ghidraRevengService; + private final JPopupMenu portalPopup = new JPopupMenu(); public RecentAnalysisDialog(PluginTool tool, Program program) { super(ReaiPluginPackage.WINDOW_PREFIX + "Recent Analyses", true); @@ -53,34 +54,33 @@ private void buildInterface() { JPanel titlePanel = createTitlePanel("Find existing analyses for this binary"); mainPanel.add(titlePanel, BorderLayout.NORTH); - // Create the table content - // Add mouse listener to handle clicks on the Analysis ID column + // Consuming the right-click keeps the dialog's docking popup, with its tool-wide actions, from appearing + JMenuItem openInPortalItem = new JMenuItem("Open in Portal"); + openInPortalItem.addActionListener(e -> { + var selected = recentAnalysesTable.getSelectedRowObject(); + if (selected != null) { + ghidraRevengService.openPortalFor(tool, + new TypedApiInterface.AnalysisID(Math.toIntExact(selected.getAnalysisId()))); + } + }); + portalPopup.add(openInPortalItem); recentAnalysesTable.getTable().addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + showPortalPopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + showPortalPopup(e); + } + @Override public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 1) { - int row = recentAnalysesTable.getTable().rowAtPoint(e.getPoint()); - int col = recentAnalysesTable.getTable().columnAtPoint(e.getPoint()); - - if (row >= 0 && col >= 0) { - // Check if clicked column is "Analysis ID" (column 0) - String columnName = recentAnalysesTable.getTable().getColumnName(col); - if ("Analysis ID".equals(columnName)) { - AnalysisRecordBody result = recentAnalysesTable.getModel().getRowObject(row); - if (result != null) { - var analysisID = new TypedApiInterface.AnalysisID(Math.toIntExact(result.getAnalysisId())); - tool.execute(new Task("Open analysis in portal", false, false, false) { - @Override - public void run(TaskMonitor monitor) { - try { - ghidraRevengService.openPortalFor(tool, analysisID); - } catch (Exception ex) { - Msg.error(RecentAnalysisDialog.this, "Failed to open analysis in portal: " + ex.getMessage(), ex); - } - } - }, 0); - } - } + if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) { + var selected = recentAnalysesTable.getSelectedRowObject(); + if (selected != null) { + pickAnalysis(selected); } } } @@ -108,6 +108,19 @@ public void run(TaskMonitor monitor) { addWorkPanel(mainPanel); } + private void showPortalPopup(MouseEvent e) { + if (!e.isPopupTrigger()) { + return; + } + e.consume(); + JTable table = recentAnalysesTable.getTable(); + int row = table.rowAtPoint(e.getPoint()); + if (row >= 0) { + table.setRowSelectionInterval(row, row); + portalPopup.show(table, e.getX(), e.getY()); + } + } + private void pickAnalysis(AnalysisRecordBody result) { var service = tool.getService(GhidraRevengService.class); tool.execute(new Task("Attach to analysis", true, false, false) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java index 4c72652a..fdd18366 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java @@ -10,6 +10,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import ghidra.app.services.GoToService; import ghidra.app.services.ProgramManager; @@ -20,7 +21,6 @@ import ghidra.program.model.listing.Program; import ghidra.program.model.symbol.SourceType; import ghidra.program.util.ProgramLocation; -import ghidra.util.BrowserLoader; import ghidra.util.exception.DuplicateNameException; import ghidra.util.exception.InvalidInputException; import ghidra.util.task.Task; @@ -312,7 +312,7 @@ private void onLinkActivated(String href) { // A link from the agent's markdown (e.g. a portal or docs URL) — open it in the browser. if (href.startsWith("http://") || href.startsWith("https://")) { try { - BrowserLoader.display(URI.create(href).toURL(), null, tool); + WebBrowser.open(URI.create(href)); } catch (Exception e) { loggingService().warn("Failed to open link " + href + ": " + e.getMessage()); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index e573227e..0acfb3b9 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -5,6 +5,7 @@ import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.SelectableItem; import ai.reveng.toolkit.ghidra.core.AnalysisLogConsumer; import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; +import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionBoundary; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; @@ -30,7 +31,6 @@ import ghidra.program.model.symbol.*; import ghidra.program.model.util.LongPropertyMap; import ghidra.program.model.util.StringPropertyMap; -import ghidra.util.BrowserLoader; import ghidra.util.InvalidNameException; import ghidra.util.Msg; import ghidra.util.exception.CancelledException; @@ -43,7 +43,6 @@ import java.awt.*; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.MalformedURLException; import java.net.URI; import java.nio.file.InvalidPathException; import java.nio.file.Path; @@ -1131,24 +1130,7 @@ public void openPortal(ServiceProvider serviceProvider, String... subPath) { } sb.append(s); } - openURI(serviceProvider, URI.create(sb.toString())); - } - - /// Ghidra's BrowserLoader is more reliable than java.awt.Desktop, which frequently no-ops or is - /// reported unsupported inside Ghidra's JVM. It reads the manual-viewer options off the service - /// provider, which Ghidra 12.2 made mandatory, so the tool has to be threaded this far down. - private void openURI(ServiceProvider serviceProvider, URI uri){ - try { - BrowserLoader.display(uri.toURL(), null, serviceProvider); - } catch (MalformedURLException e) { - Msg.showError( - this, - null, - "URI Opening Failed", - "Browsing to URI %s failed".formatted(uri), - e - ); - } + WebBrowser.open(URI.create(sb.toString())); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowser.java b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowser.java new file mode 100644 index 00000000..607c45f9 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowser.java @@ -0,0 +1,36 @@ +package ai.reveng.toolkit.ghidra.core.ui; + +import ghidra.framework.OperatingSystem; +import ghidra.framework.Platform; +import ghidra.util.Msg; + +import java.io.IOException; +import java.net.URI; +import java.util.List; + +/// Opens URLs in the user's default browser via the OS launcher. Ghidra's BrowserLoader goes through +/// the manual-viewer option, whose macOS default in 12.2 is `anaconda-navigator`; java.awt.Desktop +/// frequently no-ops or is reported unsupported inside Ghidra's JVM. +public final class WebBrowser { + + private WebBrowser() { + } + + public static void open(URI uri) { + try { + new ProcessBuilder(command(Platform.CURRENT_PLATFORM.getOperatingSystem(), uri)).start(); + } catch (IOException e) { + Msg.showError(WebBrowser.class, null, "URI Opening Failed", + "Browsing to URI %s failed".formatted(uri), e); + } + } + + static List command(OperatingSystem os, URI uri) { + String url = uri.toString(); + return switch (os) { + case MAC_OS_X -> List.of("open", url); + case WINDOWS -> List.of("rundll32", "url.dll,FileProtocolHandler", url); + default -> List.of("xdg-open", url); + }; + } +} diff --git a/src/test/java/ai/reveng/RecentAnalysisDialogTest.java b/src/test/java/ai/reveng/RecentAnalysisDialogTest.java index aae9693b..75e4fdfe 100644 --- a/src/test/java/ai/reveng/RecentAnalysisDialogTest.java +++ b/src/test/java/ai/reveng/RecentAnalysisDialogTest.java @@ -107,6 +107,53 @@ public void testSelectRecentAnalysisFiresEventAndUpdatesKnownProgram() throws Ex eventProgramWithID.program(), knownProgram.get().program()); } + @Test + public void testDoubleClickPicksAnalysisAndRightClickOffersPortal() throws Exception { + var tool = env.getTool(); + var service = addMockedService(tool, new RecentAnalysesMockApi()); + + var builder = newX64Program("test_binary"); + builder.createMemory("test", "0x1000", 100); + var program = builder.getProgram(); + env.showTool(program); + waitForSwing(); + + AtomicBoolean eventReceived = new AtomicBoolean(false); + tool.addEventListener(RevEngAIAnalysisStatusChangedEvent.class, e -> eventReceived.set(true)); + + RecentAnalysisDialog dialog = runSwing(() -> new RecentAnalysisDialog(tool, program)); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(RecentAnalysisDialog.class); + + @SuppressWarnings("unchecked") + var tableModel = (docking.widgets.table.threaded.ThreadedTableModel) + getInstanceField("recentAnalysesTableModel", foundDialog); + waitForTableModel(tableModel); + @SuppressWarnings("unchecked") + var table = ((ghidra.util.table.GhidraFilterTable) + getInstanceField("recentAnalysesTable", foundDialog)).getTable(); + + clickTableCell(table, 0, 0, 1); + assertFalse("Single click should only select", eventReceived.get()); + + var cell = runSwing(() -> table.getCellRect(0, 0, true)); + var rightClick = new java.awt.event.MouseEvent(table, java.awt.event.MouseEvent.MOUSE_PRESSED, + System.currentTimeMillis(), java.awt.event.InputEvent.BUTTON3_DOWN_MASK, + cell.x + 1, cell.y + 1, 1, true, java.awt.event.MouseEvent.BUTTON3); + runSwing(() -> table.dispatchEvent(rightClick)); + var popup = (JPopupMenu) getInstanceField("portalPopup", foundDialog); + assertTrue("Right click should show the portal popup", runSwing(popup::isVisible)); + assertTrue("Right click should not reach the docking popup", rightClick.isConsumed()); + assertEquals(1, popup.getComponentCount()); + assertEquals("Open in Portal", ((JMenuItem) popup.getComponent(0)).getText()); + runSwing(() -> popup.setVisible(false)); + + clickTableCell(table, 0, 0, 2); + waitForCondition(eventReceived::get, "Double click should pick the analysis"); + assertEquals(RecentAnalysesMockApi.MOCK_ANALYSIS_ID, + service.getKnownProgram(program).orElseThrow().analysisID().id()); + } + @Test public void testDialogShowsRecentAnalyses() throws Exception { var tool = env.getTool(); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowserTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowserTest.java new file mode 100644 index 00000000..ff9363c3 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowserTest.java @@ -0,0 +1,34 @@ +package ai.reveng.toolkit.ghidra.core.ui; + +import ghidra.framework.OperatingSystem; +import org.junit.Test; + +import java.net.URI; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Guards that URLs open with the OS's own launcher, not Ghidra's manual-viewer setting, whose 12.2 + * macOS default ({@code anaconda-navigator}) is usually missing (ENG-4233). + */ +public class WebBrowserTest { + + private static final URI URL = URI.create("https://portal.reveng.ai/analyses/1229816"); + + @Test + public void macUsesOpen() { + assertEquals(List.of("open", URL.toString()), WebBrowser.command(OperatingSystem.MAC_OS_X, URL)); + } + + @Test + public void linuxUsesXdgOpen() { + assertEquals(List.of("xdg-open", URL.toString()), WebBrowser.command(OperatingSystem.LINUX, URL)); + } + + @Test + public void windowsUsesUrlProtocolHandler() { + assertEquals(List.of("rundll32", "url.dll,FileProtocolHandler", URL.toString()), + WebBrowser.command(OperatingSystem.WINDOWS, URL)); + } +} From 129d27d0b1a6948af30bebf7dc78f602ebb5ef89 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:54:04 +0000 Subject: [PATCH 04/76] fix(ENG-4402): sort and colour BigDecimal similarity and confidence cells (#221) --- .../AbstractFunctionMatchingDialog.java | 24 +--- ...nctionLevelFunctionMatchingDialogTest.java | 105 ++++++++++++++++++ 2 files changed, 108 insertions(+), 21 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 6a28b86f..13975510 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -351,8 +351,8 @@ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - if (value instanceof String percentageStr) { - Color textColor = getColorForPercentage(percentageStr); + if (value instanceof java.math.BigDecimal percentage) { + Color textColor = getColorForPercentage(percentage.toPlainString()); if (!isSelected) { // Set text color based on percentage value @@ -404,20 +404,6 @@ private Color getColorForPercentage(String percentageStr) { } } - /** - * Parse a percentage string (e.g., "95.50%") into a double value for sorting - */ - protected Double parsePercentage(String percentageStr) { - if (percentageStr == null || percentageStr.equals("N/A")) { - return -1.0; // Sort N/A values to the bottom - } - try { - return Double.parseDouble(percentageStr.replace("%", "").trim()); - } catch (NumberFormatException e) { - return -1.0; // Sort unparseable values to the bottom - } - } - /** * Configure custom comparators for percentage columns to enable proper numerical sorting * @param similarityColumnIndex the index of the similarity column @@ -426,11 +412,7 @@ protected Double parsePercentage(String percentageStr) { protected void configurePercentageColumnSorting(int similarityColumnIndex, int confidenceColumnIndex) { if (resultsTable.getRowSorter() != null) { javax.swing.table.TableRowSorter sorter = (javax.swing.table.TableRowSorter) resultsTable.getRowSorter(); - java.util.Comparator percentageComparator = (s1, s2) -> { - Double val1 = parsePercentage(s1); - Double val2 = parsePercentage(s2); - return val1.compareTo(val2); - }; + java.util.Comparator percentageComparator = java.math.BigDecimal::compareTo; sorter.setComparator(similarityColumnIndex, percentageComparator); sorter.setComparator(confidenceColumnIndex, percentageComparator); } diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index 50a7f74b..253765e5 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -16,6 +16,8 @@ import org.junit.Test; import javax.swing.*; +import java.awt.Color; +import java.math.BigDecimal; import java.util.List; import static org.junit.Assert.*; @@ -322,6 +324,109 @@ public void testSelectedMatchFollowsSortOrderNotModelOrder() throws Exception { waitForSwing(); } + @Test + public void testSortBySimilarityAndConfidence() throws Exception { + var tool = env.getTool(); + + var mockApi = new MultiMatchMockApi() { + @Override + public GetMatchesOutputBody getFunctionsMatches(List functionIds) { + var response = super.getFunctionsMatches(functionIds); + var matches = response.getMatches().get(0).getMatchedFunctions(); + matches.get(0).setConfidence(0.0); + matches.get(2).setConfidence(null); + return response; + } + }; + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForTasks(); + waitForSwing(); + waitForCondition(() -> resultsTable.getRowCount() == 3, + "Results table should hold all three mocked matches"); + + // Similarity: zeta 0.50, alpha 0.95, mid 0.72 + runSwing(() -> resultsTable.getRowSorter().toggleSortOrder(1)); + waitForSwing(); + assertEquals("zeta_match", resultsTable.getValueAt(0, 0)); + assertEquals("mid_match", resultsTable.getValueAt(1, 0)); + assertEquals("alpha_match", resultsTable.getValueAt(2, 0)); + + // Confidence: zeta 0, alpha 0.95, mid null + runSwing(() -> resultsTable.getRowSorter().toggleSortOrder(2)); + waitForSwing(); + assertEquals("mid_match", resultsTable.getValueAt(0, 0)); + assertEquals("zeta_match", resultsTable.getValueAt(1, 0)); + assertEquals("alpha_match", resultsTable.getValueAt(2, 0)); + + close(foundDialog); + waitForSwing(); + } + + @Test + public void testSimilarityAndConfidenceCellsAreColorCoded() throws Exception { + var tool = env.getTool(); + + var mockApi = new FunctionMatchingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForTasks(); + waitForSwing(); + waitForCondition(() -> resultsTable.getRowCount() > 0, "Results table should have rows"); + + // Similarity (1) and Confidence (2) hold BigDecimal values on a 0-100 scale + for (int column : new int[]{1, 2}) { + var renderer = runSwing(() -> resultsTable.getCellRenderer(0, column)); + var high = runSwing(() -> renderer.getTableCellRendererComponent( + resultsTable, new BigDecimal("99.93"), false, false, 0, column).getForeground()); + assertEquals(new Color(0, 100, 0), high); + var low = runSwing(() -> renderer.getTableCellRendererComponent( + resultsTable, BigDecimal.ZERO, false, false, 0, column).getForeground()); + assertEquals(new Color(255, 0, 0), low); + } + + close(foundDialog); + waitForSwing(); + } + /** * Returns several matches whose server order differs from their alphabetical order, so that * sorting the results table genuinely separates view indices from model indices. From d98da388b3ca66ef076f28a749506745873f7051 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:00:57 +0000 Subject: [PATCH 05/76] fix(ENG-4412): show only status in check status dialog (#222) --- .../ghidra/plugins/AnalysisManagementPlugin.java | 6 +++++- .../plugins/AnalysisManagementPluginTest.java | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index e850e755..51e48278 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -238,7 +238,7 @@ public void run(TaskMonitor monitor) { SwingUtilities.invokeLater(() -> { analysisLogComponent.setLogs(logs); Msg.showInfo(AnalysisManagementPlugin.this, null, ReaiPluginPackage.WINDOW_PREFIX + "Check status", - "Status of analysis " + knownProgram + ": " + status); + checkStatusMessage(status)); }); } catch (Exception e) { Msg.error(AnalysisManagementPlugin.this, "Failed to check analysis status: " + e.getMessage(), e); @@ -378,4 +378,8 @@ public void processEvent(PluginEvent event) { } } + static String checkStatusMessage(AnalysisStatus status) { + return "Analysis status: " + status; + } + } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java b/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java new file mode 100644 index 00000000..45e31cca --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java @@ -0,0 +1,14 @@ +package ai.reveng.toolkit.ghidra.plugins; + +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AnalysisManagementPluginTest { + + @Test + public void checkStatusMessageShowsOnlyStatus() { + assertEquals("Analysis status: Complete", AnalysisManagementPlugin.checkStatusMessage(AnalysisStatus.Complete)); + } +} From 81f7b7aa51b96ec93e113a00b2221c2588adbe70 Mon Sep 17 00:00:00 2001 From: Rob Marsal Date: Tue, 10 Nov 2026 17:11:31 +0000 Subject: [PATCH 06/76] test: assert theme colours in similarity cell colour test --- .../ai/reveng/FunctionLevelFunctionMatchingDialogTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index 253765e5..419295e4 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -16,7 +16,7 @@ import org.junit.Test; import javax.swing.*; -import java.awt.Color; +import generic.theme.GColor; import java.math.BigDecimal; import java.util.List; @@ -417,10 +417,10 @@ public void testSimilarityAndConfidenceCellsAreColorCoded() throws Exception { var renderer = runSwing(() -> resultsTable.getCellRenderer(0, column)); var high = runSwing(() -> renderer.getTableCellRendererComponent( resultsTable, new BigDecimal("99.93"), false, false, 0, column).getForeground()); - assertEquals(new Color(0, 100, 0), high); + assertEquals(new GColor("color.fg.reveng.similarity.low"), high); var low = runSwing(() -> renderer.getTableCellRendererComponent( resultsTable, BigDecimal.ZERO, false, false, 0, column).getForeground()); - assertEquals(new Color(255, 0, 0), low); + assertEquals(new GColor("color.fg.reveng.similarity.critical"), low); } close(foundDialog); From 66076e14368bb2afdeb6de1f8d7717beb82e0d17 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:18:08 +0000 Subject: [PATCH 07/76] feat(ENG-4404): open matched binary in portal from function matching results (#223) --- .../AbstractFunctionMatchingDialog.java | 49 ++++++++++++++++- .../BinaryLevelFunctionMatchingDialog.java | 2 +- .../FunctionLevelFunctionMatchingDialog.java | 2 +- .../services/api/types/FunctionMatch.java | 6 ++- .../java/ai/reveng/ApplyMatchCmdTest.java | 3 +- ...nctionLevelFunctionMatchingDialogTest.java | 52 +++++++++++++++++++ .../core/services/api/SdkSchemaTest.java | 2 +- 7 files changed, 108 insertions(+), 8 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 13975510..a8a477ee 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -11,6 +11,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; +import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Function; import ghidra.util.task.Task; import ghidra.util.task.TaskBuilder; @@ -24,6 +25,8 @@ import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -32,6 +35,7 @@ import java.util.stream.Collectors; public abstract class AbstractFunctionMatchingDialog extends RevEngDialogComponentProvider { + protected final PluginTool tool; protected final GhidraRevengService revengService; protected final GhidraRevengService.AnalysedProgram analyzedProgram; @@ -56,6 +60,7 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone // Assembly comparison panel protected AssemblyDiffPanel assemblyDiffPanel; + private final JPopupMenu portalPopup = new JPopupMenu(); // Data protected AnalysisBasicInfoOutputBody analysisBasicInfo; @@ -65,10 +70,11 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone // Polling configuration protected static final int POLL_INTERVAL_MS = 2000; // Poll every 2 seconds - protected AbstractFunctionMatchingDialog(String title, Boolean isModal, GhidraRevengService revengService, + protected AbstractFunctionMatchingDialog(String title, Boolean isModal, PluginTool tool, GhidraRevengService.AnalysedProgram analyzedProgram) { super(title, isModal); - this.revengService = revengService; + this.tool = tool; + this.revengService = tool.getService(GhidraRevengService.class); this.analyzedProgram = analyzedProgram; this.taskMonitorComponent = new TaskMonitorComponent(false, true); this.functionMatchResults = new ArrayList<>(); @@ -601,6 +607,27 @@ protected JPanel createResultsContainer() { } }); + // Consuming the right-click keeps the dialog's docking popup, with its tool-wide actions, from appearing + JMenuItem openInPortalItem = new JMenuItem("Open in Portal"); + openInPortalItem.addActionListener(e -> { + var analysisID = getSelectedMatchedAnalysisID(); + if (analysisID != null) { + revengService.openPortalFor(tool, analysisID); + } + }); + portalPopup.add(openInPortalItem); + resultsTable.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + showPortalPopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + showPortalPopup(e); + } + }); + // Create assembly comparison panel assemblyDiffPanel = new AssemblyDiffPanel(); @@ -641,6 +668,24 @@ protected void onTableSelectionChanged() { assemblyDiffPanel.showAssemblyFor(selectedMatch, revengService); } + private void showPortalPopup(MouseEvent e) { + if (!e.isPopupTrigger()) { + return; + } + e.consume(); + int row = resultsTable.rowAtPoint(e.getPoint()); + if (row >= 0) { + resultsTable.setRowSelectionInterval(row, row); + portalPopup.getComponent(0).setEnabled(getSelectedMatchedAnalysisID() != null); + portalPopup.show(resultsTable, e.getX(), e.getY()); + } + } + + private TypedApiInterface.AnalysisID getSelectedMatchedAnalysisID() { + var selected = getSelectedMatches(); + return selected.size() == 1 ? selected.get(0).functionMatch().nearest_neighbor_analysis_id() : null; + } + protected JPanel createRenameButtonsPanel() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java index 0721b759..3a3d3284 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java @@ -16,7 +16,7 @@ public class BinaryLevelFunctionMatchingDialog extends AbstractFunctionMatchingD public BinaryLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID) { super(ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", true, - tool.getService(GhidraRevengService.class), programWithBinaryID); + tool, programWithBinaryID); } @Override diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java index 9cb72692..25bdd4cb 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java @@ -18,7 +18,7 @@ public class FunctionLevelFunctionMatchingDialog extends AbstractFunctionMatchin public FunctionLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID, Function function) { super(ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", true, - tool.getService(GhidraRevengService.class), programWithBinaryID); + tool, programWithBinaryID); this.function = function; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java index 14ce1906..6c042552 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java @@ -22,7 +22,8 @@ public record FunctionMatch( TypedApiInterface.BinaryHash nearest_neighbor_sha_256_hash, Boolean nearest_neighbor_debug, BigDecimal similarity, - BigDecimal confidence + BigDecimal confidence, + @Nullable TypedApiInterface.AnalysisID nearest_neighbor_analysis_id ) { @@ -36,7 +37,8 @@ public static FunctionMatch fromMatchedFunctionAPIType(MatchedFunction matchedFu new TypedApiInterface.BinaryHash(matchedFunction.getSha256Hash()), matchedFunction.getDebug(), matchedFunction.getSimilarity() == null ? null : BigDecimal.valueOf(matchedFunction.getSimilarity()), - matchedFunction.getConfidence() == null ? null : BigDecimal.valueOf(matchedFunction.getConfidence()) + matchedFunction.getConfidence() == null ? null : BigDecimal.valueOf(matchedFunction.getConfidence()), + matchedFunction.getAnalysisId() == null ? null : new TypedApiInterface.AnalysisID(Math.toIntExact(matchedFunction.getAnalysisId())) ); } diff --git a/src/test/java/ai/reveng/ApplyMatchCmdTest.java b/src/test/java/ai/reveng/ApplyMatchCmdTest.java index bade3af4..74493e01 100644 --- a/src/test/java/ai/reveng/ApplyMatchCmdTest.java +++ b/src/test/java/ai/reveng/ApplyMatchCmdTest.java @@ -43,7 +43,8 @@ public void testFailedServerRenameDoesNotLeakTransaction() throws Exception { new BinaryHash("abc123"), false, BigDecimal.valueOf(0.9), - BigDecimal.valueOf(0.9)); + BigDecimal.valueOf(0.9), + null); var ghidraMatch = new GhidraFunctionMatchWithSignature(func1, match, null); var cmd = new ApplyMatchCmd(service, analysedProgram, ghidraMatch, true); diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index 419295e4..e7f93070 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -427,6 +427,58 @@ public void testSimilarityAndConfidenceCellsAreColorCoded() throws Exception { waitForSwing(); } + @Test + public void testRightClickOffersMatchedBinaryInPortal() throws Exception { + var tool = env.getTool(); + + var mockApi = new MultiMatchMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + assertNull(invokeInstanceMethod("getSelectedMatchedAnalysisID", foundDialog)); + + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForTasks(); + waitForSwing(); + waitForCondition(() -> resultsTable.getRowCount() == 3, + "Results table should hold all three mocked matches"); + + var cell = runSwing(() -> resultsTable.getCellRect(1, 0, true)); + var rightClick = new java.awt.event.MouseEvent(resultsTable, java.awt.event.MouseEvent.MOUSE_PRESSED, + System.currentTimeMillis(), java.awt.event.InputEvent.BUTTON3_DOWN_MASK, + cell.x + 1, cell.y + 1, 1, true, java.awt.event.MouseEvent.BUTTON3); + runSwing(() -> resultsTable.dispatchEvent(rightClick)); + var popup = (JPopupMenu) getInstanceField("portalPopup", foundDialog); + assertTrue("Right click should show the portal popup", runSwing(popup::isVisible)); + assertTrue("Right click should not reach the docking popup", rightClick.isConsumed()); + assertEquals("Right click should select the row under the cursor", 1, resultsTable.getSelectedRow()); + var item = (JMenuItem) popup.getComponent(0); + assertEquals("Open in Portal", item.getText()); + assertTrue(item.isEnabled()); + assertEquals(new TypedApiInterface.AnalysisID(12345), + invokeInstanceMethod("getSelectedMatchedAnalysisID", foundDialog)); + runSwing(() -> popup.setVisible(false)); + + close(foundDialog); + waitForSwing(); + } + /** * Returns several matches whose server order differs from their alphabetical order, so that * sorting the results table genuinely separates view indices from model indices. diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java index 7a058ddd..465f7d57 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java @@ -130,7 +130,7 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { "getCollectionIds", "getBinaryIds", "getDebugTypes"); requireMethods(missing, "ai.reveng.model.GetMatchesOutputBody", "getMatches", "getStatus"); requireMethods(missing, "ai.reveng.model.MatchedFunction", - "getFunctionId", "getFunctionName", "getSimilarity", "getConfidence"); + "getFunctionId", "getFunctionName", "getSimilarity", "getConfidence", "getAnalysisId"); requireMethods(missing, "ai.reveng.model.BatchRenameInputBody", "setFunctions"); requireMethods(missing, "ai.reveng.model.BatchRenameItem", "setFunctionId", "setNewName", "setNewMangledName"); From 01c30a87cd4352f3d64ae4b57fab1a73a8ae7c0e Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:25:34 +0000 Subject: [PATCH 08/76] feat(ENG-4399): auto-run single function matching with 5 results (#224) --- .../FunctionLevelFunctionMatchingDialog.java | 7 ++++++- .../FunctionLevelFunctionMatchingDialogTest.java | 13 ++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java index 25bdd4cb..dbe61604 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java @@ -24,6 +24,11 @@ public FunctionLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService. private List matchingFunctionIds; + @Override + protected void dialogShown() { + filterResults(); + } + @Override protected MatchingProgress startMatching() throws ApiException { var functionIDOpt = analyzedProgram.getIDForFunction(function); @@ -35,7 +40,7 @@ protected MatchingProgress startMatching() throws ApiException { var request = new StartMatchingForFunctionsInputBody(); request.setFunctionIds(matchingFunctionIds); request.setMinSimilarity((double) getThreshold()); - request.setResultsPerFunction(25L); + request.setResultsPerFunction(5L); request.setFilters(buildMatchFilters()); var response = revengService.startFunctionsMatching(request); diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index e7f93070..b9123c01 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -177,11 +177,12 @@ public void testFunctionMatchingTriggersAPICall() throws Exception { var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); assertNotNull("Dialog should be shown", foundDialog); - // Verify the initial status message - JLabel statusLabel = (JLabel) getInstanceField("statusLabel", foundDialog); - assertNotNull("Status label should exist", statusLabel); - assertTrue("Status should show ready message", - statusLabel.getText().contains("Ready")); + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + waitForCondition(() -> resultsTable.getRowCount() > 0, + "Results table should populate without pressing Match Functions"); + assertTrue("Function matching API should have been called", mockApi.functionMatchingCalled); + assertEquals("Should request 5 results per function", + Long.valueOf(5L), mockApi.lastMatchingRequest.getResultsPerFunction()); // Close the dialog close(foundDialog); @@ -530,6 +531,7 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { static class FunctionMatchingMockApi extends UnimplementedAPI { private final AnalysisStatus currentStatus = AnalysisStatus.Complete; boolean functionMatchingCalled = false; + StartMatchingForFunctionsInputBody lastMatchingRequest; @Override public TypedApiInterface.AnalysisID analyse(AnalysisOptionsBuilder options) { @@ -568,6 +570,7 @@ public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.Analys @Override public StartMatchingOutputBody startFunctionsMatching(StartMatchingForFunctionsInputBody request) { functionMatchingCalled = true; + lastMatchingRequest = request; var response = new StartMatchingOutputBody(); response.setStatus(StartMatchingOutputBody.StatusEnum.COMPLETED); return response; From 9ef714331b2f5b25f78eec32907d352d3209b885 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:27:59 +0000 Subject: [PATCH 09/76] feat(ENG-4401): prompt users to update the plugin (#225) --- .../ui/about/AboutDialog.java | 42 +++---- .../core/services/update/UpdateChecker.java | 110 ++++++++++++++++++ .../ghidra/plugins/ReaiAPIServicePlugin.java | 57 ++++++++- .../services/update/UpdateCheckerTest.java | 60 ++++++++++ 4 files changed, 245 insertions(+), 24 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java index c7de3e9e..d9c2f935 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java @@ -1,42 +1,30 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.about; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; +import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker; +import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker.UpdateInfo; +import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import ghidra.framework.plugintool.PluginTool; -import resources.ResourceManager; import javax.swing.*; import java.awt.*; -import java.io.IOException; -import java.nio.charset.StandardCharsets; +import java.net.URI; +import java.util.Optional; import ai.reveng.invoker.Configuration; /** * Shows a dialog with about information. */ public class AboutDialog extends RevEngDialogComponentProvider { - public AboutDialog(PluginTool tool) { - super(ReaiPluginPackage.WINDOW_PREFIX + "About", true); + private final Optional update; - buildInterface(getPluginVersion()); - setPreferredSize(300, 210); - } + public AboutDialog(PluginTool tool, Optional update) { + super(ReaiPluginPackage.WINDOW_PREFIX + "About", true); + this.update = update; - private String getPluginVersion() { - String pluginVersion = "unknown"; - try { - // This resource is written by the release workflow, so it is absent from a local build - // and the stream is then null. - var inputStream = ResourceManager.getResourceAsStream("reai_ghidra_plugin_version.txt"); - if (inputStream != null) { - pluginVersion = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8).trim(); - inputStream.close(); - } - } catch (IOException e) { - // ignore — fall back to "unknown" - } - - return pluginVersion; + buildInterface(UpdateChecker.currentVersion()); + setPreferredSize(300, update.isPresent() ? 250 : 210); } private void buildInterface(String pluginVersion) { @@ -73,6 +61,14 @@ private JPanel createAboutContent(String pluginVersion) { sdkLabel.setAlignmentX(Component.CENTER_ALIGNMENT); panel.add(sdkLabel); + update.ifPresent(u -> { + panel.add(Box.createVerticalStrut(10)); + JButton updateButton = new JButton("Update available: " + u.version()); + updateButton.setAlignmentX(Component.CENTER_ALIGNMENT); + updateButton.addActionListener(e -> WebBrowser.open(URI.create(u.releaseUrl()))); + panel.add(updateButton); + }); + return panel; } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java new file mode 100644 index 00000000..07b4daa5 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java @@ -0,0 +1,110 @@ +package ai.reveng.toolkit.ghidra.core.services.update; + +import org.json.JSONException; +import org.json.JSONObject; +import resources.ResourceManager; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** + * Checks GitHub for a plugin release newer than the installed one. + */ +public class UpdateChecker { + public static final String UNKNOWN_VERSION = "unknown"; + private static final String LATEST_RELEASE_URL = + "https://api.github.com/repos/RevEngAI/plugin-ghidra/releases/latest"; + + public record UpdateInfo(String version, String releaseUrl, String downloadUrl) {} + + /** + * The installed plugin's release tag, or {@link #UNKNOWN_VERSION} for local builds. + */ + public static String currentVersion() { + // This resource is written by the release workflow, so it is absent from a local build + // and the stream is then null. + try (var inputStream = ResourceManager.getResourceAsStream("reai_ghidra_plugin_version.txt")) { + if (inputStream != null) { + return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + } catch (IOException e) { + // ignore — fall back to "unknown" + } + return UNKNOWN_VERSION; + } + + /** + * Fetches the latest release. Completes empty when up to date, when no build exists for + * {@code ghidraVersion}, or on any failure. + */ + public static CompletableFuture> check(String currentVersion, String ghidraVersion) { + var request = HttpRequest.newBuilder(URI.create(LATEST_RELEASE_URL)) + .header("Accept", "application/vnd.github+json") + .timeout(Duration.ofSeconds(10)) + .build(); + return HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()) + .thenApply(response -> response.statusCode() == 200 + ? findUpdate(currentVersion, ghidraVersion, response.body()) + : Optional.empty()) + .exceptionally(e -> Optional.empty()); + } + + static Optional findUpdate(String currentVersion, String ghidraVersion, String releaseJson) { + try { + var release = new JSONObject(releaseJson); + var latest = release.getString("tag_name"); + if (!isNewer(latest, currentVersion)) { + return Optional.empty(); + } + var assetName = "ghidra_" + ghidraVersion + "_plugin-ghidra.zip"; + var assets = release.getJSONArray("assets"); + for (int i = 0; i < assets.length(); i++) { + var asset = assets.getJSONObject(i); + if (assetName.equals(asset.getString("name"))) { + return Optional.of(new UpdateInfo(latest, release.getString("html_url"), + asset.getString("browser_download_url"))); + } + } + } catch (JSONException ignored) { + } + return Optional.empty(); + } + + static boolean isNewer(String candidate, String current) { + var a = parse(candidate); + var b = parse(current); + if (a.isEmpty() || b.isEmpty()) { + return false; + } + for (int i = 0; i < 3; i++) { + if (a.get()[i] != b.get()[i]) { + return a.get()[i] > b.get()[i]; + } + } + return false; + } + + private static Optional parse(String version) { + var parts = version.strip().replaceFirst("^v", "").split("\\."); + if (parts.length != 3) { + return Optional.empty(); + } + try { + var numbers = new int[3]; + for (int i = 0; i < 3; i++) { + numbers[i] = Integer.parseInt(parts[i]); + } + return Optional.of(numbers); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java index 9a4c49db..5a2202a2 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java @@ -4,21 +4,28 @@ import ai.reveng.toolkit.ghidra.binarysimilarity.ui.help.HelpDialog; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.ApiInfo; +import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker; +import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker.UpdateInfo; +import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardManager; import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardStateKey; import docking.ActionContext; import docking.action.builder.ActionBuilder; +import docking.widgets.OptionDialog; import docking.wizard.WizardManager; import docking.wizard.WizardState; import ghidra.app.plugin.PluginCategoryNames; +import ghidra.framework.Application; import ghidra.framework.plugintool.Plugin; import ghidra.framework.plugintool.PluginInfo; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.util.PluginStatus; import ghidra.util.Msg; +import ghidra.util.Swing; import org.json.JSONException; import java.io.FileNotFoundException; +import java.net.URI; import java.nio.file.Path; import java.util.Optional; @@ -34,14 +41,21 @@ ) public class ReaiAPIServicePlugin extends Plugin { private GhidraRevengService revengService; + private Optional update = Optional.empty(); + // One startup prompt per Ghidra session, even with several tools open. + private static boolean updatePromptShown = false; private static final String REAI_PLUGIN_SETUP_MENU_GROUP = "RevEng.AI Setup"; public static final String REAI_WIZARD_RUN_PREF = "REAISetupWizardRun"; + public static final String CHECK_FOR_UPDATES_PREF = "Check for updates"; + public static final String SKIPPED_UPDATE_PREF = "Skipped update version"; public ReaiAPIServicePlugin(PluginTool tool) { super(tool); tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(REAI_WIZARD_RUN_PREF, "false", null, "If the setup wizard has been run"); + tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(CHECK_FOR_UPDATES_PREF, true, null, "Check GitHub for a newer plugin release on startup"); + tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(SKIPPED_UPDATE_PREF, "", null, "Release the user chose not to be prompted about"); // Try to get API info from config file or tool options Optional apiInfoOpt = getApiInfoFromConfig() @@ -61,6 +75,47 @@ public ReaiAPIServicePlugin(PluginTool tool) { registerServiceProvided(GhidraRevengService.class, revengService); setupActions(); + checkForUpdates(); + } + + private void checkForUpdates() { + var currentVersion = UpdateChecker.currentVersion(); + if (!tool.getOptions(REAI_OPTIONS_CATEGORY).getBoolean(CHECK_FOR_UPDATES_PREF, true) + || currentVersion.equals(UpdateChecker.UNKNOWN_VERSION)) { + return; + } + UpdateChecker.check(currentVersion, Application.getApplicationVersion()) + .thenAccept(result -> result.ifPresent(u -> Swing.runLater(() -> notifyUpdate(u)))); + } + + private void notifyUpdate(UpdateInfo u) { + // The check can outlive the tool. + if (isDisposed()) { + return; + } + update = Optional.of(u); + + new ActionBuilder("Update available", this.toString()) + .withContext(ActionContext.class) + .onAction(context -> WebBrowser.open(URI.create(u.downloadUrl()))) + .menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "Update available (" + u.version() + ")" }) + .menuGroup(REAI_PLUGIN_SETUP_MENU_GROUP, "050") + .buildAndInstall(tool); + tool.setStatusInfo("RevEng.AI plugin " + u.version() + " is available"); + + var options = tool.getOptions(REAI_OPTIONS_CATEGORY); + if (updatePromptShown || u.version().equals(options.getString(SKIPPED_UPDATE_PREF, ""))) { + return; + } + updatePromptShown = true; + int choice = OptionDialog.showOptionNoCancelDialog(tool.getToolFrame(), "RevEng.AI update available", + "RevEng.AI plugin " + u.version() + " is available. You have " + UpdateChecker.currentVersion() + ".", + "Download", "Later", "Skip this version", OptionDialog.INFORMATION_MESSAGE); + if (choice == OptionDialog.OPTION_ONE) { + WebBrowser.open(URI.create(u.downloadUrl())); + } else if (choice == OptionDialog.OPTION_THREE) { + options.setString(SKIPPED_UPDATE_PREF, u.version()); + } } /** @@ -114,7 +169,7 @@ private void setupActions() { new ActionBuilder("About", this.toString()) .withContext(ActionContext.class) .onAction(context -> { - var aboutDialog = new AboutDialog(tool); + var aboutDialog = new AboutDialog(tool, update); tool.showDialog(aboutDialog); }) .menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "About" }) diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java new file mode 100644 index 00000000..f1d83225 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java @@ -0,0 +1,60 @@ +package ai.reveng.toolkit.ghidra.core.services.update; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** Unit tests for the pure parts of {@link UpdateChecker}. */ +public class UpdateCheckerTest { + + private static final String RELEASE = """ + {"tag_name": "v1.2.0", + "html_url": "https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0", + "assets": [ + {"name": "ghidra_12.1.3_plugin-ghidra.zip", "browser_download_url": "https://example/12.1.3.zip"}, + {"name": "ghidra_12.2_plugin-ghidra.zip", "browser_download_url": "https://example/12.2.zip"} + ]} + """; + + @Test + public void comparesSemanticVersions() { + assertTrue(UpdateChecker.isNewer("v1.2.0", "v1.1.9")); + assertTrue(UpdateChecker.isNewer("v2.0.0", "v1.10.10")); + assertTrue(UpdateChecker.isNewer("v1.10.0", "v1.9.0")); + assertFalse(UpdateChecker.isNewer("v1.1.0", "v1.1.0")); + assertFalse(UpdateChecker.isNewer("v1.0.9", "v1.1.0")); + } + + @Test + public void unparseableVersionsAreNeverNewer() { + assertFalse(UpdateChecker.isNewer("v1.2.0", UpdateChecker.UNKNOWN_VERSION)); + assertFalse(UpdateChecker.isNewer("latest", "v1.0.0")); + assertFalse(UpdateChecker.isNewer("v1.2", "v1.0.0")); + } + + @Test + public void findsAssetForGhidraVersion() { + var update = UpdateChecker.findUpdate("v1.1.0", "12.2", RELEASE).orElseThrow(); + assertEquals("v1.2.0", update.version()); + assertEquals("https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0", update.releaseUrl()); + assertEquals("https://example/12.2.zip", update.downloadUrl()); + } + + @Test + public void noUpdateWhenCurrent() { + assertTrue(UpdateChecker.findUpdate("v1.2.0", "12.2", RELEASE).isEmpty()); + } + + @Test + public void noUpdateWithoutAssetForGhidraVersion() { + assertTrue(UpdateChecker.findUpdate("v1.1.0", "11.4", RELEASE).isEmpty()); + } + + @Test + public void noUpdateOnMalformedJson() { + assertTrue(UpdateChecker.findUpdate("v1.1.0", "12.2", "not json").isEmpty()); + assertTrue(UpdateChecker.findUpdate("v1.1.0", "12.2", "{}").isEmpty()); + } +} From a34938f190dbd0487575c67fda1acabb69d6c6fa Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:28:14 +0000 Subject: [PATCH 10/76] feat(ENG-4405): always show user submitted debug symbols option (#226) --- .../AbstractFunctionMatchingDialog.java | 4 +- ...nctionLevelFunctionMatchingDialogTest.java | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index a8a477ee..0671ba6d 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -779,11 +779,11 @@ protected JPanel createDebugSymbolsPanel() { debugSymbolsCheckBox = new JCheckBox("Only include functions with debug symbols", false); debugSymbolsCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); debugSymbolsCheckBox.addActionListener( - e -> userSubmittedDebugSymbolsCheckBox.setVisible(debugSymbolsCheckBox.isSelected())); + e -> userSubmittedDebugSymbolsCheckBox.setEnabled(debugSymbolsCheckBox.isSelected())); userSubmittedDebugSymbolsCheckBox = new JCheckBox("Include user submitted debug symbols", false); userSubmittedDebugSymbolsCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); - userSubmittedDebugSymbolsCheckBox.setVisible(false); + userSubmittedDebugSymbolsCheckBox.setEnabled(false); JPanel indentedPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); indentedPanel.setAlignmentX(Component.LEFT_ALIGNMENT); diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index b9123c01..880e50d4 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -152,6 +152,47 @@ public void testAssemblyComparisonPanelExists() throws Exception { waitForSwing(); } + @Test + public void testUserSubmittedDebugSymbolsAlwaysVisibleAndEnabledByParent() throws Exception { + var tool = env.getTool(); + + var mockApi = new FunctionMatchingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JCheckBox debugSymbols = (JCheckBox) getInstanceField("debugSymbolsCheckBox", foundDialog); + JCheckBox userSubmitted = (JCheckBox) getInstanceField("userSubmittedDebugSymbolsCheckBox", foundDialog); + + assertTrue(userSubmitted.isVisible()); + assertFalse(userSubmitted.isEnabled()); + + setToggleButtonSelected(debugSymbols, true); + assertTrue(userSubmitted.isVisible()); + assertTrue(userSubmitted.isEnabled()); + + setToggleButtonSelected(debugSymbols, false); + assertTrue(userSubmitted.isVisible()); + assertFalse(userSubmitted.isEnabled()); + + close(foundDialog); + waitForSwing(); + } + @Test public void testFunctionMatchingTriggersAPICall() throws Exception { var tool = env.getTool(); From d0f1c98c833afb9cba6a2d1132750b9460566692 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:35:40 +0000 Subject: [PATCH 11/76] fix(ENG-4375): handle unsized data types in decoder (#227) --- .../services/api/ServerDataTypeDecoder.java | 2 +- .../ai/reveng/ServerDataTypeDecoderTest.java | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java index e915caca..c10bfb0f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java @@ -338,7 +338,7 @@ private static long toLong(String value) { /// An exact-width filler for a type we could not build. Ghidra only has undefined1/2/4/8, so /// anything else becomes an array of undefined1 to keep the surrounding layout intact. - private static DataType undefined(long size) { + private static DataType undefined(@Nullable Long size) { long clamped = clampSize(size); if (clamped == 1 || clamped == 2 || clamped == 4 || clamped == 8) { return Undefined.getUndefinedDataType((int) clamped); diff --git a/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java b/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java index 6772a52a..03619c96 100644 --- a/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java +++ b/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java @@ -218,4 +218,21 @@ public void resolvesBaseTypesByName() { assertEquals("int", decoder.typeFor(1L, 0).getName()); } + + /// `size` is nullable on the wire. An unsized type that falls back to a filler must not fail the + /// decode. + @Test + public void unsizedTypesFallBackToFiller() { + var decoder = ServerDataTypeDecoder.decode(types(""" + {"items": [ + {"data_type_id": 1, "namespace": "", "name": "not_a_ghidra_type", "kind": "BASE", + "size": null, "source_type": "AUTO", "has_definition": false}, + {"data_type_id": 2, "namespace": "", "name": "orphan_t", "kind": "TYPEDEF", + "source_type": "AUTO", "has_definition": false} + ]} + """)); + + assertEquals(1, decoder.typeFor(1L, 0).getLength()); + assertTrue(decoder.typeFor(2L, 0) instanceof TypeDef); + } } From a0859be1097f1c5ff95787e5fd8f2116c6ecbc24 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:15:11 +0000 Subject: [PATCH 12/76] feat(ENG-4421): bump ai.reveng:sdk to 4.75.1-rc.1 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index d218f62c..1c0150b1 100644 --- a/build.gradle +++ b/build.gradle @@ -69,7 +69,7 @@ dependencies { implementation group: 'com.fifesoft', name: 'rsyntaxtextarea', version: '3.5.2' implementation 'org.commonmark:commonmark:0.24.0' implementation 'org.commonmark:commonmark-ext-gfm-tables:0.24.0' - implementation('ai.reveng:sdk:4.75.0') + implementation('ai.reveng:sdk:4.75.1-rc.1') testImplementation('junit:junit:4.13.1') testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.8.2") // Version comes from the junit-bom pulled in by junit-vintage-engine. From 6567b3bd7366994d36777ca3a538ea184836347f Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:26:11 +0000 Subject: [PATCH 13/76] ci: run tests on PRs into staging --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9e1a6082..91f1b817 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,7 +2,7 @@ name: build on: pull_request: - branches: [ "main" ] + branches: [ "main", "staging" ] jobs: build: From 839ad1ff79576ca3b266e855a3012f1915a50c54 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:07:34 +0000 Subject: [PATCH 14/76] fix(ENG-4400): keep Ghidra responsive when the network is down Bound DNS lookups on the SDK HTTP client, since OkHttp's connect timeout does not cover resolution and offline it can block for minutes. Move the analysis status check on program open and the loading of finished analysis results off the Swing thread into background tasks. --- .../ghidra/core/services/api/TimeoutDns.java | 49 ++++++++++ .../services/api/TypedApiImplementation.java | 8 +- .../plugins/AnalysisManagementPlugin.java | 92 +++++++++++-------- .../reveng/PortalAnalysisIntegrationTest.java | 2 + .../core/services/api/TimeoutDnsTest.java | 59 ++++++++++++ 5 files changed, 171 insertions(+), 39 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDns.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDnsTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDns.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDns.java new file mode 100644 index 00000000..e384e01e --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDns.java @@ -0,0 +1,49 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import okhttp3.Dns; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/// A {@link Dns} that gives up on a lookup after {@code timeout}. +/// +/// OkHttp's connect timeout only starts once an address is resolved. Without a working network +/// the system resolver can block for far longer than that, so every request, and any thread +/// waiting on one, hangs until the OS gives up on DNS. +public record TimeoutDns(Dns delegate, Duration timeout) implements Dns { + + private static final ExecutorService RESOLVER = Executors.newCachedThreadPool(runnable -> { + var thread = new Thread(runnable, "RevEng.AI-DNS"); + thread.setDaemon(true); + return thread; + }); + + @Override + public List lookup(String hostname) throws UnknownHostException { + var lookup = RESOLVER.submit(() -> delegate.lookup(hostname)); + try { + return lookup.get(timeout.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + lookup.cancel(true); + throw new UnknownHostException("DNS lookup for %s timed out after %ds".formatted(hostname, timeout.toSeconds())); + } catch (ExecutionException e) { + if (e.getCause() instanceof UnknownHostException unknownHost) { + throw unknownHost; + } + var unknownHost = new UnknownHostException("DNS lookup for %s failed".formatted(hostname)); + unknownHost.initCause(e.getCause()); + throw unknownHost; + } catch (InterruptedException e) { + lookup.cancel(true); + Thread.currentThread().interrupt(); + throw new UnknownHostException("DNS lookup for %s was interrupted".formatted(hostname)); + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 76c7cffb..0061881c 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.time.Duration; import java.util.*; import java.util.stream.Collectors; @@ -31,6 +32,7 @@ import com.google.gson.JsonParser; import ai.reveng.invoker.auth.ApiKeyAuth; import ai.reveng.invoker.ApiException; +import okhttp3.Dns; import static ai.reveng.toolkit.ghidra.core.services.api.LoggingInterceptor.*; @@ -85,7 +87,11 @@ public TypedApiImplementation(String baseUrl, String apiKey) { // Use a custom HTTP client to add Ghidra specific logging // Set withResponseBody to true if debugging issues with the API to see the full response body - apiClient.setHttpClient(apiClient.getHttpClient().newBuilder().addInterceptor(ghidraLogger(false)).build()); + // Bound DNS too: the connect timeout below doesn't cover it, and offline it can hang for minutes + apiClient.setHttpClient(apiClient.getHttpClient().newBuilder() + .addInterceptor(ghidraLogger(false)) + .dns(new TimeoutDns(Dns.SYSTEM, Duration.ofSeconds(5))) + .build()); apiClient.setConnectTimeout(5000); apiClient.setReadTimeout(15000); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 51e48278..130017a0 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -287,32 +287,45 @@ protected void programOpened(Program program) { // This can happen if the analysis was started in a previous session but hadn't finished when closing Ghidra // Either the analysis is finished already now, or we want to actively wait for it to finish log.info("Detected known program that hasn't been fully loaded yet: {}", knownProgram.get()); - var status = revengService.status(knownProgram.get()); - switch (status) { - case Complete -> { - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); + // Off the Swing thread: programs are opened on it, and without network the request blocks until it times out + tool.execute(new Task("Check RevEng.AI analysis status", false, false, false) { + @Override + public void run(TaskMonitor monitor) { + AnalysisStatus status; + try { + status = revengService.status(knownProgram.get()); + } catch (Exception e) { + Msg.warn(AnalysisManagementPlugin.this, + "Could not check the RevEng.AI analysis status for " + knownProgram.get() + ": " + e.getMessage()); + return; + } + switch (status) { + case Complete -> { + tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent( + "programOpened", + knownProgram.get(), + status)); + } + case Queued, Processing -> { + // This is the same code as above, but it has the implicit assumption that someone + /// Currently this is done by {@link AnalysisLogComponent#processEvent(RevEngAIAnalysisStatusChangedEvent)} + tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent( + "programOpened", + knownProgram.get(), + status)); + } + + + case Error -> { + // The analysis failed on the server side + Msg.showError(AnalysisManagementPlugin.this, null, "Analysis Error", + "The RevEng.AI analysis for the program " + knownProgram.get() + " is in error state on the server side."); + } + } } - case Queued, Processing -> { - // This is the same code as above, but it has the implicit assumption that someone - /// Currently this is done by {@link AnalysisLogComponent#processEvent(RevEngAIAnalysisStatusChangedEvent)} - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); - } - - - case Error -> { - // The analysis failed on the server side - Msg.showError(this, null, "Analysis Error", - "The RevEng.AI analysis for the program " + knownProgram.get() + " is in error state on the server side."); - } - } + }, 0); } } else { log.info("Opened unknown program: {}", program.getName()); @@ -361,19 +374,22 @@ public void processEvent(PluginEvent event) { // If the analysis is complete, we refresh the function signatures from the server var program = analysisEvent.getProgramWithBinaryID(); - try { - // TODO: Can we get a better taskmonitor here? - // Or should we never do something here that warrants a monitor in the first place? - var analysedProgram = revengService.registerFinishedAnalysisForProgram(program, TaskMonitor.DUMMY); - localEditSyncService.attach(program.program()); - tool.firePluginEvent(new RevEngAIAnalysisResultsLoaded("AnalysisManagementPlugin", analysedProgram)); - // Auto-unstrip runs server-side after the analysis is marked complete, so poll for it - // and sync the recovered names / data types once it finishes (PLU-300). - autoUnstripSyncService.pollAndSync(analysedProgram, true); - } catch (Exception e) { - Msg.error(this, "Error registering finished analysis for program " + program, e); - return; - } + // Events arrive on the Swing thread, and loading the results makes several requests + tool.execute(new Task("Load RevEng.AI analysis results", true, false, false) { + @Override + public void run(TaskMonitor monitor) { + try { + var analysedProgram = revengService.registerFinishedAnalysisForProgram(program, monitor); + localEditSyncService.attach(program.program()); + tool.firePluginEvent(new RevEngAIAnalysisResultsLoaded("AnalysisManagementPlugin", analysedProgram)); + // Auto-unstrip runs server-side after the analysis is marked complete, so poll for it + // and sync the recovered names / data types once it finishes (PLU-300). + autoUnstripSyncService.pollAndSync(analysedProgram, true); + } catch (Exception e) { + Msg.error(AnalysisManagementPlugin.this, "Error registering finished analysis for program " + program, e); + } + } + }, 0); } } } diff --git a/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java b/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java index 016b1fd8..a8fc6cc8 100644 --- a/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java +++ b/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java @@ -190,6 +190,8 @@ public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { ), false ); + // The results are loaded in a background task + waitForTasks(); waitForSwing(); // Check that we received the results loaded event, i.e. other plugins would have been notified assertTrue(receivedResultsLoadedEvent.get()); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDnsTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDnsTest.java new file mode 100644 index 00000000..bf021ac1 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDnsTest.java @@ -0,0 +1,59 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import okhttp3.Dns; +import org.junit.Test; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CountDownLatch; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * Covers {@link TimeoutDns}, which stops a hanging DNS lookup (e.g. with no network) from + * blocking a request past OkHttp's connect timeout. + */ +public class TimeoutDnsTest { + + @Test + public void returnsTheDelegatesAddresses() throws Exception { + var addresses = List.of(InetAddress.getByAddress("api.reveng.ai", new byte[]{10, 0, 0, 1})); + var dns = new TimeoutDns(hostname -> addresses, Duration.ofSeconds(1)); + + assertEquals(addresses, dns.lookup("api.reveng.ai")); + } + + @Test + public void failsWhenTheLookupHangs() { + var neverReleased = new CountDownLatch(1); + Dns hanging = hostname -> { + try { + neverReleased.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return List.of(); + }; + var dns = new TimeoutDns(hanging, Duration.ofMillis(200)); + + long start = System.nanoTime(); + var e = assertThrows(UnknownHostException.class, () -> dns.lookup("api.reveng.ai")); + long elapsedMillis = (System.nanoTime() - start) / 1_000_000; + + assertTrue(e.getMessage(), e.getMessage().contains("timed out")); + assertTrue("lookup should give up near the timeout, took " + elapsedMillis + "ms", elapsedMillis < 2000); + } + + @Test + public void passesThroughUnknownHost() { + var unknown = new UnknownHostException("no such host"); + var dns = new TimeoutDns(hostname -> { throw unknown; }, Duration.ofSeconds(1)); + + assertSame(unknown, assertThrows(UnknownHostException.class, () -> dns.lookup("nope.invalid"))); + } +} From 3e4ba55f6e9849e25a8883ddd1484fe43c5f9659 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:28:21 +0000 Subject: [PATCH 15/76] feat(ENG-4403): add platform, architecture and user filters to function matching Match the portal's Match Settings: platform (Linux, Windows, Android) and architecture (x86 64/32-bit, ARM 64-bit) toggles, where none ticked means any, and a user search backed by v3ListUsers. The selections go out in MatchFilters for both binary- and function-level matching, which now share one buildMatchFilters. --- .../ui/components/UserSelectionPanel.java | 35 ++++++ .../AbstractFunctionMatchingDialog.java | 119 +++++++++++++++++- .../BinaryLevelFunctionMatchingDialog.java | 19 --- .../FunctionLevelFunctionMatchingDialog.java | 19 --- .../services/api/GhidraRevengService.java | 21 ++++ .../services/api/TypedApiImplementation.java | 8 ++ .../core/services/api/TypedApiInterface.java | 4 + ...nctionLevelFunctionMatchingDialogTest.java | 53 +++++++- .../core/services/api/SdkSchemaTest.java | 5 +- 9 files changed, 242 insertions(+), 41 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/UserSelectionPanel.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/UserSelectionPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/UserSelectionPanel.java new file mode 100644 index 00000000..b63a13d4 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/UserSelectionPanel.java @@ -0,0 +1,35 @@ +package ai.reveng.toolkit.ghidra.binarysimilarity.ui.components; + +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.List; + +/** + * A component that allows multiple selection of users with autocomplete support. + * This is a specialized version of ItemSelectionPanel for users. + */ +public class UserSelectionPanel extends ItemSelectionPanel { + + /** + * @param dynamicUserLoader Function that takes a query string and returns matching users + * @param minimumQueryLength Minimum characters before triggering API calls (the users endpoint needs 3) + */ + public UserSelectionPanel(Function>> dynamicUserLoader, int minimumQueryLength) { + super(dynamicUserLoader, minimumQueryLength, "User"); + } + + /** + * Gets the IDs of currently selected users + */ + public Set getSelectedUserIds() { + return getSelectedItemIds(); + } + + /** + * Gets the names of currently selected users + */ + public Set getSelectedUserNames() { + return getSelectedItemNames(); + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 0671ba6d..3301e86d 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -8,6 +8,7 @@ import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.CollectionSelectionPanel; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.BinarySelectionPanel; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.SelectableItem; +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.UserSelectionPanel; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; @@ -28,6 +29,7 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -50,6 +52,10 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone protected JLabel thresholdValueLabel; protected JCheckBox debugSymbolsCheckBox; protected JCheckBox userSubmittedDebugSymbolsCheckBox; + protected UserSelectionPanel userSelector; + // Nothing ticked means any platform / architecture, as in the portal + protected final Map platformCheckBoxes = new LinkedHashMap<>(); + protected final Map architectureCheckBoxes = new LinkedHashMap<>(); protected JLabel statusLabel; protected JTextArea errorArea; protected JScrollPane errorScrollPane; @@ -560,6 +566,21 @@ protected JPanel createFilterPanel() { gbc.insets = new Insets(0, 0, 0, 0); filterPanel.add(createDebugSymbolsPanel(), gbc); + // Row 2, Col 0: Platform and architecture toggles (50% width), as tall as the user selector beside it + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 2; + gbc.weightx = 0.5; + gbc.insets = new Insets(10, 0, 0, 10); + filterPanel.add(createPlatformArchitecturePanel(), gbc); + + // Row 2, Col 1: User selector (50% width) + gbc.gridx = 1; + gbc.gridy = 2; + gbc.weightx = 0.5; + gbc.insets = new Insets(10, 0, 0, 0); + filterPanel.add(createUserSelectorPanel(), gbc); + return filterPanel; } @@ -798,6 +819,52 @@ protected JPanel createDebugSymbolsPanel() { return panel; } + protected JPanel createPlatformArchitecturePanel() { + JPanel panel = new JPanel(new GridBagLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Platform & architecture")); + panel.setToolTipText("Leave unticked to match any platform or architecture"); + + platformCheckBoxes.put(MatchFilters.PlatformsEnum.LINUX, new JCheckBox("Linux")); + platformCheckBoxes.put(MatchFilters.PlatformsEnum.WINDOWS, new JCheckBox("Windows")); + platformCheckBoxes.put(MatchFilters.PlatformsEnum.ANDROID, new JCheckBox("Android")); + + architectureCheckBoxes.put(MatchFilters.ArchitecturesEnum.X86_64, new JCheckBox("x86 (64-bit)")); + architectureCheckBoxes.put(MatchFilters.ArchitecturesEnum.X86_32, new JCheckBox("x86 (32-bit)")); + architectureCheckBoxes.put(MatchFilters.ArchitecturesEnum.ARM_64, new JCheckBox("ARM (64-bit)")); + + GridBagConstraints gbc = new GridBagConstraints(); + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(0, 5, 0, 5); + + gbc.gridy = 0; + panel.add(new JLabel("Platforms:"), gbc); + for (JCheckBox checkBox : platformCheckBoxes.values()) { + panel.add(checkBox, gbc); + } + + gbc.gridy = 1; + panel.add(new JLabel("Architectures:"), gbc); + for (JCheckBox checkBox : architectureCheckBoxes.values()) { + panel.add(checkBox, gbc); + } + + // Keep the toggles left-aligned when the panel is wider than they are + gbc.gridy = 0; + gbc.weightx = 1; + panel.add(Box.createHorizontalGlue(), gbc); + + return panel; + } + + protected JPanel createUserSelectorPanel() { + userSelector = new UserSelectionPanel( + query -> revengService.searchUsersWithIds(query), + 3 + ); + + return userSelector; + } + protected JPanel createFunctionFilterPanel() { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createTitledBorder("Filter matches by function virtual address, name, hash or binary")); @@ -879,6 +946,52 @@ public boolean isUserSubmittedDebugSymbolsEnabled() { return userSubmittedDebugSymbolsCheckBox != null && userSubmittedDebugSymbolsCheckBox.isSelected(); } + public List getSelectedPlatforms() { + return platformCheckBoxes.entrySet().stream() + .filter(entry -> entry.getValue().isSelected()) + .map(Map.Entry::getKey) + .toList(); + } + + public List getSelectedArchitectures() { + return architectureCheckBoxes.entrySet().stream() + .filter(entry -> entry.getValue().isSelected()) + .map(Map.Entry::getKey) + .toList(); + } + + /// The filters sent with the matching request, from the current state of the filter panel + protected MatchFilters buildMatchFilters() { + var filters = new MatchFilters(); + filters.setCollectionIds(collectionSelector.getSelectedCollectionIds().stream() + .map(Integer::longValue).toList()); + filters.setBinaryIds(binarySelector.getSelectedBinaryIds().stream() + .map(Integer::longValue).toList()); + + if (isDebugSymbolsEnabled()) { + var debugTypes = new ArrayList(); + debugTypes.add("SYSTEM"); + if (isUserSubmittedDebugSymbolsEnabled()) { + debugTypes.add("USER"); + } + filters.setDebugTypes(debugTypes); + } + + var platforms = getSelectedPlatforms(); + if (!platforms.isEmpty()) { + filters.setPlatforms(platforms); + } + var architectures = getSelectedArchitectures(); + if (!architectures.isEmpty()) { + filters.setArchitectures(architectures); + } + var userIds = userSelector.getSelectedUserIds(); + if (!userIds.isEmpty()) { + filters.setUserIds(userIds.stream().map(Integer::longValue).toList()); + } + return filters; + } + protected void filterResults() { Set selectedCollectionIds = collectionSelector.getSelectedCollectionIds(); Set selectedBinaryIds = binarySelector.getSelectedBinaryIds(); @@ -899,7 +1012,11 @@ protected void filterResults() { " (IDs: " + selectedBinaryIds + "), threshold: " + threshold + ", debug symbols: " + includeDebugSymbols + - ", user submitted debug symbols: " + includeUserSubmittedDebugSymbols); + ", user submitted debug symbols: " + includeUserSubmittedDebugSymbols + + ", platforms: " + getSelectedPlatforms() + + ", architectures: " + getSelectedArchitectures() + + ", users: " + userSelector.getSelectedUserNames() + + " (IDs: " + userSelector.getSelectedUserIds() + ")"); taskMonitorComponent.setVisible(true); startFunctionMatching(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java index 3a3d3284..9862076f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java @@ -10,7 +10,6 @@ import javax.swing.*; import java.awt.*; -import java.util.ArrayList; public class BinaryLevelFunctionMatchingDialog extends AbstractFunctionMatchingDialog { @@ -47,24 +46,6 @@ protected java.util.List fetchMatches() throws ApiExcepti return flattenMatches(revengService.getAnalysisFunctionMatches(analyzedProgram.analysisID()).getMatches()); } - private MatchFilters buildMatchFilters() { - var filters = new MatchFilters(); - filters.setCollectionIds(collectionSelector.getSelectedCollectionIds().stream() - .map(Integer::longValue).toList()); - filters.setBinaryIds(binarySelector.getSelectedBinaryIds().stream() - .map(Integer::longValue).toList()); - - if (isDebugSymbolsEnabled()) { - var debugTypes = new ArrayList(); - debugTypes.add("SYSTEM"); - if (isUserSubmittedDebugSymbolsEnabled()) { - debugTypes.add("USER"); - } - filters.setDebugTypes(debugTypes); - } - return filters; - } - @Override protected String[] getTableColumnNames() { return new String[]{"Virtual Address", "Function Name", "Matched Function", "Similarity", "Confidence", "Matched Hash", "Matched Binary"}; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java index dbe61604..2ee713fa 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java @@ -10,7 +10,6 @@ import javax.swing.*; import java.awt.*; -import java.util.ArrayList; import java.util.List; public class FunctionLevelFunctionMatchingDialog extends AbstractFunctionMatchingDialog { @@ -64,24 +63,6 @@ protected List fetchMatches() throws ApiException { return flattenMatches(revengService.getFunctionsMatches(matchingFunctionIds).getMatches()); } - private MatchFilters buildMatchFilters() { - var filters = new MatchFilters(); - filters.setCollectionIds(collectionSelector.getSelectedCollectionIds().stream() - .map(Integer::longValue).toList()); - filters.setBinaryIds(binarySelector.getSelectedBinaryIds().stream() - .map(Integer::longValue).toList()); - - if (isDebugSymbolsEnabled()) { - var debugTypes = new ArrayList(); - debugTypes.add("SYSTEM"); - if (isUserSubmittedDebugSymbolsEnabled()) { - debugTypes.add("USER"); - } - filters.setDebugTypes(debugTypes); - } - return filters; - } - @Override protected String[] getTableColumnNames() { return new String[]{"Matched Function", "Similarity", "Confidence", "Matched Hash", "Matched Binary"}; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 0acfb3b9..be055262 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1273,6 +1273,27 @@ public CompletableFuture> searchBinariesWithIds(String quer }); } + public CompletableFuture> searchUsersWithIds(String query) { + return CompletableFuture.supplyAsync(() -> { + try { + List selectableItems = api.searchUsers(query).stream() + .filter(result -> result.getUsername() != null && !result.getUsername().trim().isEmpty()) + .map(result -> new SelectableItem( + Math.toIntExact(result.getUserId()), + result.getUsername() + )) + .collect(Collectors.toList()); + + Msg.info(this, "Found " + selectableItems.size() + " users matching '" + query + "'"); + return selectableItems; + + } catch (Exception e) { + Msg.error(this, "Error searching users: " + e.getMessage(), e); + return List.of(); + } + }); + } + public AnalysisBasicInfoOutputBody getBasicDetailsForAnalysis(TypedApiInterface.AnalysisID analysisID) throws ApiException { return api.getAnalysisBasicInfo(analysisID); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 0061881c..65bd3de6 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -60,6 +60,7 @@ public class TypedApiImplementation implements TypedApiInterface { private final FunctionsAiDecompilationApi functionsAiDecompilationApi; private final DataTypesApi dataTypesApi; private final IamUsersApi iamUsersApi; + private final AuthenticationUsersApi authenticationUsersApi; private final Map analysisBasicInfoCache = new HashMap<>(); @@ -109,6 +110,7 @@ public TypedApiImplementation(String baseUrl, String apiKey) { this.dataTypesApi = new DataTypesApi(apiClient); this.configApi = new ConfigApi(apiClient); this.iamUsersApi = new IamUsersApi(apiClient); + this.authenticationUsersApi = new AuthenticationUsersApi(apiClient); } @@ -599,6 +601,12 @@ public List searchBinaries(String partialBinaryName, String return this.searchApi.searchBinaries(1, 10, partialBinaryName, null, null, modelName, null, null, null).getData().getResults(); } + @Override + public List searchUsers(String searchTerm) throws ApiException { + var results = this.authenticationUsersApi.v3ListUsers(searchTerm).getResults(); + return results != null ? results : List.of(); + } + @Override public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(AnalysisID analysisID) throws ApiException { AnalysisBasicInfoOutputBody cachedResult = analysisBasicInfoCache.get(analysisID); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java index 789ab84e..7cf48888 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java @@ -209,6 +209,10 @@ default List searchBinaries(String partialCollectionName, St throw new UnsupportedOperationException("searchBinaries not implemented yet"); } + default List searchUsers(String searchTerm) throws ApiException { + throw new UnsupportedOperationException("searchUsers not implemented yet"); + } + default AnalysisBasicInfoOutputBody getAnalysisBasicInfo(AnalysisID analysisID) throws ApiException { throw new UnsupportedOperationException("getAnalysisBasicInfo not implemented yet"); } diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index 880e50d4..e1c0c49f 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -230,6 +230,57 @@ public void testFunctionMatchingTriggersAPICall() throws Exception { waitForSwing(); } + @Test + @SuppressWarnings("unchecked") + public void testPlatformAndArchitectureTogglesAreSentAsMatchFilters() throws Exception { + var tool = env.getTool(); + + var mockApi = new FunctionMatchingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + // The automatic run on open leaves platform, architecture and user unfiltered, i.e. any + waitForCondition(() -> mockApi.lastMatchingRequest != null, "Matching should start when the dialog opens"); + MatchFilters initialFilters = mockApi.lastMatchingRequest.getFilters(); + assertNull(initialFilters.getPlatforms()); + assertNull(initialFilters.getArchitectures()); + assertNull(initialFilters.getUserIds()); + waitForTasks(); + + var platforms = (java.util.Map) getInstanceField("platformCheckBoxes", foundDialog); + var architectures = (java.util.Map) getInstanceField("architectureCheckBoxes", foundDialog); + setToggleButtonSelected(platforms.get(MatchFilters.PlatformsEnum.LINUX), true); + setToggleButtonSelected(architectures.get(MatchFilters.ArchitecturesEnum.ARM_64), true); + + var firstRequest = mockApi.lastMatchingRequest; + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForCondition(() -> mockApi.lastMatchingRequest != firstRequest, "Pressing Match Functions should start a new match"); + waitForTasks(); + + MatchFilters filters = mockApi.lastMatchingRequest.getFilters(); + assertEquals(List.of(MatchFilters.PlatformsEnum.LINUX), filters.getPlatforms()); + assertEquals(List.of(MatchFilters.ArchitecturesEnum.ARM_64), filters.getArchitectures()); + assertNull(filters.getUserIds()); + + close(foundDialog); + waitForSwing(); + } + @Test public void testClickMatchButtonPopulatesResultsTable() throws Exception { var tool = env.getTool(); @@ -572,7 +623,7 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { static class FunctionMatchingMockApi extends UnimplementedAPI { private final AnalysisStatus currentStatus = AnalysisStatus.Complete; boolean functionMatchingCalled = false; - StartMatchingForFunctionsInputBody lastMatchingRequest; + volatile StartMatchingForFunctionsInputBody lastMatchingRequest; @Override public TypedApiInterface.AnalysisID analyse(AnalysisOptionsBuilder options) { diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java index 465f7d57..1c60d6d9 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java @@ -34,6 +34,7 @@ public void apiClientsExposeMethodsThePluginCalls() { apis.put("ai.reveng.api.ConfigApi", new String[]{"getConfig"}); apis.put("ai.reveng.api.SearchApi", new String[]{"searchBinaries"}); apis.put("ai.reveng.api.CollectionsApi", new String[]{"v3ListCollections"}); + apis.put("ai.reveng.api.AuthenticationUsersApi", new String[]{"v3ListUsers"}); apis.put("ai.reveng.api.AnalysesCoreApi", new String[]{ "uploadFile", "createAnalysis", "getAnalysisStatus", "getAnalysisBasicInfo_0", "startAnalysisFunctionMatching", "getAnalysisFunctionMatchingStatus", "getAnalysisFunctionMatches", @@ -127,7 +128,9 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.StartMatchingForFunctionsInputBody", "getFunctionIds", "getResultsPerFunction", "getFilters", "getMinSimilarity"); requireMethods(missing, "ai.reveng.model.MatchFilters", - "getCollectionIds", "getBinaryIds", "getDebugTypes"); + "getCollectionIds", "getBinaryIds", "getDebugTypes", "getPlatforms", "getArchitectures", "getUserIds"); + requireMethods(missing, "ai.reveng.model.ListPublicUsersOutputBody", "getResults"); + requireMethods(missing, "ai.reveng.model.PublicUserBody", "getUserId", "getUsername"); requireMethods(missing, "ai.reveng.model.GetMatchesOutputBody", "getMatches", "getStatus"); requireMethods(missing, "ai.reveng.model.MatchedFunction", "getFunctionId", "getFunctionName", "getSimilarity", "getConfidence", "getAnalysisId"); From e5286151cee8ec94203799f3edc22307782daf1a Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:34:49 +0000 Subject: [PATCH 16/76] feat(ENG-4406): redesign function matching dialog and fix its progress bar Split the dialog into "Filter Search" and "Filter Results" sections with the Match Functions button right-aligned under the filters. Filters get captions instead of titled boxes, in two equal columns; selectors show a search hint and only show their tag strip once something is selected. The results count moves next to the results filter, and the table and assembly comparison share the space evenly. Progress: the step reported by the server is now shown (it was dropped), the bar fills by completed steps, and the Match button turns into a working Cancel while a run is going. A cancelled run can no longer hide the progress bar of, or write results into, the run that replaced it. Renames get a task dialog instead of the hidden matching bar. --- .../ui/components/ItemSelectionPanel.java | 42 +- .../components/SimpleAutocompleteField.java | 11 +- .../AbstractFunctionMatchingDialog.java | 423 ++++++++++-------- .../BinaryLevelFunctionMatchingDialog.java | 10 +- .../FunctionLevelFunctionMatchingDialog.java | 8 +- ...nctionLevelFunctionMatchingDialogTest.java | 103 ++++- 6 files changed, 367 insertions(+), 230 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java index 835080ea..d1a8e73e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java @@ -18,6 +18,7 @@ public class ItemSelectionPanel extends JPanel { private SimpleAutocompleteField autocompleteField; private JPanel selectedItemsPanel; + private JScrollPane tagsScrollPane; private final Set selectedItems; private final List listeners; private Function>> dynamicItemLoader; @@ -42,29 +43,35 @@ public ItemSelectionPanel(Function addSelectedItem()); @@ -125,8 +133,13 @@ private void addItemTag(SelectableItem item) { tagPanel.add(removeButton, BorderLayout.EAST); selectedItemsPanel.add(tagPanel); - selectedItemsPanel.revalidate(); - selectedItemsPanel.repaint(); + updateTagsVisibility(); + } + + private void updateTagsVisibility() { + tagsScrollPane.setVisible(!selectedItems.isEmpty()); + revalidate(); + repaint(); } private Border createTagBorder() { @@ -139,8 +152,7 @@ private Border createTagBorder() { private void removeItem(SelectableItem item, JPanel tagPanel) { selectedItems.remove(item); selectedItemsPanel.remove(tagPanel); - selectedItemsPanel.revalidate(); - selectedItemsPanel.repaint(); + updateTagsVisibility(); notifyListeners(); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java index 20560e8a..46f4c4a1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java @@ -1,5 +1,7 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.components; +import docking.widgets.textfield.HintTextField; + import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; @@ -19,7 +21,7 @@ * Uses dynamic API-based collection fetching only. */ public class SimpleAutocompleteField extends JPanel { - private JTextField textField; + private HintTextField textField; private JList suggestionsList; private JScrollPane suggestionsScrollPane; private JPopupMenu suggestionsPopup; @@ -45,7 +47,7 @@ private void initializeComponents() { setLayout(new BorderLayout()); // Create text field - textField = new JTextField(); + textField = new HintTextField(""); textField.setPreferredSize(new Dimension(250, textField.getPreferredSize().height)); add(textField, BorderLayout.CENTER); @@ -234,6 +236,11 @@ public void setText(String text) { textField.setText(text); } + /// Greyed-out text shown while the field is empty + public void setHint(String hint) { + textField.setHint(hint); + } + public void clear() { textField.setText(""); hideSuggestions(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 3301e86d..d2bb5b63 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -12,12 +12,12 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; +import docking.widgets.textfield.HintTextField; import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Function; import ghidra.util.task.Task; import ghidra.util.task.TaskBuilder; import ghidra.util.task.TaskMonitor; -import ghidra.util.task.TaskMonitorComponent; import ghidra.util.Msg; import resources.ResourceManager; import generic.theme.GThemeDefaults.Colors.Messages; @@ -57,11 +57,15 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone protected final Map platformCheckBoxes = new LinkedHashMap<>(); protected final Map architectureCheckBoxes = new LinkedHashMap<>(); protected JLabel statusLabel; + protected JProgressBar matchingProgressBar; + protected JButton matchButton; + private Icon matchIcon; + protected JLabel resultsCountLabel; protected JTextArea errorArea; protected JScrollPane errorScrollPane; - protected final TaskMonitorComponent taskMonitorComponent; - protected volatile boolean matchingCancelled; - protected Thread matchingThread; + /// The thread of the current matching run; null when idle or cancelled. A run whose thread is no + /// longer this one has been superseded, and must not touch the UI. + protected volatile Thread matchingThread; protected JPanel renameButtonsPanel; // Assembly comparison panel @@ -82,7 +86,6 @@ protected AbstractFunctionMatchingDialog(String title, Boolean isModal, PluginTo this.tool = tool; this.revengService = tool.getService(GhidraRevengService.class); this.analyzedProgram = analyzedProgram; - this.taskMonitorComponent = new TaskMonitorComponent(false, true); this.functionMatchResults = new ArrayList<>(); this.filteredFunctionMatchResults = new ArrayList<>(); @@ -105,23 +108,37 @@ protected AbstractFunctionMatchingDialog(String title, Boolean isModal, PluginTo setPreferredSize(1200, 1000); // Don't start function matching automatically - wait for user to click Match button - statusLabel.setText("Ready - adjust filters and click 'Match Functions' to begin search"); - taskMonitorComponent.setVisible(false); + statusLabel.setText("Ready: adjust the filters and press Match Functions"); } protected void startFunctionMatching() { - // Show initial status. All network work runs on a background thread so the UI stays responsive; - // the bar is indeterminate (animated) until/unless the server reports step counters. + // All network work runs on a background thread so the UI stays responsive statusLabel.setText("Starting function matching..."); - taskMonitorComponent.initialize(100); - taskMonitorComponent.setIndeterminate(true); + matchingProgressBar.setIndeterminate(true); + setMatchingInProgress(true); - matchingCancelled = false; matchingThread = new Thread(this::runMatchingLoop, "RevEngAI function matching"); matchingThread.setDaemon(true); matchingThread.start(); } + /// Shows or hides the progress bar, and turns the Match button into Cancel while a run is going + protected void setMatchingInProgress(boolean inProgress) { + matchingProgressBar.setVisible(inProgress); + matchButton.setText(inProgress ? "Cancel" : "Match Functions"); + matchButton.setIcon(inProgress ? null : matchIcon); + } + + /// Runs {@code update} on the EDT, unless the run on {@code self} has been cancelled or superseded + /// by the time it gets there + private void onEdtIfCurrent(Thread self, Runnable update) { + SwingUtilities.invokeLater(() -> { + if (matchingThread == self) { + update.run(); + } + }); + } + /// Normalised view of the v3 matching progress, shared by the start and status responses protected record MatchingProgress(String status, String step, Long stepIndex, Long stepsTotal, String errorMessage) {} @@ -135,19 +152,20 @@ protected record MatchingProgress(String status, String step, Long stepIndex, Lo protected abstract List fetchMatches() throws ai.reveng.invoker.ApiException; private void runMatchingLoop() { + final Thread self = Thread.currentThread(); try { MatchingProgress progress = startMatching(); - while (!matchingCancelled) { + while (matchingThread == self) { final MatchingProgress current = progress; - SwingUtilities.invokeLater(() -> updateProgressUI(current)); + onEdtIfCurrent(self, () -> updateProgressUI(current)); if ("FAILED".equals(progress.status())) { String errorMsg = progress.errorMessage() != null && !progress.errorMessage().isEmpty() ? progress.errorMessage() : "Function matching returned an error status"; - SwingUtilities.invokeLater(() -> { - statusLabel.setText("Function matching failed"); + onEdtIfCurrent(self, () -> { handleError(errorMsg); + statusLabel.setText("Function matching failed"); }); return; } @@ -155,41 +173,45 @@ private void runMatchingLoop() { break; } Thread.sleep(POLL_INTERVAL_MS); - if (matchingCancelled) return; + if (matchingThread != self) return; progress = pollMatchingStatus(); } - if (matchingCancelled) return; + if (matchingThread != self) return; // Resolving type signatures fires many requests, so keep it off the EDT too - SwingUtilities.invokeLater(() -> { - taskMonitorComponent.setIndeterminate(true); - taskMonitorComponent.setMessage("Loading type information..."); + onEdtIfCurrent(self, () -> { + matchingProgressBar.setIndeterminate(true); statusLabel.setText("Loading type information..."); }); - var matches = fetchMatches(); - if (matchingCancelled) return; - processFunctionMatchingResults(matches); - // The status label is the only thing that says what this dialog is doing, and nothing - // used to write to it again after the "Loading type information..." above. The work - // finished, the bar went away, and the label sat there claiming to still be loading — - // indistinguishable from a request that never returned. - SwingUtilities.invokeLater(() -> statusLabel.setText( - "Matching complete: %d match(es)".formatted(functionMatchResults.size()))); + var built = buildMatchResults(fetchMatches()); + // The status label is the only thing that says what this dialog is doing, so it has to be + // told the work finished, or it sits there claiming to still be loading. + onEdtIfCurrent(self, () -> { + functionMatchResults.clear(); + functionMatchResults.addAll(built); + // Apply any existing function filter, which also refreshes the table + onFunctionFilterChanged(); + statusLabel.setText("Matching complete: %d match(es)".formatted(functionMatchResults.size())); + }); } catch (InterruptedException e) { // matching was cancelled, nothing to report } catch (Throwable t) { // Throwable rather than Exception: an Error thrown in here — a clash between a bundled // jar and Ghidra's own, or a large binary's type closure exhausting the heap — killed - // this thread without a word and left the progress message up for ever. Whatever it is, + // this thread without a word and left the progress bar up for ever. Whatever it is, // the user is told. - SwingUtilities.invokeLater(() -> { - Msg.error(this, "Function matching failed: " + t, t); + Msg.error(this, "Function matching failed: " + t, t); + onEdtIfCurrent(self, () -> { handleError("Function matching failed: " + t); statusLabel.setText("Function matching failed"); }); } finally { - // No path out of here may leave the progress bar spinning. - SwingUtilities.invokeLater(() -> taskMonitorComponent.setVisible(false)); + // No path out of here may leave the progress bar spinning. A cancelled run has already + // been reset by stopPolling, and must not hide the bar of the run that replaced it. + onEdtIfCurrent(self, () -> { + matchingThread = null; + setMatchingInProgress(false); + }); } } @@ -226,10 +248,9 @@ protected static List flattenMatches(List response) { + /// Builds the result rows. This resolves type signatures, which is the expensive part, so it is + /// expected to run off the EDT and does not touch Swing. + protected List buildMatchResults(List response) { List matches = new ArrayList<>(); final Map functionMap = analyzedProgram.getFunctionMap(); @@ -254,34 +275,34 @@ protected void processFunctionMatchingResults(List respon var sig = ghidraResultsWithSignatures.get(match); built.add(new GhidraFunctionMatchWithSignature(match.function(), match.functionMatch(), sig)); } - - SwingUtilities.invokeLater(() -> { - functionMatchResults.clear(); - functionMatchResults.addAll(built); - // Apply any existing function filter, which also refreshes the table - onFunctionFilterChanged(); - }); + return built; } protected void updateProgressUI(MatchingProgress progress) { if (progress == null) return; - // Update progress bar from the v3 step counters when present; otherwise show an animated - // (indeterminate) bar so the user can see that matching is still running. + // A determinate bar when the server reports step counters (step_index is zero-based, so the bar + // fills by completed steps); otherwise an animated one so the user can see it is still running. + // The step itself goes in the status text: painted on the bar it overlaps the thin macOS track. + String step = progress.step() != null && !progress.step().isBlank() ? progress.step() : null; if (progress.stepsTotal() != null && progress.stepsTotal() > 0 && progress.stepIndex() != null) { - int percent = (int) Math.min(100, Math.max(0, progress.stepIndex() * 100 / progress.stepsTotal())); - taskMonitorComponent.setIndeterminate(false); - taskMonitorComponent.setProgress(percent); - taskMonitorComponent.setMessage(progress.step() != null ? progress.step() : percent + "%"); + int total = (int) Math.min(Integer.MAX_VALUE, progress.stepsTotal()); + int index = (int) Math.max(0, Math.min(total, progress.stepIndex())); + matchingProgressBar.setIndeterminate(false); + matchingProgressBar.setMaximum(total); + matchingProgressBar.setValue(index); + if (step != null) { + step = "%s (step %d of %d)".formatted(step, Math.min(index + 1, total), total); + } } else { - taskMonitorComponent.setIndeterminate(true); - taskMonitorComponent.setMessage(progress.step() != null ? progress.step() : "Matching functions..."); + matchingProgressBar.setIndeterminate(true); } - // Update status - if (progress.status() != null) { - statusLabel.setText("Status: " + getFriendlyStatusMessage(progress.status())); + if (step != null) { + statusLabel.setText(step); + } else if (progress.status() != null) { + statusLabel.setText(getFriendlyStatusMessage(progress.status())); } // Handle error message - dynamically add/remove error panel @@ -290,9 +311,6 @@ protected void updateProgressUI(MatchingProgress progress) { } else { hideError(); } - - // Update results table - updateResultsTable(); } /// The results that back the table model, in model-row order: all results when no function filter @@ -318,16 +336,12 @@ public boolean isCellEditable(int row, int column) { } resultsTable.setModel(model); - // Update the dynamic title with filtered count + // Show how many of the matches the results filter lets through int totalMatchCount = functionMatchResults.size(); int displayedMatchCount = resultsToShow.size(); - String title; - if (filterText.isEmpty()) { - title = getTableTitle() + " (" + totalMatchCount + " matches found)"; - } else { - title = getTableTitle() + " (" + displayedMatchCount + " of " + totalMatchCount + " matches shown)"; - } - resultsScrollPane.setBorder(BorderFactory.createTitledBorder(title)); + resultsCountLabel.setText(filterText.isEmpty() + ? "%d match%s".formatted(totalMatchCount, totalMatchCount == 1 ? "" : "es") + : "%d of %d shown".formatted(displayedMatchCount, totalMatchCount)); // Show/hide rename buttons based on whether we have results boolean hasResults = displayedMatchCount > 0; @@ -350,7 +364,6 @@ public boolean isCellEditable(int row, int column) { protected abstract String[] getTableColumnNames(); protected abstract Object[] getTableRowData(GhidraFunctionMatchWithSignature result); - protected abstract String getTableTitle(); protected abstract int getTableSelectionMode(); protected abstract void configureTableColumns(); @@ -439,19 +452,18 @@ protected String getFriendlyStatusMessage(String apiStatus) { } return switch (apiStatus) { - case "UNINITIALISED", "PENDING" -> "starting function matching..."; - case "RUNNING" -> "running function matching..."; - case "COMPLETED" -> "completed function matching"; - case "FAILED" -> "function matching failed"; + case "UNINITIALISED", "PENDING" -> "Starting function matching..."; + case "RUNNING" -> "Running function matching..."; + case "COMPLETED" -> "Completed function matching"; + case "FAILED" -> "Function matching failed"; default -> apiStatus; // Fallback to original if unknown }; } protected void handleError(String message) { Msg.error(this, message); - statusLabel.setText("An error occurred, press 'Match Functions' again to retry"); + statusLabel.setText("An error occurred, press Match Functions again to retry"); showError(message); - taskMonitorComponent.setMessage("Error"); } protected void showError(String message) { @@ -474,10 +486,13 @@ protected void hideError() { } protected void stopPolling() { - matchingCancelled = true; - if (matchingThread != null) { - matchingThread.interrupt(); - matchingThread = null; + Thread running = matchingThread; + matchingThread = null; + if (running != null) { + running.interrupt(); + } + if (matchingProgressBar != null) { + setMatchingInProgress(false); } } @@ -490,25 +505,23 @@ protected JComponent buildMainPanel() { // Create content panel contentPanel = new JPanel(new BorderLayout()); + contentPanel.setBorder(BorderFactory.createEmptyBorder(12, 16, 12, 16)); - // Create top panel with progress and filters - JPanel topPanel = new JPanel(new BorderLayout()); - - // Progress panel at the top - JPanel progressPanel = createProgressPanel(); - topPanel.add(progressPanel, BorderLayout.NORTH); + // Top half: the filters sent with the matching request, then status and the Match button + JPanel searchSection = new JPanel(new BorderLayout(0, 10)); + searchSection.add(createSectionHeading("Filter Search"), BorderLayout.NORTH); + searchSection.add(createFilterPanel(), BorderLayout.CENTER); + searchSection.add(createMatchActionPanel(), BorderLayout.SOUTH); + contentPanel.add(searchSection, BorderLayout.NORTH); - // Create filter panel - JPanel filterPanel = createFilterPanel(); - topPanel.add(filterPanel, BorderLayout.CENTER); - contentPanel.add(topPanel, BorderLayout.NORTH); + // Bottom half: narrowing down the results that came back + JPanel resultsHeader = new JPanel(new BorderLayout(0, 10)); + resultsHeader.setBorder(BorderFactory.createEmptyBorder(18, 0, 0, 0)); + resultsHeader.add(createSectionHeading("Filter Results"), BorderLayout.NORTH); + resultsHeader.add(createFunctionFilterPanel(), BorderLayout.CENTER); - // Match button panel and function filter - JPanel buttonAndFilterPanel = createButtonAndFilterPanel(); - - // Create a center panel to hold the button and results - JPanel centerPanel = new JPanel(new BorderLayout()); - centerPanel.add(buttonAndFilterPanel, BorderLayout.NORTH); + JPanel centerPanel = new JPanel(new BorderLayout(0, 8)); + centerPanel.add(resultsHeader, BorderLayout.NORTH); // Initialize error area but don't add it to the panel yet errorArea = new JTextArea(5, 60); @@ -531,85 +544,102 @@ protected JComponent buildMainPanel() { protected abstract String getDialogDescription(); - protected JPanel createFilterPanel() { - JPanel filterPanel = new JPanel(new GridBagLayout()); + /// A bold heading followed by a rule across the rest of the row, splitting the dialog into sections + protected static JComponent createSectionHeading(String text) { + JLabel label = new JLabel(text); + label.setFont(label.getFont().deriveFont(Font.BOLD, label.getFont().getSize2D() + 1f)); + + JPanel heading = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridy = 0; + gbc.anchor = GridBagConstraints.WEST; + heading.add(label, gbc); + + gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.weighty = 0; + gbc.insets = new Insets(0, 8, 0, 0); + heading.add(new JSeparator(), gbc); + return heading; + } - // Row 0, Col 0: Collection selector (50% width) - gbc.gridx = 0; - gbc.gridy = 0; - gbc.gridwidth = 1; - gbc.weightx = 0.5; - gbc.insets = new Insets(10, 0, 10, 10); - filterPanel.add(createCollectionSelectorPanel(), gbc); + protected JPanel createFilterPanel() { + JPanel filterPanel = new JPanel(); + filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS)); + + filterPanel.add(createFilterRow(createCollectionSelectorPanel(), createBinarySelectorPanel())); + filterPanel.add(Box.createVerticalStrut(12)); + filterPanel.add(createFilterRow( + createField("Minimum similarity", createThresholdPanel()), + createField("Debug symbols", createDebugSymbolsPanel()))); + filterPanel.add(Box.createVerticalStrut(12)); + filterPanel.add(createFilterRow( + createField("Platform & architecture", createPlatformArchitecturePanel()), + createUserSelectorPanel())); - // Row 0, Col 1: Binary selector (50% width) - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 0.5; - gbc.insets = new Insets(10, 0, 10, 0); - filterPanel.add(createBinarySelectorPanel(), gbc); + return filterPanel; + } - // Row 1, Col 0: Threshold panel (50% width) - gbc.gridx = 0; - gbc.gridy = 1; - gbc.weightx = 0.5; - gbc.insets = new Insets(0, 0, 0, 10); - filterPanel.add(createThresholdPanel(), gbc); + /// Two filters side by side in equal-width columns, top-aligned + private static JPanel createFilterRow(JComponent left, JComponent right) { + JPanel row = new JPanel(new GridLayout(1, 2, 24, 0)); + row.add(topAligned(left)); + row.add(topAligned(right)); + row.setAlignmentX(Component.LEFT_ALIGNMENT); + return row; + } - // Row 1, Col 1: Debug symbols toggle (50% width) - gbc.gridx = 1; - gbc.gridy = 1; - gbc.weightx = 0.5; - gbc.insets = new Insets(0, 0, 0, 0); - filterPanel.add(createDebugSymbolsPanel(), gbc); - - // Row 2, Col 0: Platform and architecture toggles (50% width), as tall as the user selector beside it - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.gridy = 2; - gbc.weightx = 0.5; - gbc.insets = new Insets(10, 0, 0, 10); - filterPanel.add(createPlatformArchitecturePanel(), gbc); - - // Row 2, Col 1: User selector (50% width) - gbc.gridx = 1; - gbc.gridy = 2; - gbc.weightx = 0.5; - gbc.insets = new Insets(10, 0, 0, 0); - filterPanel.add(createUserSelectorPanel(), gbc); + private static JPanel topAligned(JComponent component) { + JPanel wrapper = new JPanel(new BorderLayout()); + wrapper.add(component, BorderLayout.NORTH); + return wrapper; + } - return filterPanel; + /// A bold caption above a filter's controls + protected static JPanel createField(String caption, JComponent control) { + JLabel label = new JLabel(caption); + label.setFont(label.getFont().deriveFont(Font.BOLD)); + + JPanel field = new JPanel(new BorderLayout(0, 4)); + field.add(label, BorderLayout.NORTH); + field.add(control, BorderLayout.CENTER); + return field; } - protected JPanel createButtonAndFilterPanel() { - // Match button panel - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); - JButton matchButton = new JButton("Match Functions"); + /// Status on the left; progress and the Match button right-aligned beneath the filters they apply + protected JPanel createMatchActionPanel() { + JPanel panel = new JPanel(new BorderLayout(12, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0)); + + statusLabel = new JLabel("Initializing..."); + panel.add(statusLabel, BorderLayout.CENTER); + + matchingProgressBar = new JProgressBar(); + matchingProgressBar.setPreferredSize(new Dimension(220, matchingProgressBar.getPreferredSize().height)); + matchingProgressBar.setVisible(false); + + matchButton = new JButton("Match Functions"); // Add magnifying glass icon to the button try { - Icon icon = ResourceManager.loadImage("images/magnifier.png"); - matchButton.setIcon(icon); + matchIcon = ResourceManager.loadImage("images/magnifier.png"); + matchButton.setIcon(matchIcon); } catch (Exception e) { // If icon loading fails, button will just show text without icon } matchButton.addActionListener(e -> onMatchButtonClicked()); - buttonPanel.add(matchButton); - - // Function filter panel - JPanel functionFilterPanel = createFunctionFilterPanel(); - - // Create a combined panel for button and function filter - JPanel buttonAndFilterPanel = new JPanel(new BorderLayout()); - buttonAndFilterPanel.add(buttonPanel, BorderLayout.NORTH); - buttonAndFilterPanel.add(functionFilterPanel, BorderLayout.CENTER); + // The button sets the row's height, so showing or hiding the bar beside it moves nothing + JPanel actions = new JPanel(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridy = 0; + gbc.insets = new Insets(0, 0, 0, 10); + actions.add(matchingProgressBar, gbc); + gbc.insets = new Insets(0, 0, 0, 0); + actions.add(matchButton, gbc); + panel.add(actions, BorderLayout.EAST); - return buttonAndFilterPanel; + return panel; } protected JPanel createResultsContainer() { @@ -618,8 +648,11 @@ protected JPanel createResultsContainer() { // Results table resultsTable = new JTable(); resultsTable.setAutoCreateRowSorter(true); + resultsTable.setFillsViewportHeight(true); + resultsTable.setRowHeight(resultsTable.getRowHeight() + 4); + resultsTable.setShowVerticalLines(false); resultsScrollPane = new JScrollPane(resultsTable); - resultsScrollPane.setBorder(BorderFactory.createTitledBorder("Function Matching Results")); + resultsScrollPane.setPreferredSize(new Dimension(0, 200)); // Add selection listener for assembly comparison resultsTable.getSelectionModel().addListSelectionListener(e -> { @@ -649,15 +682,19 @@ public void mouseReleased(MouseEvent e) { } }); - // Create assembly comparison panel + // Create assembly comparison panel; its two halves are titled, so it needs no box of its own here assemblyDiffPanel = new AssemblyDiffPanel(); + assemblyDiffPanel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); + // Its default 300px left the table only a few rows in a dialog of the default size + assemblyDiffPanel.setPreferredSize(new Dimension(0, 200)); - // Create vertical split pane with results table on top and assembly comparison below + // Create vertical split pane with results table on top and assembly comparison below, + // sized from their preferred heights and sharing any extra room JSplitPane mainSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); mainSplitPane.setTopComponent(resultsScrollPane); mainSplitPane.setBottomComponent(assemblyDiffPanel); - mainSplitPane.setResizeWeight(0.4); - mainSplitPane.setDividerLocation(250); + mainSplitPane.setResizeWeight(0.5); + mainSplitPane.setBorder(null); resultsContainer.add(mainSplitPane, BorderLayout.CENTER); @@ -708,7 +745,8 @@ private TypedApiInterface.AnalysisID getSelectedMatchedAnalysisID() { } protected JPanel createRenameButtonsPanel() { - JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); + JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); JButton renameAllButton = new JButton("Rename All"); renameAllButton.addActionListener(e -> onRenameAllButtonClicked()); @@ -721,29 +759,6 @@ protected JPanel createRenameButtonsPanel() { return panel; } - protected JPanel createProgressPanel() { - JPanel panel = new JPanel(new GridBagLayout()); - GridBagConstraints gbc = new GridBagConstraints(); - gbc.insets = new Insets(10, 10, 0, 10); - gbc.anchor = GridBagConstraints.WEST; - - // Progress bar - gbc.gridx = 0; - gbc.gridy = 0; - gbc.gridwidth = 2; - gbc.fill = GridBagConstraints.HORIZONTAL; - panel.add(taskMonitorComponent, gbc); - - // Status label - gbc.gridy = 1; - gbc.gridwidth = 1; - gbc.fill = GridBagConstraints.NONE; - statusLabel = new JLabel("Initializing..."); - panel.add(statusLabel, gbc); - - return panel; - } - protected JPanel createCollectionSelectorPanel() { collectionSelector = new CollectionSelectionPanel( query -> revengService.searchCollectionsWithIds(query), @@ -766,7 +781,6 @@ protected JPanel createBinarySelectorPanel() { protected JPanel createThresholdPanel() { JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Minimum similarity")); thresholdSlider = new JSlider(0, 100, 70); thresholdSlider.setMajorTickSpacing(25); @@ -774,8 +788,11 @@ protected JPanel createThresholdPanel() { thresholdSlider.setPaintTicks(true); thresholdSlider.setPaintLabels(true); - thresholdValueLabel = new JLabel("70%", SwingConstants.CENTER); + thresholdValueLabel = new JLabel("70%", SwingConstants.RIGHT); thresholdValueLabel.setFont(thresholdValueLabel.getFont().deriveFont(Font.BOLD, 14f)); + // Room for "100%" so the slider doesn't shift as the value changes + thresholdValueLabel.setPreferredSize(new Dimension(48, thresholdValueLabel.getPreferredSize().height)); + thresholdSlider.addChangeListener(e -> thresholdValueLabel.setText(thresholdSlider.getValue() + "%")); @@ -790,12 +807,9 @@ protected JPanel createThresholdPanel() { protected JPanel createDebugSymbolsPanel() { JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Debug symbols")); JPanel checkboxPanel = new JPanel(); checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.Y_AXIS)); - checkboxPanel.setPreferredSize(new Dimension(0, 52)); - checkboxPanel.setMinimumSize(new Dimension(0, 52)); debugSymbolsCheckBox = new JCheckBox("Only include functions with debug symbols", false); debugSymbolsCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); @@ -806,13 +820,14 @@ protected JPanel createDebugSymbolsPanel() { userSubmittedDebugSymbolsCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); userSubmittedDebugSymbolsCheckBox.setEnabled(false); + // Indented under the box it depends on JPanel indentedPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); indentedPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + indentedPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); indentedPanel.add(userSubmittedDebugSymbolsCheckBox); checkboxPanel.add(debugSymbolsCheckBox); checkboxPanel.add(indentedPanel); - checkboxPanel.add(Box.createVerticalGlue()); panel.add(checkboxPanel, BorderLayout.CENTER); @@ -821,7 +836,6 @@ protected JPanel createDebugSymbolsPanel() { protected JPanel createPlatformArchitecturePanel() { JPanel panel = new JPanel(new GridBagLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Platform & architecture")); panel.setToolTipText("Leave unticked to match any platform or architecture"); platformCheckBoxes.put(MatchFilters.PlatformsEnum.LINUX, new JCheckBox("Linux")); @@ -834,7 +848,7 @@ protected JPanel createPlatformArchitecturePanel() { GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.WEST; - gbc.insets = new Insets(0, 5, 0, 5); + gbc.insets = new Insets(0, 0, 0, 10); gbc.gridy = 0; panel.add(new JLabel("Platforms:"), gbc); @@ -866,11 +880,10 @@ protected JPanel createUserSelectorPanel() { } protected JPanel createFunctionFilterPanel() { - JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Filter matches by function virtual address, name, hash or binary")); + JPanel panel = new JPanel(new BorderLayout(8, 0)); + panel.add(new JLabel("Filter:"), BorderLayout.WEST); - functionFilterField = new JTextField(); - functionFilterField.setPreferredSize(new Dimension(0, 30)); + functionFilterField = new HintTextField(getFunctionFilterHint()); functionFilterField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() { @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { @@ -890,9 +903,17 @@ public void changedUpdate(javax.swing.event.DocumentEvent e) { panel.add(functionFilterField, BorderLayout.CENTER); + resultsCountLabel = new JLabel("No matches yet"); + panel.add(resultsCountLabel, BorderLayout.EAST); + return panel; } + /// Placeholder for the results filter, naming the columns {@link #matchesFilter} searches + protected String getFunctionFilterHint() { + return "Matched function name, hash or binary"; + } + // Event handler methods protected void onCollectionSelectionChanged(Set selectedCollections) { Set collectionIds = selectedCollections.stream() @@ -1018,11 +1039,16 @@ protected void filterResults() { ", users: " + userSelector.getSelectedUserNames() + " (IDs: " + userSelector.getSelectedUserIds() + ")"); - taskMonitorComponent.setVisible(true); startFunctionMatching(); } + /// Starts a match, or cancels the one in progress (the button reads Cancel while it runs) protected void onMatchButtonClicked() { + if (matchingThread != null) { + stopPolling(); + statusLabel.setText("Cancelled: press Match Functions to search again"); + return; + } filterResults(); } @@ -1066,7 +1092,8 @@ public void run(TaskMonitor monitor) { importFunctionNames(matches); } }; - TaskBuilder.withTask(task).launchInBackground(taskMonitorComponent); + // Shown in a task dialog: the dialog's progress bar belongs to matching, and is hidden by now + TaskBuilder.withTask(task).setParent(getComponent()).launchModal(); } protected void batchRenameFunctions(List functionMatches) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java index 9862076f..37af713e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java @@ -64,11 +64,6 @@ protected Object[] getTableRowData(GhidraFunctionMatchWithSignature result) { }; } - @Override - protected String getTableTitle() { - return "Function matching results"; - } - @Override protected int getTableSelectionMode() { return ListSelectionModel.MULTIPLE_INTERVAL_SELECTION; @@ -123,6 +118,11 @@ protected String getDialogDescription() { return "Match functions in this binary against previously seen samples"; } + @Override + protected String getFunctionFilterHint() { + return "Virtual address, function name, matched function name, hash or binary"; + } + @Override protected boolean matchesFilter(GhidraFunctionMatchWithSignature result) { String filterText = functionFilterField.getText().trim().toLowerCase(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java index 2ee713fa..c06c2ac7 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java @@ -79,11 +79,6 @@ protected Object[] getTableRowData(GhidraFunctionMatchWithSignature result) { }; } - @Override - protected String getTableTitle() { - return "Function Matching Results"; - } - @Override protected int getTableSelectionMode() { return ListSelectionModel.SINGLE_SELECTION; @@ -132,7 +127,8 @@ protected boolean matchesFilter(GhidraFunctionMatchWithSignature result) { @Override protected JPanel createRenameButtonsPanel() { - JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); + JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); // Only show "Rename Selected" button for function-level matching // since we're only matching a single function diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index e1c0c49f..b9bd9cee 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -12,13 +12,14 @@ import docking.DockingWindowManager; import ghidra.program.model.data.Undefined; import ghidra.util.task.TaskMonitor; -import ghidra.util.task.TaskMonitorComponent; import org.junit.Test; import javax.swing.*; import generic.theme.GColor; import java.math.BigDecimal; import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; @@ -339,9 +340,8 @@ public void testClickMatchButtonPopulatesResultsTable() throws Exception { "Status label should stop saying it is loading once matching has finished"); assertTrue("The finished status should report the matches, was: " + statusLabel.getText(), statusLabel.getText().contains("Matching complete")); - TaskMonitorComponent monitor = - (TaskMonitorComponent) getInstanceField("taskMonitorComponent", foundDialog); - assertFalse("The progress bar should not be left spinning", monitor.isVisible()); + JProgressBar progressBar = (JProgressBar) getInstanceField("matchingProgressBar", foundDialog); + assertFalse("The progress bar should not be left spinning", progressBar.isVisible()); // Close the dialog close(foundDialog); @@ -616,6 +616,101 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { } } + /// A run that is cancelled and replaced must not reach the UI. Its thread, once its request came back, + /// used to hide the progress bar of the run that replaced it on the way out. + @Test + public void testCancelledRunDoesNotHideTheNextRunsProgress() throws Exception { + var tool = env.getTool(); + + var mockApi = new StillRunningMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JProgressBar progressBar = (JProgressBar) getInstanceField("matchingProgressBar", foundDialog); + JLabel statusLabel = (JLabel) getInstanceField("statusLabel", foundDialog); + // The first run's request is held by the mock, as a slow server would; while running, the Match button cancels + waitForCondition(() -> mockApi.lastMatchingRequest != null, "Matching should start when the dialog opens"); + pressButton(findButtonByText(foundDialog.getComponent(), "Cancel")); + waitForSwing(); + assertFalse("Cancelling should hide the progress bar", progressBar.isVisible()); + + var firstRequest = mockApi.lastMatchingRequest; + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForCondition(() -> mockApi.lastMatchingRequest != firstRequest, "Pressing Match Functions should start a new run"); + waitForCondition(() -> statusLabel.getText().contains("step 2 of 4"), + "The step reported by the server should be shown"); + + // Only now does the cancelled run's request come back + mockApi.firstStartGate.countDown(); + waitForCondition(() -> mockApi.firstStartReturned, "The cancelled run's request should return"); + Thread.sleep(200); + waitForSwing(); + assertTrue("The cancelled run must not hide the new run's progress bar", progressBar.isVisible()); + + close(foundDialog); + waitForSwing(); + } + + /// Reports matching as still running, on the second of four steps, so a run never finishes on its own. + /// The first request to start matching is held until {@link #firstStartGate} opens. + static class StillRunningMockApi extends FunctionMatchingMockApi { + final CountDownLatch firstStartGate = new CountDownLatch(1); + volatile boolean firstStartReturned = false; + private final AtomicInteger starts = new AtomicInteger(); + + @Override + public StartMatchingOutputBody startFunctionsMatching(StartMatchingForFunctionsInputBody request) { + boolean first = starts.getAndIncrement() == 0; + super.startFunctionsMatching(request); + if (first) { + // Like a blocking HTTP call, cancelling (an interrupt) doesn't cut this short + boolean interrupted = false; + while (true) { + try { + firstStartGate.await(); + break; + } catch (InterruptedException e) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + firstStartReturned = true; + } + var response = new StartMatchingOutputBody(); + response.setStatus(StartMatchingOutputBody.StatusEnum.RUNNING); + response.setStep("Searching for similar functions"); + response.setStepIndex(1L); + response.setStepsTotal(4L); + return response; + } + + @Override + public GetMatchesStatusOutputBody getFunctionsMatchingStatus(List functionIds) { + var response = new GetMatchesStatusOutputBody(); + response.setStatus(GetMatchesStatusOutputBody.StatusEnum.RUNNING); + response.setStep("Searching for similar functions"); + response.setStepIndex(1L); + response.setStepsTotal(4L); + return response; + } + } + /** * Mock API implementation for function matching dialog tests. * Provides necessary responses for the dialog to function without a real server. From 347caea7a86110d0a94d55519cf25be81b65bc84 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:48:35 +0000 Subject: [PATCH 17/76] test(ENG-4406): wait for the automatic match before pressing Match Functions The function-level dialog starts matching when it opens, and the Match button now reads Cancel while a run is going. On slower CI runners the tests' press landed during that first run and cancelled it, so the table never filled. Wait for the first run to finish before pressing. --- ...nctionLevelFunctionMatchingDialogTest.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index b9bd9cee..b564ea5d 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -268,6 +268,7 @@ public void testPlatformAndArchitectureTogglesAreSentAsMatchFilters() throws Exc setToggleButtonSelected(platforms.get(MatchFilters.PlatformsEnum.LINUX), true); setToggleButtonSelected(architectures.get(MatchFilters.ArchitecturesEnum.ARM_64), true); + waitForMatchingIdle(foundDialog); var firstRequest = mockApi.lastMatchingRequest; pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); waitForCondition(() -> mockApi.lastMatchingRequest != firstRequest, "Pressing Match Functions should start a new match"); @@ -307,16 +308,17 @@ public void testClickMatchButtonPopulatesResultsTable() throws Exception { var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); assertNotNull("Dialog should be shown", foundDialog); - // Get the results table before clicking JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); assertNotNull("Results table should exist", resultsTable); - assertEquals("Results table should be empty initially", 0, resultsTable.getRowCount()); - // Find and click the "Match Functions" button + // Find and click the "Match Functions" button once the automatic match on open is done + waitForMatchingIdle(foundDialog); + var firstRequest = mockApi.lastMatchingRequest; JButton matchButton = findButtonByText(foundDialog.getComponent(), "Match Functions"); assertNotNull("Match Functions button should exist", matchButton); pressButton(matchButton); + waitForCondition(() -> mockApi.lastMatchingRequest != firstRequest, "Pressing Match Functions should start a new match"); // Wait for the API call to complete and results to be processed // The mock API returns COMPLETED status immediately, so we just need to wait for Swing @@ -379,6 +381,7 @@ public void testSelectedMatchFollowsSortOrderNotModelOrder() throws Exception { JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + waitForMatchingIdle(foundDialog); pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); waitForTasks(); waitForSwing(); @@ -451,6 +454,7 @@ public GetMatchesOutputBody getFunctionsMatches(List functionIds) { JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + waitForMatchingIdle(foundDialog); pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); waitForTasks(); waitForSwing(); @@ -500,6 +504,7 @@ public void testSimilarityAndConfidenceCellsAreColorCoded() throws Exception { JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + waitForMatchingIdle(foundDialog); pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); waitForTasks(); waitForSwing(); @@ -546,6 +551,7 @@ public void testRightClickOffersMatchedBinaryInPortal() throws Exception { JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); assertNull(invokeInstanceMethod("getSelectedMatchedAnalysisID", foundDialog)); + waitForMatchingIdle(foundDialog); pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); waitForTasks(); waitForSwing(); @@ -616,6 +622,16 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { } } + /// The function-level dialog matches by itself when it opens, and its Match button reads Cancel while + /// a run is going. Waits for that first run to finish, so that pressing Match starts a new run rather + /// than, on a slow machine, cancelling the one that started after the button was looked up. + private void waitForMatchingIdle(FunctionLevelFunctionMatchingDialog dialog) { + JLabel statusLabel = (JLabel) getInstanceField("statusLabel", dialog); + waitForCondition(() -> statusLabel.getText().startsWith("Matching complete") + && getInstanceField("matchingThread", dialog) == null, + "The automatic match on open should finish"); + } + /// A run that is cancelled and replaced must not reach the UI. Its thread, once its request came back, /// used to hide the progress bar of the run that replaced it on the way out. @Test From 9ff2be74e342c5a88cff9acb88ca43a0df1b6cdd Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:51:22 +0000 Subject: [PATCH 18/76] fix: guard against null pointer exceptions and related crashes (#230) * fix: guard against null pointer exceptions * fix: harden type names, recent analysis picker, chat worker and pull transaction * test: give each test fork its own Ghidra temp dir --- build.gradle | 6 + ghidra_scripts/RevEngExamplePostScript.java | 4 + .../binarysimilarity/cmds/ApplyMatchCmd.java | 2 +- .../recentanalyses/RecentAnalysisDialog.java | 8 +- .../ghidra/chat/ui/ChatController.java | 4 +- .../services/api/GhidraRevengService.java | 221 +++++++++--------- .../services/api/ServerDataTypeDecoder.java | 13 +- .../services/api/TypedApiImplementation.java | 9 + .../api/datatypes/ServerDataTypeReader.java | 7 +- .../core/services/api/types/ApiInfo.java | 3 + .../services/api/types/TypePathAndName.java | 7 +- .../ghidra/plugins/AgentChatPlugin.java | 12 +- .../plugins/BinarySimilarityPlugin.java | 6 +- .../ai/reveng/AIDecompilerComponentTest.java | 14 ++ .../java/ai/reveng/AgentChatWindowTest.java | 15 ++ src/test/java/ai/reveng/ForkTempDir.java | 32 +++ src/test/java/ai/reveng/ForkTempDirTest.java | 24 ++ .../ai/reveng/PullSignaturesOnSyncTest.java | 63 ++++- .../ai/reveng/ReaiAPIServicePluginTest.java | 25 ++ .../ai/reveng/RecentAnalysisDialogTest.java | 66 ++++++ .../ai/reveng/ServerDataTypeDecoderTest.java | 45 ++++ .../ghidra/chat/ui/ChatControllerTest.java | 17 ++ .../services/api/EmptyResponseDataTest.java | 29 +++ .../api/types/TypePathAndNameTest.java | 16 ++ ....platform.launcher.LauncherSessionListener | 1 + 25 files changed, 525 insertions(+), 124 deletions(-) create mode 100644 src/test/java/ai/reveng/ForkTempDir.java create mode 100644 src/test/java/ai/reveng/ForkTempDirTest.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java create mode 100644 src/test/resources/META-INF/services/org.junit.platform.launcher.LauncherSessionListener diff --git a/build.gradle b/build.gradle index 1c0150b1..29e4824a 100644 --- a/build.gradle +++ b/build.gradle @@ -74,6 +74,8 @@ dependencies { testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.8.2") // Version comes from the junit-bom pulled in by junit-vintage-engine. testRuntimeOnly('org.junit.platform:junit-platform-launcher') + // Compile-time API for ForkTempDir; matches the runtime version above. + testCompileOnly('org.junit.platform:junit-platform-launcher:1.8.2') // https://mvnrepository.com/artifact/org.jetbrains/annotations implementation group: 'org.jetbrains', name: 'annotations', version: '26.0.2' @@ -107,6 +109,10 @@ test { useJUnitPlatform() jvmArgs '--add-exports=java.desktop/sun.awt=ALL-UNNAMED' systemProperty "ghidra.test.property.batch.mode", 'true' + // Parent of the per-fork Ghidra temp dirs created by ForkTempDir. + def forkTempRoot = layout.buildDirectory.dir('tmp/ghidra-test-forks').get().asFile + systemProperty 'reveng.test.fork.tmproot', forkTempRoot.path + doFirst { forkTempRoot.mkdirs() } // Ghidra 12.1+ installs a serial filter factory during application initialization. The JVM // only allows this if no ObjectInputStream has been constructed yet, but Gradle's test diff --git a/ghidra_scripts/RevEngExamplePostScript.java b/ghidra_scripts/RevEngExamplePostScript.java index e9ee7c40..29351d41 100644 --- a/ghidra_scripts/RevEngExamplePostScript.java +++ b/ghidra_scripts/RevEngExamplePostScript.java @@ -8,6 +8,10 @@ public class RevEngExamplePostScript extends GhidraScript { @Override protected void run() throws Exception { + if (currentProgram == null) { + printerr("No program open"); + return; + } // Services are not available in headless mode, so we have to instantiate it ourselves var ghidraRevengService = new GhidraRevengService(ApiInfo.fromConfig(ReaiPluginPackage.DEFAULT_CONFIG_PATH)); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java index 08a3c2b3..1bed1ced 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java @@ -55,7 +55,7 @@ private boolean shouldApplyMatch() { !match.functionMatch().nearest_neighbor_mangled_function_name().contains(" ") && !match.functionMatch().nearest_neighbor_function_name().contains(" ") // Only rename if the function ID is known (boundaries matched) - && analyzedProgram.getIDForFunction(func).map(id -> id.functionID() != match.functionMatch().origin_function_id()).orElse(false); + && analyzedProgram.getIDForFunction(func).isPresent(); } @Override diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java index f7c91c0a..5e4bc850 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java @@ -90,10 +90,9 @@ public void mouseClicked(MouseEvent e) { JButton pickMostRecentButton = new JButton("Pick most recent"); pickMostRecentButton.setName("Pick most recent"); pickMostRecentButton.addActionListener(e -> { - var mostRecent = recentAnalysesTable.getModel().getModelData().stream().max( + recentAnalysesTable.getModel().getModelData().stream().max( Comparator.comparing(AnalysisRecordBody::getCreation) - ).orElseThrow(); - pickAnalysis(mostRecent); + ).ifPresent(this::pickAnalysis); }); addButton(pickMostRecentButton); @@ -101,6 +100,9 @@ public void mouseClicked(MouseEvent e) { pickSelectedButton.setName("Pick selected"); pickSelectedButton.addActionListener(e -> { var selectedRowObject = recentAnalysesTable.getSelectedRowObject(); + if (selectedRowObject == null) { + return; + } pickAnalysis(selectedRowObject); }); addButton(pickSelectedButton); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java index 58a64533..165601ed 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java @@ -113,7 +113,7 @@ public void loadConversation(String conversationUuid) { lastEventId = null; setState(withTitle); }); - } catch (ChatServiceException e) { + } catch (ChatServiceException | RuntimeException e) { log.warn("Failed to load conversation: " + e.getMessage()); } }); @@ -245,7 +245,7 @@ public void run() { } service.stream(id, resumeFromEventId, stopped::get, event -> runOnUi(() -> onStreamEvent(event))); - } catch (ChatServiceException e) { + } catch (ChatServiceException | RuntimeException e) { if (!stopped.get()) { runOnUi(() -> setState(ChatReducer.reduce(state, new ApiError(e.getMessage())))); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index be055262..cf5df715 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -684,7 +684,7 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, Set remotePresent = signatures() .getMany(List.copyOf(matchedIds), false) .items().stream() - .filter(BatchFunctionSignatureEntry::getHasSignature) + .filter(item -> Boolean.TRUE.equals(item.getHasSignature())) .map(item -> new TypedApiInterface.FunctionID(item.getFunctionId())) .collect(Collectors.toSet()); @@ -781,132 +781,139 @@ private List pullFunctionInfoFromAnalysisInternal(AnalysedProgram List renameResults = new ArrayList<>(); int failedRenames = 0; + try { - var revEngNamespace = getRevEngAINameSpace(analysedProgram.program()); + var revEngNamespace = getRevEngAINameSpace(analysedProgram.program()); - Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() - .collect( - Collectors.toMap( - FunctionInfo::functionID, - fi -> fi - ) - ); - - - // /v3/functions/signatures is addressed by function id rather than by analysis, so ask for - // the functions this analysis reported. The response carries the types those signatures - // reference alongside them, which is what the decoders below are built from. - var signatureBatch = signatures().getMany(List.copyOf(functionInfoMap.keySet())); - Map decoders = new HashMap<>(); - Map signatureMap = signatureBatch.items() - .stream() - .filter(BatchFunctionSignatureEntry::getHasSignature) - .collect( - Collectors.toMap( - item -> new TypedApiInterface.FunctionID(item.getFunctionId()), - item -> item, - (existing, replacement) -> existing - ) - ); + Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() + .collect( + Collectors.toMap( + FunctionInfo::functionID, + fi -> fi + ) + ); - for (Function function : analysedProgram.program().getFunctionManager().getFunctions(true)) { - if (monitor.isCancelled()) { - continue; - } - var ghidraMangledName = function.getSymbol().getName(false); - // Skip external and thunk functions because we don't support them - if (function.isExternal() || function.isThunk()) { - Msg.debug(this, "Skipping external/thunk function %s".formatted(ghidraMangledName)); - continue; - } - var fID = analysedProgram.getIDForFunction(function); - if (fID.isEmpty()) { - Msg.info(this, "Function %s has no associated FunctionID, skipping".formatted(function.getName())); - continue; - } + // /v3/functions/signatures is addressed by function id rather than by analysis, so ask for + // the functions this analysis reported. The response carries the types those signatures + // reference alongside them, which is what the decoders below are built from. + var signatureBatch = signatures().getMany(List.copyOf(functionInfoMap.keySet())); + Map decoders = new HashMap<>(); + Map signatureMap = signatureBatch.items() + .stream() + .filter(item -> Boolean.TRUE.equals(item.getHasSignature())) + .collect( + Collectors.toMap( + item -> new TypedApiInterface.FunctionID(item.getFunctionId()), + item -> item, + (existing, replacement) -> existing + ) + ); - // Get the current name on the server side - FunctionInfo details = functionInfoMap.get(fID.get().functionID); + for (Function function : analysedProgram.program().getFunctionManager().getFunctions(true)) { + if (monitor.isCancelled()) { + continue; + } + var ghidraMangledName = function.getSymbol().getName(false); + // Skip external and thunk functions because we don't support them + if (function.isExternal() || function.isThunk()) { + Msg.debug(this, "Skipping external/thunk function %s".formatted(ghidraMangledName)); + continue; + } - // Extract the mangled name from Ghidra - var revEngMangledName = details.functionMangledName(); - var revEngDemangledName = details.functionName(); + var fID = analysedProgram.getIDForFunction(function); + if (fID.isEmpty()) { + Msg.info(this, "Function %s has no associated FunctionID, skipping".formatted(function.getName())); + continue; + } - // Skip invalid function mangled names - if (revEngMangledName.contains(" ") || revEngDemangledName.contains(" ")) { - Msg.warn(this, "Skipping renaming of function %s to invalid name %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); - continue; - } + // Get the current name on the server side + FunctionInfo details = functionInfoMap.get(fID.get().functionID); + if (details == null) { + Msg.warn(this, "No server info for function %s, skipping".formatted(function.getName())); + continue; + } - // Get the type information on the server side. Every type the signature refers to is - // resolved by id against its analysis' decoder, so there is nothing left to fail on. - Optional functionSignatureMessageOpt = - Optional.ofNullable(signatureMap.get(fID.get().functionID)) - .map(entry -> getFunctionSignature(entry, decoderFor(decoders, signatureBatch, entry))); - - - analysedProgram.setMangledNameForFunction(function, revEngMangledName); - - /// Source types: - /// DEFAULT: placeholder name automatically assigned by Ghidra when it doesn’t know the real name. - /// ANALYSIS: A name/signature inferred by one of Ghidra’s analysis engines (or demangler) rather than simply “default.” - /// IMPORTED: Information taken from an external source — symbols or signatures imported from a file or database. - /// USER_DEFINED: A name or signature explicitly set by the analyst. - /// See {@link ghidra.program.model.symbol.SourceType} for more details - // The name and the signature are separate decisions. Gating the signature on the name - // source hid every type the portal held for a function that was already named — by the - // analyst, or by an earlier run of this same pull — and the signature apply is what - // carries the data types down. - if (functionSignatureMessageOpt.isEmpty()) { - // No signature to apply, so a rename is all that is left. Skip server-side default - // names — Ghidra's own "FUN_" and IDA's "sub_" — so we never overwrite Ghidra's - // default placeholder with an IDA-style one. - if (function.getSymbol().getSource() == SourceType.DEFAULT - && !revEngMangledName.startsWith("FUN_") && !revEngMangledName.startsWith("sub_") - && !function.getSymbol().getName(false).equals(revEngDemangledName)) { - Msg.info(this, "Renaming function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); - try { - function.setParentNamespace(revEngNamespace); - } catch (DuplicateNameException | InvalidInputException | CircularDependencyException e) { - throw new RuntimeException(e); + // Extract the mangled name from Ghidra + var revEngMangledName = details.functionMangledName(); + var revEngDemangledName = details.functionName(); + + // Skip invalid function mangled names + if (revEngMangledName.contains(" ") || revEngDemangledName.contains(" ")) { + Msg.warn(this, "Skipping renaming of function %s to invalid name %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); + continue; + } + + // Get the type information on the server side. Every type the signature refers to is + // resolved by id against its analysis' decoder, so there is nothing left to fail on. + Optional functionSignatureMessageOpt = + Optional.ofNullable(signatureMap.get(fID.get().functionID)) + .map(entry -> getFunctionSignature(entry, decoderFor(decoders, signatureBatch, entry))); + + + analysedProgram.setMangledNameForFunction(function, revEngMangledName); + + /// Source types: + /// DEFAULT: placeholder name automatically assigned by Ghidra when it doesn’t know the real name. + /// ANALYSIS: A name/signature inferred by one of Ghidra’s analysis engines (or demangler) rather than simply “default.” + /// IMPORTED: Information taken from an external source — symbols or signatures imported from a file or database. + /// USER_DEFINED: A name or signature explicitly set by the analyst. + /// See {@link ghidra.program.model.symbol.SourceType} for more details + // The name and the signature are separate decisions. Gating the signature on the name + // source hid every type the portal held for a function that was already named — by the + // analyst, or by an earlier run of this same pull — and the signature apply is what + // carries the data types down. + if (functionSignatureMessageOpt.isEmpty()) { + // No signature to apply, so a rename is all that is left. Skip server-side default + // names — Ghidra's own "FUN_" and IDA's "sub_" — so we never overwrite Ghidra's + // default placeholder with an IDA-style one. + if (function.getSymbol().getSource() == SourceType.DEFAULT + && !revEngMangledName.startsWith("FUN_") && !revEngMangledName.startsWith("sub_") + && !function.getSymbol().getName(false).equals(revEngDemangledName)) { + Msg.info(this, "Renaming function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); + try { + function.setParentNamespace(revEngNamespace); + } catch (DuplicateNameException | InvalidInputException | CircularDependencyException e) { + throw new RuntimeException(e); + } + var success = new SetFunctionNameCmd(function.getEntryPoint(), revEngDemangledName, SourceType.ANALYSIS) + .applyTo(analysedProgram.program()); + if (success) { + renameResults.add(new RenameResult( + function, + ghidraMangledName, + revEngDemangledName + )); + } else { + failedRenames++; + Msg.error(this, "Failed to rename function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); + } } - var success = new SetFunctionNameCmd(function.getEntryPoint(), revEngDemangledName, SourceType.ANALYSIS) - .applyTo(analysedProgram.program()); - if (success) { + } else if (function.getSignatureSource() != SourceType.USER_DEFINED) { + // RENAME_IF_DEFAULT preserves the long-standing behaviour that applying a signature + // also names a function still carrying Ghidra's placeholder, and leaves every other + // name alone. + var application = applyRemoteSignature(analysedProgram.program(), function, + functionSignatureMessageOpt.get(), monitor, FunctionRenameOption.RENAME_IF_DEFAULT); + // For unclear reasons the signature source is not set by the command in Ghidra 11.2.x and lower + if (application.success()) { renameResults.add(new RenameResult( function, ghidraMangledName, revEngDemangledName )); } else { + Msg.error(this, "Failed to apply signature to function %s".formatted(function.getName())); failedRenames++; - Msg.error(this, "Failed to rename function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); } } - } else if (function.getSignatureSource() != SourceType.USER_DEFINED) { - // RENAME_IF_DEFAULT preserves the long-standing behaviour that applying a signature - // also names a function still carrying Ghidra's placeholder, and leaves every other - // name alone. - var application = applyRemoteSignature(analysedProgram.program(), function, - functionSignatureMessageOpt.get(), monitor, FunctionRenameOption.RENAME_IF_DEFAULT); - // For unclear reasons the signature source is not set by the command in Ghidra 11.2.x and lower - if (application.success()) { - renameResults.add(new RenameResult( - function, - ghidraMangledName, - revEngDemangledName - )); - } else { - Msg.error(this, "Failed to apply signature to function %s".formatted(function.getName())); - failedRenames++; - } - } + } + } finally { + // Done iterating over all functions. If nothing changed, discard the transaction, to keep undo history clean + analysedProgram.program().endTransaction(transactionId, !renameResults.isEmpty() && !monitor.isCancelled()); } - // Done iterating over all functions. If nothing changed, discard the transaction, to keep undo history clean - analysedProgram.program().endTransaction(transactionId, !renameResults.isEmpty() && !monitor.isCancelled()); if (failedRenames > 0){ Msg.showError(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function Update Summary", ("Failed to update %d functions from RevEng.AI. Please check the error log for details.").formatted( @@ -1203,7 +1210,7 @@ public Map getSignatures(java.u // Create a map from FunctionID to signature for easy lookup, only where the server has one. // The same neighbour can still appear more than once in the response, so keep the first. Map signatureMap = batch.items().stream() - .filter(BatchFunctionSignatureEntry::getHasSignature) + .filter(item -> Boolean.TRUE.equals(item.getHasSignature())) .collect(Collectors.toMap( item -> new TypedApiInterface.FunctionID(item.getFunctionId()), item -> item, diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java index c10bfb0f..8cab262e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java @@ -290,7 +290,7 @@ private static CategoryPath categoryPath(ServerDataType type) { if (namespace == null || namespace.isBlank()) { return CategoryPath.ROOT; } - return TypePathAndName.fromString(namespace + "::" + leafName(type)).toCategoryPath(); + return TypePathAndName.fromString(sanitise(namespace) + "::" + leafName(type)).toCategoryPath(); } private static String leafName(ServerDataType type) { @@ -298,7 +298,13 @@ private static String leafName(ServerDataType type) { if (name == null || name.isBlank()) { return "anon_%d".formatted(type.id()); } - return TypePathAndName.fromString(name).name(); + String leaf = sanitise(TypePathAndName.fromString(name).name()); + return leaf.isBlank() ? "anon_%d".formatted(type.id()) : leaf; + } + + /// Ghidra rejects names containing control characters. + private static String sanitise(String name) { + return name.replaceAll("\\p{Cntrl}", "_"); } /// Ghidra sizes are `int`; the API's are `long`. Anything that does not fit is not a real type. @@ -333,6 +339,9 @@ private static int pointerLength(@Nullable Long size) { /// Enum values stay strings on the wire because they may be negative or exceed 64 unsigned bits. /// Ghidra can only hold a `long`, so widen through {@link BigInteger} and take the low 64 bits. private static long toLong(String value) { + if (value == null) { + throw new NumberFormatException("missing value"); + } return new BigInteger(value.trim()).longValue(); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 65bd3de6..0143687a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -126,6 +126,9 @@ public BinaryHash upload(Path binPath) throws FileNotFoundException, ApiExceptio var result = this.analysisCoreApi.uploadFile(UploadFileType.fromValue("BINARY"), bin, null, true); + if (result.getData() == null) { + throw new ApiException("Upload response carried no data"); + } return new BinaryHash(result.getData().getSha256Hash()); } @@ -162,12 +165,18 @@ public List search(BinaryHash hash) { public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { var analysisRequest = options.toAnalysisCreateRequest(); var result = this.analysisCoreApi.createAnalysis(analysisRequest, null); + if (result.getData() == null) { + throw new ApiException("Analysis creation response carried no data"); + } return new AnalysisID(result.getData().getAnalysisId()); } @Override public AnalysisStatus status(AnalysisID analysisID) throws ApiException { var status = analysisCoreApi.getAnalysisStatus(analysisID.id()); + if (status.getData() == null) { + throw new ApiException("Analysis status response carried no data"); + } return AnalysisStatus.fromApiValue(status.getData().getAnalysisStatus()); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java index 372628ca..72219ee3 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java @@ -7,6 +7,7 @@ import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** * Reads the spec's {@code DataTypeEntry} JSON straight into the flattened {@link ServerDataType}, @@ -60,7 +61,9 @@ public static List readEntries(JsonElement body, String field) { } List entries = new ArrayList<>(); for (JsonElement entry : array.getAsJsonArray()) { - entries.add(readEntry(entry)); + if (!entry.isJsonNull()) { + entries.add(readEntry(entry)); + } } return entries; } @@ -108,7 +111,7 @@ private static List list(JsonObject owner, String field, Type type, JsonD return List.of(); } List items = context.deserialize(array, type); - return items == null ? List.of() : items; + return items == null ? List.of() : items.stream().filter(Objects::nonNull).toList(); } private static String string(JsonObject owner, String field) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java index 037e3600..020c468d 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java @@ -27,6 +27,9 @@ public static ApiInfo fromConfig(Path configFilePath) throws FileNotFoundExcepti } catch (java.io.IOException e) { throw new RuntimeException("Failed to read config file: " + configFilePath, e); } + if (config == null || config.getPluginSettings() == null) { + throw new JSONException("Invalid config file: pluginSettings missing"); + } var apikey = config.getPluginSettings().getApiKey(); var hostname = config.getPluginSettings().getHostname(); var portalHostname = config.getPluginSettings().getPortalHostname(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java index 5a572744..d16bd4e0 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java @@ -2,6 +2,8 @@ import ghidra.program.model.data.CategoryPath; +import java.util.Arrays; + /// A scoped type name split into its Ghidra {@link CategoryPath} and its leaf name. /// /// The server reports a type's scope in a `namespace` field, using `::` as the separator, e.g. @@ -20,7 +22,10 @@ public record TypePathAndName( public static TypePathAndName fromString(String str){ // split into path and name on "::" if (str.contains("::")) { - String[] pathPlusType = str.split("::"); + String[] pathPlusType = Arrays.stream(str.split("::", -1)).filter(s -> !s.isEmpty()).toArray(String[]::new); + if (pathPlusType.length == 0) { + return new TypePathAndName("", new String[0]); + } var baseType = pathPlusType[pathPlusType.length - 1]; String[] parts = new String[pathPlusType.length - 1]; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java index 579c5e6e..66b3fd47 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java @@ -30,10 +30,16 @@ //@formatter:on public class AgentChatPlugin extends ProgramPlugin { - private final AgentChatWindow chatWindow; + private AgentChatWindow chatWindow; public AgentChatPlugin(PluginTool tool) { super(tool); + } + + @Override + protected void init() { + // Required services are only resolved by now + super.init(); chatWindow = new AgentChatWindow(tool, getName(), new ConversationsApiChatService()); chatWindow.addToTool(); setupActions(); @@ -55,7 +61,9 @@ protected void locationChanged(ProgramLocation location) { @Override protected void dispose() { - chatWindow.dispose(); + if (chatWindow != null) { + chatWindow.dispose(); + } super.dispose(); } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java index f797b076..2223dfa1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java @@ -181,7 +181,7 @@ public void run(TaskMonitor monitor) { .withContext(ProgramLocationActionContext.class) .enabledWhen(context -> { var apiService = getApiService(); - if (apiService == null) return false; + if (apiService == null || context.getAddress() == null) return false; var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress()); return func != null // Exclude thunks and external functions because we do not support them in the portal @@ -209,7 +209,7 @@ public void run(TaskMonitor monitor) { .withContext(ProgramLocationActionContext.class) .enabledWhen(context -> { var apiService = getApiService(); - if (apiService == null) return false; + if (apiService == null || context.getAddress() == null) return false; var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress()); return func != null // Exclude thunks and external functions because we do not support them in the portal @@ -243,7 +243,7 @@ public void run(TaskMonitor monitor) { .withContext(ProgramLocationActionContext.class) .enabledWhen(context -> { var apiService = getApiService(); - if (apiService == null) return false; + if (apiService == null || context.getAddress() == null) return false; var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress()); return func != null && apiService.getAnalysedProgram(context.getProgram()).isPresent(); diff --git a/src/test/java/ai/reveng/AIDecompilerComponentTest.java b/src/test/java/ai/reveng/AIDecompilerComponentTest.java index c5e1d637..65dce2d9 100644 --- a/src/test/java/ai/reveng/AIDecompilerComponentTest.java +++ b/src/test/java/ai/reveng/AIDecompilerComponentTest.java @@ -504,4 +504,18 @@ public void aiDecompRating(FunctionID functionID, String rating, String reason) super.aiDecompRating(functionID, rating, reason); } } + + /// The Decompiler reports a context without an address when the cursor is on a blank line. + @Test + public void popupActionsAreDisabledForContextWithoutAddress() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new UnimplementedAPI()); + env.addPlugin(BinarySimilarityPlugin.class); + var program = newX64Program().getProgram(); + + var context = new ProgramLocationActionContext(null, program, null, null, null); + for (String name : List.of("Match function", "AI Decompilation", "View function in portal")) { + assertFalse(name, getAction(tool, name).isEnabledForContext(context)); + } + } } diff --git a/src/test/java/ai/reveng/AgentChatWindowTest.java b/src/test/java/ai/reveng/AgentChatWindowTest.java index 10f02c58..96bc0e38 100644 --- a/src/test/java/ai/reveng/AgentChatWindowTest.java +++ b/src/test/java/ai/reveng/AgentChatWindowTest.java @@ -12,6 +12,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.plugins.AgentChatPlugin; +import ai.reveng.toolkit.ghidra.plugins.LoggingPlugin; import ghidra.program.model.data.Undefined; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.Program; @@ -157,4 +158,18 @@ public List getFunctionInfo(AnalysisID analysisID) { assertEquals("agent rename must overwrite the existing local name", "renamed_by_agent", func.getName()); } + + /// Plugins are constructed in list order, before services are resolved, so the chat must not + /// capture the logging service until it is available. + @Test + public void capturesLoggingServiceWhenLoadedBeforeLoggingPlugin() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new UnimplementedAPI()); + tool.removePlugins(List.of(env.getPlugin(LoggingPlugin.class))); + + tool.addPlugins(List.of(AgentChatPlugin.class.getName(), LoggingPlugin.class.getName())); + + var controller = getInstanceField("controller", getComponentProvider(AgentChatWindow.class)); + assertNotNull(getInstanceField("log", controller)); + } } diff --git a/src/test/java/ai/reveng/ForkTempDir.java b/src/test/java/ai/reveng/ForkTempDir.java new file mode 100644 index 00000000..b583641d --- /dev/null +++ b/src/test/java/ai/reveng/ForkTempDir.java @@ -0,0 +1,32 @@ +package ai.reveng; + +import org.junit.platform.launcher.LauncherSession; +import org.junit.platform.launcher.LauncherSessionListener; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; + +/// Gives each test JVM its own Ghidra temp dir. Ghidra clears and restores write permission on that +/// dir whenever a JVM initialises, so forks sharing one fail file creation with "Permission denied". +public class ForkTempDir implements LauncherSessionListener { + + static final String PROPERTY = "application.tempdir"; + + @Override + public void launcherSessionOpened(LauncherSession session) { + if (System.getProperty(PROPERTY) != null) { + return; + } + try { + String root = System.getProperty("reveng.test.fork.tmproot"); + var dir = root == null + ? Files.createTempDirectory("ghidra-test-fork") + : Files.createTempDirectory(Path.of(root), "fork"); + System.setProperty(PROPERTY, dir.toString()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/src/test/java/ai/reveng/ForkTempDirTest.java b/src/test/java/ai/reveng/ForkTempDirTest.java new file mode 100644 index 00000000..d5bc7623 --- /dev/null +++ b/src/test/java/ai/reveng/ForkTempDirTest.java @@ -0,0 +1,24 @@ +package ai.reveng; + +import ghidra.framework.Application; +import ghidra.test.AbstractGhidraHeadlessIntegrationTest; +import org.junit.Test; + +import java.io.File; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/// Ghidra briefly drops write permission on its user temp dir whenever a JVM starts, so parallel +/// test forks sharing one dir fail to create files at random. Each fork must get its own. +public class ForkTempDirTest extends AbstractGhidraHeadlessIntegrationTest { + + @Test + public void ghidraTempDirIsPrivateToThisFork() { + String forkTempDir = System.getProperty("application.tempdir"); + assertNotNull("per-fork temp dir must be set", forkTempDir); + File userTempDir = Application.getUserTempDirectory(); + assertTrue(userTempDir + " should be under " + forkTempDir, + userTempDir.toPath().startsWith(new File(forkTempDir).toPath())); + } +} diff --git a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java index 09131892..7a8e681d 100644 --- a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java +++ b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java @@ -23,6 +23,7 @@ import java.util.Map; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /// The portal -> Ghidra half of "Sync With Portal": the signature the portal holds, and the data /// types it names, land on the matched function. @@ -52,6 +53,10 @@ private static class SignatureApi extends UnimplementedAPI { String remoteSignatureName = FUNCTION_NAME; /// The name the portal gives the single parameter, or null for a parameter it does not name. String remoteParameterName = "count"; + /// What the portal reports as `has_signature`; the generated model lets a JSON null through. + Boolean remoteHasSignature = true; + /// Calls of {@link #getFunctionInfo} after which the portal stops listing the function. + int functionInfoCallsBeforeRemoval = Integer.MAX_VALUE; @Override public AnalysisStatus status(AnalysisID analysisID) { @@ -60,6 +65,9 @@ public AnalysisStatus status(AnalysisID analysisID) { @Override public List getFunctionInfo(AnalysisID analysisID) { + if (functionInfoCallsBeforeRemoval-- <= 0) { + return List.of(); + } return List.of(new FunctionInfo( new FunctionID(FUNCTION_ID), FUNCTION_NAME, FUNCTION_NAME, ADDRESS, 0x100)); } @@ -74,7 +82,7 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID entry.setAnalysisId(1L); entry.setFunctionId(FUNCTION_ID); entry.setFunctionName(remoteSignatureName); - entry.setHasSignature(true); + entry.setHasSignature(remoteHasSignature); entry.setReturnDataTypeId(1L); var parameter = new SignatureParameterEntry(); parameter.setOrdinal(0L); @@ -215,4 +223,57 @@ public void leavesASignatureTheAnalystWroteAlone() throws Exception { 0, summary.appliedSignatures()); assertEquals("char", function.getReturnType().getName()); } + + @Test + public void nullHasSignatureIsTreatedAsNoSignature() throws Exception { + var api = new SignatureApi(); + api.remoteReturnType = "int"; + api.remoteHasSignature = null; + + var fixture = attachWithoutRemoteSignature(api); + + assertEquals("undefined8", fixture.function().getReturnType().getName()); + } + + /// The function list can change between the attach-time association and the pull that follows. + @Test + public void functionNoLongerListedByThePortalIsSkipped() throws Exception { + var api = new SignatureApi(); + api.functionInfoCallsBeforeRemoval = 1; + + var fixture = attachWithoutRemoteSignature(api); + + assertEquals(FUNCTION_NAME, fixture.function().getName()); + } + + /// A failure while pulling must not leave the program's transaction open. + @Test + public void failedPullDoesNotLeakTransaction() throws Exception { + var api = new SignatureApi() { + int calls = 0; + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + // The pull runs after the attach-time association; make it fail there. + if (calls++ == 0) { + return super.getFunctionInfo(analysisID); + } + throw new RuntimeException("simulated failure"); + } + }; + var service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("mem", "0x4000", 0x100); + builder.createEmptyFunction(FUNCTION_NAME, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); + + try { + service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + } catch (RuntimeException expected) { + // the transaction is what matters + } + + assertNull("transaction must be closed", program.getCurrentTransactionInfo()); + } } diff --git a/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java b/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java index 7fc07b6c..c9b04e23 100644 --- a/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java +++ b/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java @@ -108,4 +108,29 @@ public void testPluginFailsToLoadWithMalformedConfigFile() throws Exception { var service = tool.getService(GhidraRevengService.class); assertNull("GhidraRevengService should not be registered with bad config", service); } + + /// Valid JSON lacking `pluginSettings` must be reported like a malformed file, not crash the plugin. + @Test + public void testPluginFailsToLoadWithConfigFileMissingPluginSettings() throws Exception { + setErrorGUIEnabled(true); + var tool = env.getTool(); + + Path configFile = createTempDirectory("reai-test").toPath().resolve("reai.json"); + Files.writeString(configFile, "{}"); + + TestableReaiAPIServicePlugin.setConfigPathOverride(configFile); + + runSwing(() -> { + try { + tool.addPlugin(TestableReaiAPIServicePlugin.class.getName()); + } catch (Exception e) { + // Expected — plugin should fail after showing error dialog + } + }, false); + + var errorDialog = waitForDialogComponent("Load Config"); + assertNotNull("Error dialog should appear for config without pluginSettings", errorDialog); + close(errorDialog); + waitForSwing(); + } } diff --git a/src/test/java/ai/reveng/RecentAnalysisDialogTest.java b/src/test/java/ai/reveng/RecentAnalysisDialogTest.java index 75e4fdfe..856d7c56 100644 --- a/src/test/java/ai/reveng/RecentAnalysisDialogTest.java +++ b/src/test/java/ai/reveng/RecentAnalysisDialogTest.java @@ -8,10 +8,14 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.model.AnalysisRecordBody; import docking.DockingWindowManager; +import ghidra.framework.Log4jErrorLogger; +import ghidra.util.DefaultErrorLogger; +import ghidra.util.Msg; import org.junit.Test; import javax.swing.*; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -192,6 +196,68 @@ public void testDialogShowsRecentAnalyses() throws Exception { waitForSwing(); } + @Test + public void testPickSelectedWithoutSelectionDoesNothing() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new RecentAnalysesMockApi()); + + var builder = newX64Program("test_binary"); + builder.createMemory("test", "0x1000", 100); + var program = builder.getProgram(); + env.showTool(program); + waitForSwing(); + + List errors = new CopyOnWriteArrayList<>(); + Msg.setErrorLogger(new DefaultErrorLogger() { + @Override + public void error(Object originator, Object message, Throwable throwable) { + errors.add(message); + } + }); + try { + RecentAnalysisDialog dialog = runSwing(() -> new RecentAnalysisDialog(tool, program)); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(RecentAnalysisDialog.class); + + pressButton(findButtonByText(foundDialog.getComponent(), "Pick selected")); + waitForTasks(); + waitForSwing(); + + assertEquals(List.of(), errors); + close(foundDialog); + } finally { + Msg.setErrorLogger(new Log4jErrorLogger()); + } + } + + @Test + public void testPickMostRecentWithoutAnalysesDoesNothing() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new UnimplementedAPI() { + @Override + public List search(TypedApiInterface.BinaryHash hash) { + return List.of(); + } + }); + + var builder = newX64Program("test_binary"); + builder.createMemory("test", "0x1000", 100); + var program = builder.getProgram(); + env.showTool(program); + waitForSwing(); + + RecentAnalysisDialog dialog = runSwing(() -> new RecentAnalysisDialog(tool, program)); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(RecentAnalysisDialog.class); + waitForTasks(); + + pressButton(findButtonByText(foundDialog.getComponent(), "Pick most recent")); + waitForSwing(); + + assertTrue("dialog should stay open", foundDialog.isVisible()); + close(foundDialog); + } + /** * Mock API implementation for recent analysis dialog tests. * Provides necessary responses for the dialog to function without a real server. diff --git a/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java b/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java index 03619c96..25870b62 100644 --- a/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java +++ b/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java @@ -235,4 +235,49 @@ public void unsizedTypesFallBackToFiller() { assertEquals(1, decoder.typeFor(1L, 0).getLength()); assertTrue(decoder.typeFor(2L, 0) instanceof TypeDef); } + + /// Null entries in any array are skipped rather than failing the whole decode. + @Test + public void skipsNullArrayElements() { + var decoder = ServerDataTypeDecoder.decode(types(""" + {"items": [ + null, + {"data_type_id": 1, "namespace": "", "name": "S", "kind": "STRUCT", + "size": 4, "source_type": "AUTO", "has_definition": true, + "definition": {"members": [ + null, + {"name": "x", "offset": 0, "size": 4, "data_type_id": null, "is_bitfield": false}]}}, + {"data_type_id": 2, "namespace": "", "name": "U", "kind": "UNION", + "size": 4, "source_type": "AUTO", "has_definition": true, + "definition": {"members": [null]}}, + {"data_type_id": 3, "namespace": "", "name": "E", "kind": "ENUM", + "size": 4, "source_type": "AUTO", "has_definition": true, + "definition": {"values": [null, {"name": "NO_VALUE", "value": null}, {"name": "A", "value": "1"}]}}, + {"data_type_id": 4, "namespace": "", "name": "F", "kind": "FUNCTION_DEFINITION", + "size": 0, "source_type": "AUTO", "has_definition": true, + "definition": {"return_data_type_id": null, "parameters": [null]}} + ]} + """)); + + assertEquals("x", ((Structure) decoder.typeFor(1L, 0)).getComponentAt(0).getFieldName()); + assertEquals(1L, ((Enum) decoder.typeFor(3L, 0)).getValue("A")); + } + + /// Names Ghidra rejects (control characters, empty namespace segments) must not fail the decode. + @Test + public void sanitisesNamesGhidraRejects() { + var decoder = ServerDataTypeDecoder.decode(types(""" + {"items": [ + {"data_type_id": 1, "namespace": "ns::::inner", "name": "bad\\nname", "kind": "STRUCT", + "size": 4, "source_type": "AUTO", "has_definition": false}, + {"data_type_id": 2, "namespace": "", "name": "::", "kind": "TYPEDEF", + "size": 4, "source_type": "AUTO", "has_definition": false} + ]} + """)); + + DataType struct = decoder.typeFor(1L, 0); + assertEquals("bad_name", struct.getName()); + assertEquals("/ns/inner", struct.getCategoryPath().getPath()); + assertNotNull(decoder.typeFor(2L, 0)); + } } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java index 362a61f8..9f228c2e 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java @@ -231,4 +231,21 @@ public void loadConversationSetsTitleAndState() { assertEquals("Prior chat", view.lastState.title()); } + + /// An unchecked failure in the worker must end the run, or Send stays disabled. + @Test + public void uncheckedWorkerFailureEndsTheRun() { + var service = new FakeChatService() { + @Override + public void sendMessage(String conversationId, String content, ConversationContext context) { + throw new IllegalStateException("boom"); + } + }; + var view = new RecordingView(); + var controller = controller(service, view, new RecordingCallbacks()); + + controller.send("hello"); + + assertEquals("error", view.lastState.runStatus()); + } } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java new file mode 100644 index 00000000..2cb50090 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java @@ -0,0 +1,29 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +/// `data` is optional on the base response wrapper, so a body without it must surface as an +/// {@link ApiException} rather than a NullPointerException. +public class EmptyResponseDataTest extends AbstractStubServerTest { + + private static final String EMPTY = "{\"status\": false, \"data\": null, \"message\": \"nope\"}"; + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> respondJson(exchange, EMPTY)); + } + + @Test(expected = ApiException.class) + public void statusWithoutDataThrowsApiException() throws Exception { + api().status(new TypedApiInterface.AnalysisID(1)); + } + + @Test(expected = ApiException.class) + public void analyseWithoutDataThrowsApiException() throws Exception { + api().analyse(new AnalysisOptionsBuilder() + .hash(new TypedApiInterface.BinaryHash("a".repeat(64))) + .fileName("test.bin")); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java index fd0da949..1165b88b 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java @@ -22,4 +22,20 @@ public void fromString_leavesAnUnqualifiedNameWithAnEmptyPath() { assertEquals("PlainName", path.name()); assertArrayEquals("an unqualified name has no path segments", new String[]{}, path.path()); } + + @Test + public void fromString_ignoresEmptySegments() { + var path = TypePathAndName.fromString("a::::b"); + + assertEquals("b", path.name()); + assertArrayEquals(new String[]{"a"}, path.path()); + } + + @Test + public void fromString_acceptsABareSeparator() { + var path = TypePathAndName.fromString("::"); + + assertEquals("", path.name()); + assertArrayEquals(new String[]{}, path.path()); + } } diff --git a/src/test/resources/META-INF/services/org.junit.platform.launcher.LauncherSessionListener b/src/test/resources/META-INF/services/org.junit.platform.launcher.LauncherSessionListener new file mode 100644 index 00000000..0f9fe372 --- /dev/null +++ b/src/test/resources/META-INF/services/org.junit.platform.launcher.LauncherSessionListener @@ -0,0 +1 @@ +ai.reveng.ForkTempDir From 5690732c7fd5bcdc5ed82ae5694bf25817f2481f Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:52:41 +0000 Subject: [PATCH 19/76] test(ENG-4406): check the dialog is idle on the EDT before pressing Match The run is marked finished and the button relabelled in one Swing update; checking from the test thread could see it half done and find the button still reading Cancel. --- .../reveng/FunctionLevelFunctionMatchingDialogTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index b564ea5d..d9fae5b7 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -627,8 +627,12 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { /// than, on a slow machine, cancelling the one that started after the button was looked up. private void waitForMatchingIdle(FunctionLevelFunctionMatchingDialog dialog) { JLabel statusLabel = (JLabel) getInstanceField("statusLabel", dialog); - waitForCondition(() -> statusLabel.getText().startsWith("Matching complete") - && getInstanceField("matchingThread", dialog) == null, + JButton matchButton = (JButton) getInstanceField("matchButton", dialog); + // Checked on the EDT: the run is marked finished and the button relabelled in one Swing update, + // which a check from the test thread can otherwise see half done + waitForCondition(() -> runSwing(() -> statusLabel.getText().startsWith("Matching complete") + && getInstanceField("matchingThread", dialog) == null + && matchButton.getText().equals("Match Functions")), "The automatic match on open should finish"); } From eec4a86e4e645bdca66325460e49d01114b501bc Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:49:05 +0000 Subject: [PATCH 20/76] feat(ENG-4411): transfer name, signature or both from function matching Replace the Rename buttons with Transfer dropdowns (Name / Signature / Name and Signature), as in the portal. ApplyMatchCmd takes the part to transfer; a signature-only transfer keeps the function's name and namespace and pushes no rename to the portal. --- .../binarysimilarity/cmds/ApplyMatchCmd.java | 93 +++++++++++++--- .../AbstractFunctionMatchingDialog.java | 83 ++++++++------ .../FunctionLevelFunctionMatchingDialog.java | 8 +- .../java/ai/reveng/ApplyMatchCmdTest.java | 103 ++++++++++++++++++ 4 files changed, 233 insertions(+), 54 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java index 1bed1ced..6cedbf1b 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java @@ -3,8 +3,11 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; import ghidra.app.cmd.function.ApplyFunctionSignatureCmd; +import ghidra.app.cmd.function.FunctionRenameOption; import ghidra.app.cmd.label.RenameLabelCmd; import ghidra.framework.cmd.Command; +import ghidra.program.model.data.DataTypeConflictHandler; +import ghidra.program.model.data.FunctionDefinitionDataType; import ghidra.program.model.listing.CircularDependencyException; import ghidra.program.model.listing.Program; import ghidra.program.model.symbol.Namespace; @@ -20,14 +23,41 @@ /// The central command to apply a function match to a {@link Program} /// It centralizes product design decisions about how to apply a match, like moving it to a namespace, /// renaming it, applying the signature, etc. -/// It will apply the function signature if available, otherwise it will just rename the function +/// What it transfers is chosen by {@link Transfer}: the matched name, the matched signature (its data +/// types), or both. A signature is only transferred when the match has one. /// There are various considerations when ap public class ApplyMatchCmd implements Command { + /// The parts of a match that can be transferred onto the local function, as offered in the portal + public enum Transfer { + NAME("Name"), + SIGNATURE("Signature"), + NAME_AND_SIGNATURE("Name and Signature"); + + private final String label; + + Transfer(String label) { + this.label = label; + } + + public String label() { + return label; + } + + public boolean includesName() { + return this != SIGNATURE; + } + + public boolean includesSignature() { + return this != NAME; + } + } + private final GhidraRevengService.AnalysedProgram analyzedProgram; private final GhidraFunctionMatchWithSignature match; @Nullable private final GhidraRevengService service; private final Boolean includeBinaryNameInNameSpace; + private final Transfer transfer; public ApplyMatchCmd( @Nullable GhidraRevengService service, @@ -35,27 +65,44 @@ public ApplyMatchCmd( @NotNull GhidraFunctionMatchWithSignature match, Boolean includeBinaryNameInNameSpace + ) { + this(service, program, match, includeBinaryNameInNameSpace, Transfer.NAME_AND_SIGNATURE); + } + + public ApplyMatchCmd( + @Nullable GhidraRevengService service, + @NotNull GhidraRevengService.AnalysedProgram program, + @NotNull GhidraFunctionMatchWithSignature match, + Boolean includeBinaryNameInNameSpace, + @NotNull Transfer transfer ) { super(); this.analyzedProgram = program; this.match = match; this.service = service; this.includeBinaryNameInNameSpace = includeBinaryNameInNameSpace; + this.transfer = transfer; } private boolean shouldApplyMatch() { var func = match.function(); - return func != null && - // Do not override user-defined function names - func.getSymbol().getSource() != SourceType.USER_DEFINED && + if (func == null || // Exclude thunks and external functions - !func.isThunk() && - !func.isExternal() && + func.isThunk() || + func.isExternal() || + // Only apply if the function ID is known (boundaries matched) + analyzedProgram.getIDForFunction(func).isEmpty()) { + return false; + } + if (transfer == Transfer.SIGNATURE) { + // The name is left alone, so only a signature to apply matters + return match.signature() != null; + } + // Do not override user-defined function names + return func.getSymbol().getSource() != SourceType.USER_DEFINED && // Only accept valid names (no spaces) !match.functionMatch().nearest_neighbor_mangled_function_name().contains(" ") && - !match.functionMatch().nearest_neighbor_function_name().contains(" ") - // Only rename if the function ID is known (boundaries matched) - && analyzedProgram.getIDForFunction(func).isPresent(); + !match.functionMatch().nearest_neighbor_function_name().contains(" "); } @Override @@ -68,8 +115,14 @@ public boolean applyTo(Program obj) { return false; } - var nameSpace = includeBinaryNameInNameSpace ? getLibraryNameSpaceForName(match.functionMatch().nearest_neighbor_binary_name()): getRevEngAINameSpace(); var function = match.function(); + var signature = match.signature(); + if (transfer == Transfer.SIGNATURE) { + // Keep the function's own name: only the prototype and its data types come across + return applySignature(signature); + } + + var nameSpace = includeBinaryNameInNameSpace ? getLibraryNameSpaceForName(match.functionMatch().nearest_neighbor_binary_name()): getRevEngAINameSpace(); try { function.setParentNamespace(nameSpace); } catch (DuplicateNameException e) { @@ -82,15 +135,12 @@ public boolean applyTo(Program obj) { this.analyzedProgram.setMangledNameForFunction(function, match.functionMatch().nearest_neighbor_mangled_function_name()); - var signature = match.signature(); - if (signature != null) { - var cmd = new ApplyFunctionSignatureCmd(function.getEntryPoint(), signature, SourceType.USER_DEFINED); - cmd.applyTo(analyzedProgram.program()); - } - else { - var renameCmd = new RenameLabelCmd(match.function().getSymbol(), match.functionMatch().name(), SourceType.USER_DEFINED); - renameCmd.applyTo(analyzedProgram.program()); + if (transfer.includesSignature() && signature != null) { + // The name is set explicitly below: left to the signature command, it would only replace a default name + applySignature(signature); } + var renameCmd = new RenameLabelCmd(function.getSymbol(), match.functionMatch().name(), SourceType.USER_DEFINED); + renameCmd.applyTo(analyzedProgram.program()); // If we have a service then push the name. If not then it was explicitly not provided, i.e. the caller // is responsible for pushing the names in batch if (service != null) { @@ -105,6 +155,13 @@ public boolean applyTo(Program obj) { return true; } + /// Applies the prototype and its data types, leaving the function's name to the caller + private boolean applySignature(FunctionDefinitionDataType signature) { + var cmd = new ApplyFunctionSignatureCmd(match.function().getEntryPoint(), signature, SourceType.USER_DEFINED, + false, false, DataTypeConflictHandler.DEFAULT_HANDLER, FunctionRenameOption.NO_CHANGE); + return cmd.applyTo(analyzedProgram.program()); + } + public void applyWithTransaction() { var program = this.analyzedProgram.program(); var tID = program.startTransaction("RevEng.AI: Apply Match"); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index d2bb5b63..3ebe6fbc 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -34,6 +34,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.function.Consumer; import java.util.stream.Collectors; public abstract class AbstractFunctionMatchingDialog extends RevEngDialogComponentProvider { @@ -66,7 +67,7 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone /// The thread of the current matching run; null when idle or cancelled. A run whose thread is no /// longer this one has been superseded, and must not touch the UI. protected volatile Thread matchingThread; - protected JPanel renameButtonsPanel; + protected JPanel transferButtonsPanel; // Assembly comparison panel protected AssemblyDiffPanel assemblyDiffPanel; @@ -343,11 +344,11 @@ public boolean isCellEditable(int row, int column) { ? "%d match%s".formatted(totalMatchCount, totalMatchCount == 1 ? "" : "es") : "%d of %d shown".formatted(displayedMatchCount, totalMatchCount)); - // Show/hide rename buttons based on whether we have results + // Show/hide transfer buttons based on whether we have results boolean hasResults = displayedMatchCount > 0; - renameButtonsPanel.setVisible(hasResults); + transferButtonsPanel.setVisible(hasResults); - // Enable table selection model for rename operations + // Enable table selection model for transfer operations if (hasResults) { resultsTable.setSelectionMode(getTableSelectionMode()); resultsTable.setRowSelectionAllowed(true); @@ -532,7 +533,7 @@ protected JComponent buildMainPanel() { errorArea.setBorder(BorderFactory.createTitledBorder("Error Details")); errorScrollPane = new JScrollPane(errorArea); - // Results table with rename buttons container + // Results table with transfer buttons container JPanel resultsContainer = createResultsContainer(); centerPanel.add(resultsContainer, BorderLayout.CENTER); @@ -698,10 +699,10 @@ public void mouseReleased(MouseEvent e) { resultsContainer.add(mainSplitPane, BorderLayout.CENTER); - // Rename buttons panel - renameButtonsPanel = createRenameButtonsPanel(); - renameButtonsPanel.setVisible(false); - resultsContainer.add(renameButtonsPanel, BorderLayout.SOUTH); + // Transfer buttons panel + transferButtonsPanel = createTransferButtonsPanel(); + transferButtonsPanel.setVisible(false); + resultsContainer.add(transferButtonsPanel, BorderLayout.SOUTH); return resultsContainer; } @@ -744,19 +745,27 @@ private TypedApiInterface.AnalysisID getSelectedMatchedAnalysisID() { return selected.size() == 1 ? selected.get(0).functionMatch().nearest_neighbor_analysis_id() : null; } - protected JPanel createRenameButtonsPanel() { + protected JPanel createTransferButtonsPanel() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0)); panel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); + panel.add(createTransferButton("Transfer All", this::onTransferAll)); + panel.add(createTransferButton("Transfer Selected", this::onTransferSelected)); + return panel; + } - JButton renameAllButton = new JButton("Rename All"); - renameAllButton.addActionListener(e -> onRenameAllButtonClicked()); - panel.add(renameAllButton); - - JButton renameSelectedButton = new JButton("Rename Selected"); - renameSelectedButton.addActionListener(e -> onRenameSelectedButtonClicked()); - panel.add(renameSelectedButton); + /// A button that drops down the parts of a match that can be transferred, as the portal's + /// Transfer Symbol button does, and hands the chosen one to {@code onChosen} + protected static JButton createTransferButton(String text, Consumer onChosen) { + JPopupMenu menu = new JPopupMenu(); + for (ApplyMatchCmd.Transfer transfer : ApplyMatchCmd.Transfer.values()) { + JMenuItem item = new JMenuItem(transfer.label()); + item.addActionListener(e -> onChosen.accept(transfer)); + menu.add(item); + } - return panel; + JButton button = new JButton(text + " \u25BE"); + button.addActionListener(e -> menu.show(button, 0, button.getHeight())); + return button; } protected JPanel createCollectionSelectorPanel() { @@ -1053,8 +1062,9 @@ protected void onMatchButtonClicked() { } - protected void onRenameAllButtonClicked() { - renameInBackground(functionMatchResults); + protected void onTransferAll(ApplyMatchCmd.Transfer transfer) { + hideError(); + transferInBackground(functionMatchResults, transfer); } /// The results behind the currently selected table rows. @@ -1074,22 +1084,27 @@ protected List getSelectedMatches() { return selectedMatches; } - protected void onRenameSelectedButtonClicked() { + protected void onTransferSelected(ApplyMatchCmd.Transfer transfer) { if (resultsTable.getSelectedRowCount() == 0) { - showError("Please select one or more rows to rename."); + showError("Please select one or more rows to transfer."); return; } hideError(); - renameInBackground(getSelectedMatches()); + transferInBackground(getSelectedMatches(), transfer); } - private void renameInBackground(List matches) { - var task = new Task("Applying Renames", true, false, false) { + private void transferInBackground(List matches, ApplyMatchCmd.Transfer transfer) { + var task = new Task("Transferring " + transfer.label(), true, false, false) { @Override public void run(TaskMonitor monitor) { - batchRenameFunctions(matches); - importFunctionNames(matches); + // The portal only stores names, so a signature-only transfer has nothing to push + if (transfer.includesName()) { + batchRenameFunctions(matches); + } + int applied = applyMatches(matches, transfer); + SwingUtilities.invokeLater(() -> statusLabel.setText("Transferred %s to %d of %d function(s)" + .formatted(transfer.label().toLowerCase(), applied, matches.size()))); } }; // Shown in a task dialog: the dialog's progress bar belongs to matching, and is hidden by now @@ -1105,19 +1120,25 @@ protected void batchRenameFunctions(List funct } } - protected void importFunctionNames(List functionMatches) { + /// Applies the matches to the program and returns how many functions were changed. Matches can be + /// skipped, e.g. a signature transfer for a match the portal has no signature for. + protected int applyMatches(List functionMatches, ApplyMatchCmd.Transfer transfer) { var program = analyzedProgram.program(); + int[] applied = {0}; - program.withTransaction("Apply Function Matching Renames", () -> { + program.withTransaction("Apply Function Matching " + transfer.label(), () -> { for (GhidraFunctionMatchWithSignature match : functionMatches) { // We don't pass a service, because we don't need to update individual functions on the portal // batchRenameFunctions already does that for us - var cmd = new ApplyMatchCmd(null, analyzedProgram, match, false); - cmd.applyTo(program); + var cmd = new ApplyMatchCmd(null, analyzedProgram, match, false, transfer); + if (cmd.applyTo(program)) { + applied[0]++; + } } } ); SwingUtilities.invokeLater(this::updateResultsTable); + return applied[0]; } @Override diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java index c06c2ac7..2f711c0e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java @@ -126,15 +126,13 @@ protected boolean matchesFilter(GhidraFunctionMatchWithSignature result) { } @Override - protected JPanel createRenameButtonsPanel() { + protected JPanel createTransferButtonsPanel() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); panel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); - // Only show "Rename Selected" button for function-level matching + // Only offer the selected match for function-level matching, // since we're only matching a single function - JButton renameSelectedButton = new JButton("Rename Selected"); - renameSelectedButton.addActionListener(e -> onRenameSelectedButtonClicked()); - panel.add(renameSelectedButton); + panel.add(createTransferButton("Transfer Symbol", this::onTransferSelected)); return panel; } diff --git a/src/test/java/ai/reveng/ApplyMatchCmdTest.java b/src/test/java/ai/reveng/ApplyMatchCmdTest.java index 74493e01..1c69876c 100644 --- a/src/test/java/ai/reveng/ApplyMatchCmdTest.java +++ b/src/test/java/ai/reveng/ApplyMatchCmdTest.java @@ -3,6 +3,7 @@ import ai.reveng.invoker.ApiException; import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.BinaryHash; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; @@ -11,18 +12,28 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; +import ghidra.program.model.data.FunctionDefinitionDataType; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.data.ParameterDefinitionImpl; +import ghidra.program.model.data.PointerDataType; import ghidra.program.model.data.Undefined; +import ghidra.program.model.listing.Function; import ghidra.util.task.TaskMonitor; import org.junit.Test; import java.math.BigDecimal; import java.util.List; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ApplyMatchCmdTest extends RevEngMockableHeadedIntegrationTest { + private GhidraRevengService.AnalysedProgram analysedProgram; + @Test public void testFailedServerRenameDoesNotLeakTransaction() throws Exception { var tool = env.getTool(); @@ -59,6 +70,98 @@ public void testFailedServerRenameDoesNotLeakTransaction() throws Exception { program.getCurrentTransactionInfo()); } + @Test + public void testTransferNameLeavesSignatureAlone() throws Exception { + var function = setUpFunction(); + + assertTrue(apply(function, matchWithSignature(function), ApplyMatchCmd.Transfer.NAME)); + + assertEquals("renamed_func", function.getName()); + assertEquals("the signature must not be transferred", 0, function.getParameterCount()); + } + + @Test + public void testTransferSignatureKeepsName() throws Exception { + var function = setUpFunction(); + var originalName = function.getName(); + + assertTrue(apply(function, matchWithSignature(function), ApplyMatchCmd.Transfer.SIGNATURE)); + + assertEquals("the name must not be transferred", originalName, function.getName()); + assertEquals("the function must stay in its namespace", + function.getProgram().getGlobalNamespace(), function.getParentNamespace()); + assertEquals(2, function.getParameterCount()); + assertEquals(IntegerDataType.dataType.getName(), function.getReturnType().getName()); + assertEquals("buf", function.getParameter(1).getName()); + } + + @Test + public void testTransferNameAndSignature() throws Exception { + var function = setUpFunction(); + + assertTrue(apply(function, matchWithSignature(function), ApplyMatchCmd.Transfer.NAME_AND_SIGNATURE)); + + assertEquals("renamed_func", function.getName()); + assertEquals(2, function.getParameterCount()); + assertEquals("buf", function.getParameter(1).getName()); + } + + @Test + public void testTransferSignatureWithoutOneDoesNothing() throws Exception { + var function = setUpFunction(); + var originalName = function.getName(); + var match = new GhidraFunctionMatchWithSignature(function, functionMatch(), null); + + assertFalse(apply(function, match, ApplyMatchCmd.Transfer.SIGNATURE)); + assertEquals(originalName, function.getName()); + } + + private Function setUpFunction() throws Exception { + var service = addMockedService(env.getTool(), new RenameFailsAPI()); + var builder = newX64Program(); + var function = builder.createEmptyFunction(null, "0x1000", 10, Undefined.getUndefinedDataType(4)); + service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + analysedProgram = service.getAnalysedProgram(builder.getProgram()).orElseThrow(); + return function; + } + + /// Applied without a service, as the matching dialog does, so nothing is pushed to the portal + private boolean apply(Function function, GhidraFunctionMatchWithSignature match, ApplyMatchCmd.Transfer transfer) { + var program = function.getProgram(); + var cmd = new ApplyMatchCmd(null, analysedProgram, match, false, transfer); + var tx = program.startTransaction("test"); + boolean applied = false; + try { + applied = cmd.applyTo(program); + } finally { + program.endTransaction(tx, applied); + } + return applied; + } + + private static FunctionMatch functionMatch() { + return new FunctionMatch( + new FunctionID(1), + new FunctionID(2), + "renamed_func", + "renamed_func_mangled", + "libfoo.so", + new BinaryHash("abc123"), + false, + BigDecimal.valueOf(0.9), + BigDecimal.valueOf(0.9), + null); + } + + private static GhidraFunctionMatchWithSignature matchWithSignature(Function function) { + var signature = new FunctionDefinitionDataType("renamed_func"); + signature.setReturnType(IntegerDataType.dataType); + signature.setArguments( + new ParameterDefinitionImpl("len", IntegerDataType.dataType, null), + new ParameterDefinitionImpl("buf", PointerDataType.dataType, null)); + return new GhidraFunctionMatchWithSignature(function, functionMatch(), signature); + } + static class RenameFailsAPI extends UnimplementedAPI { @Override public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { From b8cb86c0088fc001ca87be143e3c22a28f9cc7bb Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:10:51 +0000 Subject: [PATCH 21/76] fix(ENG-4453): don't overwrite real signatures with the server placeholder Type extraction stores `undefined f(void)` (source SYSTEM, no parameters, return type id 0 or none) for every function Ghidra had no signature for, and reports it with has_signature true. Attaching an analysis applied it over DWARF and analysis signatures, matching transferred it, and sync never pushed the better local signature because the server seemed to have one. - Treat the placeholder as no signature when pulling, syncing and matching. - Don't let a SYSTEM signature replace a local IMPORTED or ANALYSIS one; the function still takes the portal's name. Portal edits (USER) still apply. - Count a placeholder as missing when pushing back. Its row exists, so the signature PUT accepts the local signature. --- .../api/FunctionSignatureService.java | 21 ++- .../services/api/GhidraRevengService.java | 39 +++-- .../ai/reveng/PullSignaturesOnSyncTest.java | 140 +++++++++++++++++- .../api/FunctionSignatureServiceTest.java | 64 ++++++++ 4 files changed, 247 insertions(+), 17 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java index 1f013f92..60c77e6b 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java @@ -40,11 +40,30 @@ public FunctionSignatureService(TypedApiInterface api) { /// One function's signature together with the types it references. public record Resolved(BatchFunctionSignatureEntry entry, List dataTypes) {} + /// Whether the entry carries a signature worth applying: the server holds one, and it is more than + /// the placeholder described at {@link #isPlaceholder}. + public static boolean hasUsableSignature(BatchFunctionSignatureEntry entry) { + return Boolean.TRUE.equals(entry.getHasSignature()) && !isPlaceholder(entry); + } + + /// Type extraction stores a signature for every function it reaches, including the ones Ghidra had + /// nothing for, and those come back as `undefined f(void)` with `has_signature` true: source SYSTEM, + /// no parameters, and a return type of data type id 0 — always Ghidra's `undefined` in an analysis' + /// type table — or none at all. Applying one erases whatever the function had locally, and counting + /// it as present stops the better local signature from being pushed. A real `void f(void)` returns + /// `void`, not `undefined`, so it is not mistaken for one. + public static boolean isPlaceholder(BatchFunctionSignatureEntry entry) { + Long returnType = entry.getReturnDataTypeId(); + return entry.getSourceType() == BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM + && (entry.getParameters() == null || entry.getParameters().isEmpty()) + && (returnType == null || returnType == 0L); + } + /// The signature of a single function, or empty when the server holds none for it. public Optional get(FunctionID functionID) { FunctionSignatureBatch batch = getMany(List.of(functionID)); return batch.items().stream() - .filter(entry -> Boolean.TRUE.equals(entry.getHasSignature())) + .filter(FunctionSignatureService::hasUsableSignature) .findFirst() .map(entry -> new Resolved(entry, batch.dataTypesFor(analysisOf(entry)))); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index cf5df715..3726ceef 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -531,10 +531,12 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, /// applied this run, so the command is given {@link FunctionRenameOption#NO_CHANGE} and nothing /// here competes with it. /// - /// A signature is applied unless the analyst wrote the local one by hand; anything Ghidra's own - /// analysis inferred is fair game. That is also what makes a second sync useful: an earlier pull - /// stamps {@link SourceType#ANALYSIS}, so a "default only" guard would turn every pull after the - /// first into a no-op. + /// A signature is applied unless the analyst wrote the local one by hand, or the server only has + /// what it extracted itself and the local one is better-founded — see + /// {@link #localSignatureOutranks}. A signature edited in the portal still replaces one Ghidra + /// inferred. That is also what makes a second sync useful: an earlier pull stamps + /// {@link SourceType#ANALYSIS}, so a "default only" guard would turn every pull after the first + /// into a no-op. private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) { var functionMap = analysedProgram.getFunctionMap(); if (functionMap.isEmpty()) { @@ -550,12 +552,13 @@ private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor m if (monitor.isCancelled()) { break; } - if (!Boolean.TRUE.equals(entry.getHasSignature())) { + if (!FunctionSignatureService.hasUsableSignature(entry)) { continue; } var function = functionMap.get(new TypedApiInterface.FunctionID(entry.getFunctionId())); if (function == null || function.isExternal() || function.isThunk() - || function.getSignatureSource() == SourceType.USER_DEFINED) { + || function.getSignatureSource() == SourceType.USER_DEFINED + || localSignatureOutranks(function, entry)) { continue; } var signature = getFunctionSignature(entry, decoderFor(decoders, batch, entry)); @@ -585,6 +588,15 @@ private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor m return applied; } + /// Whether the function's own signature beats one the server extracted itself. A SYSTEM signature + /// is what server-side Ghidra worked out, so it adds nothing over a signature imported from debug + /// info locally, or one local analysis inferred, and replacing either can only lose information. + private static boolean localSignatureOutranks(Function function, BatchFunctionSignatureEntry entry) { + var local = function.getSignatureSource(); + return entry.getSourceType() == BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM + && (local == SourceType.IMPORTED || local == SourceType.ANALYSIS); + } + /// Apply one server-sourced signature to a function. /// /// The conflict handler is the load-bearing argument. Ghidra's default keeps the local type and @@ -679,12 +691,14 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, Set matchedIds, TaskMonitor monitor, ReaiLoggingService log) { - // Only the matched functions are candidates, and only whether the server holds a signature - // at all matters here, so ask for exactly those ids and skip the type closure. + // Only the matched functions are candidates, and only whether the server holds a usable + // signature matters here, so ask for exactly those ids and skip the type closure. A placeholder + // counts as missing: unlike a function with no signature at all, it is a stored row the + // signature PUT accepts, so these are the functions a push can actually fill in. Set remotePresent = signatures() .getMany(List.copyOf(matchedIds), false) .items().stream() - .filter(item -> Boolean.TRUE.equals(item.getHasSignature())) + .filter(FunctionSignatureService::hasUsableSignature) .map(item -> new TypedApiInterface.FunctionID(item.getFunctionId())) .collect(Collectors.toSet()); @@ -801,7 +815,7 @@ private List pullFunctionInfoFromAnalysisInternal(AnalysedProgram Map decoders = new HashMap<>(); Map signatureMap = signatureBatch.items() .stream() - .filter(item -> Boolean.TRUE.equals(item.getHasSignature())) + .filter(FunctionSignatureService::hasUsableSignature) .collect( Collectors.toMap( item -> new TypedApiInterface.FunctionID(item.getFunctionId()), @@ -846,8 +860,11 @@ private List pullFunctionInfoFromAnalysisInternal(AnalysedProgram // Get the type information on the server side. Every type the signature refers to is // resolved by id against its analysis' decoder, so there is nothing left to fail on. + // A signature the local one outranks is treated as absent, so the function can still + // take the portal's name below. Optional functionSignatureMessageOpt = Optional.ofNullable(signatureMap.get(fID.get().functionID)) + .filter(entry -> !localSignatureOutranks(function, entry)) .map(entry -> getFunctionSignature(entry, decoderFor(decoders, signatureBatch, entry))); @@ -1210,7 +1227,7 @@ public Map getSignatures(java.u // Create a map from FunctionID to signature for easy lookup, only where the server has one. // The same neighbour can still appear more than once in the response, so keep the first. Map signatureMap = batch.items().stream() - .filter(item -> Boolean.TRUE.equals(item.getHasSignature())) + .filter(FunctionSignatureService::hasUsableSignature) .collect(Collectors.toMap( item -> new TypedApiInterface.FunctionID(item.getFunctionId()), item -> item, diff --git a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java index 7a8e681d..203cc78e 100644 --- a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java +++ b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java @@ -2,7 +2,9 @@ import ai.reveng.model.BatchFunctionSignatureEntry; import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.model.CreateAnalysisDataTypesInputBody; import ai.reveng.model.SignatureParameterEntry; +import ai.reveng.model.UpdateFunctionSignatureInputBody; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; @@ -19,11 +21,13 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /// The portal -> Ghidra half of "Sync With Portal": the signature the portal holds, and the data /// types it names, land on the matched function. @@ -57,6 +61,14 @@ private static class SignatureApi extends UnimplementedAPI { Boolean remoteHasSignature = true; /// Calls of {@link #getFunctionInfo} after which the portal stops listing the function. int functionInfoCallsBeforeRemoval = Integer.MAX_VALUE; + /// The `source_type` the portal reports for its signature. + BatchFunctionSignatureEntry.SourceTypeEnum remoteSourceType; + /// When true the portal holds only the `undefined f(void)` placeholder extraction stores for a + /// function Ghidra had no signature for. + boolean remotePlaceholder = false; + /// Every function a signature was pushed for. + final List pushedSignatures = new ArrayList<>(); + private long nextDataTypeId = 100; @Override public AnalysisStatus status(AnalysisID analysisID) { @@ -75,14 +87,24 @@ public List getFunctionInfo(AnalysisID analysisID) { @Override public FunctionSignatureBatch listFunctionSignatures(List functionIDs, boolean includeDataTypes) { - if (remoteReturnType == null) { - return FunctionSignatureBatch.empty(); - } var entry = new BatchFunctionSignatureEntry(); entry.setAnalysisId(1L); entry.setFunctionId(FUNCTION_ID); entry.setFunctionName(remoteSignatureName); entry.setHasSignature(remoteHasSignature); + if (remotePlaceholder) { + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM); + entry.setReturnDataTypeId(0L); + entry.setParameters(List.of()); + var undefined = new ServerDataType(0L, "", "undefined", ServerDataType.Kind.BASE, + 1L, "AUTO", false, null, null, null); + return new FunctionSignatureBatch(List.of(entry), + Map.of(new AnalysisID(1), List.of(undefined))); + } + if (remoteReturnType == null) { + return FunctionSignatureBatch.empty(); + } + entry.setSourceType(remoteSourceType); entry.setReturnDataTypeId(1L); var parameter = new SignatureParameterEntry(); parameter.setOrdinal(0L); @@ -100,6 +122,26 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID public void batchRenameFunctions(BatchRenameInputBody request) { // A name pushback is not what these tests are about; accept and ignore it. } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public List createAnalysisDataTypes(AnalysisID analysisID, + CreateAnalysisDataTypesInputBody request) { + return request.getDataTypes().stream() + .map(type -> new ServerDataType(nextDataTypeId++, "", "pushed", + ServerDataType.Kind.BASE, null, "USER", false, null, null, null)) + .toList(); + } + + @Override + public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID, + UpdateFunctionSignatureInputBody signature) { + pushedSignatures.add(functionID); + } } private record Fixture(GhidraRevengService service, GhidraRevengService.AnalysedProgram analysed, @@ -108,6 +150,11 @@ private record Fixture(GhidraRevengService service, GhidraRevengService.Analysed /// Attach an analysis that holds no signature yet, so the attach-time pull leaves the local /// signature alone and each test can decide what the portal gains afterwards. private Fixture attachWithoutRemoteSignature(SignatureApi api) throws Exception { + return attachWithoutRemoteSignature(api, SourceType.ANALYSIS); + } + + private Fixture attachWithoutRemoteSignature(SignatureApi api, SourceType localSignatureSource) + throws Exception { var service = new GhidraRevengService(api); var builder = newX64Program(); builder.createMemory("mem", "0x4000", 0x100); @@ -118,8 +165,8 @@ private Fixture attachWithoutRemoteSignature(SignatureApi api) throws Exception // to leave alone. A real stripped binary's signature comes from Ghidra's own analysis, and // that is the case under test: it is neither hand-written nor default, so the old // "default signatures only" guard skipped exactly these. - program.withTransaction("mark the signature analysis-derived", () -> - function.setSignatureSource(SourceType.ANALYSIS)); + program.withTransaction("set the local signature's source", () -> + function.setSignatureSource(localSignatureSource)); var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); @@ -224,6 +271,89 @@ public void leavesASignatureTheAnalystWroteAlone() throws Exception { assertEquals("char", function.getReturnType().getName()); } + /// Extraction stores `undefined f(void)` for every function Ghidra had nothing for. Applying it + /// erased real DWARF and analysis signatures on every QA binary. + @Test + public void doesNotApplyThePortalsPlaceholderSignature() throws Exception { + var api = new SignatureApi(); + api.remotePlaceholder = true; + var fixture = attachWithoutRemoteSignature(api, SourceType.IMPORTED); + + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(0, summary.appliedSignatures()); + assertEquals("the local signature survives attach and sync", + "undefined8", fixture.function().getReturnType().getName()); + } + + /// A placeholder is a stored row the signature PUT accepts, so it is exactly where the better + /// local signature can be pushed. + @Test + public void pushesTheLocalSignatureWhenThePortalOnlyHasAPlaceholder() throws Exception { + var api = new SignatureApi(); + api.remotePlaceholder = true; + var fixture = attachWithoutRemoteSignature(api, SourceType.IMPORTED); + + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(1, summary.pushedTypeSets()); + assertEquals(List.of(new FunctionID(FUNCTION_ID)), api.pushedSignatures); + } + + /// A function Ghidra knows nothing about has nothing worth pushing over the placeholder. + @Test + public void doesNotPushADefaultLocalSignatureOverAPlaceholder() throws Exception { + var api = new SignatureApi(); + api.remotePlaceholder = true; + var fixture = attachWithoutRemoteSignature(api, SourceType.DEFAULT); + + fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertTrue(api.pushedSignatures.isEmpty()); + } + + /// A signature the server extracted itself is what server-side Ghidra worked out, so it never + /// replaces one local analysis inferred or debug info supplied. + @Test + public void aSignatureTheServerExtractedDoesNotReplaceALocalAnalysisOne() throws Exception { + var api = new SignatureApi(); + api.remoteSourceType = BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM; + var fixture = attachWithoutRemoteSignature(api); + + api.remoteReturnType = "int"; + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(0, summary.appliedSignatures()); + assertEquals("undefined8", fixture.function().getReturnType().getName()); + } + + @Test + public void aSignatureTheServerExtractedStillFillsADefaultLocalOne() throws Exception { + var api = new SignatureApi(); + api.remoteSourceType = BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM; + var fixture = attachWithoutRemoteSignature(api, SourceType.DEFAULT); + + api.remoteReturnType = "int"; + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(1, summary.appliedSignatures()); + assertEquals("int", fixture.function().getReturnType().getName()); + } + + /// An edit made in the portal still beats what Ghidra inferred. + @Test + public void aSignatureEditedInThePortalReplacesALocalAnalysisOne() throws Exception { + var api = new SignatureApi(); + api.remoteSourceType = BatchFunctionSignatureEntry.SourceTypeEnum.USER; + var fixture = attachWithoutRemoteSignature(api); + + api.remoteReturnType = "int"; + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(1, summary.appliedSignatures()); + assertEquals("int", fixture.function().getReturnType().getName()); + } + @Test public void nullHasSignatureIsTreatedAsNoSignature() throws Exception { var api = new SignatureApi(); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java index 25d3db02..221ed273 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java @@ -2,6 +2,7 @@ import ai.reveng.invoker.ApiException; import ai.reveng.model.BatchFunctionSignatureEntry; +import ai.reveng.model.SignatureParameterEntry; import ai.reveng.model.UpdateFunctionSignatureInputBody; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; @@ -120,6 +121,69 @@ public void getReturnsOnlyFunctionsTheServerHasASignatureFor() { assertTrue(service.get(new FunctionID(3)).isEmpty()); } + /// What the server stores for a function Ghidra had no signature for: `undefined f(void)`. + private static BatchFunctionSignatureEntry placeholder() { + var entry = new BatchFunctionSignatureEntry(); + entry.setHasSignature(true); + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM); + entry.setParameters(List.of()); + entry.setReturnDataTypeId(0L); + return entry; + } + + @Test + public void undefinedReturnAndNoParametersFromTheServerIsAPlaceholder() { + assertTrue(FunctionSignatureService.isPlaceholder(placeholder())); + assertFalse(FunctionSignatureService.hasUsableSignature(placeholder())); + } + + @Test + public void unresolvedReturnTypeAndNoParametersIsAPlaceholder() { + var entry = placeholder(); + entry.setReturnDataTypeId(null); + assertTrue(FunctionSignatureService.isPlaceholder(entry)); + } + + /// `void f(void)` is a real signature: its return type is `void`, not `undefined` (id 0). + @Test + public void aRealReturnTypeIsNotAPlaceholder() { + var entry = placeholder(); + entry.setReturnDataTypeId(5L); + assertFalse(FunctionSignatureService.isPlaceholder(entry)); + assertTrue(FunctionSignatureService.hasUsableSignature(entry)); + } + + @Test + public void parametersMakeItARealSignature() { + var entry = placeholder(); + entry.setParameters(List.of(new SignatureParameterEntry())); + assertFalse(FunctionSignatureService.isPlaceholder(entry)); + } + + /// Once someone edits or copies a signature it is theirs, even if it reads `undefined f(void)`. + @Test + public void aSignatureSomeoneWroteIsNotAPlaceholder() { + var entry = placeholder(); + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.USER); + assertFalse(FunctionSignatureService.isPlaceholder(entry)); + } + + @Test + public void getSkipsAPlaceholder() { + var service = new FunctionSignatureService(new UnimplementedAPI() { + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, + boolean includeDataTypes) { + var entry = placeholder(); + entry.setAnalysisId(1L); + entry.setFunctionId(functionIDs.get(0).value()); + return new FunctionSignatureBatch(List.of(entry), Map.of()); + } + }); + + assertTrue(service.get(new FunctionID(1)).isEmpty()); + } + /// Accepts a signature write for one function and answers 404 for every other, which is how the /// endpoint reports a function it never extracted a signature for. private static class WritingApi extends UnimplementedAPI { From 82c139b715d8eedb5f6b720aca3aebb35507f44c Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:59:27 +0000 Subject: [PATCH 22/76] ci: don't fail the build when publishing the test report flakes dorny/test-reporter creates the check run and updates it about 0.3 s later. The update intermittently returns 404, which failed jobs whose tests had passed and needed re-runs. Failing tests already fail the Run tests step, so the report step can continue on error. --- .github/workflows/build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 91f1b817..b2ff3003 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -77,6 +77,9 @@ jobs: - name: Publish test report if: always() + # Updating the check run right after creating it intermittently 404s, which failed jobs whose + # tests had passed. Failing tests already fail "Run tests", so the report is display only. + continue-on-error: true uses: dorny/test-reporter@d61b558e8df85cb60d09ca3e5b09653b4477cea7 # v1 with: name: Tests (Ghidra ${{ matrix.ghidra }}) From 1ee24c4ab10baac0895abaf822db8f62b3627ec5 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:17:22 +0000 Subject: [PATCH 23/76] Give each TypedApiImplementation its own ApiClient TypedApiImplementation configured the SDK's process-global default client, so the setup wizard's validation instance re-targeted the running session (a typo meant 401s until restart) and every instance stacked another logging interceptor. Each instance now owns a new ApiClient, the chat service reads the running service's client, and finishing the wizard reconfigures the running service in place. ENG-4454 --- .../service/ConversationsApiChatService.java | 21 ++-- .../services/api/GhidraRevengService.java | 29 ++++- .../services/api/TypedApiImplementation.java | 15 ++- .../ghidra/plugins/AgentChatPlugin.java | 4 +- .../ghidra/plugins/ReaiAPIServicePlugin.java | 11 ++ .../services/api/AbstractStubServerTest.java | 13 --- .../services/api/ApiClientIsolationTest.java | 106 ++++++++++++++++++ .../services/api/ConversationReplayTest.java | 7 +- 8 files changed, 176 insertions(+), 30 deletions(-) create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java index 854441ea..ca247b52 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java @@ -3,7 +3,6 @@ import ai.reveng.api.ConversationsApi; import ai.reveng.invoker.ApiClient; import ai.reveng.invoker.ApiException; -import ai.reveng.invoker.Configuration; import ai.reveng.invoker.auth.ApiKeyAuth; import ai.reveng.model.ConfirmToolInputBody; import ai.reveng.model.Conversation; @@ -28,12 +27,14 @@ import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; import java.util.function.Consumer; +import java.util.function.Supplier; /** - * {@link ChatService} backed by the SDK's {@link ConversationsApi}. Short requests reuse the shared, - * already-authenticated {@link Configuration#getDefaultApiClient() default client}; the SSE stream - * uses a dedicated client cloned from it with a long read timeout, since the default 15s read timeout - * would cut a live agent run short. + * {@link ChatService} backed by the SDK's {@link ConversationsApi}. Short requests reuse the + * already-authenticated client of the running {@code GhidraRevengService}; the SSE stream uses a + * dedicated client cloned from it with a long read timeout, since the default 15s read timeout would + * cut a live agent run short. The client is looked up per call, so re-running the setup wizard + * re-targets chat along with everything else. */ public class ConversationsApiChatService implements ChatService { @@ -43,13 +44,19 @@ public class ConversationsApiChatService implements ChatService { private volatile okhttp3.Call activeStreamCall; + private final Supplier client; + + public ConversationsApiChatService(Supplier client) { + this.client = client; + } + private ConversationsApi shortCallApi() { - return new ConversationsApi(Configuration.getDefaultApiClient()); + return new ConversationsApi(client.get()); } /// A conversations client whose HTTP read timeout is long enough to hold a live SSE stream open. private ConversationsApi streamingApi() { - ApiClient shared = Configuration.getDefaultApiClient(); + ApiClient shared = client.get(); ApiClient streamClient = new ApiClient(); streamClient.setBasePath(shared.getBasePath()); streamClient.setHttpClient(shared.getHttpClient().newBuilder() diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 3726ceef..9c6ed817 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1,5 +1,6 @@ package ai.reveng.toolkit.ghidra.core.services.api; +import ai.reveng.invoker.ApiClient; import ai.reveng.invoker.ApiException; import ai.reveng.model.*; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.SelectableItem; @@ -80,8 +81,8 @@ public class GhidraRevengService { private static final String REVENG_BOOKMARK_CATEGORY = "Analysed Function"; private final Map statusCache = new HashMap<>(); - private TypedApiInterface api; - private ApiInfo apiInfo; + private volatile TypedApiInterface api; + private volatile ApiInfo apiInfo; /// Set while the plugin is applying server-sourced changes locally (pull / analysis-sync), so the /// reactive listener does not echo those changes straight back to the portal. Mirrors the IDA @@ -141,6 +142,30 @@ public URI getServer() { return this.apiInfo.hostURI(); } + /// Points the running service at new credentials, as the setup wizard does when it finishes. + /// Swapped in place rather than replaced, because every plugin holds the instance it was handed + /// as a service. Returns false when nothing changed. + public synchronized boolean reconfigure(ApiInfo newApiInfo) { + if (newApiInfo.equals(apiInfo)) { + return false; + } + this.api = new TypedApiImplementation(newApiInfo); + this.apiInfo = newApiInfo; + // Both wrap the old API, and analysis ids from the old host mean nothing on the new one. + this.signatureService = null; + this.analysisDataTypesService = null; + statusCache.clear(); + return true; + } + + /// The HTTP client behind the API, for SDK APIs that {@link TypedApiInterface} does not wrap. + public ApiClient apiClient() { + if (api instanceof TypedApiImplementation impl) { + return impl.apiClient(); + } + throw new IllegalStateException("The configured API is not backed by an HTTP client"); + } + public ProgramWithID registerAnalysisForProgram(Program program, TypedApiInterface.AnalysisID analysisID) { return addAnalysisIDtoProgramOptions(program, analysisID); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 0143687a..5d9c8239 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -24,7 +24,7 @@ import java.util.*; import java.util.stream.Collectors; -import ai.reveng.invoker.Configuration; +import ai.reveng.invoker.ApiClient; import ai.reveng.invoker.JSON; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -64,8 +64,14 @@ public class TypedApiImplementation implements TypedApiInterface { private final Map analysisBasicInfoCache = new HashMap<>(); + private final ApiClient apiClient; + + /// Every instance owns its client. The SDK's default client is process-global, so configuring it + /// here let the setup wizard's throwaway validation instance re-target the running session, and + /// stacked one more logging interceptor onto it per instance. public TypedApiImplementation(String baseUrl, String apiKey) { - var apiClient = Configuration.getDefaultApiClient(); + var apiClient = new ApiClient(); + this.apiClient = apiClient; apiClient.setBasePath(baseUrl); String pluginVersion = "unknown"; @@ -118,6 +124,11 @@ public TypedApiImplementation(ApiInfo info){ this(info.hostURI().toString(), info.apiKey()); } + /// The configured client this instance talks through, for SDK APIs it does not wrap. + public ApiClient apiClient() { + return apiClient; + } + public BinaryHash upload(Path binPath) throws FileNotFoundException, ApiException { File bin = binPath.toFile(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java index 66b3fd47..cc382900 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java @@ -40,7 +40,9 @@ public AgentChatPlugin(PluginTool tool) { protected void init() { // Required services are only resolved by now super.init(); - chatWindow = new AgentChatWindow(tool, getName(), new ConversationsApiChatService()); + var revengService = tool.getService(GhidraRevengService.class); + chatWindow = new AgentChatWindow(tool, getName(), + new ConversationsApiChatService(revengService::apiClient)); chatWindow.addToTool(); setupActions(); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java index 5a2202a2..22c8a0c5 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java @@ -215,6 +215,17 @@ protected void runSetupWizard() { SetupWizardManager setupManager = new SetupWizardManager(wizardState, getTool()); WizardManager wizardManager = new WizardManager("RevEng.AI: Configuration", true, setupManager); wizardManager.showWizard(tool.getToolFrame()); + + // The wizard is modal, so it has finished or been cancelled by now. Finishing stores the new + // credentials in the tool options; the running service has to follow them, or it keeps + // talking to the old host with the old key until Ghidra restarts. + if (revengService != null) { + getApiInfoFromToolOptions().ifPresent(apiInfo -> { + if (revengService.reconfigure(apiInfo)) { + Msg.info(this, "RevEng.AI service now uses " + apiInfo.hostURI()); + } + }); + } } } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java index efeb5a0e..261538c9 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java @@ -1,7 +1,5 @@ package ai.reveng.toolkit.ghidra.core.services.api; -import ai.reveng.invoker.ApiClient; -import ai.reveng.invoker.Configuration; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import ghidra.test.AbstractGhidraHeadlessIntegrationTest; @@ -19,17 +17,9 @@ public abstract class AbstractStubServerTest extends AbstractGhidraHeadlessIntegrationTest { protected HttpServer server; - private ApiClient originalApiClient; @Before public void startStubServer() throws Exception { - // TypedApiImplementation mutates the ApiClient that Configuration holds as a process-global - // singleton (base path, stacked interceptors). The test task forks in parallel and runs - // several classes per fork, so without this save/restore one class leaks its client into - // whichever class runs next in the same fork. - originalApiClient = Configuration.getDefaultApiClient(); - Configuration.setDefaultApiClient(new ApiClient()); - server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); configureStubs(server); server.start(); @@ -40,9 +30,6 @@ public void stopStubServer() { if (server != null) { server.stop(0); } - if (originalApiClient != null) { - Configuration.setDefaultApiClient(originalApiClient); - } } /// Registers the contexts this test serves. Called before the server is started. diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java new file mode 100644 index 00000000..5dd3bb7b --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java @@ -0,0 +1,106 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.Configuration; +import ai.reveng.toolkit.ghidra.core.services.api.types.ApiInfo; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * Every {@link TypedApiImplementation} owns its HTTP client. They used to share the SDK's + * process-global default client, so the setup wizard's throwaway validation instance re-targeted + * the running session: a mistyped key there made every later call fail with 401. + */ +public class ApiClientIsolationTest extends AbstractStubServerTest { + + private final List authorizations = new CopyOnWriteArrayList<>(); + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> { + authorizations.add(exchange.getRequestHeaders().getFirst("Authorization")); + exchange.sendResponseHeaders(401, -1); + exchange.close(); + }); + } + + private String stubUrl() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + /// Any request will do; only the credentials it carries are of interest. + private static void call(TypedApiInterface api) { + try { + api.getAnalysisBasicInfo(new TypedApiInterface.AnalysisID(1)); + } catch (Exception expected) { + // the stub answers 401 + } + } + + @Test + public void validatingOtherCredentialsDoesNotChangeTheRunningInstancesKey() { + var running = new TypedApiImplementation(stubUrl(), "real-key"); + new TypedApiImplementation("http://127.0.0.1:1", "typo-key"); + + call(running); + + assertEquals(List.of("real-key"), authorizations); + assertEquals(stubUrl(), running.apiClient().getBasePath()); + } + + @Test + public void instancesDoNotTouchTheSdksDefaultClient() { + var defaultClient = Configuration.getDefaultApiClient(); + var basePath = defaultClient.getBasePath(); + + var api = api(); + + assertNotSame(defaultClient, api.apiClient()); + assertSame(defaultClient, Configuration.getDefaultApiClient()); + assertEquals(basePath, defaultClient.getBasePath()); + } + + /// Each instance used to add one more interceptor to the shared client, so every request was + /// logged once per instance ever created. + @Test + public void eachClientLogsRequestsOnce() { + api(); + api(); + var third = api(); + + long loggers = third.apiClient().getHttpClient().interceptors().stream() + .filter(LoggingInterceptor.class::isInstance) + .count(); + assertEquals(1, loggers); + } + + @Test + public void reconfiguringTheServiceSwitchesItsCredentials() { + var service = new GhidraRevengService(new ApiInfo(stubUrl(), "http://portal.invalid", "old-key")); + var oldClient = service.apiClient(); + + assertTrue(service.reconfigure(new ApiInfo(stubUrl(), "http://portal.invalid", "new-key"))); + call(service.getApi()); + + assertEquals(List.of("new-key"), authorizations); + assertNotSame(oldClient, service.apiClient()); + } + + @Test + public void reconfiguringWithTheSameCredentialsKeepsTheClient() { + var info = new ApiInfo(stubUrl(), "http://portal.invalid", "key"); + var service = new GhidraRevengService(info); + var client = service.apiClient(); + + assertFalse(service.reconfigure(new ApiInfo(stubUrl(), "http://portal.invalid", "key"))); + assertSame(client, service.apiClient()); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java index 6fa62d81..d8fa4787 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java @@ -1,7 +1,5 @@ package ai.reveng.toolkit.ghidra.core.services.api; -import ai.reveng.invoker.ApiClient; -import ai.reveng.invoker.Configuration; import ai.reveng.toolkit.ghidra.chat.model.Conversations.ConversationReplay; import ai.reveng.toolkit.ghidra.chat.service.ChatServiceException; import ai.reveng.toolkit.ghidra.chat.service.ConversationsApiChatService; @@ -31,9 +29,8 @@ protected void configureStubs(HttpServer server) { } private ConversationReplay replay() throws ChatServiceException { - ApiClient client = Configuration.getDefaultApiClient(); - client.setBasePath("http://127.0.0.1:" + server.getAddress().getPort()); - return new ConversationsApiChatService().getConversation(UUID); + var client = api().apiClient(); + return new ConversationsApiChatService(() -> client).getConversation(UUID); } @Test From 03937b4e430409af3042c2cd98fa4e2600cba58c Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:24:29 +0000 Subject: [PATCH 24/76] Retry idempotent requests on 5xx/429 and give uploads their own client Adds a RetryInterceptor: GET/HEAD/PUT/DELETE/OPTIONS answered with a 5xx or 429 are retried up to four attempts, backing off 1s/2s/4s, or waiting as long as Retry-After asks (seconds or HTTP date) up to 30s. POST and PATCH are never retried. Uploads go through a separate client with 5 minute read/write timeouts; every other request keeps 15s. ENG-4479 --- .../core/services/api/RetryInterceptor.java | 108 ++++++++++++ .../services/api/TypedApiImplementation.java | 77 +++++--- .../services/api/ApiClientIsolationTest.java | 22 +++ .../services/api/RetryInterceptorTest.java | 164 ++++++++++++++++++ 4 files changed, 345 insertions(+), 26 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptor.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptorTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptor.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptor.java new file mode 100644 index 00000000..a08295e7 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptor.java @@ -0,0 +1,108 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import okhttp3.Interceptor; +import okhttp3.Response; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.time.Duration; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Optional; +import java.util.Set; + +/// Retries idempotent requests that the server answered with a 5xx or a 429. +/// +/// The wait doubles from {@link #baseDelay} on each attempt, unless the response carries a +/// `Retry-After`, which wins. A `Retry-After` longer than {@link #maxDelay} is not waited out: the +/// response goes back to the caller as it is, since blocking a Ghidra task for minutes is worse than +/// failing. POST and PATCH are never retried, because the first attempt may already have taken effect. +/// +/// Installed ahead of the logging interceptor, so every attempt is logged. +public class RetryInterceptor implements Interceptor { + + private static final Set IDEMPOTENT_METHODS = Set.of("GET", "HEAD", "PUT", "DELETE", "OPTIONS"); + + /// Pauses between attempts; tests replace it so they need not sleep. + @FunctionalInterface + public interface Sleeper { + void sleep(Duration duration) throws InterruptedException; + } + + private final int maxAttempts; + private final Duration baseDelay; + private final Duration maxDelay; + private final Sleeper sleeper; + + public RetryInterceptor(int maxAttempts, Duration baseDelay, Duration maxDelay, Sleeper sleeper) { + this.maxAttempts = maxAttempts; + this.baseDelay = baseDelay; + this.maxDelay = maxDelay; + this.sleeper = sleeper; + } + + /// Four attempts, waiting 1 s, 2 s and 4 s in between, and at most 30 s for a `Retry-After`. + public static RetryInterceptor standard() { + return new RetryInterceptor(4, Duration.ofSeconds(1), Duration.ofSeconds(30), + duration -> Thread.sleep(duration.toMillis())); + } + + @Override + public Response intercept(Chain chain) throws IOException { + var request = chain.request(); + var response = chain.proceed(request); + if (!IDEMPOTENT_METHODS.contains(request.method())) { + return response; + } + for (int attempt = 1; attempt < maxAttempts && isRetryable(response.code()); attempt++) { + var delay = delayBefore(attempt, response); + if (delay.isEmpty()) { + return response; + } + response.close(); + try { + sleeper.sleep(delay.get()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Interrupted while waiting to retry " + request.url()); + } + response = chain.proceed(request); + } + return response; + } + + private static boolean isRetryable(int code) { + return code == 429 || (code >= 500 && code < 600); + } + + /// How long to wait before attempt `attempt + 1`, or empty when the server asked for longer than + /// this interceptor is willing to wait. + private Optional delayBefore(int attempt, Response response) { + var retryAfter = retryAfter(response.header("Retry-After")); + if (retryAfter.isPresent()) { + return retryAfter.get().compareTo(maxDelay) <= 0 ? retryAfter : Optional.empty(); + } + var backoff = baseDelay.multipliedBy(1L << (attempt - 1)); + return Optional.of(backoff.compareTo(maxDelay) <= 0 ? backoff : maxDelay); + } + + /// `Retry-After` is either a number of seconds or an HTTP date. + static Optional retryAfter(String header) { + if (header == null || header.isBlank()) { + return Optional.empty(); + } + var value = header.trim(); + try { + return Optional.of(Duration.ofSeconds(Math.max(0, Long.parseLong(value)))); + } catch (NumberFormatException notSeconds) { + try { + var at = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME); + var wait = Duration.between(ZonedDateTime.now(at.getZone()), at); + return Optional.of(wait.isNegative() ? Duration.ZERO : wait); + } catch (DateTimeParseException notADate) { + return Optional.empty(); + } + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 5d9c8239..7eb1852a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -65,15 +65,54 @@ public class TypedApiImplementation implements TypedApiInterface { private final Map analysisBasicInfoCache = new HashMap<>(); private final ApiClient apiClient; + private final ApiClient uploadClient; + private final AnalysesCoreApi uploadApi; + + /// Ordinary requests: a page of functions or a batch of signatures, which the server answers quickly. + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(15); + + /// Uploading a large binary, and the server hashing and storing it before it answers, takes far + /// longer than any other request. + private static final Duration UPLOAD_TIMEOUT = Duration.ofMinutes(5); /// Every instance owns its client. The SDK's default client is process-global, so configuring it /// here let the setup wizard's throwaway validation instance re-target the running session, and /// stacked one more logging interceptor onto it per instance. public TypedApiImplementation(String baseUrl, String apiKey) { - var apiClient = new ApiClient(); + var userAgent = userAgent(); + var apiClient = newClient(baseUrl, apiKey, userAgent, REQUEST_TIMEOUT); this.apiClient = apiClient; - apiClient.setBasePath(baseUrl); + this.uploadClient = newClient(baseUrl, apiKey, userAgent, UPLOAD_TIMEOUT); + this.uploadApi = new AnalysesCoreApi(uploadClient); + + this.analysisCoreApi = new AnalysesCoreApi(apiClient); + this.searchApi = new SearchApi(apiClient); + this.collectionsApi = new CollectionsApi(apiClient); + this.functionsCoreApi = new FunctionsCoreApi(apiClient); + this.functionsRenamingHistoryApi = new FunctionsRenamingHistoryApi(apiClient); + this.functionsAiDecompilationApi = new FunctionsAiDecompilationApi(apiClient); + this.dataTypesApi = new DataTypesApi(apiClient); + this.configApi = new ConfigApi(apiClient); + this.iamUsersApi = new IamUsersApi(apiClient); + this.authenticationUsersApi = new AuthenticationUsersApi(apiClient); + } + + + public TypedApiImplementation(ApiInfo info){ + this(info.hostURI().toString(), info.apiKey()); + } + + /// The configured client this instance talks through, for SDK APIs it does not wrap. + public ApiClient apiClient() { + return apiClient; + } + /// The client uploads go through, with a longer timeout than {@link #apiClient()}. + ApiClient uploadClient() { + return uploadClient; + } + + private static String userAgent() { String pluginVersion = "unknown"; try { // This file comes from the release.yml running in the CI @@ -87,45 +126,31 @@ public TypedApiImplementation(String baseUrl, String apiKey) { } // Looks like: // Ghidra/11.3.2-PUBLIC (LINUX(Linux) X86_64(amd64)) RevEng.AI_Plugin/v0.15 - var userAgent = "%s/%s-%s (%s) RevEng.AI_Plugin/%s".formatted(Application.getName(), Application.getApplicationVersion(), Platform.CURRENT_PLATFORM, Application.getApplicationReleaseName(), pluginVersion); + return "%s/%s-%s (%s) RevEng.AI_Plugin/%s".formatted(Application.getName(), Application.getApplicationVersion(), Platform.CURRENT_PLATFORM, Application.getApplicationReleaseName(), pluginVersion); + } + private static ApiClient newClient(String baseUrl, String apiKey, String userAgent, Duration timeout) { + var apiClient = new ApiClient(); + apiClient.setBasePath(baseUrl); apiClient.setUserAgent(userAgent); apiClient.addDefaultHeader("X-RevEng-Application", userAgent); // Use a custom HTTP client to add Ghidra specific logging // Set withResponseBody to true if debugging issues with the API to see the full response body // Bound DNS too: the connect timeout below doesn't cover it, and offline it can hang for minutes + // Retry sits ahead of the logger so that every attempt is logged apiClient.setHttpClient(apiClient.getHttpClient().newBuilder() + .addInterceptor(RetryInterceptor.standard()) .addInterceptor(ghidraLogger(false)) .dns(new TimeoutDns(Dns.SYSTEM, Duration.ofSeconds(5))) .build()); apiClient.setConnectTimeout(5000); - apiClient.setReadTimeout(15000); - apiClient.setWriteTimeout(15000); + apiClient.setReadTimeout(Math.toIntExact(timeout.toMillis())); + apiClient.setWriteTimeout(Math.toIntExact(timeout.toMillis())); ApiKeyAuth APIKey = (ApiKeyAuth) apiClient.getAuthentication("APIKey"); APIKey.setApiKey(apiKey); - - this.analysisCoreApi = new AnalysesCoreApi(apiClient); - this.searchApi = new SearchApi(apiClient); - this.collectionsApi = new CollectionsApi(apiClient); - this.functionsCoreApi = new FunctionsCoreApi(apiClient); - this.functionsRenamingHistoryApi = new FunctionsRenamingHistoryApi(apiClient); - this.functionsAiDecompilationApi = new FunctionsAiDecompilationApi(apiClient); - this.dataTypesApi = new DataTypesApi(apiClient); - this.configApi = new ConfigApi(apiClient); - this.iamUsersApi = new IamUsersApi(apiClient); - this.authenticationUsersApi = new AuthenticationUsersApi(apiClient); - } - - - public TypedApiImplementation(ApiInfo info){ - this(info.hostURI().toString(), info.apiKey()); - } - - /// The configured client this instance talks through, for SDK APIs it does not wrap. - public ApiClient apiClient() { return apiClient; } @@ -135,7 +160,7 @@ public BinaryHash upload(Path binPath) throws FileNotFoundException, ApiExceptio if (!bin.exists()) throw new FileNotFoundException("Binary to upload does not exist"); - var result = this.analysisCoreApi.uploadFile(UploadFileType.fromValue("BINARY"), bin, null, true); + var result = this.uploadApi.uploadFile(UploadFileType.fromValue("BINARY"), bin, null, true); if (result.getData() == null) { throw new ApiException("Upload response carried no data"); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java index 5dd3bb7b..b4521cf0 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java @@ -82,6 +82,28 @@ public void eachClientLogsRequestsOnce() { assertEquals(1, loggers); } + /// Uploads used to share the 15 s limit of every other request. + @Test + public void uploadsGetALongerTimeoutThanOtherRequests() { + var api = api(); + + assertEquals(15_000, api.apiClient().getHttpClient().readTimeoutMillis()); + assertEquals(300_000, api.uploadClient().getHttpClient().readTimeoutMillis()); + assertEquals(300_000, api.uploadClient().getHttpClient().writeTimeoutMillis()); + assertEquals(stubUrl(), api.uploadClient().getBasePath()); + } + + @Test + public void bothClientsRetry() { + var api = api(); + + for (var client : List.of(api.apiClient(), api.uploadClient())) { + assertEquals(1, client.getHttpClient().interceptors().stream() + .filter(RetryInterceptor.class::isInstance) + .count()); + } + } + @Test public void reconfiguringTheServiceSwitchesItsCredentials() { var service = new GhidraRevengService(new ApiInfo(stubUrl(), "http://portal.invalid", "old-key")); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptorTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptorTest.java new file mode 100644 index 00000000..00cf045f --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptorTest.java @@ -0,0 +1,164 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import com.sun.net.httpserver.HttpServer; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.time.Duration; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/// Exercised through a real {@link OkHttpClient} against a loopback server, with the waits recorded +/// instead of slept. +public class RetryInterceptorTest { + + /// One canned answer: a status code and, optionally, a `Retry-After`. + private record Answer(int code, String retryAfter) { + static Answer of(int code) { + return new Answer(code, null); + } + } + + private HttpServer server; + private final ConcurrentLinkedQueue answers = new ConcurrentLinkedQueue<>(); + private final List methods = new ArrayList<>(); + private final List sleeps = new ArrayList<>(); + private OkHttpClient client; + + @Before + public void start() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + synchronized (methods) { + methods.add(exchange.getRequestMethod()); + } + var answer = answers.isEmpty() ? Answer.of(200) : answers.poll(); + if (answer.retryAfter() != null) { + exchange.getResponseHeaders().add("Retry-After", answer.retryAfter()); + } + exchange.getRequestBody().readAllBytes(); + exchange.sendResponseHeaders(answer.code(), -1); + exchange.close(); + }); + server.start(); + client = new OkHttpClient.Builder() + .addInterceptor(new RetryInterceptor(4, Duration.ofSeconds(1), Duration.ofSeconds(30), sleeps::add)) + .build(); + } + + @After + public void stop() { + server.stop(0); + } + + private int send(String method) throws IOException { + var body = method.equals("GET") ? null : RequestBody.create("{}", MediaType.get("application/json")); + var request = new Request.Builder() + .url("http://127.0.0.1:" + server.getAddress().getPort() + "/v2/anything") + .method(method, body) + .build(); + try (var response = client.newCall(request).execute()) { + return response.code(); + } + } + + private void answer(Answer... canned) { + answers.addAll(List.of(canned)); + } + + @Test + public void retriesAServerErrorAndReturnsTheEventualSuccess() throws IOException { + answer(Answer.of(503)); + + assertEquals(200, send("GET")); + assertEquals(2, methods.size()); + assertEquals(List.of(Duration.ofSeconds(1)), sleeps); + } + + @Test + public void backsOffExponentiallyAndGivesUpAfterTheLastAttempt() throws IOException { + answer(Answer.of(500), Answer.of(502), Answer.of(503), Answer.of(504)); + + assertEquals("the last answer reaches the caller", 504, send("GET")); + assertEquals(4, methods.size()); + assertEquals(List.of(Duration.ofSeconds(1), Duration.ofSeconds(2), Duration.ofSeconds(4)), sleeps); + } + + @Test + public void waitsAsLongAsRetryAfterAsks() throws IOException { + answer(new Answer(429, "3")); + + assertEquals(200, send("GET")); + assertEquals(List.of(Duration.ofSeconds(3)), sleeps); + } + + /// Blocking a Ghidra task for minutes is worse than reporting the rate limit. + @Test + public void doesNotWaitOutARetryAfterBeyondTheCap() throws IOException { + answer(new Answer(429, "120")); + + assertEquals(429, send("GET")); + assertEquals(1, methods.size()); + assertTrue(sleeps.isEmpty()); + } + + /// The first attempt may already have taken effect. + @Test + public void neverRetriesPostOrPatch() throws IOException { + answer(Answer.of(503), Answer.of(503)); + + assertEquals(503, send("POST")); + assertEquals(503, send("PATCH")); + assertEquals(List.of("POST", "PATCH"), methods); + assertTrue(sleeps.isEmpty()); + } + + @Test + public void retriesPutAndDelete() throws IOException { + answer(Answer.of(503)); + assertEquals(200, send("PUT")); + answer(Answer.of(503)); + assertEquals(200, send("DELETE")); + assertEquals(List.of("PUT", "PUT", "DELETE", "DELETE"), methods); + } + + @Test + public void leavesClientErrorsAlone() throws IOException { + for (int code : new int[] {400, 401, 404, 422}) { + answer(Answer.of(code)); + assertEquals(code, send("GET")); + } + assertEquals(4, methods.size()); + assertTrue(sleeps.isEmpty()); + } + + @Test + public void readsRetryAfterAsSecondsOrAnHttpDate() { + assertEquals(Duration.ofSeconds(7), RetryInterceptor.retryAfter("7").orElseThrow()); + assertTrue(RetryInterceptor.retryAfter("soon").isEmpty()); + assertTrue(RetryInterceptor.retryAfter(null).isEmpty()); + + var inTenSeconds = ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(10) + .format(DateTimeFormatter.RFC_1123_DATE_TIME); + var wait = RetryInterceptor.retryAfter(inTenSeconds).orElseThrow(); + assertTrue(wait + " should be about ten seconds", + wait.compareTo(Duration.ofSeconds(8)) >= 0 && wait.compareTo(Duration.ofSeconds(10)) <= 0); + + var past = ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(1).format(DateTimeFormatter.RFC_1123_DATE_TIME); + assertEquals(Duration.ZERO, RetryInterceptor.retryAfter(past).orElseThrow()); + } +} From 897ba7f986727be364d459a4e43d39452b3fe08f Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:06:59 +0000 Subject: [PATCH 25/76] Key debounced local-edit pushes by program as well as address/type path --- .../services/sync/LocalEditSyncService.java | 23 ++-- .../LocalEditSyncAcrossProgramsTest.java | 110 ++++++++++++++++++ 2 files changed, 125 insertions(+), 8 deletions(-) create mode 100644 src/test/java/ai/reveng/LocalEditSyncAcrossProgramsTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index 1f19e354..a4ca311e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -47,9 +47,14 @@ public class LocalEditSyncService { private final ReaiLoggingService loggingService; private final ScheduledExecutorService scheduler; private final Map listeners = new ConcurrentHashMap<>(); - private final Map> pendingRenames = new ConcurrentHashMap<>(); - private final Map> pendingTypes = new ConcurrentHashMap<>(); - private final Map> pendingDataTypeScans = new ConcurrentHashMap<>(); + private final Map, ScheduledFuture> pendingRenames = new ConcurrentHashMap<>(); + private final Map, ScheduledFuture> pendingTypes = new ConcurrentHashMap<>(); + private final Map, ScheduledFuture> pendingDataTypeScans = new ConcurrentHashMap<>(); + + /// A debounce key. One service handles every open program, and two programs can have functions at + /// the same address (two versions of one binary, or any two PEs with code at `0x140001000`), so an + /// address or type path alone would let an edit in one program cancel the other's pending push. + private record InProgram(Program program, K key) {} public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService) { this.revengService = revengService; @@ -165,7 +170,7 @@ private void onDataTypeChanged(Program program, DomainObjectChangeRecord record) dataType = previous; } if (dataType != null) { - scheduleDataTypeScan(program, dataType.getName()); + scheduleDataTypeScan(program, dataType); } } @@ -174,15 +179,17 @@ private static boolean isSyncable(Function function) { } private void scheduleRename(Program program, Address entryPoint) { - schedule(pendingRenames, entryPoint, () -> pushRename(program, entryPoint)); + schedule(pendingRenames, new InProgram<>(program, entryPoint), () -> pushRename(program, entryPoint)); } private void scheduleTypes(Program program, Address entryPoint) { - schedule(pendingTypes, entryPoint, () -> pushTypes(program, entryPoint)); + schedule(pendingTypes, new InProgram<>(program, entryPoint), () -> pushTypes(program, entryPoint)); } - private void scheduleDataTypeScan(Program program, String typeName) { - schedule(pendingDataTypeScans, typeName, () -> pushFunctionsReferencingType(program, typeName)); + private void scheduleDataTypeScan(Program program, DataType dataType) { + var typeName = dataType.getName(); + schedule(pendingDataTypeScans, new InProgram<>(program, dataType.getPathName()), + () -> pushFunctionsReferencingType(program, typeName)); } private void schedule(Map> pending, K key, Runnable task) { diff --git a/src/test/java/ai/reveng/LocalEditSyncAcrossProgramsTest.java b/src/test/java/ai/reveng/LocalEditSyncAcrossProgramsTest.java new file mode 100644 index 00000000..6848dc05 --- /dev/null +++ b/src/test/java/ai/reveng/LocalEditSyncAcrossProgramsTest.java @@ -0,0 +1,110 @@ +package ai.reveng; + +import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.Assert.assertEquals; + +/// One {@link LocalEditSyncService} serves every open program, so its debounce must not let an edit in +/// one program cancel a pending push for another program that happens to have a function at the same +/// address. +public class LocalEditSyncAcrossProgramsTest extends RevEngMockableHeadedIntegrationTest { + + private static final long ENTRY = 0x4000L; + + /// Each analysis holds one function at {@link #ENTRY}, with the analysis id as its function id. + private static class RecordingApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + var id = new FunctionID(analysisID.id()); + return List.of(new FunctionInfo(id, "FUN_00004000", "FUN_00004000", ENTRY, 0x100)); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public void batchRenameFunctions(BatchRenameInputBody request) { + for (var item : request.getFunctions()) { + renamed.put(item.getFunctionId(), item.getNewName()); + } + } + } + + private LocalEditSyncService sync; + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + private Function analysedFunction(GhidraRevengService service, String name, long analysisId) throws Exception { + var builder = newX64Program(name); + builder.createMemory("code", "0x4000", 0x200); + Function function = builder.createEmptyFunction("FUN_00004000", "0x4000", 0x100, new IntegerDataType()); + var program = builder.getProgram(); + var withId = service.registerAnalysisForProgram(program, new AnalysisID((int) analysisId)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + return function; + } + + private static void rename(Function function, String newName) throws Exception { + Program program = function.getProgram(); + int tx = program.startTransaction("rename"); + try { + function.setName(newName, SourceType.USER_DEFINED); + } finally { + program.endTransaction(tx, true); + } + program.flushEvents(); + } + + @Test + public void editsAtTheSameAddressInTwoProgramsAreBothPushed() throws Exception { + var api = new RecordingApi(); + var service = new GhidraRevengService(api); + Function inA = analysedFunction(service, "a", 1); + Function inB = analysedFunction(service, "b", 2); + + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class)); + sync.attach(inA.getProgram()); + sync.attach(inB.getProgram()); + + // Both inside one debounce window, which is where the second used to cancel the first. + rename(inA, "renamed_in_a"); + rename(inB, "renamed_in_b"); + + waitForCondition(() -> api.renamed.size() == 2, "both renames should be pushed"); + assertEquals(Map.of(1L, "renamed_in_a", 2L, "renamed_in_b"), api.renamed); + } +} From 754cbd35931ddb994ed4ae510cd75aca4fc29b52 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:56:50 +0000 Subject: [PATCH 26/76] Suppress pushback per program and only around the sync's own writes Pushback suppression was one service-wide flag held for the whole of a sync or pull, network calls included, so every edit made meanwhile in any open program was dropped. Because Ghidra delivers change events later from a timer, the sync's own last events could also arrive after the flag was cleared and be pushed back. Suppression is now per program and spans only each write transaction. Events are flushed before the transaction opens and again before suppression ends, so the analyst's edits and the sync's own are told apart. Renames are never suppressed: the plugin only writes ANALYSIS names and only USER_DEFINED ones are pushed. --- .../services/api/GhidraRevengService.java | 89 ++++--- .../services/sync/LocalEditSyncService.java | 22 +- .../ai/reveng/LocalEditsDuringSyncTest.java | 237 ++++++++++++++++++ 3 files changed, 305 insertions(+), 43 deletions(-) create mode 100644 src/test/java/ai/reveng/LocalEditsDuringSyncTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 9c6ed817..1b443f1f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -51,7 +51,7 @@ import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -84,10 +84,10 @@ public class GhidraRevengService { private volatile TypedApiInterface api; private volatile ApiInfo apiInfo; - /// Set while the plugin is applying server-sourced changes locally (pull / analysis-sync), so the - /// reactive listener does not echo those changes straight back to the portal. Mirrors the IDA - /// plugin's {@code analysis_sync_service.is_worker_running()} guard. - private final AtomicBoolean pushbackSuppressed = new AtomicBoolean(false); + /// The programs the plugin is writing server-sourced changes into right now, each with how many + /// such writes overlap, so the reactive listener does not echo those changes straight back to the + /// portal. See {@link #startServerTransaction}. + private final Map applyingServerChanges = new ConcurrentHashMap<>(); /// dedicated functions on the GhidraRevengService should be used instead to enforce assumptions via /// type level guarantees @@ -429,15 +429,6 @@ private record InvalidRemoteName(Function function, TypedApiInterface.FunctionID /// for matched functions whose remote types are absent or could not be applied. Mirrors the IDA /// plugin's {@code analysis_sync.py}. public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) throws ApiException { - pushbackSuppressed.set(true); - try { - return syncAnalysisUpdatesInternal(analysedProgram, monitor, log); - } finally { - pushbackSuppressed.set(false); - } - } - - private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) throws ApiException { var program = analysedProgram.program(); log.info("Starting bidirectional sync with the RevEng.AI portal"); Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() @@ -451,7 +442,7 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, int deduped = 0; int canonicalizedNames = 0; - var transactionId = program.startTransaction("RevEng.AI: Sync Analysis Updates"); + var transactionId = startServerTransaction(program, "RevEng.AI: Sync Analysis Updates"); boolean commit = false; try { // Creating the RevEng.AI namespace is a DB write, so it must happen inside the transaction. @@ -526,7 +517,7 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, commit = !namePushbacks.isEmpty() || namesModifiedRemotely > 0; canonicalizedNames = canonicalized; } finally { - program.endTransaction(transactionId, commit && !monitor.isCancelled()); + endServerTransaction(program, transactionId, commit && !monitor.isCancelled()); } // Push back over the network only after the local transaction has closed, so we don't hold a @@ -551,7 +542,7 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, /// Apply the signatures — and with them the data types they name — that the portal holds for this /// analysis' functions, and answer with how many landed. /// - /// Names are deliberately left alone. {@link #syncAnalysisUpdatesInternal} owns that decision, + /// Names are deliberately left alone. {@link #syncAnalysisUpdates} owns that decision, /// including canonicalising names Ghidra rejects and de-duplicating the ones it has already /// applied this run, so the command is given {@link FunctionRenameOption#NO_CHANGE} and nothing /// here competes with it. @@ -571,7 +562,7 @@ private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor m Map decoders = new HashMap<>(); var program = analysedProgram.program(); int applied = 0; - var transactionId = program.startTransaction("RevEng.AI: Apply Portal Signatures"); + var transactionId = startServerTransaction(program, "RevEng.AI: Apply Portal Signatures"); try { for (BatchFunctionSignatureEntry entry : batch.items()) { if (monitor.isCancelled()) { @@ -608,7 +599,7 @@ private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor m } } } finally { - program.endTransaction(transactionId, applied > 0 && !monitor.isCancelled()); + endServerTransaction(program, transactionId, applied > 0 && !monitor.isCancelled()); } return applied; } @@ -759,6 +750,47 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, } } + /// Start a transaction that writes server-sourced changes into `program`, during which the reactive + /// listener ignores that program's type and variable events. Close it with + /// {@link #endServerTransaction}. + /// + /// The window is this one write, not the whole sync: a sync spends most of its time on network + /// calls, and suppressing for all of it dropped every edit the analyst made meanwhile, in every + /// open program. Ghidra delivers change events later, from a timer, so the window is bounded by + /// flushing them: once before, so edits made up to now are delivered as the analyst's, and once + /// after, so this write's own events are delivered while they are still recognisably ours. + /// Function and variable renames are never suppressed — see + /// {@link ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService}. + private int startServerTransaction(Program program, String description) { + program.flushEvents(); + applyingServerChanges.merge(program, 1, Integer::sum); + try { + return program.startTransaction(description); + } catch (RuntimeException e) { + releaseServerChanges(program); + throw e; + } + } + + private void endServerTransaction(Program program, int transactionId, boolean commit) { + try { + program.endTransaction(transactionId, commit); + program.flushEvents(); + } finally { + releaseServerChanges(program); + } + } + + private void releaseServerChanges(Program program) { + applyingServerChanges.computeIfPresent(program, (p, writes) -> writes > 1 ? writes - 1 : null); + } + + /// True while the plugin is writing server-sourced changes into `program`; the reactive listener + /// uses this to avoid pushing those changes back to the portal. + public boolean isApplyingServerChanges(Program program) { + return applyingServerChanges.containsKey(program); + } + private boolean applyRemoteName(Program program, Function function, Namespace revEngNamespace, String name) { try { function.setParentNamespace(revEngNamespace); @@ -800,22 +832,7 @@ static boolean isInvalidGhidraName(String name) { /// The initial association happens in {@link #associateFunctionInfo(ProgramWithID)} /// public List pullFunctionInfoFromAnalysis(AnalysedProgram analysedProgram, TaskMonitor monitor) { - pushbackSuppressed.set(true); - try { - return pullFunctionInfoFromAnalysisInternal(analysedProgram, monitor); - } finally { - pushbackSuppressed.set(false); - } - } - - /// True while the plugin is applying server-sourced changes locally; the reactive listener uses - /// this to avoid pushing those changes back to the portal. - public boolean isPushbackSuppressed() { - return pushbackSuppressed.get(); - } - - private List pullFunctionInfoFromAnalysisInternal(AnalysedProgram analysedProgram, TaskMonitor monitor) { - var transactionId = analysedProgram.program().startTransaction("RevEng.AI: Pull Function Info from Analysis"); + var transactionId = startServerTransaction(analysedProgram.program(), "RevEng.AI: Pull Function Info from Analysis"); List renameResults = new ArrayList<>(); @@ -954,7 +971,7 @@ private List pullFunctionInfoFromAnalysisInternal(AnalysedProgram } } finally { // Done iterating over all functions. If nothing changed, discard the transaction, to keep undo history clean - analysedProgram.program().endTransaction(transactionId, !renameResults.isEmpty() && !monitor.isCancelled()); + endServerTransaction(analysedProgram.program(), transactionId, !renameResults.isEmpty() && !monitor.isCancelled()); } if (failedRenames > 0){ Msg.showError(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function Update Summary", diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index a4ca311e..3b344367 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -34,9 +34,11 @@ * pushes that change back to the portal in the background. * *

Mirrors the IDA plugin's {@code hooks/reactive.py} + {@code hooks/artifacts.py}: edits are - * coalesced per function (debounced) and pushes are suppressed while the plugin is applying - * server-sourced changes locally (see {@link GhidraRevengService#isPushbackSuppressed()}), so - * sync-applied changes are not echoed straight back. + * coalesced per function (debounced), and type edits are ignored while the plugin is writing + * server-sourced changes into that program (see {@link GhidraRevengService#isApplyingServerChanges}), + * so sync-applied changes are not echoed straight back. Renames need no such guard: the plugin only + * ever writes {@link SourceType#ANALYSIS} names, and only {@link SourceType#USER_DEFINED} ones are + * pushed, so an analyst's rename is pushed even when it lands in the middle of a sync. */ public class LocalEditSyncService { @@ -91,7 +93,6 @@ public void dispose() { private DomainObjectListener buildListener(Program program) { return new DomainObjectListenerBuilder(this) - .ignoreWhen(revengService::isPushbackSuppressed) .each(ProgramEvent.SYMBOL_RENAMED).call(record -> onSymbolRenamed(program, record)) // Renaming a decompiler-inferred variable commits it to the database as a new symbol, // which fires SYMBOL_ADDED rather than SYMBOL_RENAMED, so we react to both. @@ -121,6 +122,10 @@ private void onSymbolRenamed(Program program, DomainObjectChangeRecord record) { } private void onVariableSymbolChanged(Program program, DomainObjectChangeRecord record) { + // Applying a portal signature adds parameter symbols. + if (revengService.isApplyingServerChanges(program)) { + return; + } var symbol = symbolOf(record); if (symbol != null) { scheduleTypesForVariable(program, symbol); @@ -150,12 +155,11 @@ private void onFunctionChanged(Program program, DomainObjectChangeRecord record) return; } var function = functionChange.getFunction(); - if (!isSyncable(function)) { + if (!isSyncable(function) || revengService.isApplyingServerChanges(program)) { return; } // Modifier-only changes (inline/no-return/thunk/...) carry no type information to sync. - // Everything else (return type, parameters, variable types) is pushed; sync-applied changes - // are already excluded by the ignoreWhen(isPushbackSuppressed) guard on the listener. + // Everything else (return type, parameters, variable types) is pushed. if (functionChange.isFunctionModifierChange()) { return; } @@ -163,6 +167,10 @@ private void onFunctionChanged(Program program, DomainObjectChangeRecord record) } private void onDataTypeChanged(Program program, DomainObjectChangeRecord record) { + // Applying a portal signature updates the data types it names in place. + if (revengService.isApplyingServerChanges(program)) { + return; + } DataType dataType = null; if (record.getNewValue() instanceof DataType changed) { dataType = changed; diff --git a/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java new file mode 100644 index 00000000..cd0094a3 --- /dev/null +++ b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java @@ -0,0 +1,237 @@ +package ai.reveng; + +import ai.reveng.model.BatchFunctionSignatureEntry; +import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.model.CreateAnalysisDataTypesInputBody; +import ai.reveng.model.UpdateFunctionSignatureInputBody; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ghidra.program.model.data.LongDataType; +import ghidra.program.model.data.Undefined; +import ghidra.program.model.listing.Function; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/// Edits the analyst makes while a sync is running are pushed; only the changes the sync itself +/// writes are kept from going back up. +public class LocalEditsDuringSyncTest extends RevEngMockableHeadedIntegrationTest { + + private static final ReaiLoggingService NOOP_LOG = new ReaiLoggingService() { + @Override public void info(String message) {} + @Override public void warn(String message) {} + @Override public void error(String message) {} + }; + + /// Each analysis holds one function at 0x4000, with the analysis id as its function id. + private static class RecordingApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + final List pushedSignatures = new CopyOnWriteArrayList<>(); + final Map remoteNames = new ConcurrentHashMap<>(); + /// The portal's return type for every function, or null when it holds no signatures. + volatile String remoteReturnType; + /// When set, the next sync of analysis 1 waits for it while reading the portal's names. + volatile CountDownLatch holdSyncOfAnalysis1; + final CountDownLatch syncWaiting = new CountDownLatch(1); + private long nextDataTypeId = 100; + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + var hold = holdSyncOfAnalysis1; + if (hold != null && analysisID.id() == 1) { + syncWaiting.countDown(); + try { + hold.await(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + var name = remoteNames.getOrDefault(analysisID.id(), "FUN_00004000"); + return List.of(new FunctionInfo(new FunctionID(analysisID.id()), name, name, 0x4000L, 0x100)); + } + + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, boolean includeDataTypes) { + if (remoteReturnType == null) { + return FunctionSignatureBatch.empty(); + } + var entries = functionIDs.stream().map(id -> { + var entry = new BatchFunctionSignatureEntry(); + entry.setAnalysisId(id.value()); + entry.setFunctionId(id.value()); + entry.setFunctionName("FUN_00004000"); + entry.setHasSignature(true); + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.USER); + entry.setReturnDataTypeId(1L); + entry.setParameters(List.of()); + return entry; + }).toList(); + var returnType = new ServerDataType(1L, "", remoteReturnType, ServerDataType.Kind.BASE, + 4L, "AUTO", false, null, null, null); + Map> types = new ConcurrentHashMap<>(); + functionIDs.forEach(id -> types.put(new AnalysisID((int) id.value()), List.of(returnType))); + return new FunctionSignatureBatch(entries, types); + } + + @Override + public void batchRenameFunctions(BatchRenameInputBody request) { + for (var item : request.getFunctions()) { + renamed.put(item.getFunctionId(), item.getNewName()); + } + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public synchronized List createAnalysisDataTypes(AnalysisID analysisID, + CreateAnalysisDataTypesInputBody request) { + return request.getDataTypes().stream() + .map(type -> new ServerDataType(nextDataTypeId++, "", "pushed", + ServerDataType.Kind.BASE, null, "USER", false, null, null, null)) + .toList(); + } + + @Override + public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID, + UpdateFunctionSignatureInputBody signature) { + pushedSignatures.add(functionID); + } + } + + private final RecordingApi api = new RecordingApi(); + private final GhidraRevengService service = new GhidraRevengService(api); + private LocalEditSyncService sync; + + @After + public void tearDown() { + var hold = api.holdSyncOfAnalysis1; + if (hold != null) { + hold.countDown(); + } + if (sync != null) { + sync.dispose(); + } + } + + /// A function whose signature came from Ghidra's analysis, as on a real binary; ProgramBuilder + /// would otherwise stamp it user-defined, which a pull leaves alone. + private Function analysedFunction(String name, int analysisId) throws Exception { + var builder = newX64Program(name); + builder.createMemory("code", "0x4000", 0x200); + Function function = builder.createEmptyFunction( + "FUN_00004000", "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + program.withTransaction("analysis signature", () -> function.setSignatureSource(SourceType.ANALYSIS)); + var withId = service.registerAnalysisForProgram(program, new AnalysisID(analysisId)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + return function; + } + + private void listenTo(Function... functions) { + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class)); + for (Function function : functions) { + sync.attach(function.getProgram()); + } + } + + private static void edit(Function function, String description, Runnable change) { + var program = function.getProgram(); + program.withTransaction(description, change::run); + program.flushEvents(); + } + + private GhidraRevengService.SyncSummary syncWithPortal(Function function) throws Exception { + return service.syncAnalysisUpdates( + service.getAnalysedProgram(function.getProgram()).orElseThrow(), TaskMonitor.DUMMY, NOOP_LOG); + } + + @Test + public void editsMadeWhileASyncWaitsOnThePortalArePushed() throws Exception { + Function inA = analysedFunction("a", 1); + Function inB = analysedFunction("b", 2); + listenTo(inA, inB); + + var hold = new CountDownLatch(1); + api.holdSyncOfAnalysis1 = hold; + Thread syncing = new Thread(() -> { + try { + syncWithPortal(inA); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + syncing.start(); + assertTrue("the sync should be waiting on the portal", api.syncWaiting.await(30, TimeUnit.SECONDS)); + + // In the program being synced, and in another one. + edit(inA, "rename", () -> rethrow(() -> inA.setName("mine_a", SourceType.USER_DEFINED))); + edit(inB, "rename", () -> rethrow(() -> inB.setName("mine_b", SourceType.USER_DEFINED))); + edit(inB, "retype", () -> rethrow(() -> inB.setReturnType(new LongDataType(), SourceType.USER_DEFINED))); + + waitForCondition(() -> api.renamed.size() == 2 && !api.pushedSignatures.isEmpty(), + "edits made during the sync should be pushed while it is still running"); + assertEquals(Map.of(1L, "mine_a", 2L, "mine_b"), api.renamed); + assertEquals(List.of(new FunctionID(2)), api.pushedSignatures); + + hold.countDown(); + syncing.join(30_000); + assertEquals("the sync keeps the analyst's name", "mine_a", inA.getName()); + } + + @Test + public void whatTheSyncAppliesIsNotPushedBack() throws Exception { + Function function = analysedFunction("a", 1); + listenTo(function); + api.remoteNames.put(1, "theirs"); + api.remoteReturnType = "int"; + + var summary = syncWithPortal(function); + assertEquals("theirs", function.getName()); + assertEquals(1, summary.appliedSignatures()); + assertEquals("int", function.getReturnType().getName()); + + // Past the debounce, so anything the sync's own events had scheduled would have gone up. + Thread.sleep(1_000); + assertTrue("renames pushed: " + api.renamed, api.renamed.isEmpty()); + assertTrue("signatures pushed: " + api.pushedSignatures, api.pushedSignatures.isEmpty()); + } + + private interface Edit { + void run() throws Exception; + } + + private static void rethrow(Edit edit) { + try { + edit.run(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} From d71198c6edabe944c87bbe4963822cd758a03246 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:23:43 +0000 Subject: [PATCH 27/76] Batch local renames per program, skip local-variable edits, re-tag re-created functions Renames are debounced per program and sent as one batch request instead of one request per function. Only parameter symbols and return-type/parameter function changes schedule a signature push, since local variables never reach the portal's signature. A function deleted and created again at a mapped address gets its REVENGAI_SYNCED tag back. --- .../services/api/GhidraRevengService.java | 53 +++-- .../services/sync/LocalEditSyncService.java | 83 ++++++-- .../ai/reveng/LocalEditSyncScopeTest.java | 199 ++++++++++++++++++ 3 files changed, 303 insertions(+), 32 deletions(-) create mode 100644 src/test/java/ai/reveng/LocalEditSyncScopeTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 1b443f1f..331dcb1e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -304,6 +304,22 @@ private AnalysedProgram associateFunctionInfo(ProgramWithID knownProgram) { } + /// Put the synced tag back on a function at an address the analysis still maps to a server + /// function, as after the function was deleted and created again. Does nothing otherwise. + public void restoreSyncedTag(Function function) { + var program = function.getProgram(); + var analysedProgram = getAnalysedProgram(program); + if (analysedProgram.isEmpty() || analysedProgram.get().getIDForFunction(function).isEmpty()) { + return; + } + boolean tagged = function.getTags().stream() + .anyMatch(tag -> REVENGAI_FUNCTION_TAG.equals(tag.getName())); + if (!tagged) { + program.withTransaction("RevEng.AI: Tag re-created function", + () -> function.addTag(REVENGAI_FUNCTION_TAG)); + } + } + private void markFunctionAsRevEng(BookmarkManager bookmarkManager, Function function, FunctionInfo info) { function.addTag(REVENGAI_FUNCTION_TAG); bookmarkManager.setBookmark(function.getEntryPoint(), REVENG_BOOKMARK_TYPE, REVENG_BOOKMARK_CATEGORY, @@ -314,22 +330,33 @@ private void markFunctionAsRevEng(BookmarkManager bookmarkManager, Function func public record RenameResult(Function func, String originalName, String newName) { } - /// Push a local function rename back to the portal. Returns the namespace-qualified name that was - /// pushed, or empty if the function is not known on the server. - public Optional pushFunctionRename(AnalysedProgram analysedProgram, Function function) throws ApiException { - var withId = analysedProgram.getIDForFunction(function); - if (withId.isEmpty()) { - return Optional.empty(); + /// Push local function renames back to the portal in one request. Answers with the + /// namespace-qualified name pushed for each function; functions not known on the server are left + /// out, and when none is known nothing is sent. + public Map pushFunctionRenames(AnalysedProgram analysedProgram, Collection functions) + throws ApiException { + Map pushed = new LinkedHashMap<>(); + List items = new ArrayList<>(); + for (Function function : functions) { + var withId = analysedProgram.getIDForFunction(function); + if (withId.isEmpty()) { + continue; + } + String qualifiedName = qualifiedServerName(function); + var item = new BatchRenameItem(); + item.setFunctionId(withId.get().functionID().value()); + item.setNewName(qualifiedName); + item.setNewMangledName(qualifiedName); + items.add(item); + pushed.put(function, qualifiedName); + } + if (items.isEmpty()) { + return pushed; } - String qualifiedName = qualifiedServerName(function); - var item = new BatchRenameItem(); - item.setFunctionId(withId.get().functionID().value()); - item.setNewName(qualifiedName); - item.setNewMangledName(qualifiedName); var request = new BatchRenameInputBody(); - request.setFunctions(List.of(item)); + request.setFunctions(items); api.batchRenameFunctions(request); - return Optional.of(qualifiedName); + return pushed; } /// The function name as the portal expects it: qualified with its namespace path (joined by diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index 3b344367..088ddfff 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -20,7 +20,12 @@ import ghidra.program.util.ProgramEvent; import ghidra.util.Msg; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -30,11 +35,14 @@ /** * Reactive push-back of local edits to the portal (PLU-322). Registers a {@link DomainObjectListener} - * on analysed programs and, when the user renames a function or edits its signature / variables, - * pushes that change back to the portal in the background. + * on analysed programs and, when the user renames a function or edits its signature (return type, + * parameters, calling convention, or a data type those use), pushes that change back to the portal + * in the background. Local variables are not pushed: the portal's signature holds only the + * parameters and return type, so an edit to a local has nothing to send. * *

Mirrors the IDA plugin's {@code hooks/reactive.py} + {@code hooks/artifacts.py}: edits are - * coalesced per function (debounced), and type edits are ignored while the plugin is writing + * debounced, renames per program and sent as one batch (a script renaming hundreds of functions makes + * one request, not hundreds), signature edits per function. Type edits are ignored while the plugin is writing * server-sourced changes into that program (see {@link GhidraRevengService#isApplyingServerChanges}), * so sync-applied changes are not echoed straight back. Renames need no such guard: the plugin only * ever writes {@link SourceType#ANALYSIS} names, and only {@link SourceType#USER_DEFINED} ones are @@ -49,7 +57,9 @@ public class LocalEditSyncService { private final ReaiLoggingService loggingService; private final ScheduledExecutorService scheduler; private final Map listeners = new ConcurrentHashMap<>(); - private final Map, ScheduledFuture> pendingRenames = new ConcurrentHashMap<>(); + private final Map> pendingRenames = new ConcurrentHashMap<>(); + /// The functions renamed in each program since its last rename push. Guarded by itself. + private final Map> dueRenames = new HashMap<>(); private final Map, ScheduledFuture> pendingTypes = new ConcurrentHashMap<>(); private final Map, ScheduledFuture> pendingDataTypeScans = new ConcurrentHashMap<>(); @@ -98,6 +108,7 @@ private DomainObjectListener buildListener(Program program) { // which fires SYMBOL_ADDED rather than SYMBOL_RENAMED, so we react to both. .each(ProgramEvent.SYMBOL_ADDED).call(record -> onVariableSymbolChanged(program, record)) .each(ProgramEvent.FUNCTION_CHANGED).call(record -> onFunctionChanged(program, record)) + .each(ProgramEvent.FUNCTION_ADDED).call(record -> onFunctionAdded(program, record)) // Editing a data type definition (rename a struct, change its fields, ...) does not // fire a function event, so we react to the data-type events and push every server-known // function that references the edited type — the portal stores types per function. @@ -132,9 +143,9 @@ private void onVariableSymbolChanged(Program program, DomainObjectChangeRecord r } } - /// Push the containing function's types when a local variable or parameter symbol changed. + /// Push the containing function's signature when one of its parameter symbols changed. private void scheduleTypesForVariable(Program program, Symbol symbol) { - if (symbol.getSymbolType() != SymbolType.LOCAL_VAR && symbol.getSymbolType() != SymbolType.PARAMETER) { + if (symbol.getSymbolType() != SymbolType.PARAMETER) { return; } if (symbol.getParentNamespace() instanceof Function function && isSyncable(function)) { @@ -158,14 +169,26 @@ private void onFunctionChanged(Program program, DomainObjectChangeRecord record) if (!isSyncable(function) || revengService.isApplyingServerChanges(program)) { return; } - // Modifier-only changes (inline/no-return/thunk/...) carry no type information to sync. - // Everything else (return type, parameters, variable types) is pushed. - if (functionChange.isFunctionModifierChange()) { + // Only the return type and parameters reach the portal. Ghidra reports any other change — + // a local variable added, removed or retyped, the stack frame, an inline or no-return flag — + // without one of these two types, and pushing for it would resend an unchanged signature. + if (!functionChange.isFunctionSignatureChange()) { return; } scheduleTypes(program, function.getEntryPoint()); } + /// A function deleted and created again keeps its server id, because the id map is keyed by + /// address, but not its tag; put the tag back so it still shows as synced. + private void onFunctionAdded(Program program, DomainObjectChangeRecord record) { + if (record instanceof ProgramChangeRecord programChange) { + var function = program.getFunctionManager().getFunctionAt(programChange.getStart()); + if (isSyncable(function)) { + revengService.restoreSyncedTag(function); + } + } + } + private void onDataTypeChanged(Program program, DomainObjectChangeRecord record) { // Applying a portal signature updates the data types it names in place. if (revengService.isApplyingServerChanges(program)) { @@ -187,7 +210,10 @@ private static boolean isSyncable(Function function) { } private void scheduleRename(Program program, Address entryPoint) { - schedule(pendingRenames, new InProgram<>(program, entryPoint), () -> pushRename(program, entryPoint)); + synchronized (dueRenames) { + dueRenames.computeIfAbsent(program, p -> new LinkedHashSet<>()).add(entryPoint); + } + schedule(pendingRenames, program, () -> pushRenames(program)); } private void scheduleTypes(Program program, Address entryPoint) { @@ -231,16 +257,35 @@ private void pushFunctionsReferencingType(Program program, String typeName) { } } - private void pushRename(Program program, Address entryPoint) { - withAnalysedFunction(program, entryPoint, (analysedProgram, function) -> { - try { - revengService.pushFunctionRename(analysedProgram, function).ifPresent(pushedName -> - loggingService.info("Pushed rename of function at %s to \"%s\" to the RevEng.AI portal" - .formatted(entryPoint, pushedName))); - } catch (ApiException e) { - Msg.warn(this, "Failed to push rename for %s to portal".formatted(function.getName()), e); + /// Push every rename made in `program` since its last push, in one request. + private void pushRenames(Program program) { + Set

entryPoints; + synchronized (dueRenames) { + entryPoints = dueRenames.remove(program); + } + var analysedProgram = revengService.getAnalysedProgram(program); + if (entryPoints == null || analysedProgram.isEmpty()) { + return; + } + List functions = new ArrayList<>(); + for (Address entryPoint : entryPoints) { + var function = program.getFunctionManager().getFunctionAt(entryPoint); + if (isSyncable(function)) { + functions.add(function); } - }); + } + try { + var pushed = revengService.pushFunctionRenames(analysedProgram.get(), functions); + if (pushed.size() == 1) { + var only = pushed.entrySet().iterator().next(); + loggingService.info("Pushed rename of function at %s to \"%s\" to the RevEng.AI portal" + .formatted(only.getKey().getEntryPoint(), only.getValue())); + } else if (!pushed.isEmpty()) { + loggingService.info("Pushed renames of %d functions to the RevEng.AI portal".formatted(pushed.size())); + } + } catch (ApiException e) { + Msg.warn(this, "Failed to push renames of %d function(s) to portal".formatted(functions.size()), e); + } } private void pushTypes(Program program, Address entryPoint) { diff --git a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java new file mode 100644 index 00000000..61a5b2fe --- /dev/null +++ b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java @@ -0,0 +1,199 @@ +package ai.reveng; + +import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.model.CreateAnalysisDataTypesInputBody; +import ai.reveng.model.UpdateFunctionSignatureInputBody; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ghidra.program.model.address.AddressSet; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.data.LongDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.LocalVariableImpl; +import ghidra.program.model.listing.ParameterImpl; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/// What the reactive push sends, and how many requests it takes. +public class LocalEditSyncScopeTest extends RevEngMockableHeadedIntegrationTest { + + private static final String SYNCED_TAG = "REVENGAI_SYNCED"; + private static final long[] ENTRIES = {0x4000L, 0x4100L, 0x4200L}; + + /// One function per entry in {@link #ENTRIES}, with ids 1, 2 and 3. + private static class RecordingApi extends UnimplementedAPI { + final List renameRequests = new CopyOnWriteArrayList<>(); + final List pushedSignatures = new CopyOnWriteArrayList<>(); + private final AtomicInteger nextDataTypeId = new AtomicInteger(100); + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return java.util.stream.IntStream.range(0, ENTRIES.length) + .mapToObj(i -> new FunctionInfo(new FunctionID(i + 1), "FUN_" + i, "FUN_" + i, ENTRIES[i], 0x100)) + .toList(); + } + + @Override + public void batchRenameFunctions(BatchRenameInputBody request) { + renameRequests.add(request); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public List createAnalysisDataTypes(AnalysisID analysisID, + CreateAnalysisDataTypesInputBody request) { + return request.getDataTypes().stream() + .map(type -> new ServerDataType(nextDataTypeId.getAndIncrement(), "", "pushed", + ServerDataType.Kind.BASE, null, "USER", false, null, null, null)) + .toList(); + } + + @Override + public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID, + UpdateFunctionSignatureInputBody signature) { + pushedSignatures.add(functionID); + } + } + + private final RecordingApi api = new RecordingApi(); + private Program program; + private Function first; + private LocalEditSyncService sync; + + @Before + public void analyse() throws Exception { + var service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("code", "0x4000", 0x400); + for (long entry : ENTRIES) { + builder.createEmptyFunction(null, "0x" + Long.toHexString(entry), 0x100, new IntegerDataType()); + } + program = builder.getProgram(); + first = program.getFunctionManager().getFunctionAt(address(ENTRIES[0])); + program.withTransaction("give it a parameter", () -> rethrow(() -> first.replaceParameters( + Function.FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS, + new ParameterImpl("count", new IntegerDataType(), program)))); + + var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class)); + sync.attach(program); + } + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + private ghidra.program.model.address.Address address(long offset) { + return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset); + } + + private void edit(String description, Edit change) { + program.withTransaction(description, () -> rethrow(change)); + program.flushEvents(); + } + + private static boolean tagged(Function function) { + return function.getTags().stream().anyMatch(tag -> SYNCED_TAG.equals(tag.getName())); + } + + @Test + public void renamesInOneProgramGoUpInOneRequest() throws Exception { + for (int i = 0; i < ENTRIES.length; i++) { + var function = program.getFunctionManager().getFunctionAt(address(ENTRIES[i])); + var name = "renamed_" + i; + edit("rename", () -> function.setName(name, SourceType.USER_DEFINED)); + } + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the renames should be pushed"); + Thread.sleep(1_000); + assertEquals("one request for all three renames", 1, api.renameRequests.size()); + var pushed = api.renameRequests.get(0).getFunctions().stream() + .collect(java.util.stream.Collectors.toMap(item -> item.getFunctionId(), item -> item.getNewName())); + assertEquals(Map.of(1L, "renamed_0", 2L, "renamed_1", 3L, "renamed_2"), pushed); + } + + @Test + public void localVariableEditsPushNothingButAParameterRenameDoes() throws Exception { + edit("add a local", () -> first.addLocalVariable( + new LocalVariableImpl("local", new IntegerDataType(), -0x10, program), SourceType.USER_DEFINED)); + var local = first.getLocalVariables()[0]; + edit("rename the local", () -> local.setName("renamed_local", SourceType.USER_DEFINED)); + edit("retype the local", () -> local.setDataType(new LongDataType(), SourceType.USER_DEFINED)); + + // Past the debounce, so any push these had scheduled would have gone up. + Thread.sleep(1_000); + assertTrue("signatures pushed: " + api.pushedSignatures, api.pushedSignatures.isEmpty()); + + edit("rename the parameter", () -> first.getParameter(0).setName("renamed_count", SourceType.USER_DEFINED)); + waitForCondition(() -> !api.pushedSignatures.isEmpty(), "a parameter rename should push the signature"); + assertEquals(List.of(new FunctionID(1)), api.pushedSignatures); + } + + @Test + public void aFunctionCreatedAgainKeepsItsTag() throws Exception { + assertTrue(tagged(first)); + var entry = first.getEntryPoint(); + var body = new AddressSet(first.getBody()); + edit("delete", () -> program.getFunctionManager().removeFunction(entry)); + edit("create again", () -> program.getFunctionManager() + .createFunction(null, entry, body, SourceType.USER_DEFINED)); + + var recreated = program.getFunctionManager().getFunctionAt(entry); + waitForCondition(() -> tagged(recreated), "the re-created function should be tagged again"); + } + + @Test + public void aNewFunctionAtAnUnmappedAddressIsNotTagged() throws Exception { + var entry = address(0x4300L); + edit("create", () -> program.getFunctionManager() + .createFunction(null, entry, new AddressSet(entry, address(0x43ffL)), SourceType.USER_DEFINED)); + + Thread.sleep(500); + assertFalse(tagged(program.getFunctionManager().getFunctionAt(entry))); + } + + private interface Edit { + void run() throws Exception; + } + + private static void rethrow(Edit edit) { + try { + edit.run(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} From 34320597f75ba7b950b2292d05a32a9913ae5d37 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:52:21 +0000 Subject: [PATCH 28/76] Wait for in-flight event delivery before ending a server write Ghidra's event timer runs on the Swing thread and takes and delivers queued events in one task. A flushEvents from the sync thread could find the queue already taken and return while the sync's own events were still being delivered, so suppression ended first and the sync's signature was pushed back. Queue an empty Swing task after the flush to wait that delivery out. --- .../core/services/api/GhidraRevengService.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 331dcb1e..25baa7d1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -34,6 +34,7 @@ import ghidra.program.model.util.StringPropertyMap; import ghidra.util.InvalidNameException; import ghidra.util.Msg; +import ghidra.util.Swing; import ghidra.util.exception.CancelledException; import ghidra.util.exception.DuplicateNameException; import ghidra.util.exception.InvalidInputException; @@ -789,7 +790,7 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, /// Function and variable renames are never suppressed — see /// {@link ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService}. private int startServerTransaction(Program program, String description) { - program.flushEvents(); + deliverPendingEvents(program); applyingServerChanges.merge(program, 1, Integer::sum); try { return program.startTransaction(description); @@ -802,12 +803,23 @@ private int startServerTransaction(Program program, String description) { private void endServerTransaction(Program program, int transactionId, boolean commit) { try { program.endTransaction(transactionId, commit); - program.flushEvents(); + deliverPendingEvents(program); } finally { releaseServerChanges(program); } } + /// Deliver every change event `program` has queued, and wait until the listeners have seen them. + /// + /// {@link Program#flushEvents} alone does not wait. Ghidra's event timer runs on the Swing thread + /// and takes the queued events and delivers them in one Swing task; when it has just taken them, + /// a flush from another thread finds the queue empty and returns while they are still being + /// delivered. Queuing an empty task behind it waits that delivery out. + private static void deliverPendingEvents(Program program) { + program.flushEvents(); + Swing.runNow(() -> {}); + } + private void releaseServerChanges(Program program) { applyingServerChanges.computeIfPresent(program, (p, writes) -> writes > 1 ? writes - 1 : null); } From 0be7d6366bfb18bb52882920b474d553dc45601a Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:46:16 +0000 Subject: [PATCH 29/76] Report failed local-edit pushes and send them on the next sync A push that fails is reported in the plugin log and the status bar, including unchecked exceptions that used to die inside the discarded future. The edit stays marked in the program's user data until a push succeeds, and Sync with portal sends whatever is still marked, as one rename batch and one type pass, before it reads the remote names. A rename batch now checks renamed_count and fails when the portal renamed fewer functions than were sent, and sync reports names and signatures that differ between Ghidra and the portal instead of keeping the local copy silently. --- .../services/api/GhidraRevengService.java | 128 +++++++++-- .../services/api/TypedApiImplementation.java | 6 +- .../core/services/api/TypedApiInterface.java | 4 +- .../services/sync/LocalEditSyncService.java | 45 +++- .../core/services/sync/UnpushedEdits.java | 72 ++++++ .../plugins/AnalysisManagementPlugin.java | 8 +- .../plugins/BinarySimilarityPlugin.java | 18 +- .../java/ai/reveng/AutoUnstripSyncTest.java | 3 +- .../LocalEditSyncAcrossProgramsTest.java | 6 +- .../ai/reveng/LocalEditSyncScopeTest.java | 6 +- .../ai/reveng/LocalEditsDuringSyncTest.java | 6 +- .../ai/reveng/PullSignaturesOnSyncTest.java | 3 +- .../ai/reveng/UnpushedLocalEditsTest.java | 210 ++++++++++++++++++ 13 files changed, 479 insertions(+), 36 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/UnpushedEdits.java create mode 100644 src/test/java/ai/reveng/UnpushedLocalEditsTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 25baa7d1..705de50a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -14,6 +14,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.mocks.MockApi; import ai.reveng.toolkit.ghidra.core.services.api.types.*; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; import ghidra.app.cmd.function.ApplyFunctionSignatureCmd; import ghidra.app.cmd.function.FunctionRenameOption; @@ -334,6 +335,9 @@ public record RenameResult(Function func, String originalName, String newName) { /// Push local function renames back to the portal in one request. Answers with the /// namespace-qualified name pushed for each function; functions not known on the server are left /// out, and when none is known nothing is sent. + /// + /// @throws IllegalStateException when the portal accepted the request but renamed fewer functions + /// than were sent; it does not say which, so none counts as pushed public Map pushFunctionRenames(AnalysedProgram analysedProgram, Collection functions) throws ApiException { Map pushed = new LinkedHashMap<>(); @@ -356,7 +360,11 @@ public Map pushFunctionRenames(AnalysedProgram analysedProgram } var request = new BatchRenameInputBody(); request.setFunctions(items); - api.batchRenameFunctions(request); + long renamed = api.batchRenameFunctions(request); + if (renamed < items.size()) { + throw new IllegalStateException("The portal renamed %d of the %d function(s) sent" + .formatted(renamed, items.size())); + } return pushed; } @@ -441,9 +449,17 @@ public record SyncSummary( int canonicalizedNames, int dedupedNames, int pushedNames, - int pushedTypeSets + int pushedTypeSets, + int pushedLocalEdits, + int failedLocalEdits, + int nameConflicts, + int signatureConflicts ) {} + /// @param pushed the unpushed local edits that reached the portal this time + /// @param failed the ones that failed again and are still marked + private record LocalEditFlush(int pushed, int failed) {} + private record PendingNamePush(TypedApiInterface.FunctionID functionID, String newName, String newMangledName) {} private record InvalidRemoteName(Function function, TypedApiInterface.FunctionID functionID, String remoteName) {} @@ -459,6 +475,9 @@ private record InvalidRemoteName(Function function, TypedApiInterface.FunctionID public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) throws ApiException { var program = analysedProgram.program(); log.info("Starting bidirectional sync with the RevEng.AI portal"); + // Before the remote names are read, so an edit that goes up now is not then reported as a + // conflict with the portal's stale copy of it. + var flush = pushUnpushedEdits(analysedProgram, log); Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() .collect(Collectors.toMap(FunctionInfo::functionID, fi -> fi, (a, b) -> a)); @@ -469,6 +488,7 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni int namesModifiedRemotely = 0; int deduped = 0; int canonicalizedNames = 0; + int nameConflicts = 0; var transactionId = startServerTransaction(program, "RevEng.AI: Sync Analysis Updates"); boolean commit = false; @@ -496,8 +516,16 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni if (remoteName == null || remoteName.isBlank() || remoteName.equals(function.getName())) { continue; } - // Do not overwrite names the user has explicitly set locally. + // Do not overwrite names the user has explicitly set locally. The portal holding a + // different name for one means both sides renamed it, unless the local rename is + // still waiting to go up. if (function.getSymbol().getSource() == SourceType.USER_DEFINED) { + if (!remoteName.equals(qualifiedServerName(function)) + && !UnpushedEdits.isMarked(program, UnpushedEdits.Kind.NAME, function.getEntryPoint())) { + nameConflicts++; + log.warn("Name conflict at %s: \"%s\" locally, \"%s\" in the portal; kept the local name" + .formatted(function.getEntryPoint(), function.getName(), remoteName)); + } continue; } if (isInvalidGhidraName(remoteName)) { @@ -556,15 +584,71 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni } // Pull before pushing, so the back-fill below sees the signatures this sync just applied and // does not send the local placeholder back up for a function the portal already described. - int appliedSignatures = applyRemoteSignatures(analysedProgram, monitor, log); + var signatures = applyRemoteSignatures(analysedProgram, monitor, log); + int appliedSignatures = signatures.applied(); int pushedTypeSets = pushLocalTypesWhereRemoteMissing(analysedProgram, functionInfoMap.keySet(), monitor, log); log.info(("Sync complete: %d matched, %d name(s) applied, %d signature(s) applied, %d canonicalized, " - + "%d de-duplicated, %d name(s) and %d type set(s) pushed back") + + "%d de-duplicated, %d name(s) and %d type set(s) pushed back, %d unpushed local edit(s) " + + "pushed and %d still failing, %d name and %d signature conflict(s)") .formatted(matched, namesModifiedRemotely, appliedSignatures, canonicalizedNames, deduped, - pushedNames, pushedTypeSets)); + pushedNames, pushedTypeSets, flush.pushed(), flush.failed(), nameConflicts, + signatures.conflicts())); return new SyncSummary(matched, namesModifiedRemotely, appliedSignatures, canonicalizedNames, deduped, - pushedNames, pushedTypeSets); + pushedNames, pushedTypeSets, flush.pushed(), flush.failed(), nameConflicts, signatures.conflicts()); + } + + /// Push the local edits whose reactive push failed or never ran — see {@link UnpushedEdits}. A + /// function that is gone, or not part of the analysis, has nothing left to push and is unmarked. + private LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram, ReaiLoggingService log) { + var program = analysedProgram.program(); + int pushed = 0; + int failed = 0; + List
nameMarks = UnpushedEdits.marked(program, UnpushedEdits.Kind.NAME); + List renamed = new ArrayList<>(); + for (Address entryPoint : nameMarks) { + var function = program.getFunctionManager().getFunctionAt(entryPoint); + if (function != null) { + renamed.add(function); + } + } + if (!nameMarks.isEmpty()) { + try { + // One request for them all, as the reactive push sends them. + pushed += pushFunctionRenames(analysedProgram, renamed).size(); + nameMarks.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.NAME, entryPoint)); + } catch (Exception e) { + failed += renamed.size(); + log.warn("Could not push the local names of %d function(s): %s".formatted(renamed.size(), e)); + } + } + + List
typeMarks = UnpushedEdits.marked(program, UnpushedEdits.Kind.TYPES); + List typeEdits = new ArrayList<>(); + for (Address entryPoint : typeMarks) { + var function = program.getFunctionManager().getFunctionAt(entryPoint); + if (function != null && analysedProgram.getIDForFunction(function).isPresent()) { + typeEdits.add(function); + } + } + if (!typeMarks.isEmpty()) { + try { + // One type pass for them all, as in the back-fill below. A signature the portal has no + // extraction for is declined, but its types went up, which is all this push can do. + if (!typeEdits.isEmpty()) { + pushFunctionTypes(analysedProgram, typeEdits); + } + pushed += typeEdits.size(); + typeMarks.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, entryPoint)); + } catch (Exception e) { + failed += typeEdits.size(); + log.warn("Could not push the local types of %d function(s): %s".formatted(typeEdits.size(), e)); + } + } + if (pushed > 0) { + log.info("Pushed %d local edit(s) that had not reached the RevEng.AI portal".formatted(pushed)); + } + return new LocalEditFlush(pushed, failed); } /// Apply the signatures — and with them the data types they name — that the portal holds for this @@ -581,15 +665,20 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni /// inferred. That is also what makes a second sync useful: an earlier pull stamps /// {@link SourceType#ANALYSIS}, so a "default only" guard would turn every pull after the first /// into a no-op. - private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) { + /// + /// A hand-written local signature that differs from the portal's is counted as a conflict rather + /// than applied, unless the local edit is still waiting to go up. + private SignaturePull applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor monitor, + ReaiLoggingService log) { var functionMap = analysedProgram.getFunctionMap(); if (functionMap.isEmpty()) { - return 0; + return new SignaturePull(0, 0); } var batch = signatures().getMany(List.copyOf(functionMap.keySet())); Map decoders = new HashMap<>(); var program = analysedProgram.program(); int applied = 0; + int conflicts = 0; var transactionId = startServerTransaction(program, "RevEng.AI: Apply Portal Signatures"); try { for (BatchFunctionSignatureEntry entry : batch.items()) { @@ -601,11 +690,20 @@ private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor m } var function = functionMap.get(new TypedApiInterface.FunctionID(entry.getFunctionId())); if (function == null || function.isExternal() || function.isThunk() - || function.getSignatureSource() == SourceType.USER_DEFINED || localSignatureOutranks(function, entry)) { continue; } var signature = getFunctionSignature(entry, decoderFor(decoders, batch, entry)); + if (function.getSignatureSource() == SourceType.USER_DEFINED) { + if (!matchesLocalSignature(function, signature) + && !UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint())) { + conflicts++; + log.warn("Signature conflict for \"%s\" at %s: the portal holds %s; kept the local signature" + .formatted(function.getName(), function.getEntryPoint(), + signature.getPrototypeString())); + } + continue; + } // The portal derives a signature for every function when the analysis completes, so // most of them match what is already on the function. Applying those regardless would // churn the type manager and fill the undo history on every sync. @@ -629,9 +727,13 @@ private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor m } finally { endServerTransaction(program, transactionId, applied > 0 && !monitor.isCancelled()); } - return applied; + return new SignaturePull(applied, conflicts); } + /// @param applied portal signatures that landed locally + /// @param conflicts hand-written local signatures the portal disagrees with + private record SignaturePull(int applied, int conflicts) {} + /// Whether the function's own signature beats one the server extracted itself. A SYSTEM signature /// is what server-side Ghidra worked out, so it adds nothing over a signature imported from debug /// info locally, or one local analysis inferred, and replacing either can only lose information. @@ -725,8 +827,8 @@ private int pushNameBacks(List namePushbacks) throws ApiExcepti }).toList(); var request = new BatchRenameInputBody(); request.setFunctions(items); - api.batchRenameFunctions(request); - return namePushbacks.size(); + // The count the portal reports, not the number asked for: a rename it skipped did not happen. + return Math.toIntExact(api.batchRenameFunctions(request)); } /// Push local types for matched functions whose remote types are absent or could not be applied, diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 7eb1852a..0ac5df8c 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -699,8 +699,10 @@ public GetMatchesOutputBody getFunctionsMatches(List functionIds) throws A } @Override - public void batchRenameFunctions(BatchRenameInputBody request) throws ApiException { - this.functionsRenamingHistoryApi.batchRenameFunctions(request); + public long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + var response = this.functionsRenamingHistoryApi.batchRenameFunctions(request); + Long renamedCount = response == null ? null : response.getRenamedCount(); + return renamedCount == null ? 0 : renamedCount; } /// GET /v3/functions/{function_id}/blocks diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java index 7cf48888..afa8d8d1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java @@ -241,7 +241,9 @@ default GetMatchesOutputBody getFunctionsMatches(List functionIds) throws throw new UnsupportedOperationException("getFunctionsMatches not implemented yet"); } - default void batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + /// Answers with the number of functions the server actually renamed, which can be fewer than were + /// asked for even though the request succeeded. + default long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { throw new UnsupportedOperationException("batchRenameFunctions not implemented yet"); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index 088ddfff..b84c8af0 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -1,6 +1,5 @@ package ai.reveng.toolkit.ghidra.core.services.sync; -import ai.reveng.invoker.ApiException; import ai.reveng.toolkit.ghidra.core.services.api.GhidraDataTypeEncoder; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService.AnalysedProgram; @@ -47,6 +46,9 @@ * so sync-applied changes are not echoed straight back. Renames need no such guard: the plugin only * ever writes {@link SourceType#ANALYSIS} names, and only {@link SourceType#USER_DEFINED} ones are * pushed, so an analyst's rename is pushed even when it lands in the middle of a sync. + * + *

A push that fails is reported in the plugin log and the status bar, and the edit stays marked in + * {@link UnpushedEdits} until a push succeeds, so "Sync with portal" sends it later. */ public class LocalEditSyncService { @@ -55,6 +57,8 @@ public class LocalEditSyncService { private final GhidraRevengService revengService; private final ReaiLoggingService loggingService; + /// Shows a message in the status bar; the flag marks it as a warning. + private final BiConsumer statusNotifier; private final ScheduledExecutorService scheduler; private final Map listeners = new ConcurrentHashMap<>(); private final Map> pendingRenames = new ConcurrentHashMap<>(); @@ -68,9 +72,11 @@ public class LocalEditSyncService { /// address or type path alone would let an edit in one program cancel the other's pending push. private record InProgram(Program program, K key) {} - public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService) { + public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService, + BiConsumer statusNotifier) { this.revengService = revengService; this.loggingService = loggingService; + this.statusNotifier = statusNotifier; this.scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> { var thread = new Thread(runnable, "RevEng.AI-LocalEditSync"); thread.setDaemon(true); @@ -210,6 +216,7 @@ private static boolean isSyncable(Function function) { } private void scheduleRename(Program program, Address entryPoint) { + UnpushedEdits.mark(program, UnpushedEdits.Kind.NAME, entryPoint); synchronized (dueRenames) { dueRenames.computeIfAbsent(program, p -> new LinkedHashSet<>()).add(entryPoint); } @@ -217,6 +224,7 @@ private void scheduleRename(Program program, Address entryPoint) { } private void scheduleTypes(Program program, Address entryPoint) { + UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, entryPoint); schedule(pendingTypes, new InProgram<>(program, entryPoint), () -> pushTypes(program, entryPoint)); } @@ -233,7 +241,12 @@ private void schedule(Map> pending, K key, Runnable ta } pending.put(key, scheduler.schedule(() -> { pending.remove(key); - task.run(); + // Nothing reads the future, so anything thrown here would vanish with it. + try { + task.run(); + } catch (Exception e) { + reportFailure("RevEng.AI: could not push a local edit to the portal", e); + } }, DEBOUNCE_MS, TimeUnit.MILLISECONDS)); } @@ -283,8 +296,16 @@ private void pushRenames(Program program) { } else if (!pushed.isEmpty()) { loggingService.info("Pushed renames of %d functions to the RevEng.AI portal".formatted(pushed.size())); } - } catch (ApiException e) { - Msg.warn(this, "Failed to push renames of %d function(s) to portal".formatted(functions.size()), e); + // Every one, including those that were gone or unknown to the portal: nothing is left to send. + entryPoints.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.NAME, entryPoint)); + } catch (Exception e) { + // Marked again in case a push that started earlier succeeded and cleared them meanwhile. + entryPoints.forEach(entryPoint -> UnpushedEdits.mark(program, UnpushedEdits.Kind.NAME, entryPoint)); + var what = functions.size() == 1 + ? "the rename of \"%s\"".formatted(functions.get(0).getName()) + : "the renames of %d functions".formatted(functions.size()); + reportFailure("RevEng.AI: could not push %s to the portal; it will be sent on the next Sync with portal" + .formatted(what), e); } } @@ -306,12 +327,22 @@ private void pushTypes(Program program, Address entryPoint) { // Not part of the analysis, so there was nothing to push. } } - } catch (ApiException e) { - Msg.warn(this, "Failed to push types for %s to portal".formatted(function.getName()), e); + UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, entryPoint); + } catch (Exception e) { + UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, entryPoint); + reportFailure("RevEng.AI: could not push the types of \"%s\" to the portal; they will be sent on the next Sync with portal" + .formatted(function.getName()), e); } }); } + private void reportFailure(String message, Exception e) { + var reported = "%s: %s".formatted(message, e.getMessage() != null ? e.getMessage() : e); + Msg.warn(this, reported, e); + loggingService.warn(reported); + statusNotifier.accept(reported, true); + } + private void withAnalysedFunction(Program program, Address entryPoint, BiConsumer action) { var analysedProgram = revengService.getAnalysedProgram(program); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/UnpushedEdits.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/UnpushedEdits.java new file mode 100644 index 00000000..2f9a8893 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/UnpushedEdits.java @@ -0,0 +1,72 @@ +package ai.reveng.toolkit.ghidra.core.services.sync; + +import ghidra.program.model.address.Address; +import ghidra.program.model.listing.Program; + +import java.util.ArrayList; +import java.util.List; + +/// The functions whose local edits have not reached the portal yet. +/// +/// An edit is marked here when its push is scheduled and cleared only once a push succeeds, so a push +/// that fails, or never runs because Ghidra closed first, is still known about and "Sync with portal" +/// sends it. Sync cannot find these edits by itself: it leaves user-defined local names alone, because +/// it cannot tell an edit that never went up from one the portal has since overwritten. +/// +/// The marks live in the program's user data, which is saved with the program but sits outside its +/// undo history and does not mark the program as changed. +public final class UnpushedEdits { + + private static final String OWNER = "RevEng.AI"; + + public enum Kind { + NAME("Unpushed function names"), + TYPES("Unpushed function types"); + + private final String propertyName; + + Kind(String propertyName) { + this.propertyName = propertyName; + } + } + + private UnpushedEdits() {} + + public static synchronized void mark(Program program, Kind kind, Address entryPoint) { + var userData = program.getProgramUserData(); + int tx = userData.startTransaction(); + try { + userData.getBooleanProperty(OWNER, kind.propertyName, true).add(entryPoint); + } finally { + userData.endTransaction(tx); + } + } + + public static synchronized void clear(Program program, Kind kind, Address entryPoint) { + var userData = program.getProgramUserData(); + int tx = userData.startTransaction(); + try { + var marks = userData.getBooleanProperty(OWNER, kind.propertyName, false); + if (marks != null) { + marks.remove(entryPoint); + } + } finally { + userData.endTransaction(tx); + } + } + + public static synchronized boolean isMarked(Program program, Kind kind, Address entryPoint) { + var marks = program.getProgramUserData().getBooleanProperty(OWNER, kind.propertyName, false); + return marks != null && marks.hasProperty(entryPoint); + } + + /// The entry points marked for `kind`, in address order. + public static synchronized List

marked(Program program, Kind kind) { + var marks = program.getProgramUserData().getBooleanProperty(OWNER, kind.propertyName, false); + List
entryPoints = new ArrayList<>(); + if (marks != null) { + marks.getPropertyIterator().forEach(entryPoints::add); + } + return entryPoints; + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 130017a0..bc100b7b 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -46,6 +46,7 @@ import org.slf4j.LoggerFactory; import java.util.Objects; +import java.util.function.BiConsumer; /** * CorePlugin for accessing the RevEng.AI Platform @@ -99,9 +100,10 @@ public void init() { tool.addComponentProvider(analysisLogComponent, false); revengService = Objects.requireNonNull(tool.getService(GhidraRevengService.class)); - localEditSyncService = new LocalEditSyncService(revengService, loggingService); - autoUnstripSyncService = new AutoUnstripSyncService(revengService, loggingService, - (message, warning) -> SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, warning))); + BiConsumer statusNotifier = + (message, warning) -> SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, warning)); + localEditSyncService = new LocalEditSyncService(revengService, loggingService, statusNotifier); + autoUnstripSyncService = new AutoUnstripSyncService(revengService, loggingService, statusNotifier); setupActions(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java index 2223dfa1..47383347 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java @@ -283,7 +283,7 @@ public void run(TaskMonitor monitor) { } private static String formatSyncSummary(GhidraRevengService.SyncSummary summary) { - return ("Synced %d matched function(s) with the portal.\n" + + var text = new StringBuilder(("Synced %d matched function(s) with the portal.\n" + "Applied %d remote name(s) and %d remote signature(s); canonicalized %d and de-duplicated %d.\n" + "Pushed %d name(s) and %d type set(s) back to the portal.").formatted( summary.matchedFunctions(), @@ -292,7 +292,21 @@ private static String formatSyncSummary(GhidraRevengService.SyncSummary summary) summary.canonicalizedNames(), summary.dedupedNames(), summary.pushedNames(), - summary.pushedTypeSets()); + summary.pushedTypeSets())); + if (summary.pushedLocalEdits() > 0) { + text.append("\nPushed %d local edit(s) that had not reached the portal yet." + .formatted(summary.pushedLocalEdits())); + } + if (summary.failedLocalEdits() > 0) { + text.append("\n%d local edit(s) still could not be pushed; they will be retried on the next sync." + .formatted(summary.failedLocalEdits())); + } + if (summary.nameConflicts() > 0 || summary.signatureConflicts() > 0) { + text.append(("\n%d name(s) and %d signature(s) differ between Ghidra and the portal and were left " + + "as they are locally; the RevEng.AI log lists them.") + .formatted(summary.nameConflicts(), summary.signatureConflicts())); + } + return text.toString(); } @Override diff --git a/src/test/java/ai/reveng/AutoUnstripSyncTest.java b/src/test/java/ai/reveng/AutoUnstripSyncTest.java index 5385195c..bc583c04 100644 --- a/src/test/java/ai/reveng/AutoUnstripSyncTest.java +++ b/src/test/java/ai/reveng/AutoUnstripSyncTest.java @@ -61,8 +61,9 @@ public FunctionSignatureBatch listFunctionSignatures(List listAnalysisDataTypes(AnalysisID analysisID, long of } @Override - public void batchRenameFunctions(BatchRenameInputBody request) { + public long batchRenameFunctions(BatchRenameInputBody request) { for (var item : request.getFunctions()) { renamed.put(item.getFunctionId(), item.getNewName()); } + return request.getFunctions().size(); } } @@ -96,7 +97,8 @@ public void editsAtTheSameAddressInTwoProgramsAreBothPushed() throws Exception { Function inA = analysedFunction(service, "a", 1); Function inB = analysedFunction(service, "b", 2); - sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class)); + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class), + (message, warning) -> {}); sync.attach(inA.getProgram()); sync.attach(inB.getProgram()); diff --git a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java index 61a5b2fe..d21de7f2 100644 --- a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java +++ b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java @@ -59,8 +59,9 @@ public List getFunctionInfo(AnalysisID analysisID) { } @Override - public void batchRenameFunctions(BatchRenameInputBody request) { + public long batchRenameFunctions(BatchRenameInputBody request) { renameRequests.add(request); + return request.getFunctions().size(); } @Override @@ -105,7 +106,8 @@ public void analyse() throws Exception { var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); - sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class)); + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class), + (message, warning) -> {}); sync.attach(program); } diff --git a/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java index cd0094a3..8bdf5f81 100644 --- a/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java +++ b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java @@ -98,10 +98,11 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID } @Override - public void batchRenameFunctions(BatchRenameInputBody request) { + public long batchRenameFunctions(BatchRenameInputBody request) { for (var item : request.getFunctions()) { renamed.put(item.getFunctionId(), item.getNewName()); } + return request.getFunctions().size(); } @Override @@ -155,7 +156,8 @@ private Function analysedFunction(String name, int analysisId) throws Exception } private void listenTo(Function... functions) { - sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class)); + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class), + (message, warning) -> {}); for (Function function : functions) { sync.attach(function.getProgram()); } diff --git a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java index 203cc78e..8d567aa1 100644 --- a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java +++ b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java @@ -119,8 +119,9 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID } @Override - public void batchRenameFunctions(BatchRenameInputBody request) { + public long batchRenameFunctions(BatchRenameInputBody request) { // A name pushback is not what these tests are about; accept and ignore it. + return request.getFunctions().size(); } @Override diff --git a/src/test/java/ai/reveng/UnpushedLocalEditsTest.java b/src/test/java/ai/reveng/UnpushedLocalEditsTest.java new file mode 100644 index 00000000..b09e79a6 --- /dev/null +++ b/src/test/java/ai/reveng/UnpushedLocalEditsTest.java @@ -0,0 +1,210 @@ +package ai.reveng; + +import ai.reveng.invoker.ApiException; +import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.data.LongDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/// A local edit whose push fails is reported, stays marked as unpushed, and goes up on the next sync. +public class UnpushedLocalEditsTest extends RevEngMockableHeadedIntegrationTest { + + private static final long FUNCTION_ID = 1; + + /// One function at 0x4000. Its portal name is whatever was last pushed, unless a test sets one. + private static class FlakyApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + volatile String remoteName = "FUN_00004000"; + volatile boolean renameThrows; + volatile boolean renameSkipped; + volatile boolean typesThrow; + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of(new FunctionInfo(new FunctionID(FUNCTION_ID), remoteName, remoteName, 0x4000L, 0x100)); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + if (typesThrow) { + // How TypedApiImplementation wraps an ApiException from this call. + throw new RuntimeException(new ApiException(503, "Service Unavailable")); + } + return List.of(); + } + + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, boolean includeDataTypes) { + return FunctionSignatureBatch.empty(); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + if (renameThrows) { + throw new ApiException(503, "Service Unavailable"); + } + if (renameSkipped) { + return 0; + } + for (var item : request.getFunctions()) { + renamed.put(item.getFunctionId(), item.getNewName()); + remoteName = item.getNewName(); + } + return request.getFunctions().size(); + } + } + + private static class RecordingLog implements ReaiLoggingService { + final List warnings = new CopyOnWriteArrayList<>(); + @Override public void info(String message) {} + @Override public void warn(String message) { warnings.add(message); } + @Override public void error(String message) {} + } + + private final FlakyApi api = new FlakyApi(); + private final RecordingLog log = new RecordingLog(); + private final List statusWarnings = new CopyOnWriteArrayList<>(); + private GhidraRevengService service; + private Function function; + private Program program; + private LocalEditSyncService sync; + + @Before + public void analyse() throws Exception { + service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("code", "0x4000", 0x200); + function = builder.createEmptyFunction("FUN_00004000", "0x4000", 0x100, new IntegerDataType()); + program = builder.getProgram(); + var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + } + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + private void listen() { + sync = new LocalEditSyncService(service, log, (message, warning) -> { + if (warning) { + statusWarnings.add(message); + } + }); + sync.attach(program); + } + + private void rename(String newName) throws Exception { + program.withTransaction("rename", () -> function.setName(newName, SourceType.USER_DEFINED)); + program.flushEvents(); + } + + private boolean nameMarked() { + return UnpushedEdits.isMarked(program, UnpushedEdits.Kind.NAME, function.getEntryPoint()); + } + + private GhidraRevengService.SyncSummary syncWithPortal() throws Exception { + return service.syncAnalysisUpdates(service.getAnalysedProgram(program).orElseThrow(), TaskMonitor.DUMMY, log); + } + + @Test + public void aFailedRenameIsReportedAndSentByTheNextSync() throws Exception { + listen(); + api.renameThrows = true; + rename("mine"); + + waitForCondition(() -> !statusWarnings.isEmpty(), "the failed push should reach the status bar"); + assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("mine")); + assertTrue(log.warnings.contains(statusWarnings.get(0))); + assertTrue(api.renamed.isEmpty()); + assertTrue(nameMarked()); + + api.renameThrows = false; + var summary = syncWithPortal(); + + assertEquals(Map.of(FUNCTION_ID, "mine"), api.renamed); + assertEquals(1, summary.pushedLocalEdits()); + assertEquals(0, summary.failedLocalEdits()); + assertEquals("the edit went up first, so it is no conflict", 0, summary.nameConflicts()); + assertFalse(nameMarked()); + } + + @Test + public void aRenameThePortalSkippedCountsAsFailed() throws Exception { + listen(); + api.renameSkipped = true; + rename("mine"); + + waitForCondition(() -> !statusWarnings.isEmpty(), "a renamed_count of zero should be reported"); + assertTrue(nameMarked()); + } + + @Test + public void aSuccessfulRenameLeavesNothingMarked() throws Exception { + listen(); + rename("mine"); + + waitForCondition(() -> api.renamed.size() == 1, "the rename should be pushed"); + waitForCondition(() -> !nameMarked(), "the mark should be cleared once the push succeeded"); + assertTrue(statusWarnings.isEmpty()); + } + + /// A RuntimeException used to die unseen inside the discarded future. + @Test + public void anUncheckedFailureInATypePushIsReported() throws Exception { + listen(); + api.typesThrow = true; + program.withTransaction("retype", () -> function.setReturnType(new LongDataType(), SourceType.USER_DEFINED)); + program.flushEvents(); + + waitForCondition(() -> !statusWarnings.isEmpty(), "the failed type push should reach the status bar"); + assertTrue(UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint())); + } + + @Test + public void reportsANameBothSidesChanged() throws Exception { + // Renamed without the listener, so the local name never went up and is not marked as unpushed: + // it looks like an edit that reached the portal before the portal's copy was renamed again. + rename("mine"); + api.remoteName = "theirs"; + + var summary = syncWithPortal(); + + assertEquals(1, summary.nameConflicts()); + assertEquals("mine", function.getName()); + assertTrue(log.warnings.stream().anyMatch(warning -> warning.contains("theirs"))); + } +} From c2a91212dad87588a2e2afd6625b364a92bd96a6 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:40:20 +0000 Subject: [PATCH 30/76] Report a failing portal once and retry unpushed edits automatically Each failed push used to produce its own warning in the plugin log and the status bar. Now the first failure reports the outage once; the rest go only to Ghidra's console. The program's unpushed edits are retried in the background after 30 s, 1 m, 2 m and then every 5 m, straight away when another push gets through, and once they are up that is reported once too. --- .../services/api/GhidraRevengService.java | 25 +-- .../services/sync/LocalEditSyncService.java | 148 ++++++++++++++++-- .../ai/reveng/UnpushedLocalEditsTest.java | 41 ++++- 3 files changed, 183 insertions(+), 31 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 705de50a..914d8279 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -458,7 +458,8 @@ public record SyncSummary( /// @param pushed the unpushed local edits that reached the portal this time /// @param failed the ones that failed again and are still marked - private record LocalEditFlush(int pushed, int failed) {} + /// @param error why the last of those failed, or null when none did + public record LocalEditFlush(int pushed, int failed, @Nullable Exception error) {} private record PendingNamePush(TypedApiInterface.FunctionID functionID, String newName, String newMangledName) {} private record InvalidRemoteName(Function function, TypedApiInterface.FunctionID functionID, String remoteName) {} @@ -477,7 +478,13 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni log.info("Starting bidirectional sync with the RevEng.AI portal"); // Before the remote names are read, so an edit that goes up now is not then reported as a // conflict with the portal's stale copy of it. - var flush = pushUnpushedEdits(analysedProgram, log); + var flush = pushUnpushedEdits(analysedProgram); + if (flush.pushed() > 0) { + log.info("Pushed %d local edit(s) that had not reached the RevEng.AI portal".formatted(flush.pushed())); + } + if (flush.failed() > 0) { + log.warn("Could not push %d local edit(s) to the RevEng.AI portal: %s".formatted(flush.failed(), flush.error())); + } Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() .collect(Collectors.toMap(FunctionInfo::functionID, fi -> fi, (a, b) -> a)); @@ -600,10 +607,13 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni /// Push the local edits whose reactive push failed or never ran — see {@link UnpushedEdits}. A /// function that is gone, or not part of the analysis, has nothing left to push and is unmarked. - private LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram, ReaiLoggingService log) { + /// Failures are returned rather than logged, so a caller retrying in the background can report an + /// outage once instead of once per attempt. + public LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram) { var program = analysedProgram.program(); int pushed = 0; int failed = 0; + Exception error = null; List
nameMarks = UnpushedEdits.marked(program, UnpushedEdits.Kind.NAME); List renamed = new ArrayList<>(); for (Address entryPoint : nameMarks) { @@ -619,7 +629,7 @@ private LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram, ReaiLo nameMarks.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.NAME, entryPoint)); } catch (Exception e) { failed += renamed.size(); - log.warn("Could not push the local names of %d function(s): %s".formatted(renamed.size(), e)); + error = e; } } @@ -642,13 +652,10 @@ private LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram, ReaiLo typeMarks.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, entryPoint)); } catch (Exception e) { failed += typeEdits.size(); - log.warn("Could not push the local types of %d function(s): %s".formatted(typeEdits.size(), e)); + error = e; } } - if (pushed > 0) { - log.info("Pushed %d local edit(s) that had not reached the RevEng.AI portal".formatted(pushed)); - } - return new LocalEditFlush(pushed, failed); + return new LocalEditFlush(pushed, failed, error); } /// Apply the signatures — and with them the data types they name — that the portal holds for this diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index b84c8af0..0fe346fa 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -19,6 +19,8 @@ import ghidra.program.util.ProgramEvent; import ghidra.util.Msg; +import javax.annotation.Nullable; +import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; @@ -47,14 +49,21 @@ * ever writes {@link SourceType#ANALYSIS} names, and only {@link SourceType#USER_DEFINED} ones are * pushed, so an analyst's rename is pushed even when it lands in the middle of a sync. * - *

A push that fails is reported in the plugin log and the status bar, and the edit stays marked in - * {@link UnpushedEdits} until a push succeeds, so "Sync with portal" sends it later. + *

A push that fails leaves the edit marked in {@link UnpushedEdits} until a push succeeds. The + * marked edits of that program are then retried in the background, backing off from + * {@link #RETRY_DELAYS}, and "Sync with portal" sends them too. A failing portal is reported once, + * in the plugin log and the status bar, however many pushes fail, and once more when the edits have + * gone up; each failure is logged only to Ghidra's console. */ public class LocalEditSyncService { /// Coalesce rapid successive edits to the same function before pushing, matching IDA's debounce. private static final long DEBOUNCE_MS = 400; + /// The waits before each automatic retry of a program's unpushed edits; the last one repeats. + public static final List RETRY_DELAYS = List.of( + Duration.ofSeconds(30), Duration.ofMinutes(1), Duration.ofMinutes(2), Duration.ofMinutes(5)); + private final GhidraRevengService revengService; private final ReaiLoggingService loggingService; /// Shows a message in the status bar; the flag marks it as a warning. @@ -66,6 +75,16 @@ public class LocalEditSyncService { private final Map> dueRenames = new HashMap<>(); private final Map, ScheduledFuture> pendingTypes = new ConcurrentHashMap<>(); private final Map, ScheduledFuture> pendingDataTypeScans = new ConcurrentHashMap<>(); + private final List retryDelays; + /// The programs whose unpushed edits wait for an automatic retry. + private final Map> pendingRetries = new ConcurrentHashMap<>(); + /// How many retries have failed in a row, per program, which picks the next wait. + private final Map failedRetries = new ConcurrentHashMap<>(); + // The outage state below is only touched on the scheduler thread. + /// Whether the analyst has been told that pushes are failing. + private boolean outageReported; + /// Edits the retries have pushed since the outage was reported. + private int pushedSinceOutage; /// A debounce key. One service handles every open program, and two programs can have functions at /// the same address (two versions of one binary, or any two PEs with code at `0x140001000`), so an @@ -74,9 +93,16 @@ private record InProgram(Program program, K key) {} public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService, BiConsumer statusNotifier) { + this(revengService, loggingService, statusNotifier, RETRY_DELAYS); + } + + /// @param retryDelays the waits before each automatic retry; the last one repeats + public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService, + BiConsumer statusNotifier, List retryDelays) { this.revengService = revengService; this.loggingService = loggingService; this.statusNotifier = statusNotifier; + this.retryDelays = List.copyOf(retryDelays); this.scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> { var thread = new Thread(runnable, "RevEng.AI-LocalEditSync"); thread.setDaemon(true); @@ -99,6 +125,18 @@ public void detach(Program program) { if (listener != null) { program.removeListener(listener); } + // Its edits stay marked, so the next sync of it still sends them. + var retry = pendingRetries.remove(program); + if (retry != null) { + retry.cancel(false); + } + failedRetries.remove(program); + scheduler.execute(() -> { + if (pendingRetries.isEmpty()) { + outageReported = false; + pushedSinceOutage = 0; + } + }); } public void dispose() { @@ -220,21 +258,21 @@ private void scheduleRename(Program program, Address entryPoint) { synchronized (dueRenames) { dueRenames.computeIfAbsent(program, p -> new LinkedHashSet<>()).add(entryPoint); } - schedule(pendingRenames, program, () -> pushRenames(program)); + schedule(pendingRenames, program, program, () -> pushRenames(program)); } private void scheduleTypes(Program program, Address entryPoint) { UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, entryPoint); - schedule(pendingTypes, new InProgram<>(program, entryPoint), () -> pushTypes(program, entryPoint)); + schedule(pendingTypes, new InProgram<>(program, entryPoint), program, () -> pushTypes(program, entryPoint)); } private void scheduleDataTypeScan(Program program, DataType dataType) { var typeName = dataType.getName(); - schedule(pendingDataTypeScans, new InProgram<>(program, dataType.getPathName()), + schedule(pendingDataTypeScans, new InProgram<>(program, dataType.getPathName()), program, () -> pushFunctionsReferencingType(program, typeName)); } - private void schedule(Map> pending, K key, Runnable task) { + private void schedule(Map> pending, K key, Program program, Runnable task) { var existing = pending.get(key); if (existing != null) { existing.cancel(false); @@ -245,7 +283,7 @@ private void schedule(Map> pending, K key, Runnable ta try { task.run(); } catch (Exception e) { - reportFailure("RevEng.AI: could not push a local edit to the portal", e); + onPushFailed(program, "Could not push a local edit", e); } }, DEBOUNCE_MS, TimeUnit.MILLISECONDS)); } @@ -298,14 +336,14 @@ private void pushRenames(Program program) { } // Every one, including those that were gone or unknown to the portal: nothing is left to send. entryPoints.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.NAME, entryPoint)); + onPushSucceeded(program); } catch (Exception e) { // Marked again in case a push that started earlier succeeded and cleared them meanwhile. entryPoints.forEach(entryPoint -> UnpushedEdits.mark(program, UnpushedEdits.Kind.NAME, entryPoint)); var what = functions.size() == 1 ? "the rename of \"%s\"".formatted(functions.get(0).getName()) : "the renames of %d functions".formatted(functions.size()); - reportFailure("RevEng.AI: could not push %s to the portal; it will be sent on the next Sync with portal" - .formatted(what), e); + onPushFailed(program, "Could not push " + what, e); } } @@ -328,19 +366,97 @@ private void pushTypes(Program program, Address entryPoint) { } } UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, entryPoint); + onPushSucceeded(program); } catch (Exception e) { UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, entryPoint); - reportFailure("RevEng.AI: could not push the types of \"%s\" to the portal; they will be sent on the next Sync with portal" - .formatted(function.getName()), e); + onPushFailed(program, "Could not push the types of \"%s\"".formatted(function.getName()), e); } }); } - private void reportFailure(String message, Exception e) { - var reported = "%s: %s".formatted(message, e.getMessage() != null ? e.getMessage() : e); - Msg.warn(this, reported, e); - loggingService.warn(reported); - statusNotifier.accept(reported, true); + // Everything from here on runs on the scheduler thread. + + /// Log the failure to Ghidra's console, tell the analyst once per outage, and retry the program's + /// unpushed edits later. + private void onPushFailed(Program program, String detail, Exception e) { + Msg.warn(this, "%s: %s".formatted(detail, reasonOf(e)), e); + if (!outageReported) { + outageReported = true; + announce(("RevEng.AI: could not push local edits to the portal (%s). They are kept and will be " + + "retried automatically.").formatted(reasonOf(e)), true); + } + scheduleRetry(program, retryDelays.get(Math.min(failedRetries.getOrDefault(program, 0), retryDelays.size() - 1))); + } + + /// A push got through, so the portal is likely back: retry the program's other edits now rather + /// than at the end of the current wait. + private void onPushSucceeded(Program program) { + var waiting = pendingRetries.get(program); + if (waiting != null && waiting.cancel(false)) { + pendingRetries.remove(program); + scheduleRetry(program, Duration.ZERO); + } + } + + private void scheduleRetry(Program program, Duration delay) { + if (pendingRetries.containsKey(program) || !listeners.containsKey(program)) { + return; + } + pendingRetries.put(program, scheduler.schedule(() -> retry(program), delay.toMillis(), TimeUnit.MILLISECONDS)); + } + + private void retry(Program program) { + pendingRetries.remove(program); + var analysedProgram = revengService.getAnalysedProgram(program); + if (!listeners.containsKey(program) || analysedProgram.isEmpty()) { + failedRetries.remove(program); + endOutageIfOver(); + return; + } + GhidraRevengService.LocalEditFlush flush; + try { + flush = revengService.pushUnpushedEdits(analysedProgram.get()); + } catch (Exception e) { + flush = new GhidraRevengService.LocalEditFlush(0, 1, e); + } + pushedSinceOutage += flush.pushed(); + if (flush.failed() > 0) { + Msg.warn(this, "Retry of %d unpushed local edit(s) failed: %s" + .formatted(flush.failed(), reasonOf(flush.error())), flush.error()); + int failed = failedRetries.merge(program, 1, Integer::sum); + scheduleRetry(program, retryDelays.get(Math.min(failed, retryDelays.size() - 1))); + return; + } + failedRetries.remove(program); + endOutageIfOver(); + } + + /// Once no program has edits waiting, say so, once. + private void endOutageIfOver() { + if (!outageReported || !pendingRetries.isEmpty()) { + return; + } + outageReported = false; + announce(pushedSinceOutage > 0 + ? "RevEng.AI: pushed %d local edit(s) that had failed earlier.".formatted(pushedSinceOutage) + : "RevEng.AI: local edits are reaching the portal again.", false); + pushedSinceOutage = 0; + } + + private void announce(String message, boolean warning) { + if (warning) { + loggingService.warn(message); + } else { + loggingService.info(message); + } + statusNotifier.accept(message, warning); + } + + private static String reasonOf(@Nullable Exception e) { + if (e == null) { + return "unknown error"; + } + return e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); } private void withAnalysedFunction(Program program, Address entryPoint, diff --git a/src/test/java/ai/reveng/UnpushedLocalEditsTest.java b/src/test/java/ai/reveng/UnpushedLocalEditsTest.java index b09e79a6..9513221d 100644 --- a/src/test/java/ai/reveng/UnpushedLocalEditsTest.java +++ b/src/test/java/ai/reveng/UnpushedLocalEditsTest.java @@ -23,10 +23,12 @@ import org.junit.Before; import org.junit.Test; +import java.time.Duration; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -44,6 +46,7 @@ private static class FlakyApi extends UnimplementedAPI { volatile boolean renameThrows; volatile boolean renameSkipped; volatile boolean typesThrow; + final AtomicInteger renameAttempts = new AtomicInteger(); @Override public AnalysisStatus status(AnalysisID analysisID) { @@ -71,6 +74,7 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID @Override public long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + renameAttempts.incrementAndGet(); if (renameThrows) { throw new ApiException(503, "Service Unavailable"); } @@ -95,6 +99,7 @@ private static class RecordingLog implements ReaiLoggingService { private final FlakyApi api = new FlakyApi(); private final RecordingLog log = new RecordingLog(); private final List statusWarnings = new CopyOnWriteArrayList<>(); + private final List statusInfos = new CopyOnWriteArrayList<>(); private GhidraRevengService service; private Function function; private Program program; @@ -118,12 +123,14 @@ public void disposeSync() { } } + /// With retries far enough off that they never run during the test. private void listen() { - sync = new LocalEditSyncService(service, log, (message, warning) -> { - if (warning) { - statusWarnings.add(message); - } - }); + listen(List.of(Duration.ofHours(1))); + } + + private void listen(List retryDelays) { + sync = new LocalEditSyncService(service, log, + (message, warning) -> (warning ? statusWarnings : statusInfos).add(message), retryDelays); sync.attach(program); } @@ -147,7 +154,7 @@ public void aFailedRenameIsReportedAndSentByTheNextSync() throws Exception { rename("mine"); waitForCondition(() -> !statusWarnings.isEmpty(), "the failed push should reach the status bar"); - assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("mine")); + assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("retried automatically")); assertTrue(log.warnings.contains(statusWarnings.get(0))); assertTrue(api.renamed.isEmpty()); assertTrue(nameMarked()); @@ -162,6 +169,28 @@ public void aFailedRenameIsReportedAndSentByTheNextSync() throws Exception { assertFalse(nameMarked()); } + @Test + public void failuresAreReportedOnceAndRetriedUntilTheyGoUp() throws Exception { + listen(List.of(Duration.ofMillis(300))); + api.renameThrows = true; + rename("first"); + waitForCondition(() -> !statusWarnings.isEmpty(), "the outage should be reported"); + rename("second"); + + // The second rename's own push, then at least one automatic retry, all failing. + waitForCondition(() -> api.renameAttempts.get() >= 3, "the failed edit should be retried"); + assertEquals("one report however many pushes fail: " + statusWarnings, 1, statusWarnings.size()); + assertEquals(1, log.warnings.size()); + assertTrue(nameMarked()); + + api.renameThrows = false; + waitForCondition(() -> !statusInfos.isEmpty(), "the recovery should be reported"); + assertEquals(Map.of(FUNCTION_ID, "second"), api.renamed); + assertFalse(nameMarked()); + assertTrue(statusInfos.get(0), statusInfos.get(0).contains("pushed 1 local edit")); + assertEquals(1, statusWarnings.size()); + } + @Test public void aRenameThePortalSkippedCountsAsFailed() throws Exception { listen(); From c9776ad64494d42ffb83885fc493e8019ec1c22d Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:52:08 +0000 Subject: [PATCH 31/76] Stop retrying edits the portal will never take, and isolate them A failed push is now classified: no answer, a timeout, 5xx, 408 or 429 may pass and is retried with backoff; 401/403 means the API key was refused; any other 4xx, a rename the portal did not apply, or a local failure is final. When the portal turns a batch down, the marked edits are sent one at a time, so the ones it takes go up and only the rejected ones stay marked. Each rejected edit is reported once and not retried automatically. A refused key is reported once and retrying resumes when a push next succeeds. Rejected edits stay marked for the next Sync with portal. --- .../services/api/GhidraRevengService.java | 155 ++++++++++++---- .../ghidra/core/services/api/PushFailure.java | 44 +++++ .../services/sync/LocalEditSyncService.java | 123 +++++++++--- .../ai/reveng/RejectedLocalEditsTest.java | 175 ++++++++++++++++++ .../core/services/api/PushFailureTest.java | 47 +++++ 5 files changed, 480 insertions(+), 64 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailure.java create mode 100644 src/test/java/ai/reveng/RejectedLocalEditsTest.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailureTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 914d8279..86cac0c3 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -456,10 +456,26 @@ public record SyncSummary( int signatureConflicts ) {} - /// @param pushed the unpushed local edits that reached the portal this time - /// @param failed the ones that failed again and are still marked - /// @param error why the last of those failed, or null when none did - public record LocalEditFlush(int pushed, int failed, @Nullable Exception error) {} + /// What sending the unpushed local edits achieved. Every edit that failed is still marked. + /// + /// @param pushed the edits that reached the portal this time + /// @param unsent the edits that failed for a reason that may pass — see {@link PushFailure} + /// @param unsentError why the last of those failed, or null when none did + /// @param rejected the edits the portal turned down, or that failed for good, one entry each + public record LocalEditFlush(int pushed, int unsent, @Nullable Exception unsentError, + List rejected) { + public int failed() { + return unsent + rejected.size(); + } + } + + /// @param edit which edit, for the log: "rename of \"foo\" at 00401000" + /// @param error why it failed + public record RejectedEdit(String edit, Exception error) { + public PushFailure failure() { + return PushFailure.of(error); + } + } private record PendingNamePush(TypedApiInterface.FunctionID functionID, String newName, String newMangledName) {} private record InvalidRemoteName(Function function, TypedApiInterface.FunctionID functionID, String remoteName) {} @@ -482,8 +498,12 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni if (flush.pushed() > 0) { log.info("Pushed %d local edit(s) that had not reached the RevEng.AI portal".formatted(flush.pushed())); } - if (flush.failed() > 0) { - log.warn("Could not push %d local edit(s) to the RevEng.AI portal: %s".formatted(flush.failed(), flush.error())); + if (flush.unsent() > 0) { + log.warn("Could not push %d local edit(s) to the RevEng.AI portal: %s" + .formatted(flush.unsent(), flush.unsentError())); + } + for (RejectedEdit rejected : flush.rejected()) { + log.warn("The RevEng.AI portal did not take the %s: %s".formatted(rejected.edit(), rejected.error())); } Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() .collect(Collectors.toMap(FunctionInfo::functionID, fi -> fi, (a, b) -> a)); @@ -609,53 +629,106 @@ public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMoni /// function that is gone, or not part of the analysis, has nothing left to push and is unmarked. /// Failures are returned rather than logged, so a caller retrying in the background can report an /// outage once instead of once per attempt. + /// + /// The renames go up as one batch and the type edits through one type pass. When the portal + /// turns a batch down, the edits are sent again one at a time, so a single edit it will never + /// take does not keep the others from going up. public LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram) { var program = analysedProgram.program(); - int pushed = 0; - int failed = 0; - Exception error = null; - List

nameMarks = UnpushedEdits.marked(program, UnpushedEdits.Kind.NAME); - List renamed = new ArrayList<>(); - for (Address entryPoint : nameMarks) { - var function = program.getFunctionManager().getFunctionAt(entryPoint); - if (function != null) { - renamed.add(function); + var flush = new FlushTally(); + Map renamed = markedFunctions(program, UnpushedEdits.Kind.NAME); + sendIsolatingRejections(program, UnpushedEdits.Kind.NAME, renamed, flush, + functions -> pushFunctionRenames(analysedProgram, functions).size(), + function -> "rename of \"%s\" at %s".formatted(function.getName(), function.getEntryPoint())); + + Map retyped = markedFunctions(program, UnpushedEdits.Kind.TYPES); + // A function the analysis does not know has no types on the portal to update. + retyped.keySet().removeIf(function -> { + boolean unknown = analysedProgram.getIDForFunction(function).isEmpty(); + if (unknown) { + UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint()); } - } - if (!nameMarks.isEmpty()) { - try { - // One request for them all, as the reactive push sends them. - pushed += pushFunctionRenames(analysedProgram, renamed).size(); - nameMarks.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.NAME, entryPoint)); - } catch (Exception e) { - failed += renamed.size(); - error = e; + return unknown; + }); + // A signature the portal has no extraction for is declined, but its types went up, which is + // all this push can do. + sendIsolatingRejections(program, UnpushedEdits.Kind.TYPES, retyped, flush, + functions -> { + pushFunctionTypes(analysedProgram, functions); + return functions.size(); + }, + function -> "types of \"%s\" at %s".formatted(function.getName(), function.getEntryPoint())); + return new LocalEditFlush(flush.pushed, flush.unsent, flush.unsentError, List.copyOf(flush.rejected)); + } + + private static final class FlushTally { + int pushed; + int unsent; + Exception unsentError; + final List rejected = new ArrayList<>(); + } + + @FunctionalInterface + private interface EditSender { + /// Send the edits of these functions and answer with how many went up. + int send(List functions) throws Exception; + } + + /// The functions with a `kind` edit marked, each with the address it is marked at. A mark whose + /// function is gone is cleared, since nothing is left to send. + private static Map markedFunctions(Program program, UnpushedEdits.Kind kind) { + Map marked = new LinkedHashMap<>(); + for (Address entryPoint : UnpushedEdits.marked(program, kind)) { + var function = program.getFunctionManager().getFunctionAt(entryPoint); + if (function == null) { + UnpushedEdits.clear(program, kind, entryPoint); + } else { + marked.put(function, entryPoint); } } + return marked; + } - List
typeMarks = UnpushedEdits.marked(program, UnpushedEdits.Kind.TYPES); - List typeEdits = new ArrayList<>(); - for (Address entryPoint : typeMarks) { - var function = program.getFunctionManager().getFunctionAt(entryPoint); - if (function != null && analysedProgram.getIDForFunction(function).isPresent()) { - typeEdits.add(function); + /// Send `marked` as one batch and clear the marks of what went up. When the portal turns the + /// batch down, send each edit on its own to find the ones it will not take. A failure that may + /// pass leaves the rest for a later attempt instead, since sending them one by one would only + /// fail the same way more often. + private static void sendIsolatingRejections(Program program, UnpushedEdits.Kind kind, + Map marked, FlushTally flush, + EditSender sender, + java.util.function.Function describe) { + if (marked.isEmpty()) { + return; + } + List functions = List.copyOf(marked.keySet()); + try { + flush.pushed += sender.send(functions); + marked.values().forEach(entryPoint -> UnpushedEdits.clear(program, kind, entryPoint)); + return; + } catch (Exception e) { + if (PushFailure.of(e) != PushFailure.REJECTED || functions.size() == 1) { + record(flush, functions, e, describe); + return; } } - if (!typeMarks.isEmpty()) { + for (Function function : functions) { try { - // One type pass for them all, as in the back-fill below. A signature the portal has no - // extraction for is declined, but its types went up, which is all this push can do. - if (!typeEdits.isEmpty()) { - pushFunctionTypes(analysedProgram, typeEdits); - } - pushed += typeEdits.size(); - typeMarks.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, entryPoint)); + flush.pushed += sender.send(List.of(function)); + UnpushedEdits.clear(program, kind, marked.get(function)); } catch (Exception e) { - failed += typeEdits.size(); - error = e; + record(flush, List.of(function), e, describe); } } - return new LocalEditFlush(pushed, failed, error); + } + + private static void record(FlushTally flush, List functions, Exception e, + java.util.function.Function describe) { + if (PushFailure.of(e) == PushFailure.TRANSIENT) { + flush.unsent += functions.size(); + flush.unsentError = e; + } else { + functions.forEach(function -> flush.rejected.add(new RejectedEdit(describe.apply(function), e))); + } } /// Apply the signatures — and with them the data types they name — that the portal holds for this diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailure.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailure.java new file mode 100644 index 00000000..391e3997 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailure.java @@ -0,0 +1,44 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; + +import java.io.IOException; + +/// Why pushing a local edit failed, as far as it decides whether trying again can help. +public enum PushFailure { + /// The portal could not be reached or could not answer right now: no connection, a timeout, a + /// 5xx, a 408 or a 429. The same push can succeed later. + TRANSIENT, + /// The portal refused the credentials (401 or 403). Nothing succeeds until the API key is fixed. + AUTH, + /// The portal turned this particular edit down — another 4xx, or a rename it accepted but did not + /// apply — or the plugin failed to build the request. Sending it again gets the same answer. + REJECTED; + + /// Classify a failure by the first HTTP status or I/O error in its cause chain. The typed API + /// wraps some {@link ApiException}s in a plain RuntimeException, so the chain is searched rather + /// than the exception itself. + public static PushFailure of(Throwable failure) { + boolean unanswered = false; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof IOException) { + return TRANSIENT; + } + if (cause instanceof ApiException api) { + int code = api.getCode(); + if (code == 0) { + // The client reports a request that never got an answer as code 0, usually + // with the I/O error as its cause. + unanswered = true; + } else if (code == 401 || code == 403) { + return AUTH; + } else if (code == 408 || code == 429 || code >= 500) { + return TRANSIENT; + } else { + return REJECTED; + } + } + } + return unanswered ? TRANSIENT : REJECTED; + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index 0fe346fa..e189b7f6 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -3,6 +3,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraDataTypeEncoder; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService.AnalysedProgram; +import ai.reveng.toolkit.ghidra.core.services.api.PushFailure; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ghidra.framework.model.DomainObjectChangeRecord; import ghidra.framework.model.DomainObjectListener; @@ -49,11 +50,20 @@ * ever writes {@link SourceType#ANALYSIS} names, and only {@link SourceType#USER_DEFINED} ones are * pushed, so an analyst's rename is pushed even when it lands in the middle of a sync. * - *

A push that fails leaves the edit marked in {@link UnpushedEdits} until a push succeeds. The - * marked edits of that program are then retried in the background, backing off from - * {@link #RETRY_DELAYS}, and "Sync with portal" sends them too. A failing portal is reported once, - * in the plugin log and the status bar, however many pushes fail, and once more when the edits have - * gone up; each failure is logged only to Ghidra's console. + *

A push that fails leaves the edit marked in {@link UnpushedEdits} until a push succeeds, and + * "Sync with portal" sends whatever is marked. What happens in between depends on the failure — see + * {@link PushFailure}: + *

    + *
  • When the portal could not be reached, the program's marked edits are retried in the background, + * backing off through {@link #RETRY_DELAYS}. The outage is reported once, in the plugin log and the + * status bar, however many pushes fail, and once more when the edits have gone up.
  • + *
  • When the portal turned an edit down, the marked edits are sent again at once, one at a time + * where a batch was refused, so the ones it does take go up. Each edit it will not take is reported + * once and not retried automatically.
  • + *
  • When the portal refused the API key, that is reported once and nothing is retried until a + * push succeeds again.
  • + *
+ * Each failure is also logged to Ghidra's console. */ public class LocalEditSyncService { @@ -85,6 +95,12 @@ public class LocalEditSyncService { private boolean outageReported; /// Edits the retries have pushed since the outage was reported. private int pushedSinceOutage; + /// Whether the analyst has been told the API key was refused; cleared when a push succeeds. + private boolean authReported; + /// The programs whose retries stopped on a refused API key, to resume when a push succeeds. + private final Set stoppedOnAuth = ConcurrentHashMap.newKeySet(); + /// The rejected edits already reported, per program, so each is reported once. + private final Map> reportedRejections = new ConcurrentHashMap<>(); /// A debounce key. One service handles every open program, and two programs can have functions at /// the same address (two versions of one binary, or any two PEs with code at `0x140001000`), so an @@ -131,6 +147,8 @@ public void detach(Program program) { retry.cancel(false); } failedRetries.remove(program); + stoppedOnAuth.remove(program); + reportedRejections.remove(program); scheduler.execute(() -> { if (pendingRetries.isEmpty()) { outageReported = false; @@ -376,28 +394,36 @@ private void pushTypes(Program program, Address entryPoint) { // Everything from here on runs on the scheduler thread. - /// Log the failure to Ghidra's console, tell the analyst once per outage, and retry the program's - /// unpushed edits later. + /// Log the failure to Ghidra's console and decide what comes next: a retry after a wait when the + /// portal could not be reached, and otherwise a retry straight away, which sends the marked edits + /// one at a time where needed and finds out which ones the portal will not take. private void onPushFailed(Program program, String detail, Exception e) { Msg.warn(this, "%s: %s".formatted(detail, reasonOf(e)), e); - if (!outageReported) { - outageReported = true; - announce(("RevEng.AI: could not push local edits to the portal (%s). They are kept and will be " - + "retried automatically.").formatted(reasonOf(e)), true); + if (PushFailure.of(e) == PushFailure.TRANSIENT) { + reportOutage(e); + scheduleRetry(program, nextDelay(program)); + } else { + scheduleRetry(program, Duration.ZERO); } - scheduleRetry(program, retryDelays.get(Math.min(failedRetries.getOrDefault(program, 0), retryDelays.size() - 1))); } - /// A push got through, so the portal is likely back: retry the program's other edits now rather - /// than at the end of the current wait. + /// A push got through, so the portal is likely back and the key good: retry the program's other + /// edits now rather than at the end of the current wait. private void onPushSucceeded(Program program) { + authReported = false; var waiting = pendingRetries.get(program); if (waiting != null && waiting.cancel(false)) { pendingRetries.remove(program); scheduleRetry(program, Duration.ZERO); + } else if (stoppedOnAuth.remove(program)) { + scheduleRetry(program, Duration.ZERO); } } + private Duration nextDelay(Program program) { + return retryDelays.get(Math.min(failedRetries.getOrDefault(program, 0), retryDelays.size() - 1)); + } + private void scheduleRetry(Program program, Duration delay) { if (pendingRetries.containsKey(program) || !listeners.containsKey(program)) { return; @@ -417,29 +443,80 @@ private void retry(Program program) { try { flush = revengService.pushUnpushedEdits(analysedProgram.get()); } catch (Exception e) { - flush = new GhidraRevengService.LocalEditFlush(0, 1, e); + flush = PushFailure.of(e) == PushFailure.TRANSIENT + ? new GhidraRevengService.LocalEditFlush(0, 1, e, List.of()) + : new GhidraRevengService.LocalEditFlush(0, 0, null, + List.of(new GhidraRevengService.RejectedEdit("local edits", e))); } pushedSinceOutage += flush.pushed(); - if (flush.failed() > 0) { + if (flush.pushed() > 0) { + authReported = false; + } + if (flush.unsent() > 0) { Msg.warn(this, "Retry of %d unpushed local edit(s) failed: %s" - .formatted(flush.failed(), reasonOf(flush.error())), flush.error()); - int failed = failedRetries.merge(program, 1, Integer::sum); - scheduleRetry(program, retryDelays.get(Math.min(failed, retryDelays.size() - 1))); + .formatted(flush.unsent(), reasonOf(flush.unsentError())), flush.unsentError()); + reportOutage(flush.unsentError()); + failedRetries.merge(program, 1, Integer::sum); + scheduleRetry(program, nextDelay(program)); return; } failedRetries.remove(program); + reportRejections(program, flush.rejected()); endOutageIfOver(); } - /// Once no program has edits waiting, say so, once. + private void reportOutage(Exception e) { + if (!outageReported) { + outageReported = true; + announce(("RevEng.AI: could not push local edits to the portal (%s). They are kept and will be " + + "retried automatically.").formatted(reasonOf(e)), true); + } + } + + /// Report the edits that will not be retried automatically: a refused API key once until a push + /// succeeds, and each edit the portal turned down once. + private void reportRejections(Program program, List rejected) { + var refusedKey = rejected.stream().filter(edit -> edit.failure() == PushFailure.AUTH).findFirst(); + if (refusedKey.isPresent()) { + stoppedOnAuth.add(program); + if (!authReported) { + authReported = true; + announce(("RevEng.AI: the portal refused the API key (%s), so local edits are not being pushed. " + + "Check the key in the RevEng.AI settings; the edits are kept and will be sent on the next " + + "Sync with portal.").formatted(reasonOf(refusedKey.get().error())), true); + } + } + List turnedDown = rejected.stream() + .filter(edit -> edit.failure() != PushFailure.AUTH) + .toList(); + // Every marked edit was just sent, so this is the whole set the portal will not take; one that + // has since gone up drops out of it. + Set reported = reportedRejections.computeIfAbsent(program, p -> ConcurrentHashMap.newKeySet()); + Set current = new LinkedHashSet<>(); + turnedDown.forEach(edit -> current.add(edit.edit())); + reported.retainAll(current); + var fresh = turnedDown.stream().filter(edit -> !reported.contains(edit.edit())).toList(); + if (fresh.isEmpty()) { + return; + } + for (var edit : fresh) { + reported.add(edit.edit()); + loggingService.warn("RevEng.AI: the portal did not take the %s: %s".formatted(edit.edit(), reasonOf(edit.error()))); + } + announce(("RevEng.AI: the portal did not take %d local edit(s) (%s). They will not be retried " + + "automatically; the RevEng.AI log lists them, and they are kept for the next Sync with portal.") + .formatted(fresh.size(), reasonOf(fresh.get(0).error())), true); + } + + /// Once no program has edits waiting for a retry, say that the outage is over, once. private void endOutageIfOver() { if (!outageReported || !pendingRetries.isEmpty()) { return; } outageReported = false; - announce(pushedSinceOutage > 0 - ? "RevEng.AI: pushed %d local edit(s) that had failed earlier.".formatted(pushedSinceOutage) - : "RevEng.AI: local edits are reaching the portal again.", false); + if (pushedSinceOutage > 0) { + announce("RevEng.AI: pushed %d local edit(s) that had failed earlier.".formatted(pushedSinceOutage), false); + } pushedSinceOutage = 0; } diff --git a/src/test/java/ai/reveng/RejectedLocalEditsTest.java b/src/test/java/ai/reveng/RejectedLocalEditsTest.java new file mode 100644 index 00000000..e603c3cf --- /dev/null +++ b/src/test/java/ai/reveng/RejectedLocalEditsTest.java @@ -0,0 +1,175 @@ +package ai.reveng; + +import ai.reveng.invoker.ApiException; +import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/// Failures that sending again cannot fix: an edit the portal turns down, and a refused API key. +public class RejectedLocalEditsTest extends RevEngMockableHeadedIntegrationTest { + + /// Two functions, at 0x4000 (id 1) and 0x4100 (id 2). + private static class PickyApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + final AtomicInteger renameRequests = new AtomicInteger(); + /// The portal validates the whole request, so one name it refuses fails the batch. + volatile String refusedPrefix = "bad_"; + volatile boolean keyRefused; + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of( + new FunctionInfo(new FunctionID(1), "FUN_00004000", "FUN_00004000", 0x4000L, 0x100), + new FunctionInfo(new FunctionID(2), "FUN_00004100", "FUN_00004100", 0x4100L, 0x100)); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + renameRequests.incrementAndGet(); + if (keyRefused) { + throw new ApiException(401, "Unauthorized"); + } + if (request.getFunctions().stream().anyMatch(item -> item.getNewName().startsWith(refusedPrefix))) { + throw new ApiException(422, "Unprocessable Entity"); + } + request.getFunctions().forEach(item -> renamed.put(item.getFunctionId(), item.getNewName())); + return request.getFunctions().size(); + } + } + + private static class RecordingLog implements ReaiLoggingService { + final List warnings = new CopyOnWriteArrayList<>(); + @Override public void info(String message) {} + @Override public void warn(String message) { warnings.add(message); } + @Override public void error(String message) {} + } + + private final PickyApi api = new PickyApi(); + private final RecordingLog log = new RecordingLog(); + private final List statusWarnings = new CopyOnWriteArrayList<>(); + private Program program; + private Function first; + private Function second; + private LocalEditSyncService sync; + + @Before + public void analyse() throws Exception { + var service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("code", "0x4000", 0x200); + first = builder.createEmptyFunction("FUN_00004000", "0x4000", 0x100, new IntegerDataType()); + second = builder.createEmptyFunction("FUN_00004100", "0x4100", 0x100, new IntegerDataType()); + program = builder.getProgram(); + var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + // A retry after a wait only happens when the portal cannot be reached, which these tests + // never do; one that came anyway would show up as an extra request. + sync = new LocalEditSyncService(service, log, (message, warning) -> { + if (warning) { + statusWarnings.add(message); + } + }, List.of(Duration.ofHours(1))); + sync.attach(program); + } + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + private void rename(Function function, String newName) throws Exception { + program.withTransaction("rename", () -> function.setName(newName, SourceType.USER_DEFINED)); + program.flushEvents(); + } + + private boolean marked(Function function) { + return UnpushedEdits.isMarked(program, UnpushedEdits.Kind.NAME, function.getEntryPoint()); + } + + @Test + public void anEditThePortalTurnsDownDoesNotHoldBackTheOthers() throws Exception { + // Both in one debounce window, so they go up as one batch, which the portal refuses. + rename(first, "good_one"); + rename(second, "bad_two"); + + waitForCondition(() -> !statusWarnings.isEmpty(), "the rejected edit should be reported"); + assertEquals(Map.of(1L, "good_one"), api.renamed); + assertFalse("the accepted rename is no longer waiting", marked(first)); + assertTrue("the rejected rename stays for the next sync", marked(second)); + assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("will not be retried")); + assertTrue(log.warnings.stream().anyMatch(warning -> warning.contains("\"bad_two\""))); + + // Nothing is sent after that: a rejected edit is not retried automatically. + int requests = api.renameRequests.get(); + Thread.sleep(1_000); + assertEquals(requests, api.renameRequests.get()); + assertEquals(1, statusWarnings.size()); + } + + @Test + public void anEditTurnedDownAgainIsNotReportedAgain() throws Exception { + rename(second, "bad_two"); + waitForCondition(() -> !statusWarnings.isEmpty(), "the rejected edit should be reported"); + + // Another rejected edit to the same function sends both again; only the new one is news. + rename(first, "bad_one"); + waitForCondition(() -> statusWarnings.size() == 2, "the second rejected edit should be reported"); + assertTrue(statusWarnings.get(1), statusWarnings.get(1).contains("did not take 1 local edit")); + } + + @Test + public void aRefusedKeyIsReportedOnceAndResumesWhenAPushSucceeds() throws Exception { + api.keyRefused = true; + rename(first, "first_name"); + waitForCondition(() -> !statusWarnings.isEmpty(), "the refused key should be reported"); + assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("API key")); + + // Each rename is tried once by itself and once by the retry that follows its failure. + rename(first, "first_name_again"); + waitForCondition(() -> api.renameRequests.get() >= 4, "the second rename should be tried"); + Thread.sleep(500); + assertEquals("one report while the key is refused: " + statusWarnings, 1, statusWarnings.size()); + int requestsWhileRefused = api.renameRequests.get(); + Thread.sleep(1_000); + assertEquals("no retries while the key is refused", requestsWhileRefused, api.renameRequests.get()); + + api.keyRefused = false; + rename(second, "second_name"); + waitForCondition(() -> api.renamed.size() == 2, "the earlier rename should follow the one that got through"); + assertEquals(Map.of(1L, "first_name_again", 2L, "second_name"), api.renamed); + assertFalse(marked(first)); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailureTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailureTest.java new file mode 100644 index 00000000..8b44eb02 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailureTest.java @@ -0,0 +1,47 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import org.junit.Test; + +import java.net.SocketTimeoutException; + +import static org.junit.Assert.assertEquals; + +public class PushFailureTest { + + private static ApiException status(int code) { + return new ApiException(code, "status " + code); + } + + @Test + public void noAnswerOrAServerSideErrorMayPass() { + assertEquals(PushFailure.TRANSIENT, PushFailure.of(new ApiException(new SocketTimeoutException("timeout")))); + assertEquals(PushFailure.TRANSIENT, PushFailure.of(new ApiException("no answer"))); + for (int code : new int[] {408, 429, 500, 502, 503, 504}) { + assertEquals("status " + code, PushFailure.TRANSIENT, PushFailure.of(status(code))); + } + } + + @Test + public void aRefusedKeyNeedsTheAnalyst() { + assertEquals(PushFailure.AUTH, PushFailure.of(status(401))); + assertEquals(PushFailure.AUTH, PushFailure.of(status(403))); + } + + @Test + public void anyOtherClientErrorOrALocalFailureIsFinal() { + for (int code : new int[] {400, 404, 409, 422}) { + assertEquals("status " + code, PushFailure.REJECTED, PushFailure.of(status(code))); + } + assertEquals(PushFailure.REJECTED, PushFailure.of(new IllegalStateException("renamed 0 of 1"))); + assertEquals(PushFailure.REJECTED, PushFailure.of(new IllegalArgumentException("cannot encode"))); + } + + /// The typed API wraps some failures in a plain RuntimeException. + @Test + public void looksThroughWrappers() { + assertEquals(PushFailure.REJECTED, PushFailure.of(new RuntimeException(status(404)))); + assertEquals(PushFailure.TRANSIENT, PushFailure.of(new RuntimeException(status(503)))); + assertEquals(PushFailure.AUTH, PushFailure.of(new RuntimeException(status(401)))); + } +} From 5508ae9ae9b1cdef4fb95a8563b4c196feb79824 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:55:55 +0000 Subject: [PATCH 32/76] Report the edits that go up once a refused API key works again A refused key now counts as an outage for reporting, so the edits pushed once the key works are reported like those pushed after the portal comes back. The sync summary no longer promises that failed edits wait only for the next sync. --- .../core/services/sync/LocalEditSyncService.java | 11 +++++++---- .../ghidra/plugins/BinarySimilarityPlugin.java | 2 +- src/test/java/ai/reveng/RejectedLocalEditsTest.java | 11 ++++++----- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index e189b7f6..f16f1786 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -91,7 +91,7 @@ public class LocalEditSyncService { /// How many retries have failed in a row, per program, which picks the next wait. private final Map failedRetries = new ConcurrentHashMap<>(); // The outage state below is only touched on the scheduler thread. - /// Whether the analyst has been told that pushes are failing. + /// Whether the analyst has been told that pushes are failing, for want of an answer or a key. private boolean outageReported; /// Edits the retries have pushed since the outage was reported. private int pushedSinceOutage; @@ -150,7 +150,7 @@ public void detach(Program program) { stoppedOnAuth.remove(program); reportedRejections.remove(program); scheduler.execute(() -> { - if (pendingRetries.isEmpty()) { + if (pendingRetries.isEmpty() && stoppedOnAuth.isEmpty()) { outageReported = false; pushedSinceOutage = 0; } @@ -481,6 +481,8 @@ private void reportRejections(Program program, List 0) { - text.append("\n%d local edit(s) still could not be pushed; they will be retried on the next sync." + text.append("\n%d local edit(s) still could not be pushed; the RevEng.AI log says why, and they are kept for the next sync." .formatted(summary.failedLocalEdits())); } if (summary.nameConflicts() > 0 || summary.signatureConflicts() > 0) { diff --git a/src/test/java/ai/reveng/RejectedLocalEditsTest.java b/src/test/java/ai/reveng/RejectedLocalEditsTest.java index e603c3cf..abe7f02f 100644 --- a/src/test/java/ai/reveng/RejectedLocalEditsTest.java +++ b/src/test/java/ai/reveng/RejectedLocalEditsTest.java @@ -78,6 +78,7 @@ private static class RecordingLog implements ReaiLoggingService { private final PickyApi api = new PickyApi(); private final RecordingLog log = new RecordingLog(); private final List statusWarnings = new CopyOnWriteArrayList<>(); + private final List statusInfos = new CopyOnWriteArrayList<>(); private Program program; private Function first; private Function second; @@ -95,11 +96,9 @@ public void analyse() throws Exception { service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); // A retry after a wait only happens when the portal cannot be reached, which these tests // never do; one that came anyway would show up as an extra request. - sync = new LocalEditSyncService(service, log, (message, warning) -> { - if (warning) { - statusWarnings.add(message); - } - }, List.of(Duration.ofHours(1))); + sync = new LocalEditSyncService(service, log, + (message, warning) -> (warning ? statusWarnings : statusInfos).add(message), + List.of(Duration.ofHours(1))); sync.attach(program); } @@ -171,5 +170,7 @@ public void aRefusedKeyIsReportedOnceAndResumesWhenAPushSucceeds() throws Except waitForCondition(() -> api.renamed.size() == 2, "the earlier rename should follow the one that got through"); assertEquals(Map.of(1L, "first_name_again", 2L, "second_name"), api.renamed); assertFalse(marked(first)); + waitForCondition(() -> !statusInfos.isEmpty(), "the edits that followed should be reported"); + assertTrue(statusInfos.get(0), statusInfos.get(0).contains("pushed 1 local edit")); } } From 76fee77c18075773a0a954d2d9a6b5c6a879205f Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:34:28 +0000 Subject: [PATCH 33/76] fix(ENG-4464): bound the auto-unstrip poller, make it stoppable and stop it on Detach The poller now ends on completion, failure, stopPolling (even mid-poll), a 30 minute cap, or a non-transient error. Transient errors (no answer, 5xx, 408, 429) back off and retry. Unexpected runtime errors are reported instead of killing the poller silently, and every way of giving up is shown in the RevEng.AI log and the status bar. Detach now stops the poller and detaches local edit sync before removing the association, and the post-unstrip sync re-checks that the program is still attached to the polled analysis. --- .../services/sync/AutoUnstripSyncService.java | 239 ++++++++++++++---- .../plugins/AnalysisManagementPlugin.java | 9 + .../java/ai/reveng/AutoUnstripSyncTest.java | 190 +++++++++++++- 3 files changed, 389 insertions(+), 49 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java index 4c518469..9c540605 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java @@ -3,12 +3,14 @@ import ai.reveng.invoker.ApiException; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService.AnalysedProgram; +import ai.reveng.toolkit.ghidra.core.services.api.PushFailure; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AutoUnstripStatus; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ghidra.util.Msg; import ghidra.util.task.TaskMonitor; +import java.time.Duration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; @@ -24,25 +26,43 @@ * pull and would otherwise only appear after a manual refresh. * *

Mirrors the IDA plugin's {@code AutoUnstripStatusService} + {@code AutoUnstripStatusCoordinator}: - * a background thread polls the status endpoint every {@link #POLL_INTERVAL_SECONDS} seconds and, on + * a background thread polls the status endpoint every {@link #DEFAULT_POLL_INTERVAL} and, on * completion, runs the same reconciliation the "Sync With Portal" action uses. + * + *

Polling stops when auto-unstrip completes or fails, when {@link #stopPolling} is called (even + * if a poll is running at that moment), after {@link #DEFAULT_MAX_POLL_DURATION}, or on an error a + * retry cannot fix. A transient error (no connection, timeout, 5xx) backs off and retries within + * that time limit. Every way of giving up is reported in the log and the status bar. */ public class AutoUnstripSyncService { - private static final long POLL_INTERVAL_SECONDS = 5; + public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5); + public static final Duration DEFAULT_MAX_POLL_DURATION = Duration.ofMinutes(30); + /// Longest wait between polls while the status endpoint keeps failing transiently. + private static final Duration MAX_BACKOFF = Duration.ofSeconds(60); private final GhidraRevengService revengService; private final ReaiLoggingService loggingService; /// Surfaces a progress message to the user (text, isWarning); wired to the tool status bar in the plugin. private final BiConsumer statusNotifier; + private final long pollIntervalMillis; + private final Duration maxPollDuration; private final ScheduledExecutorService scheduler; - private final Map> pollers = new ConcurrentHashMap<>(); + private final Map pollers = new ConcurrentHashMap<>(); public AutoUnstripSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService, BiConsumer statusNotifier) { + this(revengService, loggingService, statusNotifier, DEFAULT_POLL_INTERVAL, DEFAULT_MAX_POLL_DURATION); + } + + public AutoUnstripSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService, + BiConsumer statusNotifier, + Duration pollInterval, Duration maxPollDuration) { this.revengService = revengService; this.loggingService = loggingService; this.statusNotifier = statusNotifier; + this.pollIntervalMillis = pollInterval.toMillis(); + this.maxPollDuration = maxPollDuration; this.scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> { var thread = new Thread(runnable, "RevEng.AI-AutoUnstripSync"); thread.setDaemon(true); @@ -60,75 +80,198 @@ public AutoUnstripSyncService(GhidraRevengService revengService, ReaiLoggingServ * and is not re-synced. */ public void pollAndSync(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete) { - stopPolling(analysedProgram.analysisID()); - schedule(analysedProgram, resyncIfAlreadyComplete, true, 0); + var poller = new Poller(analysedProgram, resyncIfAlreadyComplete); + var previous = pollers.put(analysedProgram.analysisID(), poller); + if (previous != null) { + previous.cancel(); + } + poller.schedule(0); } - public void stopPolling(AnalysisID analysisID) { + /// Stop polling for the given analysis. A poll that is running right now neither reschedules + /// nor starts a sync afterwards. + /// + /// @return whether polling was still active for the analysis + public boolean stopPolling(AnalysisID analysisID) { var existing = pollers.remove(analysisID); if (existing != null) { - existing.cancel(false); + existing.cancel(); + return true; } + return false; } public void dispose() { - pollers.values().forEach(future -> future.cancel(false)); + pollers.values().forEach(Poller::cancel); pollers.clear(); scheduler.shutdownNow(); } - private void schedule(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete, - boolean firstPoll, long delaySeconds) { - var future = scheduler.schedule( - () -> poll(analysedProgram, resyncIfAlreadyComplete, firstPoll), - delaySeconds, TimeUnit.SECONDS); - pollers.put(analysedProgram.analysisID(), future); - } + /// One polling run for one analysis. Cancelling it is final, so a replaced or stopped run can + /// never put itself back on the schedule. + private final class Poller { + private final AnalysedProgram analysedProgram; + private final boolean resyncIfAlreadyComplete; + private final long startNanos = System.nanoTime(); + private boolean firstPoll = true; + private int consecutiveFailures = 0; + /// Guarded by {@code this} + private boolean cancelled = false; + /// Guarded by {@code this} + private ScheduledFuture future; + + Poller(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete) { + this.analysedProgram = analysedProgram; + this.resyncIfAlreadyComplete = resyncIfAlreadyComplete; + } + + synchronized void cancel() { + cancelled = true; + if (future != null) { + future.cancel(false); + } + } - private void poll(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete, boolean firstPoll) { - AutoUnstripStatus status; - try { - status = revengService.getAutoUnstripStatus(analysedProgram.analysisID()); - } catch (ApiException e) { - pollers.remove(analysedProgram.analysisID()); - loggingService.warn("Failed to poll auto-unstrip status: " + e.getMessage()); - return; + synchronized boolean isCancelled() { + return cancelled; } - switch (status) { - case COMPLETED -> { - pollers.remove(analysedProgram.analysisID()); - if (firstPoll && !resyncIfAlreadyComplete) { + synchronized void schedule(long delayMillis) { + if (!cancelled) { + future = scheduler.schedule(this::pollSafely, delayMillis, TimeUnit.MILLISECONDS); + } + } + + /// Leave the map, unless a newer run for the same analysis has already replaced this one. + void finish() { + pollers.remove(analysedProgram.analysisID(), this); + } + + private void pollSafely() { + try { + poll(); + } catch (RuntimeException e) { + finish(); + Msg.warn(AutoUnstripSyncService.this, "Auto-unstrip polling failed", e); + if (!isCancelled()) { + announce("RevEng.AI: stopped waiting for auto-unstrip after an unexpected error (%s). " + .formatted(e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName()) + + "Use Sync With Portal to pull the recovered names later.", true); + } + } + } + + private void poll() { + if (isCancelled()) { + return; + } + AutoUnstripStatus status; + try { + status = revengService.getAutoUnstripStatus(analysedProgram.analysisID()); + } catch (ApiException e) { + if (isCancelled()) { return; } - runSync(analysedProgram); + if (PushFailure.of(e) != PushFailure.TRANSIENT) { + finish(); + announce("RevEng.AI: stopped waiting for auto-unstrip, the status check failed (%s). " + .formatted(describe(e)) + "Use Sync With Portal to pull the recovered names later.", true); + return; + } + consecutiveFailures++; + if (consecutiveFailures == 1) { + // Logged once per outage, so a portal that is down for a while does not flood the log. + loggingService.warn("Checking the auto-unstrip status failed (%s); retrying with back-off." + .formatted(describe(e))); + } + rescheduleOrGiveUp(backoffMillis()); + return; + } + if (isCancelled()) { + return; } - case FAILED -> { - pollers.remove(analysedProgram.analysisID()); - announce("RevEng.AI auto-unstrip failed; recovered names were not synced.", true); + if (consecutiveFailures > 0) { + loggingService.info("Checking the auto-unstrip status works again."); + consecutiveFailures = 0; } - default -> { - if (firstPoll) { - announce("RevEng.AI: waiting for auto-unstrip to finish before syncing recovered " - + "function names and data types…", false); + + switch (status) { + case COMPLETED -> { + finish(); + if (firstPoll && !resyncIfAlreadyComplete) { + return; + } + runSync(); + } + case FAILED -> { + finish(); + if (!isCancelled()) { + announce("RevEng.AI auto-unstrip failed; recovered names were not synced.", true); + } + } + default -> { + if (firstPoll) { + announce("RevEng.AI: waiting for auto-unstrip to finish before syncing recovered " + + "function names and data types…", false); + } + firstPoll = false; + rescheduleOrGiveUp(pollIntervalMillis); } - schedule(analysedProgram, resyncIfAlreadyComplete, false, POLL_INTERVAL_SECONDS); } } - } - private void runSync(AnalysedProgram analysedProgram) { - announce("RevEng.AI: auto-unstrip finished; syncing recovered function names and data types…", false); - try { - var summary = revengService.syncAnalysisUpdates(analysedProgram, TaskMonitor.DUMMY, loggingService); - announce(("RevEng.AI: auto-unstrip sync applied %d recovered name(s) and %d signature(s), " - + "and pushed %d local type set(s).") - .formatted(summary.namesModifiedRemotely(), summary.appliedSignatures(), - summary.pushedTypeSets()), false); - } catch (Exception e) { - Msg.warn(this, "Failed to sync analysis after auto-unstrip", e); - announce("RevEng.AI: failed to sync analysis after auto-unstrip: " + e.getMessage(), true); + private long backoffMillis() { + int doublings = Math.min(consecutiveFailures, 16); + return Math.min(pollIntervalMillis << doublings, Math.max(MAX_BACKOFF.toMillis(), pollIntervalMillis)); + } + + private void rescheduleOrGiveUp(long delayMillis) { + var elapsed = Duration.ofNanos(System.nanoTime() - startNanos); + if (elapsed.plusMillis(delayMillis).compareTo(maxPollDuration) > 0) { + finish(); + if (!isCancelled()) { + announce(("RevEng.AI: auto-unstrip has not finished after %s; stopped waiting. " + + "Use Sync With Portal to pull the recovered names later.") + .formatted(describe(maxPollDuration)), true); + } + return; + } + schedule(delayMillis); } + + private void runSync() { + // The program may have been detached, or attached to another analysis, since polling began. + var current = revengService.getAnalysedProgram(analysedProgram.program()); + if (isCancelled() || current.isEmpty() + || !current.get().analysisID().equals(analysedProgram.analysisID())) { + loggingService.info("Auto-unstrip finished for analysis %d, but the program is no longer attached to it; not syncing." + .formatted(analysedProgram.analysisID().id())); + return; + } + announce("RevEng.AI: auto-unstrip finished; syncing recovered function names and data types…", false); + try { + var summary = revengService.syncAnalysisUpdates(current.get(), TaskMonitor.DUMMY, loggingService); + announce(("RevEng.AI: auto-unstrip sync applied %d recovered name(s) and %d signature(s), " + + "and pushed %d local type set(s).") + .formatted(summary.namesModifiedRemotely(), summary.appliedSignatures(), + summary.pushedTypeSets()), false); + } catch (Exception e) { + Msg.warn(AutoUnstripSyncService.this, "Failed to sync analysis after auto-unstrip", e); + if (isCancelled()) { + // Detached mid-sync; the failure is a consequence of that, not something to report. + return; + } + announce("RevEng.AI: failed to sync analysis after auto-unstrip: " + e.getMessage(), true); + } + } + } + + private static String describe(ApiException e) { + return e.getCode() > 0 ? "HTTP " + e.getCode() : String.valueOf(e.getMessage()); + } + + private static String describe(Duration duration) { + return duration.toMinutes() >= 1 ? duration.toMinutes() + " minute(s)" : duration.toSeconds() + " second(s)"; } /// Record a message in the plugin log and surface it to the user (status bar). diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index bc100b7b..fb30064c 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -207,6 +207,15 @@ private void setupActions() { // For now this is the only place to trigger the removal of the association // If this changes, the RevEngAIAnalysisStatusChanged event should be changed to accommodate // this kind of event + // Stop the background work tied to this analysis first, so none of it runs against the + // association while it is being removed, or later against a different analysis. + localEditSyncService.detach(program); + if (autoUnstripSyncService.stopPolling(knownProgram.get().analysisID())) { + var message = "RevEng.AI: stopped waiting for auto-unstrip; the program was detached from " + + displayText + "."; + tool.getService(ReaiLoggingService.class).info(message); + tool.setStatusInfo(message); + } program.withTransaction("Undo binary association", () -> revengService.removeProgramAssociation(program)); // Refresh action states after detaching diff --git a/src/test/java/ai/reveng/AutoUnstripSyncTest.java b/src/test/java/ai/reveng/AutoUnstripSyncTest.java index bc583c04..be877f4c 100644 --- a/src/test/java/ai/reveng/AutoUnstripSyncTest.java +++ b/src/test/java/ai/reveng/AutoUnstripSyncTest.java @@ -1,5 +1,6 @@ package ai.reveng; +import ai.reveng.invoker.ApiException; import ai.reveng.model.BatchRenameInputBody; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; @@ -15,12 +16,19 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.time.Duration; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; @@ -66,12 +74,58 @@ public long batchRenameFunctions(BatchRenameInputBody request) { return request.getFunctions().size(); } + /// Thrown, in order, by the first status polls before {@link #unstripStatuses} is consulted. + final Deque failures = new ArrayDeque<>(); + final AtomicInteger statusCalls = new AtomicInteger(); + /// When set, a status poll blocks until it is released. + volatile CountDownLatch inPoll; + volatile CountDownLatch releasePoll; + @Override - public AutoUnstripStatus getAutoUnstripStatus(TypedApiInterface.AnalysisID analysisID) { + public AutoUnstripStatus getAutoUnstripStatus(TypedApiInterface.AnalysisID analysisID) throws ApiException { + statusCalls.incrementAndGet(); + if (inPoll != null) { + inPoll.countDown(); + try { + releasePoll.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + var failure = failures.poll(); + if (failure instanceof WrappedApiException wrapped) { + throw wrapped.apiException; + } + if (failure != null) { + throw failure; + } return unstripStatuses.size() > 1 ? unstripStatuses.poll() : unstripStatuses.peek(); } } + /// Lets an {@link ApiException} sit in the failure script next to runtime exceptions. + private static class WrappedApiException extends RuntimeException { + final ApiException apiException; + + WrappedApiException(int code) { + this.apiException = new ApiException(code, "HTTP " + code); + } + } + + /// Records every message the service surfaces to the user. + private static class Announcements implements BiConsumer { + final List warnings = new CopyOnWriteArrayList<>(); + final List all = new CopyOnWriteArrayList<>(); + + @Override + public void accept(String message, Boolean warning) { + all.add(message); + if (warning) { + warnings.add(message); + } + } + } + private record Fixture(GhidraRevengService service, GhidraRevengService.AnalysedProgram analysed, Function function) {} private Fixture setUp(UnstripApi api) throws Exception { @@ -148,4 +202,138 @@ public void syncsAfterUnstripTransitionsToComplete() throws Exception { syncService.dispose(); } } + + private static AutoUnstripSyncService fastService(Fixture fixture, BiConsumer notifier, + Duration maxPollDuration) { + return new AutoUnstripSyncService(fixture.service(), NOOP_LOG, notifier, + Duration.ofMillis(50), maxPollDuration); + } + + @Test + public void stopPollingDuringAPollEndsPolling() throws Exception { + var api = new UnstripApi(); + api.unstripStatuses.add(AutoUnstripStatus.RUNNING); + api.inPoll = new CountDownLatch(1); + api.releasePoll = new CountDownLatch(1); + var fixture = setUp(api); + + var syncService = fastService(fixture, (m, w) -> {}, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue(api.inPoll.await(5, TimeUnit.SECONDS)); + assertTrue(syncService.stopPolling(fixture.analysed().analysisID())); + api.inPoll = null; + api.releasePoll.countDown(); + Thread.sleep(500); + assertEquals("a poll running when polling stops must not schedule another", 1, api.statusCalls.get()); + assertFalse("polling is no longer active", syncService.stopPolling(fixture.analysed().analysisID())); + } finally { + syncService.dispose(); + } + } + + @Test + public void givesUpAndWarnsWhenUnstripNeverFinishes() throws Exception { + var api = new UnstripApi(); + api.unstripStatuses.add(AutoUnstripStatus.RUNNING); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMillis(400)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue("running out of time is reported", waitUntil(() -> !announcements.warnings.isEmpty(), 5000)); + int calls = api.statusCalls.get(); + Thread.sleep(300); + assertEquals("no polls after giving up", calls, api.statusCalls.get()); + assertTrue(announcements.warnings.get(0).contains("stopped waiting")); + assertEquals(1, announcements.warnings.size()); + assertEquals(0, api.getFunctionInfoCalls); + } finally { + syncService.dispose(); + } + } + + @Test + public void retriesServerErrorsAndSyncsOnceUnstripCompletes() throws Exception { + var api = new UnstripApi(); + api.failures.add(new WrappedApiException(503)); + api.failures.add(new WrappedApiException(502)); + api.unstripStatuses.add(AutoUnstripStatus.COMPLETED); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue("a 5xx is retried and the later completion syncs", + waitUntil(() -> api.getFunctionInfoCalls > 0, 5000)); + assertEquals(3, api.statusCalls.get()); + assertTrue("a transient error is not shown as a failure", announcements.warnings.isEmpty()); + } finally { + syncService.dispose(); + } + } + + @Test + public void stopsAndWarnsOnClientError() throws Exception { + var api = new UnstripApi(); + api.failures.add(new WrappedApiException(404)); + api.unstripStatuses.add(AutoUnstripStatus.COMPLETED); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue(waitUntil(() -> !announcements.warnings.isEmpty(), 5000)); + assertTrue(announcements.warnings.get(0).contains("HTTP 404")); + Thread.sleep(300); + assertEquals("a 4xx is not retried", 1, api.statusCalls.get()); + } finally { + syncService.dispose(); + } + } + + @Test + public void reportsUnexpectedErrorsInsteadOfDyingSilently() throws Exception { + var api = new UnstripApi(); + api.failures.add(new IllegalArgumentException("malformed body")); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue("an unexpected error is reported", waitUntil(() -> !announcements.warnings.isEmpty(), 5000)); + assertTrue(announcements.warnings.get(0).contains("malformed body")); + assertFalse(syncService.stopPolling(fixture.analysed().analysisID())); + } finally { + syncService.dispose(); + } + } + + @Test + public void doesNotSyncAProgramDetachedWhilePolling() throws Exception { + var api = new UnstripApi(); + api.unstripStatuses.add(AutoUnstripStatus.COMPLETED); + api.inPoll = new CountDownLatch(1); + api.releasePoll = new CountDownLatch(1); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue(api.inPoll.await(5, TimeUnit.SECONDS)); + var program = fixture.analysed().program(); + program.withTransaction("detach", () -> fixture.service().removeProgramAssociation(program)); + api.releasePoll.countDown(); + Thread.sleep(500); + assertEquals("a detached program is not synced", 0, api.getFunctionInfoCalls); + assertTrue("nothing is reported as failed", announcements.warnings.isEmpty()); + } finally { + syncService.dispose(); + } + } } From 94c6a184eb05d6b127061b8e86404a8b06bc4974 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:35:44 +0000 Subject: [PATCH 34/76] fix(ENG-4459): undo a half-finished attach and offer a retry If pulling the function info failed after the function ids were committed, the program counted as analysed though nothing was pulled, Local Edit Sync was not attached, and loading again failed with "Previous function property map still exists". A failed or cancelled pull now takes the ids back out, loading replaces any association already on the program, and the analyst gets a Retry dialog and a Retry loading results action. --- .../services/api/GhidraRevengService.java | 61 ++++++---- .../plugins/AnalysisManagementPlugin.java | 98 +++++++++++++--- .../java/ai/reveng/IncompleteLoadTest.java | 110 ++++++++++++++++++ 3 files changed, 232 insertions(+), 37 deletions(-) create mode 100644 src/test/java/ai/reveng/IncompleteLoadTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 86cac0c3..42d0e447 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -180,12 +180,26 @@ public AnalysedProgram registerFinishedAnalysisForProgram(ProgramWithID programW } statusCache.put(programWithID.analysisID, AnalysisStatus.Complete); - var analysedProgram = associateFunctionInfo(programWithID); - pullFunctionInfoFromAnalysis(analysedProgram, monitor); - monitor.checkCancelled(); + var association = associateFunctionInfo(programWithID); + var analysedProgram = association.analysedProgram(); + try { + pullFunctionInfoFromAnalysis(analysedProgram, monitor); + monitor.checkCancelled(); + } catch (RuntimeException | CancelledException e) { + // The function ids alone make the program count as analysed, though none of the portal's names or + // types arrived. Take them out again so the program is left as it was and the load can be retried. + var program = programWithID.program(); + program.withTransaction("RevEng.AI: Undo incomplete load", () -> clearFunctionAssociation(program)); + throw e; + } + Msg.showInfo(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function loading summary", association.summary()); return analysedProgram; } + /// What {@link #associateFunctionInfo(ProgramWithID)} produced, with the summary to show once the + /// rest of the load has succeeded too. + private record FunctionAssociation(AnalysedProgram analysedProgram, String summary) {} + private ProgramWithID addAnalysisIDtoProgramOptions(Program program, TypedApiInterface.AnalysisID analysisID){ var transactionId = program.startTransaction("Associate Binary ID with Program"); program.getOptions(ReaiPluginPackage.REAI_OPTIONS_CATEGORY) @@ -223,12 +237,16 @@ private Optional getAnalysisIDFor(Program program) /// analysis is associated with the program /// Other function information like the name and signature should be loaded in [#pullFunctionInfoFromAnalysis(AnalysedProgram ,TaskMonitor)] /// because this information can change on the server, and thus needs a dedicated method to refresh it - private AnalysedProgram associateFunctionInfo(ProgramWithID knownProgram) { + /// + /// Any association already on the program is replaced, so an earlier load that stopped part way does + /// not block this one. + private FunctionAssociation associateFunctionInfo(ProgramWithID knownProgram) { var analysisID = knownProgram.analysisID(); var program = knownProgram.program(); List functionInfo = null; functionInfo = api.getFunctionInfo(analysisID); var transactionID = program.startTransaction("Associate Function Info"); + clearFunctionAssociation(program); // Create the FunctionID map LongPropertyMap functionIDMap; @@ -293,16 +311,14 @@ private AnalysedProgram associateFunctionInfo(ProgramWithID knownProgram) { } } ); - // Print summary - Msg.showInfo(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function loading summary", - ("Found %d functions from RevEng.AI. Your local Ghidra instance has %d/%d matching function " + - "boundaries. For better results, please start a new analysis from this plugin.").formatted( - functionInfo.size(), - ghidraBoundariesMatchedFunction, - ghidraFunctionCount.get() - )); + var summary = ("Found %d functions from RevEng.AI. Your local Ghidra instance has %d/%d matching function " + + "boundaries. For better results, please start a new analysis from this plugin.").formatted( + functionInfo.size(), + ghidraBoundariesMatchedFunction, + ghidraFunctionCount.get() + ); - return analysedProgram; + return new FunctionAssociation(analysedProgram, summary); } @@ -1221,7 +1237,18 @@ public List searchForHash(TypedApiInterface.BinaryHash hash) } public void removeProgramAssociation(Program program){ - // Clear all function ID data + clearFunctionAssociation(program); + var reaiOptions = program.getOptions(ReaiPluginPackage.REAI_OPTIONS_CATEGORY); + reaiOptions.setLong(OPTION_KEY_ANALYSIS_ID, ReaiPluginPackage.INVALID_ANALYSIS_ID); + // Clear the entire cache. Getting the correct ID is not worth the effort in terms of edge cases to handle + // because this method should still work even if the analysis ID or binary ID that was associated is invalid + statusCache.clear(); + + } + + /// Remove the function ids and the marks on the functions, but keep the analysis id, so the program is + /// known but no longer analysed. Must run inside a transaction. + private void clearFunctionAssociation(Program program) { program.getUsrPropertyManager().removePropertyMap(REAI_FUNCTION_PROP_MAP); program.getUsrPropertyManager().removePropertyMap(REAI_FUNCTION_MANGLED_MAP); @@ -1233,12 +1260,6 @@ public void removeProgramAssociation(Program program){ if (revengTag != null) { revengTag.delete(); } - var reaiOptions = program.getOptions(ReaiPluginPackage.REAI_OPTIONS_CATEGORY); - reaiOptions.setLong(OPTION_KEY_ANALYSIS_ID, ReaiPluginPackage.INVALID_ANALYSIS_ID); - // Clear the entire cache. Getting the correct ID is not worth the effort in terms of edge cases to handle - // because this method should still work even if the analysis ID or binary ID that was associated is invalid - statusCache.clear(); - } /// This method is private to the service, because it only concerns itself with how the service determines diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index bc100b7b..1c4e9d2e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -38,6 +38,8 @@ import ghidra.program.model.listing.Program; import ghidra.program.util.GhidraProgramUtilities; import ghidra.util.Msg; +import ghidra.util.exception.CancelledException; +import javax.annotation.Nullable; import ghidra.util.task.Task; import ghidra.util.task.TaskBuilder; import ghidra.util.task.TaskMonitor; @@ -46,6 +48,8 @@ import org.slf4j.LoggerFactory; import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; /** @@ -81,6 +85,10 @@ public class AnalysisManagementPlugin extends ProgramPlugin { private AnalysisLogComponent analysisLogComponent; private LocalEditSyncService localEditSyncService; private AutoUnstripSyncService autoUnstripSyncService; + /// Programs whose analysis results failed to load, for the Retry action. Touched from tasks and the Swing thread. + private final Set failedLoads = ConcurrentHashMap.newKeySet(); + private static final String RETRY_HINT = + "The program was left unchanged. Retry now, or later from RevEng.AI > Analysis > Retry loading results."; private PluginTool tool; @@ -252,6 +260,19 @@ public void run(TaskMonitor monitor) { .menuGroup(REAI_ANALYSIS_MANAGEMENT_MENU_GROUP, "400") .buildAndInstall(tool); + new ActionBuilder("Retry loading results", this.getName()) + .enabledWhen(context -> { + var currentProgram = tool.getService(ProgramManager.class).getCurrentProgram(); + return currentProgram != null && failedLoads.contains(currentProgram); + }) + .onAction(context -> { + var currentProgram = tool.getService(ProgramManager.class).getCurrentProgram(); + revengService.getKnownProgram(currentProgram).ifPresent(this::loadAnalysisResults); + }) + .menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "Analysis", "Retry loading results" }) + .menuGroup(REAI_ANALYSIS_MANAGEMENT_MENU_GROUP, "250") + .buildAndInstall(tool); + new ActionBuilder("View in portal", this.getName()) .enabledWhen(context -> { var currentProgram = tool.getService(ProgramManager.class).getCurrentProgram(); @@ -344,6 +365,7 @@ protected void programActivated(Program program) { @Override protected void programClosed(Program program) { super.programClosed(program); + failedLoads.remove(program); if (localEditSyncService != null) { localEditSyncService.detach(program); } @@ -375,27 +397,69 @@ public void processEvent(PluginEvent event) { Msg.info(this, "Received analysis complete event for " + analysisEvent.getProgramWithBinaryID()); // If the analysis is complete, we refresh the function signatures from the server - var program = analysisEvent.getProgramWithBinaryID(); - // Events arrive on the Swing thread, and loading the results makes several requests - tool.execute(new Task("Load RevEng.AI analysis results", true, false, false) { - @Override - public void run(TaskMonitor monitor) { - try { - var analysedProgram = revengService.registerFinishedAnalysisForProgram(program, monitor); - localEditSyncService.attach(program.program()); - tool.firePluginEvent(new RevEngAIAnalysisResultsLoaded("AnalysisManagementPlugin", analysedProgram)); - // Auto-unstrip runs server-side after the analysis is marked complete, so poll for it - // and sync the recovered names / data types once it finishes (PLU-300). - autoUnstripSyncService.pollAndSync(analysedProgram, true); - } catch (Exception e) { - Msg.error(AnalysisManagementPlugin.this, "Error registering finished analysis for program " + program, e); - } - } - }, 0); + loadAnalysisResults(analysisEvent.getProgramWithBinaryID()); } } } + private void loadAnalysisResults(GhidraRevengService.ProgramWithID program) { + failedLoads.remove(program.program()); + // Events arrive on the Swing thread, and loading the results makes several requests + tool.execute(new Task("Load RevEng.AI analysis results", true, false, false) { + @Override + public void run(TaskMonitor monitor) { + try { + var analysedProgram = revengService.registerFinishedAnalysisForProgram(program, monitor); + localEditSyncService.attach(program.program()); + tool.firePluginEvent(new RevEngAIAnalysisResultsLoaded("AnalysisManagementPlugin", analysedProgram)); + // Auto-unstrip runs server-side after the analysis is marked complete, so poll for it + // and sync the recovered names / data types once it finishes (PLU-300). + autoUnstripSyncService.pollAndSync(analysedProgram, true); + } catch (CancelledException e) { + reportFailedLoad(program, loadCancelledMessage(program), null); + } catch (Exception e) { + Msg.error(AnalysisManagementPlugin.this, "Error registering finished analysis for program " + program, e); + reportFailedLoad(program, loadFailedMessage(program, e), e); + } + } + }, 0); + } + + /// The service leaves the program as it was before the load, so it can simply be loaded again: from the + /// dialog straight away, or later from the Retry action. + private void reportFailedLoad(GhidraRevengService.ProgramWithID program, String message, @Nullable Exception error) { + failedLoads.add(program.program()); + var loggingService = tool.getService(ReaiLoggingService.class); + if (loggingService != null) { + loggingService.error(message); + } + SwingUtilities.invokeLater(() -> { + tool.setStatusInfo(message, true); + tool.contextChanged(null); + if (error == null) { + // Cancelled by the analyst, who needs no dialog to learn about it + return; + } + var choice = OptionDialog.showOptionDialog(tool.getToolFrame(), + ReaiPluginPackage.WINDOW_PREFIX + "Load analysis results", message + "\n\n" + RETRY_HINT, + "Retry", OptionDialog.ERROR_MESSAGE); + if (choice == OptionDialog.OPTION_ONE && failedLoads.contains(program.program())) { + loadAnalysisResults(program); + } + }); + } + + private static String loadFailedMessage(GhidraRevengService.ProgramWithID program, Exception error) { + var reason = error.getMessage() != null ? error.getMessage() : error.getClass().getSimpleName(); + return "Could not load the results of RevEng.AI analysis %d into %s: %s" + .formatted(program.analysisID().id(), program.program().getName(), reason); + } + + private static String loadCancelledMessage(GhidraRevengService.ProgramWithID program) { + return "Loading the results of RevEng.AI analysis %d into %s was cancelled" + .formatted(program.analysisID().id(), program.program().getName()); + } + static String checkStatusMessage(AnalysisStatus status) { return "Analysis status: " + status; } diff --git a/src/test/java/ai/reveng/IncompleteLoadTest.java b/src/test/java/ai/reveng/IncompleteLoadTest.java new file mode 100644 index 00000000..7795547d --- /dev/null +++ b/src/test/java/ai/reveng/IncompleteLoadTest.java @@ -0,0 +1,110 @@ +package ai.reveng; + +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ghidra.program.model.data.Undefined; +import ghidra.program.model.listing.Function; +import ghidra.util.task.TaskMonitor; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/// A load whose pull fails part way must leave the program as it was, and loading it again must work. +public class IncompleteLoadTest extends RevEngMockableHeadedIntegrationTest { + + private static final String REVENG_TAG = "REVENGAI_SYNCED"; + private static final String REVENG_BOOKMARK_TYPE = "RevEng.AI"; + + /// Serves one function, and fails the signature request while `portalDown` is set, as a 503 would. + private static class FlakyPortal extends UnimplementedAPI { + boolean portalDown = true; + + @Override + public AnalysisStatus status(TypedApiInterface.AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(TypedApiInterface.AnalysisID analysisID) { + return List.of( + new FunctionInfo(new TypedApiInterface.FunctionID(1), "portal_name", "portal_name", 0x4000L, 0x100) + ); + } + + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, + boolean includeDataTypes) { + if (portalDown) { + throw new RuntimeException("HTTP 503 — Service Unavailable"); + } + return FunctionSignatureBatch.empty(); + } + } + + @Test + public void failedPullLeavesProgramUnattachedAndRetrySucceeds() throws Exception { + var portal = new FlakyPortal(); + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + var originalName = function.getName(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + var error = assertThrows(RuntimeException.class, + () -> service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY)); + assertEquals("HTTP 503 — Service Unavailable", error.getMessage()); + + assertTrue("the analysis should stay associated so the load can be retried", + service.getKnownProgram(program).isPresent()); + assertTrue("a program whose pull failed must not count as analysed", + service.getAnalysedProgram(program).isEmpty()); + assertFalse("the function should not be marked as synced", hasRevEngTag(function)); + assertEquals("the function should not keep a RevEng bookmark", + 0, program.getBookmarkManager().getBookmarks(function.getEntryPoint(), REVENG_BOOKMARK_TYPE).length); + assertEquals("nothing was pulled, so the name is unchanged", originalName, function.getName()); + + portal.portalDown = false; + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + assertTrue("the retried load should attach the program", service.getAnalysedProgram(program).isPresent()); + assertEquals(1, analysedProgram.getIDForFunction(function).orElseThrow().functionID().value()); + assertTrue("the function should be marked as synced", hasRevEngTag(function)); + assertEquals("the retried load should pull the portal name", "portal_name", function.getName()); + } + + @Test + public void loadingAnAlreadyAttachedProgramAgainReplacesTheAssociation() throws Exception { + var portal = new FlakyPortal(); + portal.portalDown = false; + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + // Programs saved half attached before this was fixed still carry the property maps + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + assertEquals(1, analysedProgram.getIDForFunction(function).orElseThrow().functionID().value()); + assertEquals("the function should carry exactly one RevEng bookmark", + 1, program.getBookmarkManager().getBookmarks(function.getEntryPoint(), REVENG_BOOKMARK_TYPE).length); + assertTrue(hasRevEngTag(function)); + } + + private static boolean hasRevEngTag(Function function) { + return function.getTags().stream().anyMatch(tag -> tag.getName().equals(REVENG_TAG)); + } +} From cbe9c8f9acdcf8eb8dcf400853ed9cafff543993 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:35:52 +0000 Subject: [PATCH 35/76] fix(ENG-4457): rename on the portal only the matches applied locally The binary-level transfer sent every selected match to the portal before applying them, so functions ApplyMatchCmd skips (analyst-set names, names with spaces, thunks, unmapped functions) were renamed on the server while keeping their local name. Apply first, then batch-rename only the matches that were applied. "Apply Match" files the function under RevEng.AI::, and the reactive push sent "::". qualifiedServerName now leaves out RevEng.AI and every namespace under it. --- .../AbstractFunctionMatchingDialog.java | 37 ++++++--- .../services/api/GhidraRevengService.java | 13 ++- ...nctionLevelFunctionMatchingDialogTest.java | 81 +++++++++++++++++++ .../ai/reveng/LocalEditSyncScopeTest.java | 43 ++++++++++ 4 files changed, 157 insertions(+), 17 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 3ebe6fbc..61189869 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -1098,11 +1098,7 @@ private void transferInBackground(List matches var task = new Task("Transferring " + transfer.label(), true, false, false) { @Override public void run(TaskMonitor monitor) { - // The portal only stores names, so a signature-only transfer has nothing to push - if (transfer.includesName()) { - batchRenameFunctions(matches); - } - int applied = applyMatches(matches, transfer); + int applied = transferMatches(matches, transfer); SwingUtilities.invokeLater(() -> statusLabel.setText("Transferred %s to %d of %d function(s)" .formatted(transfer.label().toLowerCase(), applied, matches.size()))); } @@ -1111,34 +1107,49 @@ public void run(TaskMonitor monitor) { TaskBuilder.withTask(task).setParent(getComponent()).launchModal(); } + /// Applies the matches locally, then renames on the portal only the functions that were renamed + /// here. A match can be skipped locally (a name the analyst set, a thunk, ...), and pushing it + /// anyway would overwrite the portal's name for a function whose local name was kept. + /// Returns how many functions were changed. + protected int transferMatches(List matches, ApplyMatchCmd.Transfer transfer) { + var applied = applyMatches(matches, transfer); + // The portal only stores names, so a signature-only transfer has nothing to push + if (transfer.includesName() && !applied.isEmpty()) { + batchRenameFunctions(applied); + } + return applied.size(); + } + protected void batchRenameFunctions(List functionMatches) { try { revengService.batchRenamingGhidraMatchesWithSignatures(functionMatches); } catch (Exception e) { - Msg.error(this, "Failed to rename functions: " + e.getMessage(), e); - SwingUtilities.invokeLater(() -> showError("Failed to rename functions: " + e.getMessage())); + Msg.error(this, "Failed to rename functions on the portal: " + e.getMessage(), e); + SwingUtilities.invokeLater(() -> showError( + "Renamed locally, but failed to rename the functions on the portal: " + e.getMessage())); } } - /// Applies the matches to the program and returns how many functions were changed. Matches can be + /// Applies the matches to the program and returns those that changed a function. Matches can be /// skipped, e.g. a signature transfer for a match the portal has no signature for. - protected int applyMatches(List functionMatches, ApplyMatchCmd.Transfer transfer) { + protected List applyMatches(List functionMatches, + ApplyMatchCmd.Transfer transfer) { var program = analyzedProgram.program(); - int[] applied = {0}; + List applied = new ArrayList<>(); program.withTransaction("Apply Function Matching " + transfer.label(), () -> { for (GhidraFunctionMatchWithSignature match : functionMatches) { // We don't pass a service, because we don't need to update individual functions on the portal - // batchRenameFunctions already does that for us + // transferMatches renames the applied ones in one batch afterwards var cmd = new ApplyMatchCmd(null, analyzedProgram, match, false, transfer); if (cmd.applyTo(program)) { - applied[0]++; + applied.add(match); } } } ); SwingUtilities.invokeLater(this::updateResultsTable); - return applied[0]; + return applied; } @Override diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 86cac0c3..13efcced 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -369,14 +369,19 @@ public Map pushFunctionRenames(AnalysedProgram analysedProgram } /// The function name as the portal expects it: qualified with its namespace path (joined by - /// {@code ::}), excluding the artificial RevEng.AI organisational namespace and the global - /// namespace. Ghidra stores only the leaf label on the symbol, so the namespace must be - /// re-attached when pushing a rename back — the portal's function names include the namespace. + /// {@code ::}), excluding the artificial RevEng.AI organisational namespace, the namespaces + /// under it, and the global namespace. Ghidra stores only the leaf label on the symbol, so the + /// namespace must be re-attached when pushing a rename back — the portal's function names + /// include the namespace. Applying a match files the function under + /// {@code RevEng.AI::}, and that binary name is not part of the function's name. static String qualifiedServerName(Function function) { List parts = new ArrayList<>(); parts.add(function.getName()); for (Namespace ns = function.getParentNamespace(); ns != null && !ns.isGlobal(); ns = ns.getParentNamespace()) { - if (!REVENG_AI_NAMESPACE.equals(ns.getName())) { + if (REVENG_AI_NAMESPACE.equals(ns.getName())) { + // Drop the namespaces collected so far: they are all inside RevEng.AI + parts.subList(0, parts.size() - 1).clear(); + } else { parts.add(0, ns.getName()); } } diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index d9fae5b7..0e5c3929 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -1,16 +1,19 @@ package ai.reveng; import ai.reveng.model.*; +import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.FunctionLevelFunctionMatchingDialog; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; import ai.reveng.toolkit.ghidra.plugins.BinarySimilarityPlugin; import docking.DockingWindowManager; import ghidra.program.model.data.Undefined; +import ghidra.program.model.symbol.SourceType; import ghidra.util.task.TaskMonitor; import org.junit.Test; @@ -18,6 +21,7 @@ import generic.theme.GColor; import java.math.BigDecimal; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; @@ -578,6 +582,83 @@ public void testRightClickOffersMatchedBinaryInPortal() throws Exception { waitForSwing(); } + /** + * Transferring a name must only rename on the portal the functions it renamed locally. A function + * whose name the analyst set is skipped locally, so pushing the matched name for it would leave the + * portal holding a different name from the one kept in Ghidra. + */ + @Test + public void testTransferOnlyRenamesOnThePortalWhatItAppliedLocally() throws Exception { + var tool = env.getTool(); + + var mockApi = new RenameRecordingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + var program = analysedProgram.program(); + env.showTool(program); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + waitForMatchingIdle(foundDialog); + + var match = new GhidraFunctionMatchWithSignature(testFunction, new FunctionMatch( + new TypedApiInterface.FunctionID(100), + new TypedApiInterface.FunctionID(200), + "similar_function", + "similar_function", + "libc.so", + new TypedApiInterface.BinaryHash("1".repeat(64)), + false, + BigDecimal.valueOf(0.95), + BigDecimal.valueOf(0.87), + null), null); + var transferArgs = new Class[] {List.class, ApplyMatchCmd.Transfer.class}; + + // A name the analyst set is kept, so nothing about the match may reach the portal + program.withTransaction("analyst rename", () -> testFunction.setName("analyst_name", SourceType.USER_DEFINED)); + var applied = invokeInstanceMethod("transferMatches", foundDialog, transferArgs, + new Object[] {List.of(match), ApplyMatchCmd.Transfer.NAME}); + assertEquals(0, applied); + assertEquals("analyst_name", testFunction.getName()); + assertFalse("The skipped match must not be renamed on the portal: " + mockApi.pushedNames, + mockApi.pushedNames.contains("similar_function")); + + // A name the analyst did not set is replaced, and the portal gets the same name + program.withTransaction("analysis name", () -> testFunction.setName("analysis_name", SourceType.ANALYSIS)); + applied = invokeInstanceMethod("transferMatches", foundDialog, transferArgs, + new Object[] {List.of(match), ApplyMatchCmd.Transfer.NAME}); + assertEquals(1, applied); + assertEquals("similar_function", testFunction.getName()); + assertTrue("The applied match should be renamed on the portal: " + mockApi.pushedNames, + mockApi.pushedNames.contains("similar_function")); + + close(foundDialog); + waitForSwing(); + } + + /// Records the names sent to the portal for function 100, the test function. + static class RenameRecordingMockApi extends FunctionMatchingMockApi { + final List pushedNames = new CopyOnWriteArrayList<>(); + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) { + request.getFunctions().stream() + .filter(item -> item.getFunctionId() == 100L) + .forEach(item -> pushedNames.add(item.getNewName())); + return request.getFunctions().size(); + } + } + /** * Returns several matches whose server order differs from their alphabetical order, so that * sorting the results table genuinely separates view indices from model indices. diff --git a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java index d21de7f2..c7444e16 100644 --- a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java +++ b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java @@ -3,13 +3,17 @@ import ai.reveng.model.BatchRenameInputBody; import ai.reveng.model.CreateAnalysisDataTypesInputBody; import ai.reveng.model.UpdateFunctionSignatureInputBody; +import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.BinaryHash; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; +import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; import ghidra.program.model.address.AddressSet; @@ -25,6 +29,7 @@ import org.junit.Before; import org.junit.Test; +import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; @@ -89,6 +94,7 @@ public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID private Program program; private Function first; private LocalEditSyncService sync; + private GhidraRevengService.AnalysedProgram analysedProgram; @Before public void analyse() throws Exception { @@ -106,6 +112,7 @@ public void analyse() throws Exception { var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + analysedProgram = service.getAnalysedProgram(program).orElseThrow(); sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class), (message, warning) -> {}); sync.attach(program); @@ -147,6 +154,42 @@ public void renamesInOneProgramGoUpInOneRequest() throws Exception { assertEquals(Map.of(1L, "renamed_0", 2L, "renamed_1", 3L, "renamed_2"), pushed); } + /// "Apply Match" files the function under `RevEng.AI::`. That namespace only + /// organises the matches, so the rename it triggers must push the bare name, not + /// `::`. + @Test + public void anAppliedMatchPushesItsNameWithoutTheMatchedBinary() throws Exception { + var match = new GhidraFunctionMatchWithSignature(first, new FunctionMatch( + new FunctionID(1), + new FunctionID(200), + "matched_name", + "matched_name", + "libfoo.so", + new BinaryHash("abc123"), + false, + BigDecimal.valueOf(0.9), + BigDecimal.valueOf(0.9), + null), null); + edit("apply match", () -> new ApplyMatchCmd(null, analysedProgram, match, true).applyTo(program)); + assertEquals("RevEng.AI::libfoo.so", first.getParentNamespace().getName(true)); + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the rename should be pushed"); + assertEquals("matched_name", api.renameRequests.get(0).getFunctions().get(0).getNewName()); + } + + /// A namespace the analyst made is part of the function's name on the portal. + @Test + public void aRenameInsideAnAnalystNamespaceKeepsTheNamespace() throws Exception { + edit("move and rename", () -> { + var namespace = program.getSymbolTable().createNameSpace(null, "MyClass", SourceType.USER_DEFINED); + first.setParentNamespace(namespace); + first.setName("method", SourceType.USER_DEFINED); + }); + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the rename should be pushed"); + assertEquals("MyClass::method", api.renameRequests.get(0).getFunctions().get(0).getNewName()); + } + @Test public void localVariableEditsPushNothingButAParameterRenameDoes() throws Exception { edit("add a local", () -> first.addLocalVariable( From da32b9003d0f3d12d6f55684f82976a59c4e1999 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:40:32 +0000 Subject: [PATCH 36/76] fix(ENG-4457): leave the transferred renames to the reactive push Transferring names also sent its own batch rename, so every applied rename reached the portal twice, and a portal failure showed a dialog error on top of the sync service's retry. LocalEditSyncService already pushes exactly the renames applied locally, so drop the explicit batch. --- .../AbstractFunctionMatchingDialog.java | 43 ++------ .../services/api/GhidraRevengService.java | 26 ----- ...nctionLevelFunctionMatchingDialogTest.java | 103 +++++++++++------- .../ai/reveng/LocalEditSyncScopeTest.java | 17 +++ 4 files changed, 89 insertions(+), 100 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 61189869..31a6b2b8 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -1098,7 +1098,7 @@ private void transferInBackground(List matches var task = new Task("Transferring " + transfer.label(), true, false, false) { @Override public void run(TaskMonitor monitor) { - int applied = transferMatches(matches, transfer); + int applied = applyMatches(matches, transfer); SwingUtilities.invokeLater(() -> statusLabel.setText("Transferred %s to %d of %d function(s)" .formatted(transfer.label().toLowerCase(), applied, matches.size()))); } @@ -1107,49 +1107,26 @@ public void run(TaskMonitor monitor) { TaskBuilder.withTask(task).setParent(getComponent()).launchModal(); } - /// Applies the matches locally, then renames on the portal only the functions that were renamed - /// here. A match can be skipped locally (a name the analyst set, a thunk, ...), and pushing it - /// anyway would overwrite the portal's name for a function whose local name was kept. - /// Returns how many functions were changed. - protected int transferMatches(List matches, ApplyMatchCmd.Transfer transfer) { - var applied = applyMatches(matches, transfer); - // The portal only stores names, so a signature-only transfer has nothing to push - if (transfer.includesName() && !applied.isEmpty()) { - batchRenameFunctions(applied); - } - return applied.size(); - } - - protected void batchRenameFunctions(List functionMatches) { - try { - revengService.batchRenamingGhidraMatchesWithSignatures(functionMatches); - } catch (Exception e) { - Msg.error(this, "Failed to rename functions on the portal: " + e.getMessage(), e); - SwingUtilities.invokeLater(() -> showError( - "Renamed locally, but failed to rename the functions on the portal: " + e.getMessage())); - } - } - - /// Applies the matches to the program and returns those that changed a function. Matches can be - /// skipped, e.g. a signature transfer for a match the portal has no signature for. - protected List applyMatches(List functionMatches, - ApplyMatchCmd.Transfer transfer) { + /// Applies the matches to the program and returns how many functions were changed. Matches can be + /// skipped, e.g. a signature transfer for a match the portal has no signature for, or a name + /// transfer to a function the analyst named. + protected int applyMatches(List functionMatches, ApplyMatchCmd.Transfer transfer) { var program = analyzedProgram.program(); - List applied = new ArrayList<>(); + int[] applied = {0}; program.withTransaction("Apply Function Matching " + transfer.label(), () -> { for (GhidraFunctionMatchWithSignature match : functionMatches) { - // We don't pass a service, because we don't need to update individual functions on the portal - // transferMatches renames the applied ones in one batch afterwards + // We don't pass a service, because we don't need to update individual functions on the portal: + // LocalEditSyncService pushes the renames applied here, and only those, in one batch var cmd = new ApplyMatchCmd(null, analyzedProgram, match, false, transfer); if (cmd.applyTo(program)) { - applied.add(match); + applied[0]++; } } } ); SwingUtilities.invokeLater(this::updateResultsTable); - return applied; + return applied[0]; } @Override diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 13efcced..7f69e4ed 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -9,7 +9,6 @@ import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionBoundary; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; -import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import ai.reveng.toolkit.ghidra.core.services.api.mocks.MockApi; import ai.reveng.toolkit.ghidra.core.services.api.types.*; @@ -1618,31 +1617,6 @@ public GetMatchesOutputBody getFunctionsMatches(List functionIds) throws A return api.getFunctionsMatches(functionIds); } - public void batchRenamingGhidraMatchesWithSignatures(List functionsList) throws ApiException { - // Pushing types to the portal is not supported yet, so we just extract the function matches and call the other method - batchRenameMatches(functionsList.stream() - .map(GhidraFunctionMatchWithSignature::functionMatch) - .toList()); - - } - - public void batchRenameMatches(List functionsList) throws ApiException { - var items = functionsList.stream() - .map(result -> { - var item = new BatchRenameItem(); - item.setFunctionId(result.origin_function_id().value()); - item.setNewName(result.nearest_neighbor_function_name()); - item.setNewMangledName(result.nearest_neighbor_mangled_function_name()); - return item; - }) - .toList(); - - var request = new BatchRenameInputBody(); - request.setFunctions(items); - api.batchRenameFunctions(request); - } - - /// Old Helper Datatype that encapsulates a Ghidra program with a binary ID and analysis ID /// This only guarantees that the program has an associated analysis, but not that the analysis is finished /// The id of this should also be stored in the program options, but this is currently not enforced yet to allow easier testing diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index 0e5c3929..ecc1fe61 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -10,6 +10,8 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; import ai.reveng.toolkit.ghidra.plugins.BinarySimilarityPlugin; import docking.DockingWindowManager; import ghidra.program.model.data.Undefined; @@ -583,9 +585,9 @@ public void testRightClickOffersMatchedBinaryInPortal() throws Exception { } /** - * Transferring a name must only rename on the portal the functions it renamed locally. A function - * whose name the analyst set is skipped locally, so pushing the matched name for it would leave the - * portal holding a different name from the one kept in Ghidra. + * Transferring names must rename on the portal exactly the functions it renamed locally, once each. + * A function whose name the analyst set is skipped locally, so pushing the matched name for it would + * leave the portal holding a different name from the one kept in Ghidra. */ @Test public void testTransferOnlyRenamesOnThePortalWhatItAppliedLocally() throws Exception { @@ -598,63 +600,82 @@ public void testTransferOnlyRenamesOnThePortalWhatItAppliedLocally() throws Exce var builder = newX64Program("test_binary"); var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var otherFunction = builder.createEmptyFunction("other_function", "0x2000", 50, Undefined.getUndefinedDataType(4)); var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); var program = analysedProgram.program(); env.showTool(program); waitForSwing(); - FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) - ); - runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); - var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); - waitForMatchingIdle(foundDialog); + // A name the analyst set is kept, so nothing about its match may reach the portal + program.withTransaction("analyst rename", () -> testFunction.setName("analyst_name", SourceType.USER_DEFINED)); + program.withTransaction("analysis name", () -> otherFunction.setName("analysis_name", SourceType.ANALYSIS)); + + var sync = new LocalEditSyncService(service, tool.getService(ReaiLoggingService.class), (message, warning) -> {}); + sync.attach(program); + try { + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + waitForMatchingIdle(foundDialog); + + var matches = List.of( + matchFor(testFunction, 100, "similar_function"), + matchFor(otherFunction, 101, "other_similar_function")); + var applied = invokeInstanceMethod("applyMatches", foundDialog, + new Class[] {List.class, ApplyMatchCmd.Transfer.class}, + new Object[] {matches, ApplyMatchCmd.Transfer.NAME}); + assertEquals(1, applied); + assertEquals("analyst_name", testFunction.getName()); + assertEquals("other_similar_function", otherFunction.getName()); + + waitForCondition(() -> !mockApi.renameRequests.isEmpty(), "the applied rename should be pushed"); + Thread.sleep(1000); + assertEquals("Each applied rename should be pushed once: " + mockApi.renameRequests, + 1, mockApi.renameRequests.size()); + var pushed = mockApi.renameRequests.get(0).getFunctions(); + assertEquals(1, pushed.size()); + assertEquals(Long.valueOf(101), pushed.get(0).getFunctionId()); + assertEquals("other_similar_function", pushed.get(0).getNewName()); + + close(foundDialog); + waitForSwing(); + } finally { + sync.dispose(); + } + } - var match = new GhidraFunctionMatchWithSignature(testFunction, new FunctionMatch( - new TypedApiInterface.FunctionID(100), - new TypedApiInterface.FunctionID(200), - "similar_function", - "similar_function", + private static GhidraFunctionMatchWithSignature matchFor(ghidra.program.model.listing.Function function, + long functionId, String matchedName) { + return new GhidraFunctionMatchWithSignature(function, new FunctionMatch( + new TypedApiInterface.FunctionID(functionId), + new TypedApiInterface.FunctionID(functionId + 100), + matchedName, + matchedName, "libc.so", new TypedApiInterface.BinaryHash("1".repeat(64)), false, BigDecimal.valueOf(0.95), BigDecimal.valueOf(0.87), null), null); - var transferArgs = new Class[] {List.class, ApplyMatchCmd.Transfer.class}; - - // A name the analyst set is kept, so nothing about the match may reach the portal - program.withTransaction("analyst rename", () -> testFunction.setName("analyst_name", SourceType.USER_DEFINED)); - var applied = invokeInstanceMethod("transferMatches", foundDialog, transferArgs, - new Object[] {List.of(match), ApplyMatchCmd.Transfer.NAME}); - assertEquals(0, applied); - assertEquals("analyst_name", testFunction.getName()); - assertFalse("The skipped match must not be renamed on the portal: " + mockApi.pushedNames, - mockApi.pushedNames.contains("similar_function")); - - // A name the analyst did not set is replaced, and the portal gets the same name - program.withTransaction("analysis name", () -> testFunction.setName("analysis_name", SourceType.ANALYSIS)); - applied = invokeInstanceMethod("transferMatches", foundDialog, transferArgs, - new Object[] {List.of(match), ApplyMatchCmd.Transfer.NAME}); - assertEquals(1, applied); - assertEquals("similar_function", testFunction.getName()); - assertTrue("The applied match should be renamed on the portal: " + mockApi.pushedNames, - mockApi.pushedNames.contains("similar_function")); - - close(foundDialog); - waitForSwing(); } - /// Records the names sent to the portal for function 100, the test function. + /// Knows a second function, and records the renames sent to the portal. static class RenameRecordingMockApi extends FunctionMatchingMockApi { - final List pushedNames = new CopyOnWriteArrayList<>(); + final List renameRequests = new CopyOnWriteArrayList<>(); + + @Override + public List getFunctionInfo(TypedApiInterface.AnalysisID analysisID) { + return List.of( + new FunctionInfo(new TypedApiInterface.FunctionID(100), "test_function", "test_function", 0x1000L, 50), + new FunctionInfo(new TypedApiInterface.FunctionID(101), "other_function", "other_function", 0x2000L, 50)); + } @Override public long batchRenameFunctions(BatchRenameInputBody request) { - request.getFunctions().stream() - .filter(item -> item.getFunctionId() == 100L) - .forEach(item -> pushedNames.add(item.getNewName())); + renameRequests.add(request); return request.getFunctions().size(); } } diff --git a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java index c7444e16..fd5a80e4 100644 --- a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java +++ b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java @@ -190,6 +190,23 @@ public void aRenameInsideAnAnalystNamespaceKeepsTheNamespace() throws Exception assertEquals("MyClass::method", api.renameRequests.get(0).getFunctions().get(0).getNewName()); } + /// Every namespace inside RevEng.AI is dropped, while one the analyst made above it is kept. + @Test + public void aRenameDropsOnlyTheNamespacesInsideRevEngAi() throws Exception { + edit("move and rename", () -> { + var symbols = program.getSymbolTable(); + var outer = symbols.createNameSpace(null, "Outer", SourceType.USER_DEFINED); + var reveng = symbols.createNameSpace(outer, "RevEng.AI", SourceType.USER_DEFINED); + var binary = symbols.createNameSpace(reveng, "libfoo.so", SourceType.USER_DEFINED); + var inner = symbols.createNameSpace(binary, "Inner", SourceType.USER_DEFINED); + first.setParentNamespace(inner); + first.setName("name", SourceType.USER_DEFINED); + }); + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the rename should be pushed"); + assertEquals("Outer::name", api.renameRequests.get(0).getFunctions().get(0).getNewName()); + } + @Test public void localVariableEditsPushNothingButAParameterRenameDoes() throws Exception { edit("add a local", () -> first.addLocalVariable( From 33be6979f70e9787560848e90d4bad0adf974e5c Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:41:43 +0000 Subject: [PATCH 37/76] fix(ENG-4464): let Detach cancel a running auto-unstrip sync and stop quietly when unstrip never starts The poller now stays registered until its post-unstrip sync returns, so stopPolling (Detach, program close, dispose) can cancel it mid-sync. The sync runs with a monitor that is cancelled with the poller, so its transactions roll back and the failure is not reported as a warning. An analysis whose auto-unstrip stays UNINITIALISED or UNKNOWN for five minutes is no longer announced or warned about; polling ends with a log line only. Also: classify RuntimeException-wrapped API errors before giving up, point at the API key on 401/403, name the outage when the time limit is spent retrying, and log why a sync was skipped accurately. --- .../services/sync/AutoUnstripSyncService.java | 91 ++++++++++---- .../java/ai/reveng/AutoUnstripSyncTest.java | 118 +++++++++++++++++- 2 files changed, 187 insertions(+), 22 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java index 9c540605..178088d1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java @@ -8,7 +8,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AutoUnstripStatus; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ghidra.util.Msg; -import ghidra.util.task.TaskMonitor; +import ghidra.util.task.TaskMonitorAdapter; import java.time.Duration; import java.util.Map; @@ -30,14 +30,19 @@ * completion, runs the same reconciliation the "Sync With Portal" action uses. * *

Polling stops when auto-unstrip completes or fails, when {@link #stopPolling} is called (even - * if a poll is running at that moment), after {@link #DEFAULT_MAX_POLL_DURATION}, or on an error a - * retry cannot fix. A transient error (no connection, timeout, 5xx) backs off and retries within - * that time limit. Every way of giving up is reported in the log and the status bar. + * if a poll or the sync is running at that moment), after {@link #DEFAULT_MAX_POLL_DURATION}, or on + * an error a retry cannot fix. A transient error (no connection, timeout, 5xx) backs off and retries + * within that time limit. Every way of giving up is reported in the log and the status bar, except + * for an analysis whose auto-unstrip never starts within {@link #NOT_STARTED_GRACE}: that is not a + * failure, so polling ends quietly. */ public class AutoUnstripSyncService { public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5); public static final Duration DEFAULT_MAX_POLL_DURATION = Duration.ofMinutes(30); + /// How long an analysis may report auto-unstrip as not started (UNINITIALISED or UNKNOWN) before + /// polling assumes it will never run. Capped by the overall time limit. + public static final Duration NOT_STARTED_GRACE = Duration.ofMinutes(5); /// Longest wait between polls while the status endpoint keeps failing transiently. private static final Duration MAX_BACKOFF = Duration.ofSeconds(60); @@ -47,6 +52,7 @@ public class AutoUnstripSyncService { private final BiConsumer statusNotifier; private final long pollIntervalMillis; private final Duration maxPollDuration; + private final Duration notStartedGrace; private final ScheduledExecutorService scheduler; private final Map pollers = new ConcurrentHashMap<>(); @@ -63,6 +69,7 @@ public AutoUnstripSyncService(GhidraRevengService revengService, ReaiLoggingServ this.statusNotifier = statusNotifier; this.pollIntervalMillis = pollInterval.toMillis(); this.maxPollDuration = maxPollDuration; + this.notStartedGrace = NOT_STARTED_GRACE.compareTo(maxPollDuration) < 0 ? NOT_STARTED_GRACE : maxPollDuration; this.scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> { var thread = new Thread(runnable, "RevEng.AI-AutoUnstripSync"); thread.setDaemon(true); @@ -89,7 +96,7 @@ public void pollAndSync(AnalysedProgram analysedProgram, boolean resyncIfAlready } /// Stop polling for the given analysis. A poll that is running right now neither reschedules - /// nor starts a sync afterwards. + /// nor starts a sync afterwards, and a sync that is running is cancelled and rolls back. /// /// @return whether polling was still active for the analysis public boolean stopPolling(AnalysisID analysisID) { @@ -113,8 +120,12 @@ private final class Poller { private final AnalysedProgram analysedProgram; private final boolean resyncIfAlreadyComplete; private final long startNanos = System.nanoTime(); + /// Cancelled together with the poller, so a sync that is running stops and rolls back. + private final TaskMonitorAdapter syncMonitor = new TaskMonitorAdapter(true); private boolean firstPoll = true; + private boolean started = false; private int consecutiveFailures = 0; + private String lastFailure; /// Guarded by {@code this} private boolean cancelled = false; /// Guarded by {@code this} @@ -127,6 +138,7 @@ private final class Poller { synchronized void cancel() { cancelled = true; + syncMonitor.cancel(); if (future != null) { future.cancel(false); } @@ -168,21 +180,27 @@ private void poll() { AutoUnstripStatus status; try { status = revengService.getAutoUnstripStatus(analysedProgram.analysisID()); - } catch (ApiException e) { + } catch (ApiException | RuntimeException e) { + // The typed API wraps some ApiExceptions in a RuntimeException; PushFailure finds them. if (isCancelled()) { return; } - if (PushFailure.of(e) != PushFailure.TRANSIENT) { + var failure = PushFailure.of(e); + if (failure != PushFailure.TRANSIENT) { finish(); + var remedy = failure == PushFailure.AUTH + ? "Check the RevEng.AI API key in the plugin configuration." + : "Use Sync With Portal to pull the recovered names later."; announce("RevEng.AI: stopped waiting for auto-unstrip, the status check failed (%s). " - .formatted(describe(e)) + "Use Sync With Portal to pull the recovered names later.", true); + .formatted(describe(e)) + remedy, true); return; } consecutiveFailures++; + lastFailure = describe(e); if (consecutiveFailures == 1) { // Logged once per outage, so a portal that is down for a while does not flood the log. loggingService.warn("Checking the auto-unstrip status failed (%s); retrying with back-off." - .formatted(describe(e))); + .formatted(lastFailure)); } rescheduleOrGiveUp(backoffMillis()); return; @@ -197,11 +215,16 @@ private void poll() { switch (status) { case COMPLETED -> { - finish(); if (firstPoll && !resyncIfAlreadyComplete) { + finish(); return; } - runSync(); + // Stays in the map while syncing, so stopPolling (e.g. Detach) can still cancel it. + try { + runSync(); + } finally { + finish(); + } } case FAILED -> { finish(); @@ -209,11 +232,23 @@ private void poll() { announce("RevEng.AI auto-unstrip failed; recovered names were not synced.", true); } } + case UNINITIALISED, UNKNOWN -> { + firstPoll = false; + if (!started && Duration.ofNanos(System.nanoTime() - startNanos).compareTo(notStartedGrace) >= 0) { + // Auto-unstrip never started for this analysis; there is nothing to wait for or report. + finish(); + loggingService.info("Auto-unstrip has not started for analysis %d; not waiting for it." + .formatted(analysedProgram.analysisID().id())); + return; + } + rescheduleOrGiveUp(pollIntervalMillis); + } default -> { - if (firstPoll) { + if (!started) { announce("RevEng.AI: waiting for auto-unstrip to finish before syncing recovered " + "function names and data types…", false); } + started = true; firstPoll = false; rescheduleOrGiveUp(pollIntervalMillis); } @@ -230,9 +265,11 @@ private void rescheduleOrGiveUp(long delayMillis) { if (elapsed.plusMillis(delayMillis).compareTo(maxPollDuration) > 0) { finish(); if (!isCancelled()) { - announce(("RevEng.AI: auto-unstrip has not finished after %s; stopped waiting. " - + "Use Sync With Portal to pull the recovered names later.") - .formatted(describe(maxPollDuration)), true); + var cause = consecutiveFailures > 0 + ? "the auto-unstrip status could not be checked for %s (%s)".formatted(describe(maxPollDuration), lastFailure) + : "auto-unstrip has not finished after %s".formatted(describe(maxPollDuration)); + announce("RevEng.AI: %s; stopped waiting. Use Sync With Portal to pull the recovered names later." + .formatted(cause), true); } return; } @@ -242,15 +279,24 @@ private void rescheduleOrGiveUp(long delayMillis) { private void runSync() { // The program may have been detached, or attached to another analysis, since polling began. var current = revengService.getAnalysedProgram(analysedProgram.program()); - if (isCancelled() || current.isEmpty() - || !current.get().analysisID().equals(analysedProgram.analysisID())) { + if (isCancelled()) { + loggingService.info("Auto-unstrip finished for analysis %d, but polling for it was stopped; not syncing." + .formatted(analysedProgram.analysisID().id())); + return; + } + if (current.isEmpty() || !current.get().analysisID().equals(analysedProgram.analysisID())) { loggingService.info("Auto-unstrip finished for analysis %d, but the program is no longer attached to it; not syncing." .formatted(analysedProgram.analysisID().id())); return; } announce("RevEng.AI: auto-unstrip finished; syncing recovered function names and data types…", false); try { - var summary = revengService.syncAnalysisUpdates(current.get(), TaskMonitor.DUMMY, loggingService); + var summary = revengService.syncAnalysisUpdates(current.get(), syncMonitor, loggingService); + if (isCancelled()) { + loggingService.info("Stopped the auto-unstrip sync for analysis %d; its changes were rolled back." + .formatted(analysedProgram.analysisID().id())); + return; + } announce(("RevEng.AI: auto-unstrip sync applied %d recovered name(s) and %d signature(s), " + "and pushed %d local type set(s).") .formatted(summary.namesModifiedRemotely(), summary.appliedSignatures(), @@ -258,7 +304,7 @@ private void runSync() { } catch (Exception e) { Msg.warn(AutoUnstripSyncService.this, "Failed to sync analysis after auto-unstrip", e); if (isCancelled()) { - // Detached mid-sync; the failure is a consequence of that, not something to report. + // Stopped mid-sync (e.g. detached); the failure is a consequence of that, not something to report. return; } announce("RevEng.AI: failed to sync analysis after auto-unstrip: " + e.getMessage(), true); @@ -266,8 +312,11 @@ private void runSync() { } } - private static String describe(ApiException e) { - return e.getCode() > 0 ? "HTTP " + e.getCode() : String.valueOf(e.getMessage()); + private static String describe(Exception e) { + if (e instanceof ApiException api && api.getCode() > 0) { + return "HTTP " + api.getCode(); + } + return e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); } private static String describe(Duration duration) { diff --git a/src/test/java/ai/reveng/AutoUnstripSyncTest.java b/src/test/java/ai/reveng/AutoUnstripSyncTest.java index be877f4c..b16a12c1 100644 --- a/src/test/java/ai/reveng/AutoUnstripSyncTest.java +++ b/src/test/java/ai/reveng/AutoUnstripSyncTest.java @@ -49,7 +49,10 @@ private static class UnstripApi extends UnimplementedAPI { final List renameCalls = new ArrayList<>(); final Deque unstripStatuses = new ArrayDeque<>(); List functions = List.of(); - int getFunctionInfoCalls = 0; + volatile int getFunctionInfoCalls = 0; + /// When set, a function info fetch (the start of a sync) blocks until it is released. + volatile CountDownLatch inSync; + volatile CountDownLatch releaseSync; @Override public AnalysisStatus status(TypedApiInterface.AnalysisID analysisID) { @@ -59,6 +62,14 @@ public AnalysisStatus status(TypedApiInterface.AnalysisID analysisID) { @Override public List getFunctionInfo(TypedApiInterface.AnalysisID analysisID) { getFunctionInfoCalls++; + if (inSync != null) { + inSync.countDown(); + try { + releaseSync.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } return functions; } @@ -336,4 +347,109 @@ public void doesNotSyncAProgramDetachedWhilePolling() throws Exception { syncService.dispose(); } } + + @Test + public void detachDuringTheSyncCancelsItWithoutAWarning() throws Exception { + var api = new UnstripApi(); + api.unstripStatuses.add(AutoUnstripStatus.COMPLETED); + var fixture = setUp(api); + api.inSync = new CountDownLatch(1); + api.releaseSync = new CountDownLatch(1); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue(api.inSync.await(5, TimeUnit.SECONDS)); + // What the Detach action does while the sync is running. + assertTrue("a running sync can still be stopped", syncService.stopPolling(fixture.analysed().analysisID())); + var program = fixture.analysed().program(); + program.withTransaction("detach", () -> fixture.service().removeProgramAssociation(program)); + api.releaseSync.countDown(); + Thread.sleep(500); + assertTrue("a sync stopped by Detach is not reported as failed", announcements.warnings.isEmpty()); + } finally { + syncService.dispose(); + } + } + + @Test + public void doesNotSyncAProgramReattachedToAnotherAnalysisWhilePolling() throws Exception { + var api = new UnstripApi(); + api.unstripStatuses.add(AutoUnstripStatus.COMPLETED); + api.inPoll = new CountDownLatch(1); + api.releasePoll = new CountDownLatch(1); + var fixture = setUp(api); + + var syncService = fastService(fixture, (m, w) -> {}, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue(api.inPoll.await(5, TimeUnit.SECONDS)); + var program = fixture.analysed().program(); + program.withTransaction("detach", () -> fixture.service().removeProgramAssociation(program)); + var reattached = fixture.service().registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(2)); + fixture.service().registerFinishedAnalysisForProgram(reattached, TaskMonitor.DUMMY); + api.getFunctionInfoCalls = 0; + api.releasePoll.countDown(); + Thread.sleep(500); + assertEquals("the old analysis is not synced into the re-attached program", 0, api.getFunctionInfoCalls); + } finally { + syncService.dispose(); + } + } + + @Test + public void stopsQuietlyWhenUnstripNeverStarts() throws Exception { + var api = new UnstripApi(); + api.unstripStatuses.add(AutoUnstripStatus.UNINITIALISED); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMillis(400)); + try { + syncService.pollAndSync(fixture.analysed(), false); + assertTrue("polling ends", waitUntil(() -> !syncService.stopPolling(fixture.analysed().analysisID()), 5000)); + assertTrue("an unstrip that never started is neither announced nor reported", announcements.all.isEmpty()); + } finally { + syncService.dispose(); + } + } + + @Test + public void pointsAtTheApiKeyWhenTheStatusCheckIsRefused() throws Exception { + var api = new UnstripApi(); + api.failures.add(new WrappedApiException(401)); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMinutes(1)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue(waitUntil(() -> !announcements.warnings.isEmpty(), 5000)); + assertTrue(announcements.warnings.get(0).contains("API key")); + } finally { + syncService.dispose(); + } + } + + @Test + public void namesTheOutageWhenTheTimeLimitIsSpentRetrying() throws Exception { + var api = new UnstripApi(); + for (int i = 0; i < 100; i++) { + api.failures.add(new WrappedApiException(503)); + } + api.unstripStatuses.add(AutoUnstripStatus.COMPLETED); + var fixture = setUp(api); + var announcements = new Announcements(); + + var syncService = fastService(fixture, announcements, Duration.ofMillis(400)); + try { + syncService.pollAndSync(fixture.analysed(), true); + assertTrue(waitUntil(() -> !announcements.warnings.isEmpty(), 5000)); + assertTrue(announcements.warnings.get(0).contains("could not be checked")); + assertTrue(announcements.warnings.get(0).contains("HTTP 503")); + } finally { + syncService.dispose(); + } + } } From b95cf77fcdcff27f0f629578994e902560c582f2 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:42:18 +0000 Subject: [PATCH 38/76] fix(ENG-4459): roll back a failed load in one transaction Hold one transaction across associating the function ids and pulling the results, and abort it when the load fails or is cancelled. Undo can no longer bring back a half-attached program, and changes made before a local failure part way through the pull are rolled back too. Skip the Retry dialog for a program closed during the load, disable the Retry action as soon as a retry starts, and show the API error message without the wrapping exception's class name. --- .../services/api/GhidraRevengService.java | 31 ++++++++----- .../plugins/AnalysisManagementPlugin.java | 15 ++++++- .../java/ai/reveng/IncompleteLoadTest.java | 45 +++++++++++++++++++ 3 files changed, 77 insertions(+), 14 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 42d0e447..fa405e53 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -180,20 +180,26 @@ public AnalysedProgram registerFinishedAnalysisForProgram(ProgramWithID programW } statusCache.put(programWithID.analysisID, AnalysisStatus.Complete); - var association = associateFunctionInfo(programWithID); - var analysedProgram = association.analysedProgram(); + // The function ids alone make the program count as analysed, though none of the portal's names or types + // may have arrived. One transaction around the whole load is rolled back when any part of it fails, so the + // program is left as it was, the load can be retried, and the undo history holds nothing to bring it back. + var program = programWithID.program(); + var transactionId = program.startTransaction("RevEng.AI: Load analysis results"); + boolean loaded = false; + FunctionAssociation association; try { - pullFunctionInfoFromAnalysis(analysedProgram, monitor); + association = associateFunctionInfo(programWithID); + pullFunctionInfoFromAnalysis(association.analysedProgram(), monitor); monitor.checkCancelled(); - } catch (RuntimeException | CancelledException e) { - // The function ids alone make the program count as analysed, though none of the portal's names or - // types arrived. Take them out again so the program is left as it was and the load can be retried. - var program = programWithID.program(); - program.withTransaction("RevEng.AI: Undo incomplete load", () -> clearFunctionAssociation(program)); - throw e; + loaded = true; + } finally { + // A program closed during the load takes no more transactions, and must not hide why the load failed + if (!program.isClosed()) { + program.endTransaction(transactionId, loaded); + } } Msg.showInfo(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function loading summary", association.summary()); - return analysedProgram; + return association.analysedProgram(); } /// What {@link #associateFunctionInfo(ProgramWithID)} produced, with the summary to show once the @@ -1207,8 +1213,9 @@ public List pullFunctionInfoFromAnalysis(AnalysedProgram analysedP } } finally { - // Done iterating over all functions. If nothing changed, discard the transaction, to keep undo history clean - endServerTransaction(analysedProgram.program(), transactionId, !renameResults.isEmpty() && !monitor.isCancelled()); + // Done iterating over all functions. A transaction that changed nothing leaves no undo entry, and + // aborting it would abort the load it runs inside too, so it is discarded only when cancelled + endServerTransaction(analysedProgram.program(), transactionId, !monitor.isCancelled()); } if (failedRenames > 0){ Msg.showError(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function Update Summary", diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 1c4e9d2e..68b41461 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -404,6 +404,8 @@ public void processEvent(PluginEvent event) { private void loadAnalysisResults(GhidraRevengService.ProgramWithID program) { failedLoads.remove(program.program()); + // Disables the Retry action straight away, so a second click cannot start a second load + tool.contextChanged(null); // Events arrive on the Swing thread, and loading the results makes several requests tool.execute(new Task("Load RevEng.AI analysis results", true, false, false) { @Override @@ -428,12 +430,17 @@ public void run(TaskMonitor monitor) { /// The service leaves the program as it was before the load, so it can simply be loaded again: from the /// dialog straight away, or later from the Retry action. private void reportFailedLoad(GhidraRevengService.ProgramWithID program, String message, @Nullable Exception error) { - failedLoads.add(program.program()); var loggingService = tool.getService(ReaiLoggingService.class); if (loggingService != null) { loggingService.error(message); } + // On the Swing thread, like programClosed, so a program closed during the load cannot be added after it SwingUtilities.invokeLater(() -> { + if (program.program().isClosed()) { + // Closed during the load, which is likely why it failed. There is nothing left to retry on. + return; + } + failedLoads.add(program.program()); tool.setStatusInfo(message, true); tool.contextChanged(null); if (error == null) { @@ -450,7 +457,11 @@ private void reportFailedLoad(GhidraRevengService.ProgramWithID program, String } private static String loadFailedMessage(GhidraRevengService.ProgramWithID program, Exception error) { - var reason = error.getMessage() != null ? error.getMessage() : error.getClass().getSimpleName(); + // The API wraps its exceptions as `new RuntimeException(cause)`, whose message is the cause's class name + // followed by its message. The analyst only needs the message. + Throwable shown = error.getCause() != null && Objects.equals(error.getMessage(), error.getCause().toString()) + ? error.getCause() : error; + var reason = shown.getMessage() != null ? shown.getMessage() : shown.getClass().getSimpleName(); return "Could not load the results of RevEng.AI analysis %d into %s: %s" .formatted(program.analysisID().id(), program.program().getName(), reason); } diff --git a/src/test/java/ai/reveng/IncompleteLoadTest.java b/src/test/java/ai/reveng/IncompleteLoadTest.java index 7795547d..b45349c3 100644 --- a/src/test/java/ai/reveng/IncompleteLoadTest.java +++ b/src/test/java/ai/reveng/IncompleteLoadTest.java @@ -8,7 +8,9 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ghidra.program.model.data.Undefined; import ghidra.program.model.listing.Function; +import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; +import ghidra.util.task.TaskMonitorAdapter; import org.junit.Test; import java.util.List; @@ -104,6 +106,49 @@ public void loadingAnAlreadyAttachedProgramAgainReplacesTheAssociation() throws assertTrue(hasRevEngTag(function)); } + @Test + public void failedPullLeavesNothingToUndo() throws Exception { + var portal = new FlakyPortal(); + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + var undoNames = program.getAllUndoNames(); + assertThrows(RuntimeException.class, + () -> service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY)); + + assertEquals("a failed load should leave no undo entry that brings the association back", + undoNames, program.getAllUndoNames()); + assertTrue(service.getAnalysedProgram(program).isEmpty()); + assertFalse(hasRevEngTag(function)); + } + + @Test + public void cancelledLoadLeavesProgramUnattached() throws Exception { + var portal = new FlakyPortal(); + portal.portalDown = false; + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + var originalName = function.getName(); + var monitor = new TaskMonitorAdapter(true); + monitor.cancel(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + assertThrows(CancelledException.class, + () -> service.registerFinishedAnalysisForProgram(programWithID, monitor)); + + assertTrue(service.getKnownProgram(program).isPresent()); + assertTrue("a cancelled load must not count as analysed", service.getAnalysedProgram(program).isEmpty()); + assertFalse(hasRevEngTag(function)); + assertEquals(originalName, function.getName()); + } + private static boolean hasRevEngTag(Function function) { return function.getTags().stream().anyMatch(tag -> tag.getName().equals(REVENG_TAG)); } From db38bb5324db4561fe9663cafebe02a96a66ccc6 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:53:22 +0000 Subject: [PATCH 39/76] fix(ENG-4460): retry transient errors while polling analysis status (#248) --- .../ui/misc/AnalysisLogComponent.java | 15 ++-- .../services/api/GhidraRevengService.java | 46 ++++++++++-- .../ai/reveng/GhidraRevengServiceTest.java | 22 ++++++ .../ai/reveng/TestAnalysisLogComponent.java | 72 +++++++++++++++++++ 4 files changed, 143 insertions(+), 12 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index 6ed88e1b..0286bc09 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -130,12 +130,15 @@ public AnalysisMonitoringTask(GhidraRevengService.ProgramWithID programWithID, A public void run(TaskMonitor monitor) throws CancelledException { // Wait for the analysis var service = tool.getService(GhidraRevengService.class); - service.waitForFinishedAnalysis(monitor, program, this.logConsumer, tool); - /// waitForFinishedAnalysis has already sent the completion event to all plugins - /// so this task just needs to clean up the tracked programs map - // Remove ourselves from the tracked programs when done - trackedPrograms.remove(program.program()); - taskMonitorComponent.setVisible(false); + try { + service.waitForFinishedAnalysis(monitor, program, this.logConsumer, tool); + } finally { + /// waitForFinishedAnalysis has already sent the completion event to all plugins + /// so this task just needs to clean up the tracked programs map + // Remove ourselves from the tracked programs when done + trackedPrograms.remove(program.program()); + taskMonitorComponent.setVisible(false); + } } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 86cac0c3..e46a6ecb 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1436,15 +1436,40 @@ public AnalysisStatus waitForFinishedAnalysis( // Check the status of the analysis every 500ms // TODO: In the future this can be made smarter and e.g. wait longer if the analysis log hasn't changed AnalysisStatus lastStatus = null; + long delay = pollIntervalMs; + int failures = 0; while (true) { - AnalysisStatus currentStatus = this.status(programWithID); + AnalysisStatus currentStatus; + try { + currentStatus = api.status(programWithID.analysisID()); + delay = pollIntervalMs; + failures = 0; + } catch (ApiException e) { + if (!isTransient(e) || ++failures >= MAX_POLL_ATTEMPTS) { + throw new RuntimeException(e); + } + Msg.warn(this, "Transient error polling analysis status, retrying in %dms".formatted(delay), e); + monitor.checkCancelled(); + try { + Thread.sleep(delay); + } catch (InterruptedException ie) { + return lastStatus; + } + delay = Math.min(delay * 2, maxPollBackoffMs); + continue; + } if (currentStatus != AnalysisStatus.Uploaded && currentStatus != AnalysisStatus.Queued) { // Analysis log endpoint only starts to return data after the analysis is processing - String logs = this.getAnalysisLog(programWithID.analysisID()); - if (logger != null) { - logger.consumeLogs(logs, programWithID); + try { + String logs = this.getAnalysisLog(programWithID.analysisID()); + if (logger != null) { + logger.consumeLogs(logs, programWithID); + } + logs.lines().reduce((first, second) -> second).ifPresent(monitor::setMessage); + } catch (RuntimeException e) { + // Logs are cosmetic; a failed fetch must not end the wait + Msg.warn(this, "Failed to fetch analysis logs", e); } - logs.lines().reduce((first, second) -> second).ifPresent(monitor::setMessage); } if (currentStatus != lastStatus) { lastStatus = currentStatus; @@ -1459,13 +1484,22 @@ public AnalysisStatus waitForFinishedAnalysis( } monitor.checkCancelled(); try { - Thread.sleep(500); + Thread.sleep(pollIntervalMs); } catch (InterruptedException e) { return lastStatus; } } } + private long pollIntervalMs = 500; + private long maxPollBackoffMs = 30_000; + private static final int MAX_POLL_ATTEMPTS = 10; + + /// 5xx, or no response at all (code 0: connection or timeout failure) + private static boolean isTransient(ApiException e) { + return e.getCode() == 0 || e.getCode() >= 500; + } + public ProgramWithID startAnalysis(Program program, AnalysisOptionsBuilder analysisOptionsBuilder) throws ApiException { var analysisID = api.analyse(analysisOptionsBuilder); diff --git a/src/test/java/ai/reveng/GhidraRevengServiceTest.java b/src/test/java/ai/reveng/GhidraRevengServiceTest.java index 113f3f5f..c9e2c6e3 100644 --- a/src/test/java/ai/reveng/GhidraRevengServiceTest.java +++ b/src/test/java/ai/reveng/GhidraRevengServiceTest.java @@ -15,6 +15,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; public class GhidraRevengServiceTest extends RevEngMockableHeadedIntegrationTest { @@ -42,6 +43,27 @@ public void testKnownProgramLookupIsNetworkFree() throws Exception { statusCallsBefore, mock.statusCalls); } + @Test + public void testStatusPollingGivesUpAfterTenFailures() throws Exception { + var statusCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) throws ApiException { + if (++statusCalls[0] > 20) { + return AnalysisStatus.Complete; + } + throw new ApiException(503, "Service Unavailable"); + } + }); + setInstanceField("pollIntervalMs", service, 1L); + setInstanceField("maxPollBackoffMs", service, 1L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + assertThrows(RuntimeException.class, + () -> service.waitForFinishedAnalysis(TaskMonitor.DUMMY, programWithID, null, null)); + assertEquals(10, statusCalls[0]); + } + static class OfflineAfterSetupAPI extends UnimplementedAPI { volatile boolean offline = false; int statusCalls = 0; diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index a8c80870..b31b748c 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -1,5 +1,6 @@ package ai.reveng; +import ai.reveng.invoker.ApiException; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.misc.AnalysisLogComponent; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; @@ -15,6 +16,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; @@ -118,4 +120,74 @@ public List getFunctionInfo(AnalysisID analysisID) { TaskMonitorComponent taskMonitorComponent = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); assertFalse(taskMonitorComponent.isVisible()); } + + @Test + public void testTransientServerErrorsDoNotStopMonitoring() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + var logCalls = new AtomicInteger(); + + addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) throws ApiException { + return switch (statusCalls.incrementAndGet()) { + case 1 -> throw new ApiException(503, "Service Unavailable"); + case 2 -> AnalysisStatus.Processing; + default -> AnalysisStatus.Complete; + }; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + if (logCalls.incrementAndGet() == 1) { + throw new RuntimeException(new ApiException(500, "Internal Server Error")); + } + return "PLACEHOLDER_LOGS"; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of(); + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) + ); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + waitForTasks(); + + assertTrue(statusCalls.get() >= 3); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + } + + @Test + public void testCancelledMonitoringUntracksProgram() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + + addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Queued; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) + ); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + TaskMonitorComponent taskMonitor = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + taskMonitor.cancel(); + waitForTasks(); + + assertFalse(trackedPrograms.containsKey(programWithID.program())); + TaskMonitorComponent taskMonitorComponent = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + assertFalse(taskMonitorComponent.isVisible()); + } } From d43ff6698c106ce638d6c50cd796e7dda6195ad3 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:18:25 +0000 Subject: [PATCH 40/76] fix(ENG-4461): bound and back off every status polling loop Analysis, function matching, Similar Functions and AI decompilation now poll through one StatusPoller: an interval that doubles while the status is unchanged (reset on any change), an overall time limit, a terminal state for unrecognised statuses, and prompt cancellation. - Analysis: Unknown ends the wait, waits stop after 3 hours, and the analyst is told in the RevEng.AI log and status bar. Reopening a program resumes Uploaded analyses and reports Unknown ones. - Matching and Similar Functions: an unrecognised status (e.g. the server's CANCELLED) or the time limit ends the run with a message. - AI decompilation: a non-409 summary trigger failure ends the wait, a Regenerate action reruns a FAILED decompilation, and a 404 on the status poll is reported as "function not found" instead of being read as UNINITIALISED. --- .../aidecompiler/AIDecompilationdWindow.java | 179 ++++++++++++++---- .../AbstractFunctionMatchingDialog.java | 81 +++++--- .../SimilarFunctionsWindow.java | 37 ++-- .../ui/misc/AnalysisLogComponent.java | 29 ++- .../services/api/GhidraRevengService.java | 135 +++++++------ .../core/services/api/StatusPoller.java | 164 ++++++++++++++++ .../services/api/TypedApiImplementation.java | 8 +- .../plugins/AnalysisManagementPlugin.java | 14 +- .../ai/reveng/AIDecompilerComponentTest.java | 159 ++++++++++++++++ ...nctionLevelFunctionMatchingDialogTest.java | 51 +++++ .../ai/reveng/GhidraRevengServiceTest.java | 64 +++++++ .../ai/reveng/TestAnalysisLogComponent.java | 135 +++++++++++++ .../api/AIDecompilationNotFoundTest.java | 36 ++++ .../core/services/api/StatusPollerTest.java | 152 +++++++++++++++ 14 files changed, 1110 insertions(+), 134 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AIDecompilationNotFoundTest.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java index 71313737..4e5f2ff5 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java @@ -7,6 +7,7 @@ import ai.reveng.model.RenderedToken; import ai.reveng.model.WorkflowProgress; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; import ai.reveng.toolkit.ghidra.core.services.api.types.AIDecompilationStatus; @@ -34,6 +35,7 @@ import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import java.time.Duration; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; @@ -133,6 +135,32 @@ public void actionPerformed(ActionContext context) { refreshCurrentFunction(); } }); + + addLocalAction(new DockingAction("Regenerate AI Decompilation", getName()) { + { + setToolBarData(new ToolBarData(new GIcon("icon.redo"), null)); + setDescription("Run the failed AI decompilation of the current function again"); + } + + @Override + public void actionPerformed(ActionContext context) { + regenerateCurrentFunction(); + } + + @Override + public boolean isEnabledForContext(ActionContext context) { + return canRegenerate(function); + } + }); + } + + /// Whether {@code target}'s last AI decompilation failed + private boolean canRegenerate(Function target) { + if (target == null) { + return false; + } + var cachedStatus = cache.get(target); + return cachedStatus != null && cachedStatus.status() == DecompilationData.StatusEnum.FAILED; } private void sendFeedbackInBackground(Function target, String rating, String reason) { @@ -291,7 +319,7 @@ public void setDisplayedValuesBasedOnStatus(Function function, AIDecompilationSt currentRenderModel = null; String detail = status.decompilation(); setCode(detail != null && !detail.isBlank() ? detail : ""); - descriptionArea.setText("AI Decompilation failed"); + descriptionArea.setText("AI Decompilation failed. Use Regenerate AI Decompilation in the toolbar to try again."); predictedNamePanel.setVisible(false); } case UNINITIALISED, PENDING, RUNNING -> { @@ -305,6 +333,8 @@ public void setDisplayedValuesBasedOnStatus(Function function, AIDecompilationSt // Unknown status — leave existing UI state untouched. } } + // Regenerate is only offered for a failed decompilation + contextChanged(); } private static final DateTimeFormatter PROGRESS_TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); @@ -440,16 +470,21 @@ public void refresh(GhidraRevengService.FunctionWithID function) { // Start a background task unless this function is already being decompiled. Multiple // functions decompile in parallel in the background; a running task updates the view // when it polls, so revisiting an in-flight function just shows this placeholder. - if (inFlightDecompilations.add(function.functionID().value())) { - taskMonitorComponent.setVisible(true); - var task = new AIDecompTask(tool, function); - var builder = TaskBuilder.withTask(task); - builder.launchInBackground(taskMonitorComponent); - } + startDecompilation(function, false); } } } + /// Start a background decompilation task, unless the function already has one running + private void startDecompilation(GhidraRevengService.FunctionWithID function, boolean regenerate) { + if (inFlightDecompilations.add(function.functionID().value())) { + taskMonitorComponent.setVisible(true); + var task = new AIDecompTask(tool, function, regenerate); + var builder = TaskBuilder.withTask(task); + builder.launchInBackground(taskMonitorComponent); + } + } + public void locationChanged(ProgramLocation loc) { var service = tool.getService(GhidraRevengService.class); var analyzedProgram = service.getAnalysedProgram(loc.getProgram()); @@ -491,6 +526,29 @@ private void refreshCurrentFunction() { analysed.get().getIDForFunction(target).ifPresent(this::refresh); } + /// Start a new AI decompilation for the current function, whose last one failed. Refresh alone + /// only re-reads the failed result, because the task triggers a decompilation only when none exists. + private void regenerateCurrentFunction() { + Function target = this.function; + if (!canRegenerate(target)) { + return; + } + var service = tool.getService(GhidraRevengService.class); + var functionWithID = service.getAnalysedProgram(target.getProgram()) + .flatMap(analysed -> analysed.getIDForFunction(target)); + if (functionWithID.isEmpty()) { + return; + } + cache.remove(target); + currentRenderModel = null; + tool.getService(ReaiLoggingService.class).info("Regenerating the AI Decompilation for function %s".formatted(target.getName())); + setCode(""); + descriptionArea.setText("Decompiling %s ...".formatted(target.getName())); + predictedNamePanel.setVisible(false); + startDecompilation(functionWithID.get(), true); + contextChanged(); + } + // --- Rename / comment editing ------------------------------------------------------------- private void handleDoubleClick(Point point) { @@ -917,6 +975,17 @@ private void reportDecompFailure(Function failedFunction, Exception e) { }); } + /// Polling for {@code stoppedFunction} ended without a result; say why in the log and the window. + private void reportDecompStopped(Function stoppedFunction, String reason) { + var logger = tool.getService(ReaiLoggingService.class); + logger.warn("Stopped waiting for the AI Decompilation of %s: %s".formatted(stoppedFunction.getName(), reason)); + SwingUtilities.invokeLater(() -> { + if (isCurrentFunction(stoppedFunction)) { + descriptionArea.setText("Stopped waiting for the AI Decompilation: " + reason); + } + }); + } + /** * Maps each display line of the rendered decompilation back to its source line, so a click in * the text area can be resolved to the line/identifier to rename or comment on. @@ -949,13 +1018,22 @@ boolean isCodeLine(int displayLine) { class AIDecompTask extends Task { + // Poll every second, slowing to every 5 while nothing changes, for at most 15 minutes in all + // (decompilation, summary and inline comments) + private static final Duration POLL_INTERVAL = Duration.ofSeconds(1); + private static final Duration MAX_POLL_INTERVAL = Duration.ofSeconds(5); + private static final Duration MAX_DECOMPILATION_WAIT = Duration.ofMinutes(15); + private final GhidraRevengService service; private final GhidraRevengService.FunctionWithID functionWithID; + private final boolean regenerate; - public AIDecompTask(PluginTool tool, GhidraRevengService.FunctionWithID functionWithID) { + /// @param regenerate also start a new decompilation when the last one FAILED + public AIDecompTask(PluginTool tool, GhidraRevengService.FunctionWithID functionWithID, boolean regenerate) { super("AI Decomp task", true, false, false); service = tool.getService(GhidraRevengService.class); this.functionWithID = functionWithID; + this.regenerate = regenerate; } @Override @@ -963,7 +1041,9 @@ public void run(TaskMonitor monitor) throws CancelledException { try { var fID = functionWithID.functionID(); // Check if there is an existing process already, because the trigger API will fail with 400 if there is - if (service.getApi().pollAIDecompileStatus(fID).status() == DecompilationData.StatusEnum.UNINITIALISED) { + var current = service.getApi().pollAIDecompileStatus(fID).status(); + if (current == DecompilationData.StatusEnum.UNINITIALISED + || (regenerate && current == DecompilationData.StatusEnum.FAILED)) { // Trigger the decompilation service.getApi().triggerAIDecompilationForFunctionID(fID); } @@ -975,18 +1055,54 @@ public void run(TaskMonitor monitor) throws CancelledException { reportDecompFailure(functionWithID.function(), e); } finally { inFlightDecompilations.remove(functionWithID.functionID().value()); + SwingUtilities.invokeLater(() -> { + if (inFlightDecompilations.isEmpty()) { + taskMonitorComponent.setVisible(false); + } + contextChanged(); + }); } } - private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) throws CancelledException { - var logger = tool.getService(ReaiLoggingService.class); + private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) throws Exception { var api = service.getApi(); - AIDecompilationStatus lastDecompStatus = null; - boolean inlineCommentsTriggered = false; - boolean summaryTriggered = false; - while (true) { - var newStatus = api.pollAIDecompileStatus(id); + var function = functionWithID.function(); + var step = new DecompPollStep(id); + var result = new StatusPoller(POLL_INTERVAL, MAX_POLL_INTERVAL, MAX_DECOMPILATION_WAIT) + .poll(() -> api.pollAIDecompileStatus(id), status -> step.next(status, monitor), monitor::isCancelled); + switch (result.ending()) { + case CANCELLED -> monitor.checkCancelled(); + case UNRECOGNISED -> { + // Not cached, so selecting the function again checks the server afresh. + cache.remove(function); + reportDecompStopped(function, "the server reported a status this plugin does not recognise (%s)" + .formatted(result.status().status())); + } + case TIMED_OUT -> { + cache.remove(function); + reportDecompStopped(function, "it has not finished after %s; use Refresh to check again" + .formatted(StatusPoller.describe(result.waited()))); + } + case DONE -> {} + } + } + + /// Acts on each polled status: shows it, and once the decompilation is done starts the summary + /// and then the inline comments, which the server no longer runs on its own. + private final class DecompPollStep { + private final TypedApiInterface.FunctionID id; + private AIDecompilationStatus lastDecompStatus = null; + private boolean inlineCommentsTriggered = false; + private boolean summaryTriggered = false; + + DecompPollStep(TypedApiInterface.FunctionID id) { + this.id = id; + } + + StatusPoller.Verdict next(AIDecompilationStatus newStatus, TaskMonitor monitor) { + var logger = tool.getService(ReaiLoggingService.class); + var api = service.getApi(); if (lastDecompStatus == null || !Objects.equals(newStatus.status(), lastDecompStatus.status()) || !Objects.equals(newStatus.summaryStatus(), lastDecompStatus.summaryStatus()) @@ -997,28 +1113,21 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) newStatusForFunction(functionWithID.function(), newStatus); } monitor.setMessage("Waiting for AI Decompilation for %s ... Current status: %s".formatted(functionWithID.function().getName(), lastDecompStatus.status())); - monitor.checkCancelled(); switch (newStatus.status()) { case PENDING: case RUNNING: case UNINITIALISED: - try { - // Wait a second before polling again. We don't want to spam the API with requests too often - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - break; + return StatusPoller.Verdict.WAIT; case COMPLETED: monitor.setProgress(monitor.getMaximum()); // Decompilation is done; now wait for inline comments to land before stopping. var commentsStatus = newStatus.inlineCommentsStatus(); if (commentsStatus == WorkflowProgress.StatusEnum.COMPLETED) { - return; + return StatusPoller.Verdict.DONE; } if (commentsStatus == WorkflowProgress.StatusEnum.FAILED) { logger.error("Inline comments generation failed for function %s".formatted(functionWithID.function().getName())); - return; + return StatusPoller.Verdict.DONE; } var summaryStatus = newStatus.summaryStatus(); if (!summaryTriggered) { @@ -1032,7 +1141,9 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) if (e.getCause() instanceof ApiException apiException && apiException.getCode() == 409) { summaryTriggered = false; } else { + // Without a summary there are no inline comments either, so there is nothing left to wait for. logger.error("Failed to trigger summary: %s".formatted(e.getMessage())); + return StatusPoller.Verdict.DONE; } } } @@ -1040,7 +1151,7 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) // Server requires a summary to exist before inline comments can be generated; // if the summary failed there's no point triggering comments. logger.error("Summary generation failed for function %s; skipping inline comments".formatted(functionWithID.function().getName())); - return; + return StatusPoller.Verdict.DONE; } if (summaryStatus == WorkflowProgress.StatusEnum.COMPLETED && !inlineCommentsTriggered) { // Gate the inline-comments POST on summary completion — the server rejects it @@ -1050,22 +1161,16 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) api.triggerAIDecompilationInlineComments(id); } catch (RuntimeException e) { logger.error("Failed to trigger inline comments: %s".formatted(e.getMessage())); - return; + return StatusPoller.Verdict.DONE; } } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - break; + return StatusPoller.Verdict.WAIT; case FAILED: logger.error("Decompilation failed: %s".formatted(newStatus.decompilation())); - return; + return StatusPoller.Verdict.DONE; default: - throw new RuntimeException("Unknown status: %s".formatted(newStatus.status())); + return StatusPoller.Verdict.UNRECOGNISED; } - } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 31a6b2b8..57414cee 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -3,6 +3,7 @@ import ai.reveng.model.*; import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.CollectionSelectionPanel; @@ -28,6 +29,7 @@ import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import java.time.Duration; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -78,8 +80,10 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone protected final List functionMatchResults; protected final List filteredFunctionMatchResults; - // Polling configuration - protected static final int POLL_INTERVAL_MS = 2000; // Poll every 2 seconds + // Polling configuration: every 2 seconds, slowing to every 10 while nothing changes, for at most 30 minutes + protected static final Duration POLL_INTERVAL = Duration.ofSeconds(2); + protected static final Duration MAX_POLL_INTERVAL = Duration.ofSeconds(10); + protected static final Duration MAX_MATCHING_WAIT = Duration.ofMinutes(30); protected AbstractFunctionMatchingDialog(String title, Boolean isModal, PluginTool tool, GhidraRevengService.AnalysedProgram analyzedProgram) { @@ -155,27 +159,45 @@ protected record MatchingProgress(String status, String step, Long stepIndex, Lo private void runMatchingLoop() { final Thread self = Thread.currentThread(); try { - MatchingProgress progress = startMatching(); - while (matchingThread == self) { - final MatchingProgress current = progress; - onEdtIfCurrent(self, () -> updateProgressUI(current)); - - if ("FAILED".equals(progress.status())) { - String errorMsg = progress.errorMessage() != null && !progress.errorMessage().isEmpty() - ? progress.errorMessage() - : "Function matching returned an error status"; - onEdtIfCurrent(self, () -> { - handleError(errorMsg); - statusLabel.setText("Function matching failed"); - }); - return; - } - if ("COMPLETED".equals(progress.status())) { - break; - } - Thread.sleep(POLL_INTERVAL_MS); - if (matchingThread != self) return; - progress = pollMatchingStatus(); + boolean[] started = {false}; + var result = new StatusPoller(POLL_INTERVAL, MAX_POLL_INTERVAL, MAX_MATCHING_WAIT).poll( + () -> { + if (!started[0]) { + started[0] = true; + return startMatching(); + } + return pollMatchingStatus(); + }, + current -> { + onEdtIfCurrent(self, () -> updateProgressUI(current)); + return classifyMatchingStatus(current.status()); + }, + () -> matchingThread != self); + if (matchingThread != self) return; + String stopped = switch (result.ending()) { + case UNRECOGNISED -> "The server reported a function matching status this plugin does not recognise " + + "(the matching may have been cancelled). Press Match Functions to start it again."; + case TIMED_OUT -> "Function matching has not finished after %s; stopped waiting. Press Match Functions to check again." + .formatted(StatusPoller.describe(result.waited())); + default -> null; + }; + if (stopped != null) { + onEdtIfCurrent(self, () -> { + handleError(stopped); + statusLabel.setText("Stopped waiting for function matching"); + }); + return; + } + var progress = result.status(); + if ("FAILED".equals(progress.status())) { + String errorMsg = progress.errorMessage() != null && !progress.errorMessage().isEmpty() + ? progress.errorMessage() + : "Function matching returned an error status"; + onEdtIfCurrent(self, () -> { + handleError(errorMsg); + statusLabel.setText("Function matching failed"); + }); + return; } if (matchingThread != self) return; @@ -216,6 +238,19 @@ private void runMatchingLoop() { } } + /// How a v3 matching status (as its wire value) bears on the wait. The SDK turns a status it does + /// not model, such as CANCELLED, into an "unknown" value; that and a missing status end the wait. + protected static StatusPoller.Verdict classifyMatchingStatus(String status) { + if (status == null) { + return StatusPoller.Verdict.UNRECOGNISED; + } + return switch (status) { + case "COMPLETED", "FAILED" -> StatusPoller.Verdict.DONE; + case "UNINITIALISED", "PENDING", "RUNNING" -> StatusPoller.Verdict.WAIT; + default -> StatusPoller.Verdict.UNRECOGNISED; + }; + } + /// Joins the error-level {@link ProgressMessage}s of a v3 matching response into a single string protected static String errorTextFrom(List messages) { if (messages == null) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java index ec9a6f18..6e5a0bdd 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java @@ -4,6 +4,7 @@ import ai.reveng.model.GetMatchesStatusOutputBody; import ai.reveng.model.StartMatchingForFunctionsInputBody; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatch; @@ -37,6 +38,7 @@ import javax.swing.event.ListSelectionEvent; import java.awt.*; import java.math.BigDecimal; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -437,6 +439,11 @@ public boolean isCellEditable(int row, int column) { * Task to fetch similar functions from the API */ private class FetchSimilarFunctionsTask extends Task { + // Matching one function is quick: poll every half second, slowing to every 5 while nothing changes, for at most 5 minutes + private static final Duration POLL_INTERVAL = Duration.ofMillis(500); + private static final Duration MAX_POLL_INTERVAL = Duration.ofSeconds(5); + private static final Duration MAX_MATCHING_WAIT = Duration.ofMinutes(5); + private final GhidraRevengService.AnalysedProgram program; private final GhidraRevengService.FunctionWithID functionWithID; @@ -461,21 +468,27 @@ public void run(TaskMonitor monitor) { monitor.setMessage("Fetching matches from RevEng.AI..."); service.startFunctionsMatching(request); - while (true) { - if (monitor.isCancelled()) { + var polled = new StatusPoller(POLL_INTERVAL, MAX_POLL_INTERVAL, MAX_MATCHING_WAIT).poll( + () -> service.getFunctionsMatchingStatus(functionIds), + statusResponse -> AbstractFunctionMatchingDialog.classifyMatchingStatus( + statusResponse.getStatus() == null ? null : statusResponse.getStatus().getValue()), + monitor::isCancelled); + switch (polled.ending()) { + case CANCELLED -> { return; } - GetMatchesStatusOutputBody statusResponse = service.getFunctionsMatchingStatus(functionIds); - String status = statusResponse.getStatus() == null ? null : statusResponse.getStatus().getValue(); - if ("COMPLETED".equals(status)) { - break; - } - if ("FAILED".equals(status)) { - String errorMsg = AbstractFunctionMatchingDialog.errorTextFrom(statusResponse.getMessages()); - throw new RuntimeException(errorMsg == null || errorMsg.isEmpty() - ? "Function matching failed" : errorMsg); + case UNRECOGNISED -> throw new RuntimeException( + "function matching reported a status this plugin does not recognise (it may have been cancelled)"); + case TIMED_OUT -> throw new RuntimeException("function matching has not finished after %s" + .formatted(StatusPoller.describe(polled.waited()))); + case DONE -> { + var statusResponse = polled.status(); + if (statusResponse.getStatus() == GetMatchesStatusOutputBody.StatusEnum.FAILED) { + String errorMsg = AbstractFunctionMatchingDialog.errorTextFrom(statusResponse.getMessages()); + throw new RuntimeException(errorMsg == null || errorMsg.isEmpty() + ? "Function matching failed" : errorMsg); + } } - Thread.sleep(100); } GetMatchesOutputBody response = service.getFunctionsMatches(functionIds); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index 0286bc09..db33b385 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -4,6 +4,9 @@ import ai.reveng.toolkit.ghidra.core.AnalysisLogConsumer; import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ghidra.framework.plugintool.ComponentProviderAdapter; import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Program; @@ -90,7 +93,8 @@ public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { this.setVisible(true); switch (event.getStatus()) { - case Complete, Error -> {} + // Unknown: the wait for it has already ended, so starting another would end at once and loop + case Complete, Error, Unknown -> {} default -> { if (!trackedPrograms.containsKey(event.getProgram())){ // We aren't tracking this program yet, so we start a new task for it @@ -115,6 +119,22 @@ public void consumeLogs(String logs, GhidraRevengService.ProgramWithID programWi } + /// What to tell the user when the wait for an analysis ended without it finishing, or null when + /// there is nothing to tell (it finished, or the user cancelled the wait). + public static String unfinishedWaitMessage(StatusPoller.Result result, + GhidraRevengService.ProgramWithID program) { + return switch (result.ending()) { + case UNRECOGNISED -> ("RevEng.AI: analysis %d of %s reports a status this plugin does not recognise; " + + "stopped waiting for it. Use Check status or View in portal to follow it.") + .formatted(program.analysisID().id(), program.program().getName()); + case TIMED_OUT -> ("RevEng.AI: analysis %d of %s has not finished after %s (status: %s); stopped waiting. " + + "It keeps running on the server: reopen the program to resume waiting, or use View in portal.") + .formatted(program.analysisID().id(), program.program().getName(), + StatusPoller.describe(result.waited()), result.status()); + case DONE, CANCELLED -> null; + }; + } + class AnalysisMonitoringTask extends Task { private final GhidraRevengService.ProgramWithID program; @@ -131,7 +151,12 @@ public void run(TaskMonitor monitor) throws CancelledException { // Wait for the analysis var service = tool.getService(GhidraRevengService.class); try { - service.waitForFinishedAnalysis(monitor, program, this.logConsumer, tool); + var result = service.waitForAnalysis(monitor, program, this.logConsumer, tool); + var message = unfinishedWaitMessage(result, program); + if (message != null) { + tool.getService(ReaiLoggingService.class).warn(message); + SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, true)); + } } finally { /// waitForFinishedAnalysis has already sent the completion event to all plugins /// so this task just needs to clean up the tracked programs map diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index faf5e2ed..f20e7475 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -48,6 +48,7 @@ import java.net.URI; import java.nio.file.InvalidPathException; import java.nio.file.Path; +import java.time.Duration; import java.util.*; import java.util.Collection; import java.util.List; @@ -1338,7 +1339,11 @@ public AnalysisStatus status(ProgramWithID program) { public AnalysedProgram analyse(Program program, AnalysisOptionsBuilder analysisOptionsBuilder, TaskMonitor monitor) throws CancelledException, ApiException { // Check if we are on the swing thread var programWithBinaryID = startAnalysis(program, analysisOptionsBuilder); - var finalStatus = waitForFinishedAnalysis(monitor, programWithBinaryID, null, null); + var waited = waitForAnalysis(monitor, programWithBinaryID, null, null); + if (waited.ending() != StatusPoller.Ending.DONE) { + throw new IllegalStateException("Analysis %s did not finish (%s, last status: %s)" + .formatted(programWithBinaryID.analysisID().id(), waited.ending(), waited.status())); + } // TODO: Check final status for errors, and do something appropriate on failure var analysedProgram = registerFinishedAnalysisForProgram(programWithBinaryID, monitor); if (getKnownProgram(program).isEmpty()){ @@ -1427,7 +1432,9 @@ public void openPortal(ServiceProvider serviceProvider, String... subPath) { /** * @param tool The UI tool for firing an event on status changes. Can be null - * @return The final AnalysisStatus, should be either Complete or Error + * @return The final AnalysisStatus: Complete or Error when the analysis finished, Unknown when the + * server reported a status the plugin does not recognise, or the last status seen when the wait + * reached its time limit or was interrupted */ public AnalysisStatus waitForFinishedAnalysis( TaskMonitor monitor, @@ -1436,67 +1443,85 @@ public AnalysisStatus waitForFinishedAnalysis( @Nullable PluginTool tool ) throws CancelledException { + return waitForAnalysis(monitor, programWithID, logger, tool).status(); + } + + /// Like {@link #waitForFinishedAnalysis}, but also says why the wait ended, so the caller can tell + /// the user when it stopped without the analysis finishing. + /// + /// @throws CancelledException the monitor was cancelled + public StatusPoller.Result waitForAnalysis( + TaskMonitor monitor, + ProgramWithID programWithID, + @Nullable AnalysisLogConsumer logger, + @Nullable PluginTool tool + ) throws CancelledException { monitor.setMessage("Checking analysis status"); - // Check the status of the analysis every 500ms - // TODO: In the future this can be made smarter and e.g. wait longer if the analysis log hasn't changed - AnalysisStatus lastStatus = null; - long delay = pollIntervalMs; - int failures = 0; - while (true) { - AnalysisStatus currentStatus; - try { - currentStatus = api.status(programWithID.analysisID()); - delay = pollIntervalMs; - failures = 0; - } catch (ApiException e) { - if (!isTransient(e) || ++failures >= MAX_POLL_ATTEMPTS) { - throw new RuntimeException(e); - } - Msg.warn(this, "Transient error polling analysis status, retrying in %dms".formatted(delay), e); - monitor.checkCancelled(); - try { - Thread.sleep(delay); - } catch (InterruptedException ie) { - return lastStatus; - } - delay = Math.min(delay * 2, maxPollBackoffMs); - continue; - } - if (currentStatus != AnalysisStatus.Uploaded && currentStatus != AnalysisStatus.Queued) { - // Analysis log endpoint only starts to return data after the analysis is processing - try { - String logs = this.getAnalysisLog(programWithID.analysisID()); - if (logger != null) { - logger.consumeLogs(logs, programWithID); + var poller = new StatusPoller( + Duration.ofMillis(pollIntervalMs), Duration.ofMillis(maxPollIntervalMs), Duration.ofMillis(maxAnalysisWaitMs)) + .retrying(e -> { + if (e instanceof ApiException api && isTransient(api)) { + Msg.warn(this, "Transient error polling analysis status, retrying", e); + return true; } - logs.lines().reduce((first, second) -> second).ifPresent(monitor::setMessage); - } catch (RuntimeException e) { - // Logs are cosmetic; a failed fetch must not end the wait - Msg.warn(this, "Failed to fetch analysis logs", e); - } - } - if (currentStatus != lastStatus) { - lastStatus = currentStatus; - if (tool != null){ - tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus)); - } - } - - if (lastStatus == AnalysisStatus.Complete || lastStatus == AnalysisStatus.Error) { - // Show the UI message for the completion - return lastStatus; - } + return false; + }, MAX_POLL_ATTEMPTS, Duration.ofMillis(maxPollBackoffMs)); + AnalysisStatus[] lastStatus = {null}; + StatusPoller.Result result; + try { + result = poller.poll( + () -> api.status(programWithID.analysisID()), + currentStatus -> { + if (currentStatus != AnalysisStatus.Uploaded && currentStatus != AnalysisStatus.Queued) { + // Analysis log endpoint only starts to return data after the analysis is processing + try { + String logs = this.getAnalysisLog(programWithID.analysisID()); + if (logger != null) { + logger.consumeLogs(logs, programWithID); + } + logs.lines().reduce((first, second) -> second).ifPresent(monitor::setMessage); + } catch (RuntimeException e) { + // Logs are cosmetic; a failed fetch must not end the wait + Msg.warn(this, "Failed to fetch analysis logs", e); + } + } + if (currentStatus != lastStatus[0]) { + lastStatus[0] = currentStatus; + if (tool != null) { + tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus)); + } + } + return switch (currentStatus) { + case Complete, Error -> StatusPoller.Verdict.DONE; + case Uploaded, Queued, Processing -> StatusPoller.Verdict.WAIT; + case Unknown -> StatusPoller.Verdict.UNRECOGNISED; + }; + }, + monitor::isCancelled); + } catch (ApiException e) { + throw new RuntimeException(e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return new StatusPoller.Result<>(StatusPoller.Ending.CANCELLED, lastStatus[0], Duration.ZERO); + } + if (result.ending() == StatusPoller.Ending.CANCELLED) { monitor.checkCancelled(); - try { - Thread.sleep(pollIntervalMs); - } catch (InterruptedException e) { - return lastStatus; - } } + if (result.ending() == StatusPoller.Ending.TIMED_OUT) { + Msg.warn(this, "Stopped waiting for analysis %s after %s; last status: %s" + .formatted(programWithID.analysisID().id(), StatusPoller.describe(result.waited()), result.status())); + } + return result; } + /// First wait between status polls; it grows while the status stays the same private long pollIntervalMs = 500; + /// Longest wait between status polls while the analysis is running normally + private long maxPollIntervalMs = 5_000; + /// Longest wait between status polls while the status endpoint keeps failing transiently private long maxPollBackoffMs = 30_000; + /// How long to wait for an analysis before giving up; it keeps running on the server + private long maxAnalysisWaitMs = Duration.ofHours(3).toMillis(); private static final int MAX_POLL_ATTEMPTS = 10; /// 5xx, or no response at all (code 0: connection or timeout failure) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java new file mode 100644 index 00000000..72454d33 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java @@ -0,0 +1,164 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import javax.annotation.Nullable; +import java.time.Duration; +import java.util.Objects; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Predicate; + +/// Polls a server-side job until it reaches a final status, for every job the plugin waits on +/// (analysis, function matching, Similar Functions, AI decompilation). +/// +/// Polls start {@link #interval} apart. While the status stays the same the wait doubles, up to +/// {@link #maxInterval}; any change resets it, so an active job is followed closely and a long, +/// quiet one is not hammered. Polling always ends: when the status is final, when it is one the +/// caller does not recognise, when {@link #timeLimit} is reached, or when the caller cancels. +/// +/// A failed fetch ends polling by rethrowing its exception, unless {@link #retrying} marks it as +/// worth retrying; those back off separately, up to a number of consecutive failures. +public final class StatusPoller { + + /// What a fetched status means for the wait. + public enum Verdict { + /// Still running; poll again. + WAIT, + /// Final, whether it succeeded or failed; the caller reads which from the status. + DONE, + /// A status the caller does not model. Waiting on it could last for ever, so polling ends. + UNRECOGNISED + } + + /// Why polling ended. + public enum Ending { DONE, UNRECOGNISED, TIMED_OUT, CANCELLED } + + /// @param status the last status fetched, or null when none was + public record Result(Ending ending, @Nullable S status, Duration waited) {} + + @FunctionalInterface + public interface Fetch { + S get() throws E; + } + + /// Longest single sleep, so a cancellation is noticed promptly even during a long backoff. + private static final long CANCEL_CHECK_MS = 200; + + private final Duration interval; + private final Duration maxInterval; + private final Duration timeLimit; + private Predicate retryable = e -> false; + private int maxConsecutiveFailures = 1; + private Duration maxRetryBackoff; + + public StatusPoller(Duration interval, Duration maxInterval, Duration timeLimit) { + this.interval = interval; + this.maxInterval = maxInterval.compareTo(interval) < 0 ? interval : maxInterval; + this.timeLimit = timeLimit; + this.maxRetryBackoff = this.maxInterval; + } + + /// Retry a fetch that fails with an exception {@code retryable} accepts, backing off up to + /// {@code maxBackoff}, and give up on the {@code maxConsecutiveFailures}th failure in a row. + public StatusPoller retrying(Predicate retryable, int maxConsecutiveFailures, Duration maxBackoff) { + this.retryable = retryable; + this.maxConsecutiveFailures = maxConsecutiveFailures; + this.maxRetryBackoff = maxBackoff; + return this; + } + + /// Poll until {@code classify} reports a final or unrecognised status, the time limit is reached + /// or {@code cancelled} turns true. {@code classify} sees every fetched status exactly once, in + /// order, so it may also act on them (update the UI, trigger a follow-up step). + /// + /// @throws E the fetch failed, and was not retryable or failed too often in a row + /// @throws InterruptedException the polling thread was interrupted while waiting + public Result poll(Fetch fetch, Function classify, + BooleanSupplier cancelled) throws E, InterruptedException { + long start = System.nanoTime(); + S last = null; + boolean fetched = false; + long delay = interval.toMillis(); + long retryDelay = interval.toMillis(); + int failures = 0; + while (true) { + if (cancelled.getAsBoolean()) { + return result(Ending.CANCELLED, last, start); + } + S current; + try { + current = fetch.get(); + failures = 0; + retryDelay = interval.toMillis(); + } catch (Exception e) { + if (!retryable.test(e) || ++failures >= maxConsecutiveFailures) { + throw e; + } + if (!sleepWithinLimit(retryDelay, start, cancelled)) { + return result(cancelled.getAsBoolean() ? Ending.CANCELLED : Ending.TIMED_OUT, last, start); + } + retryDelay = Math.min(retryDelay * 2, maxRetryBackoff.toMillis()); + continue; + } + + if (fetched && Objects.equals(current, last)) { + delay = Math.min(delay * 2, maxInterval.toMillis()); + } else { + delay = interval.toMillis(); + } + last = current; + fetched = true; + + switch (classify.apply(current)) { + case DONE -> { + return result(Ending.DONE, current, start); + } + case UNRECOGNISED -> { + return result(Ending.UNRECOGNISED, current, start); + } + case WAIT -> { + if (!sleepWithinLimit(delay, start, cancelled)) { + return result(cancelled.getAsBoolean() ? Ending.CANCELLED : Ending.TIMED_OUT, last, start); + } + } + } + } + } + + public Duration timeLimit() { + return timeLimit; + } + + /// Sleep for {@code millis}, in short steps so a cancellation cuts it short. + /// + /// @return false, without sleeping, if the sleep would run past the time limit; false if + /// cancelled while sleeping; true otherwise + private boolean sleepWithinLimit(long millis, long start, BooleanSupplier cancelled) throws InterruptedException { + long elapsed = (System.nanoTime() - start) / 1_000_000; + if (elapsed + millis > timeLimit.toMillis()) { + return false; + } + long deadline = System.nanoTime() + millis * 1_000_000; + long remaining; + while ((remaining = (deadline - System.nanoTime()) / 1_000_000) > 0) { + if (cancelled.getAsBoolean()) { + return false; + } + Thread.sleep(Math.min(remaining, CANCEL_CHECK_MS)); + } + return !cancelled.getAsBoolean(); + } + + private static Result result(Ending ending, @Nullable S status, long start) { + return new Result<>(ending, status, Duration.ofNanos(System.nanoTime() - start)); + } + + /// "3 hours" / "30 minute(s)" / "45 second(s)", rounded, for messages that say how long the plugin + /// waited. A wait that hit its time limit stops just short of it, so it is rounded to the nearest unit. + public static String describe(Duration duration) { + long seconds = duration.toSeconds(); + if (seconds >= 2 * 3600) { + return Math.round(seconds / 3600.0) + " hours"; + } + return seconds >= 60 ? Math.round(seconds / 60.0) + " minute(s)" : seconds + " second(s)"; + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 0ac5df8c..86df7913 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -509,12 +509,12 @@ public AIDecompilationStatus pollAIDecompileStatus(FunctionID functionID) { inlineComments, decompilationProgress); } catch (ApiException e) { + // A function that was never decompiled is a 200 with status UNINITIALISED; a 404 means the + // function itself was not found, and treating it as "not started yet" polled for ever. if (e.getCode() == 404) { - return new AIDecompilationStatus( - DecompilationData.StatusEnum.UNINITIALISED, - null, null, null, null, null, List.of(), null); + throw new RuntimeException("RevEng.AI could not find function %d (HTTP 404)".formatted(functionID.value()), e); } - throw new RuntimeException("Failed to poll AI decompilation status", e); + throw new RuntimeException("Failed to poll AI decompilation status: " + describeApiException(e), e); } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index fb30064c..593da47c 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -318,7 +318,7 @@ public void run(TaskMonitor monitor) { knownProgram.get(), status)); } - case Queued, Processing -> { + case Uploaded, Queued, Processing -> { // This is the same code as above, but it has the implicit assumption that someone /// Currently this is done by {@link AnalysisLogComponent#processEvent(RevEngAIAnalysisStatusChangedEvent)} tool.firePluginEvent( @@ -334,6 +334,12 @@ public void run(TaskMonitor monitor) { Msg.showError(AnalysisManagementPlugin.this, null, "Analysis Error", "The RevEng.AI analysis for the program " + knownProgram.get() + " is in error state on the server side."); } + case Unknown -> { + // Not waited on: an unrecognised status might never change into one that ends the wait + var message = unknownStatusOnOpenMessage(knownProgram.get()); + tool.getService(ReaiLoggingService.class).warn(message); + SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, true)); + } } } }, 0); @@ -405,6 +411,12 @@ public void run(TaskMonitor monitor) { } } + static String unknownStatusOnOpenMessage(GhidraRevengService.ProgramWithID program) { + return ("RevEng.AI: analysis %d of %s reports a status this plugin does not recognise; not waiting for it. " + + "Use Check status or View in portal to follow it.") + .formatted(program.analysisID().id(), program.program().getName()); + } + static String checkStatusMessage(AnalysisStatus status) { return "Analysis status: " + status; } diff --git a/src/test/java/ai/reveng/AIDecompilerComponentTest.java b/src/test/java/ai/reveng/AIDecompilerComponentTest.java index 65dce2d9..ad975e91 100644 --- a/src/test/java/ai/reveng/AIDecompilerComponentTest.java +++ b/src/test/java/ai/reveng/AIDecompilerComponentTest.java @@ -429,6 +429,165 @@ public void triggerAIDecompilationInlineComments(FunctionID functionID) { assertEquals("summary trigger must be retried after a 409", 2, summaryTriggers.get()); } + /// A summary trigger that fails with anything but 409 ends the wait: the summary will never arrive + @Test + public void testSummaryTriggerFailureStopsPolling() throws Exception { + var tool = env.getTool(); + var summaryTriggers = new AtomicInteger(); + var polls = new AtomicInteger(); + + var service = addMockedService(tool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { + return new AnalysisID(1); + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of(new FunctionInfo(new FunctionID(1), "portal_func_1", "portal_func_1_mangled", 0x1000L, 10)); + } + + @Override + public AIDecompilationStatus pollAIDecompileStatus(FunctionID functionID) { + polls.incrementAndGet(); + return new AIDecompilationStatus( + DecompilationData.StatusEnum.COMPLETED, + "void func1() { return; }", + null, + null, + WorkflowProgress.StatusEnum.UNINITIALISED, + WorkflowProgress.StatusEnum.UNINITIALISED, + List.of(), + null); + } + + @Override + public void triggerAIDecompilationSummary(FunctionID functionID) { + summaryTriggers.incrementAndGet(); + throw new RuntimeException("Failed to trigger AI decompilation summary", + new ApiException(402, "Insufficient credits")); + } + }); + + env.addPlugin(BinarySimilarityPlugin.class); + var builder = newX64Program(); + var func1 = builder.createEmptyFunction(null, "0x1000", 10, Undefined.getUndefinedDataType(4)); + var programWithID = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(programWithID.program()); + + var aiDecompComponent = getComponentProvider(AIDecompilationdWindow.class); + aiDecompComponent.setVisible(true); + RSyntaxTextArea textArea = (RSyntaxTextArea) getInstanceField("textArea", aiDecompComponent); + + var action = getAction(tool, "AI Decompilation"); + var context = new ProgramLocationActionContext( + null, + programWithID.program(), + new ProgramLocation(programWithID.program(), func1.getEntryPoint()), + null, null); + performAction(action, context, true); + waitForTasks(); + waitForSwing(); + + assertEquals(1, summaryTriggers.get()); + // The status check before triggering, and the one poll that saw the decompilation completed + assertEquals(2, polls.get()); + assertEquals("void func1() { return; }", textArea.getText()); + } + + /// A FAILED decompilation can be run again with the Regenerate action; Refresh alone only re-reads the failure + @Test + public void testRegenerateFailedDecompilation() throws Exception { + var tool = env.getTool(); + var triggers = new AtomicInteger(); + + var service = addMockedService(tool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { + return new AnalysisID(1); + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of(new FunctionInfo(new FunctionID(1), "portal_func_1", "portal_func_1_mangled", 0x1000L, 10)); + } + + @Override + public AIDecompilationStatus pollAIDecompileStatus(FunctionID functionID) { + if (triggers.get() == 0) { + return new AIDecompilationStatus( + DecompilationData.StatusEnum.FAILED, "", null, null, null, null, List.of(), null); + } + return new AIDecompilationStatus( + DecompilationData.StatusEnum.COMPLETED, + "void func1() { return; }", + "Mocked Description Summary", + null, + WorkflowProgress.StatusEnum.COMPLETED, + WorkflowProgress.StatusEnum.COMPLETED, + List.of(), + null); + } + + @Override + public boolean triggerAIDecompilationForFunctionID(FunctionID functionID) { + triggers.incrementAndGet(); + return true; + } + }); + + env.addPlugin(BinarySimilarityPlugin.class); + var builder = newX64Program(); + var func1 = builder.createEmptyFunction(null, "0x1000", 10, Undefined.getUndefinedDataType(4)); + var programWithID = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(programWithID.program()); + + var aiDecompComponent = getComponentProvider(AIDecompilationdWindow.class); + aiDecompComponent.setVisible(true); + RSyntaxTextArea textArea = (RSyntaxTextArea) getInstanceField("textArea", aiDecompComponent); + javax.swing.JEditorPane descriptionArea = + (javax.swing.JEditorPane) getInstanceField("descriptionArea", aiDecompComponent); + + var action = getAction(tool, "AI Decompilation"); + var context = new ProgramLocationActionContext( + null, + programWithID.program(), + new ProgramLocation(programWithID.program(), func1.getEntryPoint()), + null, null); + performAction(action, context, true); + waitForTasks(); + waitForSwing(); + + assertEquals("a FAILED decompilation must not be re-triggered on its own", 0, triggers.get()); + assertTrue(descriptionArea.getText(), descriptionArea.getText().contains("Regenerate")); + + performAction(getLocalAction(aiDecompComponent, "Refresh AI Decompilation")); + waitForTasks(); + waitForSwing(); + assertEquals("Refresh only re-reads the result", 0, triggers.get()); + + var regenerate = getLocalAction(aiDecompComponent, "Regenerate AI Decompilation"); + assertTrue(runSwing(() -> regenerate.isEnabledForContext(aiDecompComponent.getActionContext(null)))); + performAction(regenerate); + waitForTasks(); + waitForSwing(); + + assertEquals(1, triggers.get()); + assertEquals("void func1() { return; }", textArea.getText()); + assertFalse("Regenerate is only offered for a failed decompilation", + runSwing(() -> regenerate.isEnabledForContext(aiDecompComponent.getActionContext(null)))); + } + static class RatingsAPI extends UnimplementedAPI { String lastFeedback; String lastReason; diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index ecc1fe61..18ff03ab 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -727,6 +727,57 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { /// The function-level dialog matches by itself when it opens, and its Match button reads Cancel while /// a run is going. Waits for that first run to finish, so that pressing Match starts a new run rather /// than, on a slow machine, cancelling the one that started after the button was looked up. + /// A status the SDK does not model (the server's CANCELLED) ends the wait instead of polling for ever + @Test + public void testUnrecognisedMatchingStatusStopsPolling() throws Exception { + var tool = env.getTool(); + var statusPolls = new java.util.concurrent.atomic.AtomicInteger(); + var mockApi = new FunctionMatchingMockApi() { + @Override + public StartMatchingOutputBody startFunctionsMatching(StartMatchingForFunctionsInputBody request) { + super.startFunctionsMatching(request); + var response = new StartMatchingOutputBody(); + response.setStatus(StartMatchingOutputBody.StatusEnum.RUNNING); + return response; + } + + @Override + public GetMatchesStatusOutputBody getFunctionsMatchingStatus(List functionIds) { + statusPolls.incrementAndGet(); + var response = new GetMatchesStatusOutputBody(); + response.setStatus(GetMatchesStatusOutputBody.StatusEnum.fromValue("CANCELLED")); + return response; + } + }; + var service = addMockedService(tool, mockApi); + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + ); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JLabel statusLabel = (JLabel) getInstanceField("statusLabel", foundDialog); + JButton matchButton = (JButton) getInstanceField("matchButton", foundDialog); + waitForCondition(() -> runSwing(() -> statusLabel.getText().equals("Stopped waiting for function matching") + && getInstanceField("matchingThread", foundDialog) == null + && matchButton.getText().equals("Match Functions")), + "An unrecognised status should end the matching run"); + JTextArea errorArea = (JTextArea) getInstanceField("errorArea", foundDialog); + assertTrue(errorArea.getText(), errorArea.getText().contains("does not recognise")); + assertEquals(1, statusPolls.get()); + + close(foundDialog); + waitForSwing(); + } + private void waitForMatchingIdle(FunctionLevelFunctionMatchingDialog dialog) { JLabel statusLabel = (JLabel) getInstanceField("statusLabel", dialog); JButton matchButton = (JButton) getInstanceField("matchButton", dialog); diff --git a/src/test/java/ai/reveng/GhidraRevengServiceTest.java b/src/test/java/ai/reveng/GhidraRevengServiceTest.java index c9e2c6e3..85a1880a 100644 --- a/src/test/java/ai/reveng/GhidraRevengServiceTest.java +++ b/src/test/java/ai/reveng/GhidraRevengServiceTest.java @@ -3,6 +3,7 @@ import ai.reveng.invoker.ApiException; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; @@ -64,6 +65,69 @@ public AnalysisStatus status(AnalysisID analysisID) throws ApiException { assertEquals(10, statusCalls[0]); } + @Test + public void testStatusPollingEndsOnUnrecognisedStatus() throws Exception { + var statusCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls[0]++; + return AnalysisStatus.Unknown; + } + }); + setInstanceField("pollIntervalMs", service, 1L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + var result = service.waitForAnalysis(TaskMonitor.DUMMY, programWithID, null, null); + assertEquals(StatusPoller.Ending.UNRECOGNISED, result.ending()); + assertEquals(AnalysisStatus.Unknown, result.status()); + assertEquals(1, statusCalls[0]); + } + + @Test + public void testStatusPollingStopsAtTheTimeLimit() throws Exception { + var logCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Processing; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + logCalls[0]++; + return "still going"; + } + }); + setInstanceField("pollIntervalMs", service, 5L); + setInstanceField("maxPollIntervalMs", service, 20L); + setInstanceField("maxAnalysisWaitMs", service, 200L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + var result = service.waitForAnalysis(TaskMonitor.DUMMY, programWithID, null, null); + assertEquals(StatusPoller.Ending.TIMED_OUT, result.ending()); + assertEquals(AnalysisStatus.Processing, result.status()); + // Backing off to 20ms, 200ms holds well under the 40 polls a fixed 5ms interval would make + assertTrue("polled " + logCalls[0] + " times", logCalls[0] < 25); + } + + @Test + public void testStatusPollingWaitsThroughUploaded() throws Exception { + var statusCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return ++statusCalls[0] < 3 ? AnalysisStatus.Uploaded : AnalysisStatus.Complete; + } + }); + setInstanceField("pollIntervalMs", service, 1L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + assertEquals(AnalysisStatus.Complete, + service.waitForFinishedAnalysis(TaskMonitor.DUMMY, programWithID, null, null)); + assertEquals(3, statusCalls[0]); + } + static class OfflineAfterSetupAPI extends UnimplementedAPI { volatile boolean offline = false; int statusCalls = 0; diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index b31b748c..4e1e85dd 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -3,6 +3,7 @@ import ai.reveng.invoker.ApiException; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.misc.AnalysisLogComponent; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.plugins.AnalysisManagementPlugin; import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; @@ -13,6 +14,7 @@ import ghidra.util.task.TaskMonitorComponent; import org.junit.Test; +import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -190,4 +192,137 @@ public AnalysisStatus status(AnalysisID analysisID) { TaskMonitorComponent taskMonitorComponent = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); assertFalse(taskMonitorComponent.isVisible()); } + + /// An analysis that was still Uploaded when Ghidra closed is waited on again when the program is reopened + @Test + public void testReopenedUploadedAnalysisIsWaitedOn() throws Exception { + var defaultTool = env.getTool(); + var statusCalls = new AtomicInteger(); + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + // Error ends the wait without loading results, which this mock does not provide + return statusCalls.incrementAndGet() <= 2 ? AnalysisStatus.Uploaded : AnalysisStatus.Error; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + + // Waits for the tool to be idle, so also for the monitoring task the reopen starts + env.showTool(program); + waitForTasks(); + + // The check on reopen, then the monitoring task polling until the analysis ends + assertEquals(3, statusCalls.get()); + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(program)); + } + + /// An analysis reporting an unrecognised status on reopen is reported, not waited on + @Test + public void testReopenedUnknownAnalysisIsNotWaitedOn() throws Exception { + var defaultTool = env.getTool(); + var statusCalls = new AtomicInteger(); + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.incrementAndGet(); + return AnalysisStatus.Unknown; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + + env.showTool(program); + waitForCondition(() -> statusCalls.get() > 0, "the status should be checked on reopen"); + waitForTasks(); + waitForSwing(); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(program)); + assertEquals(1, statusCalls.get()); + } + + /// An Unknown status neither starts a wait (it would end at once) nor restarts one when its event arrives late + @Test + public void testUnknownStatusIsNotMonitored() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + + addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.incrementAndGet(); + return AnalysisStatus.Unknown; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Unknown) + ); + waitForSwing(); + waitForTasks(); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + assertEquals(0, statusCalls.get()); + } + + /// A wait that ends on an Unknown status is reported once and is not restarted by its own status event + @Test + public void testWaitEndingOnUnknownStatusStops() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + + addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return statusCalls.incrementAndGet() == 1 ? AnalysisStatus.Processing : AnalysisStatus.Unknown; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) + ); + waitForTasks(); + waitForSwing(); + waitForTasks(); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + assertEquals(2, statusCalls.get()); + TaskMonitorComponent taskMonitorComponent = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + assertFalse(taskMonitorComponent.isVisible()); + } + + @Test + public void testUnfinishedWaitMessages() throws Exception { + var programWithID = getPlaceHolderID(); + var name = programWithID.program().getName(); + + var unrecognised = AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.UNRECOGNISED, AnalysisStatus.Unknown, Duration.ofSeconds(3)), + programWithID); + assertTrue(unrecognised, unrecognised.contains("analysis 1 of " + name)); + assertTrue(unrecognised, unrecognised.contains("does not recognise")); + + var timedOut = AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.TIMED_OUT, AnalysisStatus.Processing, Duration.ofHours(3).minusSeconds(2)), + programWithID); + assertTrue(timedOut, timedOut.contains("has not finished after 3 hours (status: Processing)")); + assertTrue(timedOut, timedOut.contains("reopen the program")); + + assertNull(AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.DONE, AnalysisStatus.Complete, Duration.ZERO), programWithID)); + assertNull(AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.CANCELLED, AnalysisStatus.Queued, Duration.ZERO), programWithID)); + } } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AIDecompilationNotFoundTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AIDecompilationNotFoundTest.java new file mode 100644 index 00000000..c6096189 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AIDecompilationNotFoundTest.java @@ -0,0 +1,36 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.*; + +/// A function that was never decompiled answers 200 with status UNINITIALISED, so a 404 means the +/// function itself was not found. Reading it as UNINITIALISED made the window poll for ever. +public class AIDecompilationNotFoundTest extends AbstractStubServerTest { + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/v3/functions/7/ai-decompilation", exchange -> { + byte[] body = "{\"error\": {\"code\": \"NOT_FOUND\", \"message\": \"function not found\"}}" + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(404, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + } + + @Test + public void notFoundIsAnErrorNotUninitialised() { + var thrown = assertThrows(RuntimeException.class, + () -> api().pollAIDecompileStatus(new TypedApiInterface.FunctionID(7))); + assertTrue(thrown.getMessage(), thrown.getMessage().contains("could not find function 7")); + assertTrue(thrown.getCause() instanceof ApiException api && api.getCode() == 404); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java new file mode 100644 index 00000000..445fe047 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java @@ -0,0 +1,152 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller.Ending; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller.Verdict; +import org.junit.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; + +public class StatusPollerTest { + + private static Verdict classify(String status) { + return switch (status) { + case "DONE", "FAILED" -> Verdict.DONE; + case "RUNNING", "STEP1", "STEP2" -> Verdict.WAIT; + default -> Verdict.UNRECOGNISED; + }; + } + + private static StatusPoller.Fetch sequence(String... statuses) { + Iterator it = List.of(statuses).iterator(); + return () -> it.hasNext() ? it.next() : statuses[statuses.length - 1]; + } + + @Test + public void endsOnFinalStatus() throws Exception { + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .poll(sequence("RUNNING", "RUNNING", "FAILED"), StatusPollerTest::classify, () -> false); + assertEquals(Ending.DONE, result.ending()); + assertEquals("FAILED", result.status()); + } + + @Test + public void endsOnUnrecognisedStatusInsteadOfPollingForEver() throws Exception { + var polls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .poll(() -> { + polls.incrementAndGet(); + return "CANCELLED"; + }, StatusPollerTest::classify, () -> false); + assertEquals(Ending.UNRECOGNISED, result.ending()); + assertEquals("CANCELLED", result.status()); + assertEquals(1, polls.get()); + } + + @Test + public void endsAtTheTimeLimit() throws Exception { + var result = new StatusPoller(Duration.ofMillis(5), Duration.ofMillis(5), Duration.ofMillis(100)) + .poll(sequence("RUNNING"), StatusPollerTest::classify, () -> false); + assertEquals(Ending.TIMED_OUT, result.ending()); + assertEquals("RUNNING", result.status()); + assertTrue(result.waited().toMillis() <= 100); + } + + @Test + public void endsWhenCancelled() throws Exception { + var polls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .poll(() -> "RUNNING", s -> { + polls.incrementAndGet(); + return classify(s); + }, () -> polls.get() >= 3); + assertEquals(Ending.CANCELLED, result.ending()); + assertEquals(3, polls.get()); + } + + @Test + public void cancellingCutsALongWaitShort() throws Exception { + long start = System.nanoTime(); + var polls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofSeconds(30), Duration.ofSeconds(30), Duration.ofMinutes(5)) + .poll(() -> { + polls.incrementAndGet(); + return "RUNNING"; + }, StatusPollerTest::classify, () -> System.nanoTime() - start > 300_000_000L); + assertEquals(Ending.CANCELLED, result.ending()); + assertEquals(1, polls.get()); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 5); + } + + @Test + public void backsOffWhileTheStatusIsUnchangedAndResetsOnChange() throws Exception { + List pollTimes = new ArrayList<>(); + var result = new StatusPoller(Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofSeconds(10)) + .poll(sequence("RUNNING", "RUNNING", "RUNNING", "RUNNING", "STEP1", "STEP2", "DONE"), s -> { + pollTimes.add(System.nanoTime() / 1_000_000); + return classify(s); + }, () -> false); + assertEquals(Ending.DONE, result.ending()); + List gaps = new ArrayList<>(); + for (int i = 1; i < pollTimes.size(); i++) { + gaps.add(pollTimes.get(i) - pollTimes.get(i - 1)); + } + // RUNNING x4: 20, then 40, then 80 (capped); after a change it is back to 20 + assertTrue("gaps: " + gaps, gaps.get(0) >= 20 && gaps.get(0) < 40); + assertTrue("gaps: " + gaps, gaps.get(1) >= 40); + assertTrue("gaps: " + gaps, gaps.get(2) >= 80); + assertTrue("gaps: " + gaps, gaps.get(4) < 40); + assertTrue("gaps: " + gaps, gaps.get(5) < 40); + } + + @Test + public void retriesRetryableFailuresThenGivesUp() { + var calls = new AtomicInteger(); + var poller = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .retrying(e -> e instanceof ApiException api && api.getCode() == 503, 4, Duration.ofMillis(1)); + var thrown = assertThrows(ApiException.class, () -> poller.poll(() -> { + calls.incrementAndGet(); + throw new ApiException(503, "Service Unavailable"); + }, StatusPollerTest::classify, () -> false)); + assertEquals(503, thrown.getCode()); + assertEquals(4, calls.get()); + } + + @Test + public void recoversFromARetryableFailure() throws Exception { + var calls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .retrying(e -> e instanceof ApiException, 4, Duration.ofMillis(1)) + .poll(() -> { + if (calls.incrementAndGet() == 1) { + throw new ApiException(503, "Service Unavailable"); + } + return "DONE"; + }, StatusPollerTest::classify, () -> false); + assertEquals(Ending.DONE, result.ending()); + } + + @Test + public void rethrowsAFailureThatIsNotRetryable() { + var calls = new AtomicInteger(); + var poller = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)); + assertThrows(ApiException.class, () -> poller.poll(() -> { + calls.incrementAndGet(); + throw new ApiException(404, "Not Found"); + }, StatusPollerTest::classify, () -> false)); + assertEquals(1, calls.get()); + } + + @Test + public void describesWaits() { + assertEquals("3 hours", StatusPoller.describe(Duration.ofHours(3).minusSeconds(4))); + assertEquals("30 minute(s)", StatusPoller.describe(Duration.ofMinutes(30).minusSeconds(3))); + assertEquals("45 second(s)", StatusPoller.describe(Duration.ofSeconds(45))); + } +} From b672cad7084f535b9662b75f2ff9aed097345f01 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:24:36 +0000 Subject: [PATCH 41/76] fix(ENG-4461): point unfinished-wait messages at a recovery that works Check status only shows the current status once and never resumes the wait, so unrecognised-status messages now tell the analyst to reopen the program. The matching timeout message says Match Functions starts the matching again, the AI decompilation message drops the SDK placeholder status name, and the decompilation cache is now a ConcurrentHashMap since background tasks write to it. --- .../ui/aidecompiler/AIDecompilationdWindow.java | 5 ++--- .../ui/functionmatching/AbstractFunctionMatchingDialog.java | 2 +- .../binarysimilarity/ui/misc/AnalysisLogComponent.java | 2 +- .../toolkit/ghidra/plugins/AnalysisManagementPlugin.java | 2 +- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java index 4e5f2ff5..704d738f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java @@ -58,7 +58,7 @@ public class AIDecompilationdWindow extends ComponentProviderAdapter { private JComponent component; private Function function; private TaskMonitorComponent taskMonitorComponent; - private final Map cache = new java.util.HashMap<>(); + private final Map cache = new java.util.concurrent.ConcurrentHashMap<>(); /// Function IDs with a decompilation task currently running. Several functions can decompile /// concurrently in the background; this guards against launching a second task for a function @@ -1076,8 +1076,7 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) case UNRECOGNISED -> { // Not cached, so selecting the function again checks the server afresh. cache.remove(function); - reportDecompStopped(function, "the server reported a status this plugin does not recognise (%s)" - .formatted(result.status().status())); + reportDecompStopped(function, "the server reported a status this plugin does not recognise"); } case TIMED_OUT -> { cache.remove(function); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 57414cee..a6b671a8 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -177,7 +177,7 @@ private void runMatchingLoop() { String stopped = switch (result.ending()) { case UNRECOGNISED -> "The server reported a function matching status this plugin does not recognise " + "(the matching may have been cancelled). Press Match Functions to start it again."; - case TIMED_OUT -> "Function matching has not finished after %s; stopped waiting. Press Match Functions to check again." + case TIMED_OUT -> "Function matching has not finished after %s; stopped waiting. Press Match Functions to start it again." .formatted(StatusPoller.describe(result.waited())); default -> null; }; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index db33b385..9fbaf10f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -125,7 +125,7 @@ public static String unfinishedWaitMessage(StatusPoller.Result r GhidraRevengService.ProgramWithID program) { return switch (result.ending()) { case UNRECOGNISED -> ("RevEng.AI: analysis %d of %s reports a status this plugin does not recognise; " - + "stopped waiting for it. Use Check status or View in portal to follow it.") + + "stopped waiting for it. Reopen the program to check it again, or use View in portal.") .formatted(program.analysisID().id(), program.program().getName()); case TIMED_OUT -> ("RevEng.AI: analysis %d of %s has not finished after %s (status: %s); stopped waiting. " + "It keeps running on the server: reopen the program to resume waiting, or use View in portal.") diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 593da47c..9f836c58 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -413,7 +413,7 @@ public void run(TaskMonitor monitor) { static String unknownStatusOnOpenMessage(GhidraRevengService.ProgramWithID program) { return ("RevEng.AI: analysis %d of %s reports a status this plugin does not recognise; not waiting for it. " - + "Use Check status or View in portal to follow it.") + + "Reopen the program to check it again, or use View in portal.") .formatted(program.analysisID().id(), program.program().getName()); } From 1dc31bbf80289de36256f23f8d5ed41de949c060 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:37:36 +0000 Subject: [PATCH 42/76] test(ENG-4461): drive StatusPoller timing tests with a fake clock The backoff and time-limit tests measured real sleeps in milliseconds and failed on slower CI runners. StatusPoller now takes an injectable clock and sleeper (package-private, tests only), and the tests assert the exact waits. --- .../core/services/api/StatusPoller.java | 30 ++++++++++---- .../core/services/api/StatusPollerTest.java | 41 +++++++++++-------- 2 files changed, 46 insertions(+), 25 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java index 72454d33..c9d15223 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java @@ -5,6 +5,7 @@ import java.util.Objects; import java.util.function.BooleanSupplier; import java.util.function.Function; +import java.util.function.LongSupplier; import java.util.function.Predicate; /// Polls a server-side job until it reaches a final status, for every job the plugin waits on @@ -40,6 +41,11 @@ public interface Fetch { S get() throws E; } + @FunctionalInterface + interface Sleeper { + void sleep(long millis) throws InterruptedException; + } + /// Longest single sleep, so a cancellation is noticed promptly even during a long backoff. private static final long CANCEL_CHECK_MS = 200; @@ -49,6 +55,8 @@ public interface Fetch { private Predicate retryable = e -> false; private int maxConsecutiveFailures = 1; private Duration maxRetryBackoff; + private LongSupplier nanoClock = System::nanoTime; + private Sleeper sleeper = Thread::sleep; public StatusPoller(Duration interval, Duration maxInterval, Duration timeLimit) { this.interval = interval; @@ -72,9 +80,17 @@ public StatusPoller retrying(Predicate retryable, int maxConsecuti /// /// @throws E the fetch failed, and was not retryable or failed too often in a row /// @throws InterruptedException the polling thread was interrupted while waiting + /// Use {@code nanoClock} and {@code sleeper} instead of the system clock, so tests can check the + /// waits without depending on how fast the machine runs. + StatusPoller withClock(LongSupplier nanoClock, Sleeper sleeper) { + this.nanoClock = nanoClock; + this.sleeper = sleeper; + return this; + } + public Result poll(Fetch fetch, Function classify, BooleanSupplier cancelled) throws E, InterruptedException { - long start = System.nanoTime(); + long start = nanoClock.getAsLong(); S last = null; boolean fetched = false; long delay = interval.toMillis(); @@ -133,23 +149,23 @@ public Duration timeLimit() { /// @return false, without sleeping, if the sleep would run past the time limit; false if /// cancelled while sleeping; true otherwise private boolean sleepWithinLimit(long millis, long start, BooleanSupplier cancelled) throws InterruptedException { - long elapsed = (System.nanoTime() - start) / 1_000_000; + long elapsed = (nanoClock.getAsLong() - start) / 1_000_000; if (elapsed + millis > timeLimit.toMillis()) { return false; } - long deadline = System.nanoTime() + millis * 1_000_000; + long deadline = nanoClock.getAsLong() + millis * 1_000_000; long remaining; - while ((remaining = (deadline - System.nanoTime()) / 1_000_000) > 0) { + while ((remaining = (deadline - nanoClock.getAsLong()) / 1_000_000) > 0) { if (cancelled.getAsBoolean()) { return false; } - Thread.sleep(Math.min(remaining, CANCEL_CHECK_MS)); + sleeper.sleep(Math.min(remaining, CANCEL_CHECK_MS)); } return !cancelled.getAsBoolean(); } - private static Result result(Ending ending, @Nullable S status, long start) { - return new Result<>(ending, status, Duration.ofNanos(System.nanoTime() - start)); + private Result result(Ending ending, @Nullable S status, long start) { + return new Result<>(ending, status, Duration.ofNanos(nanoClock.getAsLong() - start)); } /// "3 hours" / "30 minute(s)" / "45 second(s)", rounded, for messages that say how long the plugin diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java index 445fe047..274ae91a 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java @@ -49,13 +49,28 @@ public void endsOnUnrecognisedStatusInsteadOfPollingForEver() throws Exception { assertEquals(1, polls.get()); } + /// A clock that only moves when the poller sleeps, so waits are exact on any machine. + private static final class FakeClock { + long nanos; + final List sleeps = new ArrayList<>(); + + StatusPoller drive(StatusPoller poller) { + return poller.withClock(() -> nanos, millis -> { + sleeps.add(millis); + nanos += millis * 1_000_000; + }); + } + } + @Test public void endsAtTheTimeLimit() throws Exception { - var result = new StatusPoller(Duration.ofMillis(5), Duration.ofMillis(5), Duration.ofMillis(100)) + var clock = new FakeClock(); + var result = clock.drive(new StatusPoller(Duration.ofMillis(5), Duration.ofMillis(5), Duration.ofMillis(100))) .poll(sequence("RUNNING"), StatusPollerTest::classify, () -> false); assertEquals(Ending.TIMED_OUT, result.ending()); assertEquals("RUNNING", result.status()); - assertTrue(result.waited().toMillis() <= 100); + assertEquals(Duration.ofMillis(100), result.waited()); + assertEquals(20, clock.sleeps.size()); } @Test @@ -86,23 +101,13 @@ public void cancellingCutsALongWaitShort() throws Exception { @Test public void backsOffWhileTheStatusIsUnchangedAndResetsOnChange() throws Exception { - List pollTimes = new ArrayList<>(); - var result = new StatusPoller(Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofSeconds(10)) - .poll(sequence("RUNNING", "RUNNING", "RUNNING", "RUNNING", "STEP1", "STEP2", "DONE"), s -> { - pollTimes.add(System.nanoTime() / 1_000_000); - return classify(s); - }, () -> false); + var clock = new FakeClock(); + var result = clock.drive(new StatusPoller(Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofSeconds(10))) + .poll(sequence("RUNNING", "RUNNING", "RUNNING", "RUNNING", "STEP1", "STEP2", "DONE"), + StatusPollerTest::classify, () -> false); assertEquals(Ending.DONE, result.ending()); - List gaps = new ArrayList<>(); - for (int i = 1; i < pollTimes.size(); i++) { - gaps.add(pollTimes.get(i) - pollTimes.get(i - 1)); - } - // RUNNING x4: 20, then 40, then 80 (capped); after a change it is back to 20 - assertTrue("gaps: " + gaps, gaps.get(0) >= 20 && gaps.get(0) < 40); - assertTrue("gaps: " + gaps, gaps.get(1) >= 40); - assertTrue("gaps: " + gaps, gaps.get(2) >= 80); - assertTrue("gaps: " + gaps, gaps.get(4) < 40); - assertTrue("gaps: " + gaps, gaps.get(5) < 40); + // RUNNING x4: 20, then 40, then 80, then 80 (capped); after each change it is back to 20 + assertEquals(List.of(20L, 40L, 80L, 80L, 20L, 20L), clock.sleeps); } @Test From e97dc671ac02a5a5d0524623230976dc9176dcdb Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:29:01 +0000 Subject: [PATCH 43/76] fix(ENG-4476): normalise api and portal hostnames (#250) --- .../core/services/api/types/ApiInfo.java | 7 ++- .../wizard/panels/UserCredentialsPanel.java | 4 +- src/test/java/ai/reveng/SetupWizardTest.java | 41 ++++++++++++++++++ .../core/services/api/types/ApiInfoTest.java | 43 +++++++++++++++++++ 4 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfoTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java index 020c468d..70969fd2 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java @@ -15,7 +15,12 @@ public record ApiInfo( String apiKey ) { public ApiInfo(String hostURI, String portalURI, String apiKey) { - this(URI.create(hostURI), URI.create(portalURI), apiKey); + this(URI.create(normaliseHost(hostURI)), URI.create(normaliseHost(portalURI)), apiKey); + } + + public static String normaliseHost(String host) { + var normalised = host.strip().replaceAll("/+$", ""); + return normalised.isEmpty() || normalised.contains("://") ? normalised : "https://" + normalised; } public static ApiInfo fromConfig(Path configFilePath) throws FileNotFoundException { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java index 1bf4bc06..36aea5ce 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java @@ -247,8 +247,8 @@ public void leavePanel(WizardState state) { public void updateStateObjectWithPanelInfo(WizardState state) { // Save the entered information into the state object state.put(SetupWizardStateKey.API_KEY, tfApiKey.getText()); - state.put(SetupWizardStateKey.HOSTNAME, tfApiHostname.getText()); - state.put(SetupWizardStateKey.PORTAL_HOSTNAME, tfPortalHostname.getText()); + state.put(SetupWizardStateKey.HOSTNAME, ApiInfo.normaliseHost(tfApiHostname.getText())); + state.put(SetupWizardStateKey.PORTAL_HOSTNAME, ApiInfo.normaliseHost(tfPortalHostname.getText())); state.put(SetupWizardStateKey.CREDENTIALS_VALIDATED, credentialsValidated); } diff --git a/src/test/java/ai/reveng/SetupWizardTest.java b/src/test/java/ai/reveng/SetupWizardTest.java index f0be50a5..af17214a 100644 --- a/src/test/java/ai/reveng/SetupWizardTest.java +++ b/src/test/java/ai/reveng/SetupWizardTest.java @@ -179,6 +179,47 @@ public void testEditingAfterValidationResetsState() throws Exception { tool.getOptions(REAI_OPTIONS_CATEGORY).getString(ReaiPluginPackage.OPTION_KEY_APIKEY, null)); } + /** + * Hostnames without a scheme, with surrounding whitespace or trailing slashes are normalised before saving. + */ + @Test + public void testHostnamesAreNormalised() throws Exception { + var tool = env.getTool(); + + var wizardState = new WizardState(); + wizardState.put(SetupWizardStateKey.CREDENTIAL_VALIDATOR, + (CredentialValidator) apiInfo -> {}); + var tempConfigFile = createTempDirectory("reai-wizard-test").toPath().resolve("reai.json"); + wizardState.put(SetupWizardStateKey.CONFIGFILE, tempConfigFile.toString()); + + SetupWizardManager setupManager = new SetupWizardManager(wizardState, tool); + WizardManager wizardManager = new WizardManager("RevEng.AI: Configuration", true, setupManager); + runSwing(() -> wizardManager.showWizard(tool.getToolFrame()), false); + var dialog = waitForDialogComponent("RevEng.AI: Configuration"); + + JTextField apiKeyField = (JTextField) findComponentByName(dialog.getComponent(), "apiKey"); + JTextField hostnameField = (JTextField) findComponentByName(dialog.getComponent(), "apiHostname"); + JTextField portalField = (JTextField) findComponentByName(dialog.getComponent(), "portalHostname"); + setText(apiKeyField, "test-api-key"); + setText(hostnameField, "api.test.example.com:8443/ "); + setText(portalField, " https://portal.test.example.com/"); + + JButton validateButton = findButtonByText(dialog.getComponent(), "Validate Credentials"); + pressButton(validateButton); + waitForTasks(); + waitForSwing(); + + JButton finishButton = findButtonByText(dialog.getComponent(), "Finish"); + assertTrue("Finish should be enabled after validation", finishButton.isEnabled()); + pressButton(finishButton); + waitForSwing(); + + assertEquals("https://api.test.example.com:8443", + tool.getOptions(REAI_OPTIONS_CATEGORY).getString(ReaiPluginPackage.OPTION_KEY_HOSTNAME, null)); + assertEquals("https://portal.test.example.com", + tool.getOptions(REAI_OPTIONS_CATEGORY).getString(ReaiPluginPackage.OPTION_KEY_PORTAL_HOSTNAME, null)); + } + @Test public void testUserCredentialsPanel() throws Exception { var tool = env.getTool(); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfoTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfoTest.java new file mode 100644 index 00000000..593a2d37 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfoTest.java @@ -0,0 +1,43 @@ +package ai.reveng.toolkit.ghidra.core.services.api.types; + +import org.junit.Test; + +import java.net.URI; + +import static org.junit.Assert.assertEquals; + +public class ApiInfoTest { + + @Test + public void normaliseHost_addsHttpsWhenSchemeIsMissing() { + assertEquals("https://api.reveng.ai:8443", ApiInfo.normaliseHost("api.reveng.ai:8443")); + } + + @Test + public void normaliseHost_trimsWhitespace() { + assertEquals("https://api.reveng.ai", ApiInfo.normaliseHost(" https://api.reveng.ai \t")); + } + + @Test + public void normaliseHost_stripsTrailingSlashes() { + assertEquals("https://api.reveng.ai", ApiInfo.normaliseHost("https://api.reveng.ai//")); + } + + @Test + public void normaliseHost_keepsAnExplicitScheme() { + assertEquals("http://localhost:8080", ApiInfo.normaliseHost("http://localhost:8080")); + } + + @Test + public void normaliseHost_leavesBlankInputEmpty() { + assertEquals("", ApiInfo.normaliseHost(" ")); + } + + @Test + public void stringConstructor_normalisesBothHosts() { + var info = new ApiInfo(" api.reveng.ai/ ", "portal.reveng.ai/", "key"); + + assertEquals(URI.create("https://api.reveng.ai"), info.hostURI()); + assertEquals(URI.create("https://portal.reveng.ai"), info.portalURI()); + } +} From 0eb23217150a5442f021cd1769e3f530b2a4bdd3 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:34:59 +0000 Subject: [PATCH 44/76] fix(ENG-4465): report server-side analysis errors with the log tail and offer Detach An analysis started in the session that ended in Error showed nothing: the program stayed attached, so Create new and Attach stayed disabled. The plugin now handles the Error status event: it fetches the analysis log off the Swing thread and shows its last lines in a dialog offering Detach or Keep attached. Detach runs the same code as the Detach menu action. Each failure is reported once while the program is open; reopening a program with a failed analysis goes through the same path instead of its own text-only error dialog. The analysis log panel now ends with how the analysis ended (completed or failed) instead of stopping at the last server log line. --- .../ui/misc/AnalysisLogComponent.java | 54 ++++++- .../plugins/AnalysisManagementPlugin.java | 153 +++++++++++++++--- .../ai/reveng/TestAnalysisLogComponent.java | 152 +++++++++++++++++ .../plugins/AnalysisManagementPluginTest.java | 25 +++ 4 files changed, 361 insertions(+), 23 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index 9fbaf10f..aa005bdd 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -29,6 +29,8 @@ public class AnalysisLogComponent extends ComponentProviderAdapter implements An private final JPanel mainPanel; private final Map trackedPrograms = new ConcurrentHashMap<>(); private final Map storedLogs = new ConcurrentHashMap<>(); + /// How the program's analysis ended, shown below its logs; absent while it runs or when unknown + private final Map terminalStatusLines = new ConcurrentHashMap<>(); public static String NAME = ReaiPluginPackage.WINDOW_PREFIX + "Analysis Log"; private Program activeProgram; @@ -80,7 +82,16 @@ public void programActivated(Program program) { } else { taskMonitorComponent.setVisible(false); } - setLogs(storedLogs.getOrDefault(program, "No analysis logs available for the active program.")); + setLogs(displayText(program)); + } + + /// The logs last received for the program, or null when none were + public String getStoredLogs(Program program) { + return storedLogs.get(program); + } + + private String displayText(Program program) { + return withTerminalStatus(storedLogs.get(program), terminalStatusLines.get(program)); } public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { @@ -93,9 +104,19 @@ public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { this.setVisible(true); switch (event.getStatus()) { + case Complete, Error -> { + // The wait has ended; say how, so the panel does not look like it is still waiting + terminalStatusLines.put(event.getProgram(), + terminalStatusLine(event.getStatus(), event.getProgramWithBinaryID().analysisID().id())); + refreshIfActive(event.getProgram()); + } // Unknown: the wait for it has already ended, so starting another would end at once and loop - case Complete, Error, Unknown -> {} + case Unknown -> {} default -> { + // A new or resumed analysis: an earlier ending no longer applies + if (terminalStatusLines.remove(event.getProgram()) != null) { + refreshIfActive(event.getProgram()); + } if (!trackedPrograms.containsKey(event.getProgram())){ // We aren't tracking this program yet, so we start a new task for it var task = new AnalysisMonitoringTask(event.getProgramWithBinaryID(), this); @@ -113,11 +134,36 @@ public void consumeLogs(String logs, GhidraRevengService.ProgramWithID programWi storedLogs.put(programWithID.program(), logs); // If this is the currently active program, update the log display - if (activeProgram == programWithID.program()) { - setLogs(logs); + refreshIfActive(programWithID.program()); + } + + private void refreshIfActive(Program program) { + if (activeProgram == program) { + setLogs(displayText(program)); } } + /// The line that ends the log of an analysis that has finished, or null for a status that is not final + public static String terminalStatusLine(AnalysisStatus status, int analysisId) { + return switch (status) { + case Complete -> "RevEng.AI: analysis %d completed.".formatted(analysisId); + case Error -> ("RevEng.AI: analysis %d failed on the server. Use %s > Analysis > Detach, then create a " + + "new analysis or attach to an existing one.").formatted(analysisId, ReaiPluginPackage.MENU_GROUP_NAME); + default -> null; + }; + } + + /// The text the panel shows: the logs, followed by how the analysis ended when it has + public static String withTerminalStatus(String logs, String statusLine) { + boolean noLogs = logs == null || logs.isBlank(); + if (statusLine == null) { + return noLogs ? NO_LOGS : logs; + } + return noLogs ? statusLine : logs.stripTrailing() + "\n\n" + statusLine; + } + + public static final String NO_LOGS = "No analysis logs available for the active program."; + /// What to tell the user when the wait for an analysis ended without it finishing, or null when /// there is nothing to tell (it finished, or the user cancelled the wait). diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 9f836c58..f583808b 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -46,7 +46,10 @@ import org.slf4j.LoggerFactory; import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; +import java.util.stream.Collectors; /** * CorePlugin for accessing the RevEng.AI Platform @@ -84,6 +87,13 @@ public class AnalysisManagementPlugin extends ProgramPlugin { private PluginTool tool; + /// Failed analyses whose error has been shown, so each failure is reported once while the program is open + private final Set reportedErrors = ConcurrentHashMap.newKeySet(); + + /// How many of the last log lines the error dialog shows + static final int ERROR_LOG_TAIL_LINES = 15; + /// Longer log lines are cut, so one line cannot stretch the dialog + static final int ERROR_LOG_LINE_LENGTH = 200; public AnalysisManagementPlugin(PluginTool tool) { super(tool); @@ -204,22 +214,7 @@ private void setupActions() { "Detach", OptionDialog.QUESTION_MESSAGE); if (result == OptionDialog.YES_OPTION) { - // For now this is the only place to trigger the removal of the association - // If this changes, the RevEngAIAnalysisStatusChanged event should be changed to accommodate - // this kind of event - // Stop the background work tied to this analysis first, so none of it runs against the - // association while it is being removed, or later against a different analysis. - localEditSyncService.detach(program); - if (autoUnstripSyncService.stopPolling(knownProgram.get().analysisID())) { - var message = "RevEng.AI: stopped waiting for auto-unstrip; the program was detached from " - + displayText + "."; - tool.getService(ReaiLoggingService.class).info(message); - tool.setStatusInfo(message); - } - program.withTransaction("Undo binary association", () -> revengService.removeProgramAssociation(program)); - - // Refresh action states after detaching - tool.contextChanged(null); + detach(knownProgram.get()); } }) @@ -280,6 +275,30 @@ public void run(TaskMonitor monitor) { .buildAndInstall(tool); } + /// Remove the program's association with its analysis. The Detach action and the analysis error dialog + /// both end here, so they do the same thing. + private void detach(GhidraRevengService.ProgramWithID knownProgram) { + var program = knownProgram.program(); + var displayText = "analysis " + knownProgram.analysisID().id(); + // For now these are the only places to trigger the removal of the association + // If this changes, the RevEngAIAnalysisStatusChanged event should be changed to accommodate + // this kind of event + // Stop the background work tied to this analysis first, so none of it runs against the + // association while it is being removed, or later against a different analysis. + localEditSyncService.detach(program); + if (autoUnstripSyncService.stopPolling(knownProgram.analysisID())) { + var message = "RevEng.AI: stopped waiting for auto-unstrip; the program was detached from " + + displayText + "."; + tool.getService(ReaiLoggingService.class).info(message); + tool.setStatusInfo(message); + } + program.withTransaction("Undo binary association", () -> revengService.removeProgramAssociation(program)); + reportedErrors.remove(knownProgram); + + // Refresh action states after detaching + tool.contextChanged(null); + } + @Override protected void programOpened(Program program) { super.programOpened(program); @@ -330,9 +349,13 @@ public void run(TaskMonitor monitor) { case Error -> { - // The analysis failed on the server side - Msg.showError(AnalysisManagementPlugin.this, null, "Analysis Error", - "The RevEng.AI analysis for the program " + knownProgram.get() + " is in error state on the server side."); + // The analysis failed on the server side. Reported through the event, so it is + // shown the same way as a failure seen while waiting, see processEvent + tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent( + "programOpened", + knownProgram.get(), + status)); } case Unknown -> { // Not waited on: an unrecognised status might never change into one that ends the wait @@ -366,6 +389,8 @@ protected void programClosed(Program program) { revengService.getKnownProgram(program) .ifPresent(known -> autoUnstripSyncService.stopPolling(known.analysisID())); } + // Reopening a program with a failed analysis reports the failure again + reportedErrors.removeIf(reported -> reported.program() == program); } @Override @@ -407,8 +432,98 @@ public void run(TaskMonitor monitor) { } } }, 0); + } else if (analysisEvent.getStatus() == AnalysisStatus.Error) { + reportAnalysisError(analysisEvent.getProgramWithBinaryID()); + } + } + } + + /// Tell the user that the analysis failed on the server, with the end of its log, and offer to detach it so + /// they can create a new analysis or attach to another one. Shown once per failure while the program is open. + private void reportAnalysisError(GhidraRevengService.ProgramWithID failed) { + if (!reportedErrors.add(failed)) { + return; + } + Msg.info(this, "Received analysis error event for " + failed); + // Events arrive on the Swing thread, and fetching the log is a request + tool.execute(new Task("Fetch RevEng.AI analysis log", false, false, false) { + @Override + public void run(TaskMonitor monitor) { + var fetchedLogs = fetchAnalysisLog(failed); + var logs = fetchedLogs != null ? fetchedLogs : analysisLogComponent.getStoredLogs(failed.program()); + var message = analysisErrorMessage(failed.analysisID().id(), failed.program().getName(), + logTail(logs, ERROR_LOG_TAIL_LINES, ERROR_LOG_LINE_LENGTH)); + tool.getService(ReaiLoggingService.class).error( + "RevEng.AI: analysis %d failed on the server".formatted(failed.analysisID().id())); + SwingUtilities.invokeLater(() -> { + if (fetchedLogs != null) { + // Show the same log in the panel, e.g. when the failure was found on opening the program + analysisLogComponent.consumeLogs(fetchedLogs, failed); + } + offerDetachAfterError(failed, message); + }); } + }, 0); + } + + /// The analysis log, or null when it could not be fetched + private String fetchAnalysisLog(GhidraRevengService.ProgramWithID failed) { + try { + return revengService.getAnalysisLog(failed.analysisID()); + } catch (Exception e) { + // The log only adds detail; the failure is reported with what was received while waiting + Msg.warn(this, "Could not fetch the log of failed analysis " + failed, e); + return null; + } + } + + private void offerDetachAfterError(GhidraRevengService.ProgramWithID failed, String message) { + if (!isStillAttached(failed)) { + // Closed or detached while the log was fetched: there is nothing left to offer + return; + } + var choice = OptionDialog.showOptionNoCancelDialog( + tool.getToolFrame(), + ReaiPluginPackage.WINDOW_PREFIX + "Analysis failed", + message, + "Detach", + "Keep attached", + OptionDialog.ERROR_MESSAGE); + // The dialog is modal, but check again: the association is what Detach removes + if (choice == OptionDialog.OPTION_ONE && isStillAttached(failed)) { + detach(failed); + } + } + + private boolean isStillAttached(GhidraRevengService.ProgramWithID failed) { + return !failed.program().isClosed() + && revengService.getKnownProgram(failed.program()).filter(failed::equals).isPresent(); + } + + /// The last {@code maxLines} non-blank lines of the log, each cut to {@code maxLineLength}; empty when + /// there is no log + static String logTail(String logs, int maxLines, int maxLineLength) { + if (logs == null || logs.isBlank()) { + return ""; + } + var lines = logs.lines().map(String::stripTrailing).filter(line -> !line.isBlank()).toList(); + return lines.subList(Math.max(0, lines.size() - maxLines), lines.size()).stream() + .map(line -> line.length() <= maxLineLength ? line : line.substring(0, maxLineLength) + "...") + .collect(Collectors.joining("\n")); + } + + static String analysisErrorMessage(int analysisId, String programName, String logTail) { + var message = new StringBuilder("The RevEng.AI analysis %d of %s failed on the server." + .formatted(analysisId, programName)); + if (logTail.isEmpty()) { + message.append("\n\nNo analysis log is available."); + } else { + message.append("\n\nEnd of the analysis log:\n").append(logTail); } + message.append("\n\nDetach the program to create a new analysis or attach to an existing one. " + + "Keep it attached to look into the failure with View in portal; you can detach it later from " + + ReaiPluginPackage.MENU_GROUP_NAME + " > Analysis > Detach."); + return message.toString(); } static String unknownStatusOnOpenMessage(GhidraRevengService.ProgramWithID program) { diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index 4e1e85dd..0b862662 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -9,15 +9,20 @@ import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; import ai.reveng.toolkit.ghidra.core.services.api.types.*; +import docking.DefaultActionContext; +import docking.widgets.OptionDialog; import ghidra.program.model.listing.Program; import ghidra.util.task.Task; import ghidra.util.task.TaskMonitorComponent; import org.junit.Test; +import javax.swing.JTextArea; + import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; @@ -218,6 +223,153 @@ public AnalysisStatus status(AnalysisID analysisID) { AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); assertFalse(trackedPrograms.containsKey(program)); + // The wait ended in Error, which is reported + pressButtonByText(waitForDialogComponent(OptionDialog.class), "Keep attached"); + } + + private static final String FAILED_ANALYSIS_LOGS = "Unpacking binary\nDisassembling\nFATAL: worker ran out of memory\n"; + + /// An analysis that always reports Error, with a log whose last line says why + private static class FailedAnalysisAPI extends UnimplementedAPI { + final AtomicInteger logCalls = new AtomicInteger(); + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Error; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + logCalls.incrementAndGet(); + return FAILED_ANALYSIS_LOGS; + } + } + + private String logText(AnalysisLogComponent logComponent) { + return runSwing(() -> ((JTextArea) getInstanceField("textArea", logComponent)).getText()); + } + + /// An analysis started in the session that fails on the server is reported with the end of its log, and + /// Detach in that report frees the program for a new analysis, like the Detach action does + @Test + public void testErrorDuringSessionOffersDetach() throws Exception { + var tool = env.getTool(); + var service = addMockedService(tool, new FailedAnalysisAPI()); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + // As StartAnalysisTask does: associate the program, then report the analysis as queued + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); + tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued)); + + var dialog = waitForDialogComponent(OptionDialog.class); + assertTrue(dialog.getMessage(), dialog.getMessage().contains("analysis 7 of " + program.getName() + " failed")); + assertTrue(dialog.getMessage(), dialog.getMessage().contains("FATAL: worker ran out of memory")); + var context = new DefaultActionContext(); + assertFalse(getAction(tool, "Create new").isEnabledForContext(context)); + + pressButtonByText(dialog, "Detach"); + waitForSwing(); + + assertTrue(service.getKnownProgram(program).isEmpty()); + assertTrue(getAction(tool, "Create new").isEnabledForContext(context)); + assertTrue(getAction(tool, "Attach to existing").isEnabledForContext(context)); + assertFalse(getAction(tool, "Detach").isEnabledForContext(context)); + + // The log panel says how the analysis ended instead of stopping at the last log line + AnalysisLogComponent logComponent = (AnalysisLogComponent) tool.getComponentProvider(AnalysisLogComponent.NAME); + var text = logText(logComponent); + assertTrue(text, text.contains("FATAL: worker ran out of memory")); + assertTrue(text, text.endsWith(AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Error, 7))); + } + + /// Keeping the failed analysis attached leaves the association alone, and the same failure is not reported again + @Test + public void testKeepAttachedReportsFailureOnce() throws Exception { + var tool = env.getTool(); + var service = addMockedService(tool, new FailedAnalysisAPI()); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); + tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued)); + + pressButtonByText(waitForDialogComponent(OptionDialog.class), "Keep attached"); + waitForSwing(); + assertEquals(Optional.of(programWithID), service.getKnownProgram(program)); + + // The same failure reported again, e.g. by Check status or a repeated event + tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Error)); + waitForSwing(); + waitForTasks(); + waitForSwing(); + assertNull(getDialogComponent(OptionDialog.class)); + } + + /// A program reopened with an analysis that failed while Ghidra was closed gets the same single report + @Test + public void testReopenedFailedAnalysisIsReportedOnce() throws Exception { + var tool = env.getTool(); + var api = new FailedAnalysisAPI(); + var service = addMockedService(tool, api); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); + + env.showTool(program); + var dialog = waitForDialogComponent(OptionDialog.class); + assertTrue(dialog.getMessage(), dialog.getMessage().contains("FATAL: worker ran out of memory")); + pressButtonByText(dialog, "Detach"); + waitForSwing(); + waitForTasks(); + + assertTrue(service.getKnownProgram(program).isEmpty()); + assertNull(getDialogComponent(OptionDialog.class)); + // Only the report fetched the log: nothing waits on an analysis that has already ended + assertEquals(1, api.logCalls.get()); + } + + @Test + public void testTerminalStatusText() { + assertEquals("RevEng.AI: analysis 3 completed.", AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Complete, 3)); + var error = AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Error, 3); + assertTrue(error, error.contains("analysis 3 failed on the server")); + assertTrue(error, error.contains("Detach")); + assertNull(AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Processing, 3)); + + assertEquals(AnalysisLogComponent.NO_LOGS, AnalysisLogComponent.withTerminalStatus(null, null)); + assertEquals("a\nb", AnalysisLogComponent.withTerminalStatus("a\nb", null)); + assertEquals("done", AnalysisLogComponent.withTerminalStatus(" ", "done")); + assertEquals("a\nb\n\ndone", AnalysisLogComponent.withTerminalStatus("a\nb\n", "done")); + } + + /// A new analysis for the program clears how the previous one ended + @Test + public void testNewAnalysisClearsTerminalStatus() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Queued; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + AnalysisLogComponent logComponent = (AnalysisLogComponent) tool.getComponentProvider(AnalysisLogComponent.NAME); + var finished = new GhidraRevengService.ProgramWithID(program, new TypedApiInterface.AnalysisID(3)); + // Delivered to the log component directly: the plugin would load results for a Complete event + runSwing(() -> logComponent.processEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", finished, AnalysisStatus.Complete))); + assertEquals(AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Complete, 3), logText(logComponent)); + + var next = new GhidraRevengService.ProgramWithID(program, new TypedApiInterface.AnalysisID(4)); + runSwing(() -> logComponent.processEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", next, AnalysisStatus.Queued))); + assertEquals(AnalysisLogComponent.NO_LOGS, logText(logComponent)); + TaskMonitorComponent taskMonitor = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + taskMonitor.cancel(); + waitForTasks(); } /// An analysis reporting an unrecognised status on reopen is reported, not waited on diff --git a/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java b/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java index 45e31cca..0307d714 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class AnalysisManagementPluginTest { @@ -11,4 +12,28 @@ public class AnalysisManagementPluginTest { public void checkStatusMessageShowsOnlyStatus() { assertEquals("Analysis status: Complete", AnalysisManagementPlugin.checkStatusMessage(AnalysisStatus.Complete)); } + + @Test + public void logTailKeepsLastNonBlankLines() { + assertEquals("", AnalysisManagementPlugin.logTail(null, 3, 50)); + assertEquals("", AnalysisManagementPlugin.logTail(" \n ", 3, 50)); + assertEquals("b\nc\nd", AnalysisManagementPlugin.logTail("a\nb\n\nc \nd\n\n", 3, 50)); + assertEquals("a\nb", AnalysisManagementPlugin.logTail("a\r\nb", 3, 50)); + } + + @Test + public void logTailCutsLongLines() { + assertEquals("abcde...\nxy", AnalysisManagementPlugin.logTail("abcdefgh\nxy", 3, 5)); + } + + @Test + public void analysisErrorMessageShowsLogTailAndChoices() { + var message = AnalysisManagementPlugin.analysisErrorMessage(42, "prog.exe", "step 1\nFATAL"); + assertTrue(message, message.startsWith("The RevEng.AI analysis 42 of prog.exe failed on the server.")); + assertTrue(message, message.contains("End of the analysis log:\nstep 1\nFATAL")); + assertTrue(message, message.contains("Detach")); + + var noLog = AnalysisManagementPlugin.analysisErrorMessage(42, "prog.exe", ""); + assertTrue(noLog, noLog.contains("No analysis log is available.")); + } } From c3b54d97989b06d1718f91c2eb7207c99623fca7 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:40:30 +0000 Subject: [PATCH 45/76] test(ENG-4465): wait for the work behind the error dialog instead of a timeout The dialog tests waited for the dialog with a fixed timeout, which slow CI runners exceeded. They now wait for the tasks and Swing events that lead to it. --- .../java/ai/reveng/TestAnalysisLogComponent.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index 0b862662..b1416424 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -245,6 +245,18 @@ public String getAnalysisLogs(AnalysisID analysisID) { } } + /// The error dialog, once the work that leads to it has run: the wait that sees the Error, the delivery of its + /// event, and the task that fetches the log. Waiting on that work, not on a clock, keeps slow machines passing. + private OptionDialog awaitErrorDialog() { + waitForTasks(); + waitForSwing(); + waitForTasks(); + waitForSwing(); + var dialog = getDialogComponent(OptionDialog.class); + assertNotNull("the failed analysis should be reported", dialog); + return dialog; + } + private String logText(AnalysisLogComponent logComponent) { return runSwing(() -> ((JTextArea) getInstanceField("textArea", logComponent)).getText()); } @@ -262,7 +274,7 @@ public void testErrorDuringSessionOffersDetach() throws Exception { var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued)); - var dialog = waitForDialogComponent(OptionDialog.class); + var dialog = awaitErrorDialog(); assertTrue(dialog.getMessage(), dialog.getMessage().contains("analysis 7 of " + program.getName() + " failed")); assertTrue(dialog.getMessage(), dialog.getMessage().contains("FATAL: worker ran out of memory")); var context = new DefaultActionContext(); @@ -294,7 +306,7 @@ public void testKeepAttachedReportsFailureOnce() throws Exception { var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued)); - pressButtonByText(waitForDialogComponent(OptionDialog.class), "Keep attached"); + pressButtonByText(awaitErrorDialog(), "Keep attached"); waitForSwing(); assertEquals(Optional.of(programWithID), service.getKnownProgram(program)); From ff1a930e27d3e923dfe956bd07cabf51b6b90187 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:33:04 +0000 Subject: [PATCH 46/76] test(ENG-4465): wait for every stage before looking for the error dialog The Queued event, the wait, the Error event, the log fetch and the dialog alternate between Swing and background tasks; the helper stopped one stage short, so the dialog was found only when the fetch happened to be quick. --- .../java/ai/reveng/TestAnalysisLogComponent.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index b1416424..842fd41f 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -245,13 +245,16 @@ public String getAnalysisLogs(AnalysisID analysisID) { } } - /// The error dialog, once the work that leads to it has run: the wait that sees the Error, the delivery of its - /// event, and the task that fetches the log. Waiting on that work, not on a clock, keeps slow machines passing. + /// The error dialog, once the work that leads to it has run. Each stage starts the next one on the other side: + /// the Queued event is delivered on Swing and starts the wait (a task), the wait fires the Error event (Swing), + /// which starts the log fetch (a task), which shows the dialog (Swing). Waiting on each stage, not on a clock, + /// keeps slow machines passing. private OptionDialog awaitErrorDialog() { - waitForTasks(); - waitForSwing(); - waitForTasks(); waitForSwing(); + for (int stage = 0; stage < 3; stage++) { + waitForTasks(); + waitForSwing(); + } var dialog = getDialogComponent(OptionDialog.class); assertNotNull("the failed analysis should be reported", dialog); return dialog; From dab671d37afcb93e782e67e6f543111644971911 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:03:44 +0000 Subject: [PATCH 47/76] test(ENG-4465): poll for the error dialog instead of counting task rounds A fixed number of waitForTasks/waitForSwing rounds was not always enough for the event, task, event, task, dialog chain on CI runners. Poll for the dialog with a generous ceiling instead. --- .../ai/reveng/TestAnalysisLogComponent.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index 842fd41f..7b0dc592 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -224,7 +224,7 @@ public AnalysisStatus status(AnalysisID analysisID) { var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); assertFalse(trackedPrograms.containsKey(program)); // The wait ended in Error, which is reported - pressButtonByText(waitForDialogComponent(OptionDialog.class), "Keep attached"); + pressButtonByText(waitForDialogComponent(null, OptionDialog.class, 30_000), "Keep attached"); } private static final String FAILED_ANALYSIS_LOGS = "Unpacking binary\nDisassembling\nFATAL: worker ran out of memory\n"; @@ -245,17 +245,11 @@ public String getAnalysisLogs(AnalysisID analysisID) { } } - /// The error dialog, once the work that leads to it has run. Each stage starts the next one on the other side: - /// the Queued event is delivered on Swing and starts the wait (a task), the wait fires the Error event (Swing), - /// which starts the log fetch (a task), which shows the dialog (Swing). Waiting on each stage, not on a clock, - /// keeps slow machines passing. + /// The error dialog, once the work that leads to it has run: the Queued event starts the wait (a task), the wait + /// fires the Error event (Swing), which starts the log fetch (a task), which shows the dialog (Swing). How many + /// rounds that takes varies between machines, so poll for the dialog; the limit only bounds a broken run. private OptionDialog awaitErrorDialog() { - waitForSwing(); - for (int stage = 0; stage < 3; stage++) { - waitForTasks(); - waitForSwing(); - } - var dialog = getDialogComponent(OptionDialog.class); + var dialog = waitForDialogComponent(null, OptionDialog.class, 30_000); assertNotNull("the failed analysis should be reported", dialog); return dialog; } @@ -332,7 +326,7 @@ public void testReopenedFailedAnalysisIsReportedOnce() throws Exception { service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); env.showTool(program); - var dialog = waitForDialogComponent(OptionDialog.class); + var dialog = waitForDialogComponent(null, OptionDialog.class, 30_000); assertTrue(dialog.getMessage(), dialog.getMessage().contains("FATAL: worker ran out of memory")); pressButtonByText(dialog, "Detach"); waitForSwing(); From 20762339c4c48c0c81db7aaaca7ed14c6d8a8e3c Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:48:19 +0000 Subject: [PATCH 48/76] fix(ENG-4478): show the server's error message on API failures (#252) --- .../service/ConversationsApiChatService.java | 11 +-- .../services/api/GhidraRevengService.java | 10 +- .../services/api/TypedApiImplementation.java | 37 +++++--- .../ghidra/core/tasks/StartAnalysisTask.java | 7 +- .../services/api/ApiErrorMessageTest.java | 95 +++++++++++++++++++ .../tasks/StartAnalysisTaskDescribeTest.java | 26 +++++ 6 files changed, 160 insertions(+), 26 deletions(-) create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiErrorMessageTest.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTaskDescribeTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java index ca247b52..1167ec02 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java @@ -15,6 +15,7 @@ import ai.reveng.toolkit.ghidra.chat.model.Conversations.ConversationSummary; import ai.reveng.toolkit.ghidra.chat.model.Conversations.StoredEvent; import ai.reveng.toolkit.ghidra.chat.model.Conversations.UserMessageReplay; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiImplementation; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; @@ -268,7 +269,8 @@ private static Map executeForJsonMap(okhttp3.Call call, String w okhttp3.ResponseBody responseBody = response.body(); String text = responseBody == null ? "" : responseBody.string(); if (!response.isSuccessful()) { - throw new ApiException(response.code(), "Failed to %s: HTTP %d".formatted(what, response.code())); + throw new ApiException("Failed to %s: HTTP %d".formatted(what, response.code()), + response.code(), response.headers().toMultimap(), text); } Object parsed = GSON.fromJson(text, Map.class); if (!(parsed instanceof Map)) { @@ -290,10 +292,7 @@ private static String eventId(Map ev) { } private static ChatServiceException apiError(String action, ApiException e) { - String detail = e.getResponseBody(); - if (detail == null || detail.isBlank()) { - detail = e.getMessage(); - } - return new ChatServiceException("Failed to %s: %s".formatted(action, detail), e); + return new ChatServiceException( + "Failed to %s: %s".formatted(action, TypedApiImplementation.describeApiException(e)), e); } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 20e9dcbe..9c5e1abf 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1332,16 +1332,20 @@ public TypedApiInterface.BinaryHash upload(Program program) { "Hash of uploaded file %s from path %s doesn't match the hash of the program loaded in Ghidra %s" .formatted(hash, program.getExecutablePath(), hashOfProgram(program))); } - } catch (FileNotFoundException | ApiException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); + } catch (ApiException e) { + throw new RuntimeException(TypedApiImplementation.describeApiException(e), e); } } public TypedApiInterface.BinaryHash upload(Path path) { try { return api.upload(path); - } catch (FileNotFoundException | ApiException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); + } catch (ApiException e) { + throw new RuntimeException(TypedApiImplementation.describeApiException(e), e); } } @@ -1355,7 +1359,7 @@ public AnalysisStatus status(ProgramWithID program) { return api.status(program.analysisID()); } catch (ApiException e) { // This should never happen given that `ProgramWithID` guarantees a valid analysis ID - throw new RuntimeException(e); + throw new RuntimeException(TypedApiImplementation.describeApiException(e), e); } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 86df7913..fe366a5a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -339,7 +339,7 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID } return new FunctionSignatureBatch(items, dataTypes); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -355,7 +355,7 @@ public List listAnalysisDataTypes(AnalysisID analysisID, long of return ServerDataTypeReader.readEntries( executeForJsonObject(call, "list analysis data types"), "items"); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -403,7 +403,7 @@ public List getFunctionSignatureHistory(AnalysisID ana .getVersions(); return versions == null ? List.of() : versions; } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -412,7 +412,8 @@ private static JsonObject executeForJsonObject(okhttp3.Call call, String what) t okhttp3.ResponseBody responseBody = response.body(); String text = responseBody == null ? "" : responseBody.string(); if (!response.isSuccessful()) { - throw new ApiException(response.code(), "Failed to %s: HTTP %d".formatted(what, response.code())); + throw new ApiException("Failed to %s: HTTP %d".formatted(what, response.code()), + response.code(), response.headers().toMultimap(), text); } JsonElement parsed = JsonParser.parseString(text); if (!parsed.isJsonObject()) { @@ -566,10 +567,20 @@ public void deleteAIDecompilationInlineComment(FunctionID functionID, long line) functionsAiDecompilationApi.deleteAiDecompilationInlineComment(functionID.value(), line); } - private static String describeApiException(ApiException e) { - // The SDK's ApiException carries the HTTP status and response body separately from the message; - // surface both so callers logging only getMessage() can still diagnose server-side failures. - return "HTTP " + e.getCode() + " — " + (e.getResponseBody() != null ? e.getResponseBody() : e.getMessage()); + /// The status and the server's `error.message`, falling back to the raw body, then the exception's + /// own message. {@link ApiException#getMessage()} itself dumps the body and every header. + public static String describeApiException(ApiException e) { + String body = e.getResponseBody(); + String detail = body != null && !body.isBlank() ? body : e.getMessage(); + try { + JsonElement message = JsonParser.parseString(body).getAsJsonObject() + .getAsJsonObject("error").get("message"); + if (message != null && message.isJsonPrimitive() && !message.getAsString().isBlank()) { + detail = message.getAsString(); + } + } catch (RuntimeException ignored) { + } + return "HTTP " + e.getCode() + " — " + detail; } /// POST /v3/functions/rename, with a one-item body: v3 has no per-function rename route. @@ -587,7 +598,7 @@ public void renameFunction(FunctionID id, String newName, String newNameMangled) try { response = functionsRenamingHistoryApi.batchRenameFunctions(request); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } Long renamedCount = response == null ? null : response.getRenamedCount(); if (renamedCount == null || renamedCount < 1) { @@ -601,7 +612,7 @@ public FunctionDetails getFunctionDetails(FunctionID id) { try { return FunctionDetails.fromServerResponse(functionsCoreApi.getFunctionDetails_0(id.value())); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -718,7 +729,7 @@ public List getAssembly(FunctionID id) { DisassemblyOutputBody disassembly = this.functionsCoreApi.getFunctionBlocks_0(id.value()); return DisassemblyBlocksReader.readAssembly(disassembly.getBasicBlocks()); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -749,7 +760,7 @@ public ConfigResponse getConfig() { try { return this.configApi.getConfig().getData(); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -758,7 +769,7 @@ public User getMe() { try { return this.iamUsersApi.getMe(); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java index 8296937f..649efde8 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java @@ -5,6 +5,7 @@ import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiImplementation; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; @@ -96,15 +97,13 @@ private void reportFailure(TaskMonitor monitor, message, error); } - private static String describe(Throwable error) { + static String describe(Throwable error) { Throwable cause = error; if (!(cause instanceof ApiException) && cause.getCause() instanceof ApiException) { cause = cause.getCause(); } if (cause instanceof ApiException apiException) { - String body = apiException.getResponseBody(); - String detail = (body != null && !body.isBlank()) ? body : apiException.getMessage(); - return "HTTP " + apiException.getCode() + " — " + detail; + return TypedApiImplementation.describeApiException(apiException); } return cause.getMessage() != null ? cause.getMessage() : cause.toString(); } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiErrorMessageTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiErrorMessageTest.java new file mode 100644 index 00000000..03ae0867 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiErrorMessageTest.java @@ -0,0 +1,95 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import ai.reveng.toolkit.ghidra.chat.service.ChatServiceException; +import ai.reveng.toolkit.ghidra.chat.service.ConversationsApiChatService; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/// A failed request must reach the user as the server's `error.message`, not as a dropped body or +/// the SDK's full {@link ApiException} dump of message, body and headers. +public class ApiErrorMessageTest extends AbstractStubServerTest { + + private static final String SERVER_MESSAGE = "page_size must be at most 500"; + private static final String CONVERSATION_ID = "11111111-2222-3333-4444-555555555555"; + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> { + byte[] bytes = "{\"error\":{\"code\":\"BAD_REQUEST\",\"message\":\"%s\"}}" + .formatted(SERVER_MESSAGE).getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(422, bytes.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(bytes); + } + }); + } + + /// Goes through the generated `*Call` and reads the body by hand. + @Test + public void rawCallKeepsTheResponseBody() { + try { + api().createAnalysisDataTypes(new TypedApiInterface.AnalysisID(1), + new ai.reveng.model.CreateAnalysisDataTypesInputBody()); + fail("a 422 should raise"); + } catch (ApiException e) { + assertEquals(422, e.getCode()); + assertTrue(e.getResponseBody(), e.getResponseBody().contains(SERVER_MESSAGE)); + } + } + + @Test + public void rawCallFailureShowsServerMessage() { + assertShowsServerMessage(() -> api().listAnalysisDataTypes(new TypedApiInterface.AnalysisID(1), 0, 1000)); + } + + /// Goes through a generated model method. + @Test + public void modelCallFailureShowsServerMessage() { + assertShowsServerMessage(() -> api().getFunctionDetails(new TypedApiInterface.FunctionID(1))); + } + + /// Chat reads the conversation through the generated `*Call`. + @Test + public void chatRawCallFailureShowsServerMessage() { + assertChatShowsServerMessage("load conversation", chat -> chat.getConversation(CONVERSATION_ID)); + } + + @Test + public void chatModelCallFailureShowsServerMessage() { + assertChatShowsServerMessage("cancel run", chat -> chat.cancelRun(CONVERSATION_ID)); + } + + private interface ChatRequest { + void run(ConversationsApiChatService chat) throws ChatServiceException; + } + + private void assertChatShowsServerMessage(String action, ChatRequest request) { + var client = api().apiClient(); + try { + request.run(new ConversationsApiChatService(() -> client)); + fail("a 422 should raise"); + } catch (ChatServiceException e) { + assertEquals("Failed to " + action + ": HTTP 422 — " + SERVER_MESSAGE, e.getMessage()); + } + } + + private static void assertShowsServerMessage(Runnable request) { + try { + request.run(); + fail("a 422 should raise"); + } catch (RuntimeException e) { + assertEquals("HTTP 422 — " + SERVER_MESSAGE, e.getMessage()); + assertFalse(e.getMessage(), e.getMessage().contains("HTTP response headers")); + } + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTaskDescribeTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTaskDescribeTest.java new file mode 100644 index 00000000..9cddb28e --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTaskDescribeTest.java @@ -0,0 +1,26 @@ +package ai.reveng.toolkit.ghidra.core.tasks; + +import ai.reveng.invoker.ApiException; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +/// A rejected analysis request shows the server's `error.message`, not the raw error body. +public class StartAnalysisTaskDescribeTest { + + private static final ApiException REJECTED = new ApiException(402, Map.of("content-type", List.of("application/json")), + "{\"error\":{\"code\":\"INSUFFICIENT_CREDITS\",\"message\":\"Not enough credits\"}}"); + + @Test + public void showsServerMessage() { + assertEquals("HTTP 402 — Not enough credits", StartAnalysisTask.describe(REJECTED)); + } + + @Test + public void showsServerMessageWhenWrapped() { + assertEquals("HTTP 402 — Not enough credits", StartAnalysisTask.describe(new RuntimeException(REJECTED))); + } +} From 99bf1dd8503174e4b8aa8d16c894b81b37ca38b7 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:05:39 +0000 Subject: [PATCH 49/76] test(ENG-4485): cover every SDK method and model the plugin uses Extend SdkSchemaTest with the AI decompilation status/inline-comment edit calls, auto-unstrip status, canonical names, IamUsersApi.getMe and the models they return, plus the MatchedFunction name/binary/hash accessors. Add SdkRecordedResponseTest, which serves staging-shaped bodies through a stub server and drives the plugin's TypedApiImplementation calls, so a missing required field or an unknown enum value fails here rather than at runtime. --- .../services/api/SdkRecordedResponseTest.java | 199 ++++++++++++++++++ .../core/services/api/SdkSchemaTest.java | 46 +++- src/test/resources/sdk-responses/README.md | 6 + ...-decompilation-inline-comments-delete.json | 1 + ...i-decompilation-inline-comments-patch.json | 1 + ...-decompilation-inline-comments-status.json | 1 + .../ai-decompilation-inline-comments.json | 1 + .../ai-decompilation-running.json | 1 + .../ai-decompilation-status.json | 1 + .../ai-decompilation-summary-status.json | 1 + .../ai-decompilation-summary.json | 1 + .../sdk-responses/ai-decompilation.json | 1 + .../sdk-responses/analysis-matches.json | 1 + .../sdk-responses/auto-unstrip-status.json | 1 + .../sdk-responses/canonical-names.json | 1 + .../resources/sdk-responses/collections.json | 1 + src/test/resources/sdk-responses/config.json | 1 + src/test/resources/sdk-responses/iam-me.json | 1 + .../matches-status-completed.json | 1 + .../sdk-responses/matches-status-running.json | 1 + .../sdk-responses/search-binaries.json | 1 + 21 files changed, 264 insertions(+), 5 deletions(-) create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java create mode 100644 src/test/resources/sdk-responses/README.md create mode 100644 src/test/resources/sdk-responses/ai-decompilation-inline-comments-delete.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation-inline-comments-patch.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation-inline-comments-status.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation-inline-comments.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation-running.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation-status.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation-summary-status.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation-summary.json create mode 100644 src/test/resources/sdk-responses/ai-decompilation.json create mode 100644 src/test/resources/sdk-responses/analysis-matches.json create mode 100644 src/test/resources/sdk-responses/auto-unstrip-status.json create mode 100644 src/test/resources/sdk-responses/canonical-names.json create mode 100644 src/test/resources/sdk-responses/collections.json create mode 100644 src/test/resources/sdk-responses/config.json create mode 100644 src/test/resources/sdk-responses/iam-me.json create mode 100644 src/test/resources/sdk-responses/matches-status-completed.json create mode 100644 src/test/resources/sdk-responses/matches-status-running.json create mode 100644 src/test/resources/sdk-responses/search-binaries.json diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java new file mode 100644 index 00000000..aeddb871 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java @@ -0,0 +1,199 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.model.DecompilationData; +import ai.reveng.model.GetMatchesStatusOutputBody; +import ai.reveng.model.ProgressMessage; +import ai.reveng.model.User; +import ai.reveng.model.WorkflowProgress; +import ai.reveng.toolkit.ghidra.core.services.api.types.AIDecompilationStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/// Runs staging-shaped response bodies (`src/test/resources/sdk-responses`) through the generated +/// SDK models via the plugin's own {@link TypedApiImplementation} calls. {@link SdkSchemaTest} only +/// pins that the accessors exist; this checks that a real body deserialises — every required field +/// present, every enum value known — and that the values land where the plugin reads them. +public class SdkRecordedResponseTest extends AbstractStubServerTest { + + private static final long DECOMPILED_FUNCTION = 101; + private static final long RUNNING_FUNCTION = 102; + private static final int ANALYSIS = 7; + + private static final String DECOMP = "/v3/functions/" + DECOMPILED_FUNCTION + "/ai-decompilation"; + private static final String RUNNING_DECOMP = "/v3/functions/" + RUNNING_FUNCTION + "/ai-decompilation"; + + /// "METHOD path" to the recorded body served for it. + private static final Map ROUTES = Map.ofEntries( + Map.entry("GET " + DECOMP, "ai-decompilation.json"), + Map.entry("GET " + DECOMP + "/summary/status", "ai-decompilation-summary-status.json"), + Map.entry("GET " + DECOMP + "/summary", "ai-decompilation-summary.json"), + Map.entry("GET " + DECOMP + "/inline-comments/status", "ai-decompilation-inline-comments-status.json"), + Map.entry("GET " + DECOMP + "/inline-comments", "ai-decompilation-inline-comments.json"), + Map.entry("PATCH " + DECOMP + "/inline-comments", "ai-decompilation-inline-comments-patch.json"), + Map.entry("DELETE " + DECOMP + "/inline-comments/6", "ai-decompilation-inline-comments-delete.json"), + Map.entry("GET " + RUNNING_DECOMP, "ai-decompilation-running.json"), + Map.entry("GET " + RUNNING_DECOMP + "/status", "ai-decompilation-status.json"), + Map.entry("GET /v3/analyses/" + ANALYSIS + "/auto-unstrip/status", "auto-unstrip-status.json"), + Map.entry("POST /v3/functions/canonical-names", "canonical-names.json"), + Map.entry("GET /v2/iam/me", "iam-me.json"), + Map.entry("GET /v2/config", "config.json"), + Map.entry("GET /v3/analyses/" + ANALYSIS + "/functions/matches/status", "matches-status-completed.json"), + Map.entry("GET /v3/functions/matches/status", "matches-status-running.json"), + Map.entry("GET /v3/analyses/" + ANALYSIS + "/functions/matches", "analysis-matches.json"), + Map.entry("GET /v2/search/binaries", "search-binaries.json"), + Map.entry("GET /v3/collections", "collections.json")); + + private final List requests = new CopyOnWriteArrayList<>(); + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> { + String route = exchange.getRequestMethod() + " " + exchange.getRequestURI().getPath(); + requests.add(route); + String fixture = ROUTES.get(route); + if (fixture == null) { + exchange.sendResponseHeaders(404, -1); + exchange.close(); + return; + } + respondJson(exchange, recorded(fixture)); + }); + } + + @Test + public void completedDecompilationCarriesTextSummaryAndComments() { + AIDecompilationStatus status = api().pollAIDecompileStatus(new TypedApiInterface.FunctionID(DECOMPILED_FUNCTION)); + + assertEquals(DecompilationData.StatusEnum.COMPLETED, status.status()); + assertTrue(status.decompilation().startsWith("int parse_header(char *buf, int len)")); + assertEquals(WorkflowProgress.StatusEnum.COMPLETED, status.summaryStatus()); + // ai_summary is the plain-text form; summary carries markup. + assertEquals("Parses an HTTP header from buf and returns the length of the remaining payload, " + + "or -1 if the buffer is shorter than 8 bytes.", status.summary()); + assertEquals(WorkflowProgress.StatusEnum.COMPLETED, status.inlineCommentsStatus()); + assertEquals(List.of( + new AIDecompilationStatus.InlineCommentEntry(3, "Reject buffers too short to hold the 8-byte header."), + new AIDecompilationStatus.InlineCommentEntry(6, "Skip the 4-byte magic and parse the length field.")), + status.inlineComments()); + } + + @Test + public void runningDecompilationCarriesPipelineProgress() { + AIDecompilationStatus status = api().pollAIDecompileStatus(new TypedApiInterface.FunctionID(RUNNING_FUNCTION)); + + assertEquals(DecompilationData.StatusEnum.RUNNING, status.status()); + WorkflowProgress progress = status.decompilationProgress(); + assertNotNull("the progress body should deserialise", progress); + assertEquals(WorkflowProgress.StatusEnum.RUNNING, progress.getStatus()); + assertEquals("decompiling", progress.getStep()); + assertEquals(Long.valueOf(2), progress.getStepIndex()); + assertEquals(Long.valueOf(7), progress.getStepsTotal()); + assertEquals(4, progress.getMessages().size()); + ProgressMessage first = progress.getMessages().get(0); + assertEquals(ProgressMessage.LevelEnum.INFO, first.getLevel()); + assertEquals("Preparing decompilation", first.getText()); + assertNotNull(first.getTimestamp()); + } + + @Test + public void inlineCommentEditsDeserialiseTheirResponses() throws Exception { + var api = api(); + api.setAIDecompilationInlineComment(new TypedApiInterface.FunctionID(DECOMPILED_FUNCTION), 6, "Length field is big-endian."); + api.deleteAIDecompilationInlineComment(new TypedApiInterface.FunctionID(DECOMPILED_FUNCTION), 6); + + assertEquals(List.of("PATCH " + DECOMP + "/inline-comments", "DELETE " + DECOMP + "/inline-comments/6"), requests); + } + + @Test + public void autoUnstripStatusMapsToTheKnownState() throws Exception { + assertEquals(TypedApiInterface.AutoUnstripStatus.COMPLETED, + api().getAutoUnstripStatus(new TypedApiInterface.AnalysisID(ANALYSIS))); + } + + @Test + public void canonicalNamesComeBackKeyedByInput() throws Exception { + assertEquals(Map.of("_ZN3fooC1Ev", "foo", "sub_401000", "sub_401000"), + api().canonicalizeFunctionNames(List.of("_ZN3fooC1Ev", "sub_401000"))); + } + + @Test + public void currentUserCarriesTier() { + assertEquals(User.TierEnum.REVERSER, api().getMe().getTier()); + } + + @Test + public void configCarriesMaxFileSize() { + assertEquals(31_457_280L, api().getConfig().getMaxFileSizeBytes().longValue()); + } + + @Test + public void matchingStatusBodiesDeserialise() throws Exception { + var api = api(); + GetMatchesStatusOutputBody completed = api.getAnalysisFunctionMatchingStatus(new TypedApiInterface.AnalysisID(ANALYSIS)); + assertEquals(GetMatchesStatusOutputBody.StatusEnum.COMPLETED, completed.getStatus()); + assertTrue(completed.getMessages().isEmpty()); + + GetMatchesStatusOutputBody running = api.getFunctionsMatchingStatus(List.of(1109480836L)); + assertEquals(GetMatchesStatusOutputBody.StatusEnum.RUNNING, running.getStatus()); + assertEquals("matching", running.getStep()); + assertEquals(Long.valueOf(1), running.getStepIndex()); + assertEquals(Long.valueOf(3), running.getStepsTotal()); + assertEquals("Searching for similar functions", running.getMessages().get(1).getText()); + } + + @Test + public void matchedFunctionsCarryNameBinaryAndHash() throws Exception { + var body = api().getAnalysisFunctionMatches(new TypedApiInterface.AnalysisID(ANALYSIS)); + var match = body.getMatches().get(0); + var origin = new TypedApiInterface.FunctionID(match.getFunctionId()); + FunctionMatch best = FunctionMatch.fromMatchedFunctionAPIType(match.getMatchedFunctions().get(0), origin); + + assertEquals(new TypedApiInterface.FunctionID(1109480836L), best.origin_function_id()); + assertEquals(new TypedApiInterface.FunctionID(2209481173L), best.nearest_neighbor_id()); + assertEquals("std::thread::_M_start_thread", best.name()); + assertEquals("_ZNSt6thread15_M_start_threadESt10unique_ptrINS_6_StateESt14default_deleteIS1_EEPFvvE", + best.nearest_neighbor_mangled_function_name()); + assertEquals("libstdc++.so.6", best.nearest_neighbor_binary_name()); + assertEquals(new TypedApiInterface.BinaryHash("7399e7775c542bf9bd036dccad91e9fea586a383ae2b958facfcdc03749f202e"), + best.nearest_neighbor_sha_256_hash()); + assertEquals(new TypedApiInterface.AnalysisID(948099), best.nearest_neighbor_analysis_id()); + assertEquals(2, match.getMatchedFunctions().size()); + } + + @Test + public void binarySearchResultsCarryAnalysisAndName() throws Exception { + var results = api().searchBinaries("libstdc", null); + assertEquals(1, results.size()); + assertEquals(Integer.valueOf(948099), results.get(0).getAnalysisId()); + assertEquals("libstdc++.so.6", results.get(0).getBinaryName()); + } + + @Test + public void collectionResultsCarryIdAndName() throws Exception { + var results = api().searchCollections("OpenSSL"); + assertEquals(1, results.size()); + assertEquals(Long.valueOf(42), results.get(0).getCollectionId()); + assertEquals("OpenSSL builds", results.get(0).getCollectionName()); + } + + private static String recorded(String name) throws IOException { + try (InputStream in = SdkRecordedResponseTest.class.getResourceAsStream("/sdk-responses/" + name)) { + if (in == null) { + throw new IOException("missing recorded response " + name); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java index 1c60d6d9..78d72a94 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java @@ -35,13 +35,15 @@ public void apiClientsExposeMethodsThePluginCalls() { apis.put("ai.reveng.api.SearchApi", new String[]{"searchBinaries"}); apis.put("ai.reveng.api.CollectionsApi", new String[]{"v3ListCollections"}); apis.put("ai.reveng.api.AuthenticationUsersApi", new String[]{"v3ListUsers"}); + // The tier gates the private-scope option in the analysis dialog. + apis.put("ai.reveng.api.IamUsersApi", new String[]{"getMe"}); apis.put("ai.reveng.api.AnalysesCoreApi", new String[]{ "uploadFile", "createAnalysis", "getAnalysisStatus", "getAnalysisBasicInfo_0", "startAnalysisFunctionMatching", "getAnalysisFunctionMatchingStatus", "getAnalysisFunctionMatches", - "v3GetAnalysisLogs", "v3ListAnalyses"}); + "v3GetAnalysisLogs", "v3ListAnalyses", "v3GetAnalysisAutoUnstripStatus"}); apis.put("ai.reveng.api.FunctionsCoreApi", new String[]{ "startFunctionsMatching", "getFunctionsMatchingStatus", "getFunctionsMatches", - "listAnalysisFunctions", + "listAnalysisFunctions", "v3CanonicalizeFunctionNames", // v3 endpoints; the generator suffixes _0 where the deprecated v2 name collides. "getFunctionBlocks_0", "getFunctionDetails_0"}); apis.put("ai.reveng.api.FunctionsRenamingHistoryApi", new String[]{"batchRenameFunctions"}); @@ -60,10 +62,11 @@ public void apiClientsExposeMethodsThePluginCalls() { "v3CreateAnalysisDataTypesCall", "v3UpdateAnalysisDataTypesCall", "v3UpdateFunctionSignature"}); apis.put("ai.reveng.api.FunctionsAiDecompilationApi", new String[]{ - "createAiDecompilation", "getAiDecompilation", "v3GetAiDecompilationTokens", - "v3UpsertAiDecompilationOverrides", + "createAiDecompilation", "getAiDecompilation", "getAiDecompilationStatus", + "v3GetAiDecompilationTokens", "v3UpsertAiDecompilationOverrides", "getAiDecompilationSummary", "getAiDecompilationSummaryStatus", "getAiDecompilationInlineComments", "getAiDecompilationInlineCommentsStatus", + "patchAiDecompilationInlineComment", "deleteAiDecompilationInlineComment", "regenerateAiDecompilationSummary", "regenerateAiDecompilationInlineComments", "upsertAiDecompilationRating"}); @@ -132,8 +135,15 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.ListPublicUsersOutputBody", "getResults"); requireMethods(missing, "ai.reveng.model.PublicUserBody", "getUserId", "getUsername"); requireMethods(missing, "ai.reveng.model.GetMatchesOutputBody", "getMatches", "getStatus"); + // Matching is polled on the status body; its step fields drive the progress text and its + // error-level messages become the failure reason. + requireMethods(missing, "ai.reveng.model.GetMatchesStatusOutputBody", + "getStatus", "getStep", "getStepIndex", "getStepsTotal", "getMessages"); + requireMethods(missing, "ai.reveng.model.ProgressMessage", "getLevel", "getText", "getTimestamp"); + requireMethods(missing, "ai.reveng.model.FunctionMatch", "getFunctionId", "getMatchedFunctions"); requireMethods(missing, "ai.reveng.model.MatchedFunction", - "getFunctionId", "getFunctionName", "getSimilarity", "getConfidence", "getAnalysisId"); + "getFunctionId", "getFunctionName", "getMangledName", "getBinaryName", "getSha256Hash", + "getDebug", "getSimilarity", "getConfidence", "getAnalysisId"); requireMethods(missing, "ai.reveng.model.BatchRenameInputBody", "setFunctions"); requireMethods(missing, "ai.reveng.model.BatchRenameItem", "setFunctionId", "setNewName", "setNewMangledName"); @@ -183,6 +193,32 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.Token", "getValue"); requireMethods(missing, "ai.reveng.model.UpsertOverridesInputBody", "getOverrides"); + // The AI decompilation poll: the decompilation itself, its pipeline progress while it runs, + // then the summary and inline comments once it completes. + requireMethods(missing, "ai.reveng.model.DecompilationData", "getStatus", "getDecompilation"); + requireMethods(missing, "ai.reveng.model.WorkflowProgress", + "getStatus", "getStep", "getStepIndex", "getStepsTotal", "getMessages"); + requireMethods(missing, "ai.reveng.model.SummaryData", "getAiSummary", "getSummary"); + requireMethods(missing, "ai.reveng.model.CommentsData", "getInlineComments"); + requireMethods(missing, "ai.reveng.model.InlineComment", "getLine", "getComment"); + requireMethods(missing, "ai.reveng.model.PatchCommentBody", "comment", "line"); + + requireMethods(missing, "ai.reveng.model.AutoUnstripStatusOutputBody", "getStatus"); + requireMethods(missing, "ai.reveng.model.CanonicalizeNamesInputBody", "names"); + requireMethods(missing, "ai.reveng.model.CanonicalizeNamesOutputBody", "getResults"); + requireMethods(missing, "ai.reveng.model.CanonicalName", "getName", "getCanonicalName"); + + requireMethods(missing, "ai.reveng.model.User", "getTier"); + requireMethods(missing, "ai.reveng.model.BaseResponseConfigResponse", "getData"); + requireMethods(missing, "ai.reveng.model.ConfigResponse", "getMaxFileSizeBytes"); + + // The collection and binary pickers in the matching filters. + requireMethods(missing, "ai.reveng.model.BaseResponseBinarySearchResponse", "getData"); + requireMethods(missing, "ai.reveng.model.BinarySearchResponse", "getResults"); + requireMethods(missing, "ai.reveng.model.BinarySearchResult", "getAnalysisId", "getBinaryName"); + requireMethods(missing, "ai.reveng.model.ListCollectionsOutputBody", "getResults"); + requireMethods(missing, "ai.reveng.model.CollectionListItemBody", "getCollectionId", "getCollectionName"); + assertTrue("SDK model surface drifted: " + missing, missing.isEmpty()); } diff --git a/src/test/resources/sdk-responses/README.md b/src/test/resources/sdk-responses/README.md new file mode 100644 index 00000000..a0b86da3 --- /dev/null +++ b/src/test/resources/sdk-responses/README.md @@ -0,0 +1,6 @@ +Response bodies for `SdkRecordedResponseTest`, one per endpoint, in the shape the staging server +emits them: every field the server writes, including the ones the plugin never reads. They were +taken from the handlers on `platform` origin/staging (the v3 API and the auth service) and, for the +deprecated `/v2/config` and `/v2/search/binaries`, from `reai-api`. + +When an endpoint's response changes, refresh its file from a live staging response. diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments-delete.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-delete.json new file mode 100644 index 00000000..240bb0c2 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-delete.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","inline_comments":[{"line":3,"comment":"Reject buffers too short to hold the 8-byte header."}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments-patch.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-patch.json new file mode 100644 index 00000000..4136314a --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-patch.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","inline_comments":[{"line":3,"comment":"Reject buffers too short to hold the 8-byte header."},{"line":6,"comment":"Length field is big-endian."}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments-status.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-status.json new file mode 100644 index 00000000..6dc95aaa --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-status.json @@ -0,0 +1 @@ +{"status":"COMPLETED","step":"storing_comments","step_index":2,"steps_total":2,"percent":100,"step_share":0,"messages":[{"timestamp":"2026-11-13T10:05:02.220871Z","step":"generating_comments","level":"INFO","text":"Generating structured comments"},{"timestamp":"2026-11-13T10:05:09.031455Z","step":"storing_comments","level":"INFO","text":"Storing comments"}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments.json new file mode 100644 index 00000000..6e6bd1e9 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","inline_comments":[{"line":3,"comment":"Reject buffers too short to hold the 8-byte header."},{"line":6,"comment":"Skip the 4-byte magic and parse the length field."}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-running.json b/src/test/resources/sdk-responses/ai-decompilation-running.json new file mode 100644 index 00000000..6cffe653 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-running.json @@ -0,0 +1 @@ +{"status":"RUNNING"} diff --git a/src/test/resources/sdk-responses/ai-decompilation-status.json b/src/test/resources/sdk-responses/ai-decompilation-status.json new file mode 100644 index 00000000..850b4134 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-status.json @@ -0,0 +1 @@ +{"status":"RUNNING","step":"decompiling","step_index":2,"steps_total":7,"percent":28,"step_share":14,"messages":[{"timestamp":"2026-11-13T10:04:11.482913Z","step":"charging_credits","level":"INFO","text":"Preparing decompilation"},{"timestamp":"2026-11-13T10:04:11.913204Z","step":"fetching_trace","level":"INFO","text":"Reading function trace"},{"timestamp":"2026-11-13T10:04:12.301877Z","step":"decompiling","level":"INFO","text":"Decompiling function"},{"timestamp":"2026-11-13T10:04:12.301877Z","step":"decompiling","level":"INFO","text":"Searching for functionality"}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-summary-status.json b/src/test/resources/sdk-responses/ai-decompilation-summary-status.json new file mode 100644 index 00000000..8c8534e7 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-summary-status.json @@ -0,0 +1 @@ +{"status":"COMPLETED","step":"storing_summary","step_index":2,"steps_total":2,"percent":100,"step_share":0,"messages":[{"timestamp":"2026-11-13T10:05:02.114502Z","step":"summarising","level":"INFO","text":"Generating summary"},{"timestamp":"2026-11-13T10:05:06.870331Z","step":"storing_summary","level":"INFO","text":"Storing summary"}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-summary.json b/src/test/resources/sdk-responses/ai-decompilation-summary.json new file mode 100644 index 00000000..30c7b3e8 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-summary.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","summary":"Parses an HTTP header from buf and returns the length of the remaining payload, or -1 if the buffer is shorter than 8 bytes.","ai_summary":"Parses an HTTP header from buf and returns the length of the remaining payload, or -1 if the buffer is shorter than 8 bytes.","predicted_function_name":"parse_http_header"} diff --git a/src/test/resources/sdk-responses/ai-decompilation.json b/src/test/resources/sdk-responses/ai-decompilation.json new file mode 100644 index 00000000..b05a3dbc --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation.json @@ -0,0 +1 @@ +{"status":"COMPLETED","decompilation":"int parse_header(char *buf, int len)\n{\n if (len < 8) {\n return -1;\n }\n return read_field(buf + 4, len - 4);\n}\n"} diff --git a/src/test/resources/sdk-responses/analysis-matches.json b/src/test/resources/sdk-responses/analysis-matches.json new file mode 100644 index 00000000..49d342ac --- /dev/null +++ b/src/test/resources/sdk-responses/analysis-matches.json @@ -0,0 +1 @@ +{"status":"COMPLETED","matches":[{"function_id":1109480836,"matched_functions":[{"function_id":2209481173,"function_name":"std::thread::_M_start_thread","binary_id":758289,"analysis_id":948099,"function_vaddr":4198400,"debug":true,"similarity":99.42,"confidence":87.1,"mangled_name":"_ZNSt6thread15_M_start_threadESt10unique_ptrINS_6_StateESt14default_deleteIS1_EEPFvvE","binary_name":"libstdc++.so.6","sha_256_hash":"7399e7775c542bf9bd036dccad91e9fea586a383ae2b958facfcdc03749f202e"},{"function_id":2210377402,"function_name":"std::thread::_M_start_thread","binary_id":760743,"analysis_id":951312,"function_vaddr":4210688,"debug":true,"similarity":97.85,"confidence":12.9,"mangled_name":"_ZNSt6thread15_M_start_threadESt10unique_ptrINS_6_StateESt14default_deleteIS1_EEPFvvE","binary_name":"libstdc++.so.6.0.33","sha_256_hash":"c1a5e0b2f4d1e9a3b7c6d8e0f2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e6f8a0"}],"confidences":[{"name":"std::thread::_M_start_thread","confidence":100.0}]}]} diff --git a/src/test/resources/sdk-responses/auto-unstrip-status.json b/src/test/resources/sdk-responses/auto-unstrip-status.json new file mode 100644 index 00000000..f68b1e26 --- /dev/null +++ b/src/test/resources/sdk-responses/auto-unstrip-status.json @@ -0,0 +1 @@ +{"status":"COMPLETED"} diff --git a/src/test/resources/sdk-responses/canonical-names.json b/src/test/resources/sdk-responses/canonical-names.json new file mode 100644 index 00000000..ae88b94a --- /dev/null +++ b/src/test/resources/sdk-responses/canonical-names.json @@ -0,0 +1 @@ +{"results":[{"name":"_ZN3fooC1Ev","canonical_name":"foo"},{"name":"sub_401000","canonical_name":"sub_401000"}]} diff --git a/src/test/resources/sdk-responses/collections.json b/src/test/resources/sdk-responses/collections.json new file mode 100644 index 00000000..e6b0306b --- /dev/null +++ b/src/test/resources/sdk-responses/collections.json @@ -0,0 +1 @@ +{"results":[{"collection_id":42,"collection_name":"OpenSSL builds","description":"Reference builds of OpenSSL across versions","collection_scope":"PRIVATE","collection_owner":"jdoe","official_collection":false,"collection_tags":["openssl","crypto"],"collection_size":18,"team_id":12,"creation":"2026-01-14T09:30:00.104882Z","updated_at":"2026-01-15T11:02:00.733019Z"}],"page_size":20,"page_number":0,"has_next_page":false} diff --git a/src/test/resources/sdk-responses/config.json b/src/test/resources/sdk-responses/config.json new file mode 100644 index 00000000..7b1e0b29 --- /dev/null +++ b/src/test/resources/sdk-responses/config.json @@ -0,0 +1 @@ +{"status":true,"data":{"dashboard_url":"https://portal.reveng.ai","max_file_size_bytes":31457280,"ai_decompiler_unsupported_languages":["go","rust"],"ai_decompiler_supported_models":["binnet-1.0","binnet-0.7-x86-64-linux","binnet-0.7-x86-32-linux","binnet-0.7-x86-64-windows","binnet-0.7-x86-32-windows","binnet-0.7-arm-64-windows","binnet-0.7-arm-64-linux"]},"message":null,"errors":null,"meta":{"pagination":null}} diff --git a/src/test/resources/sdk-responses/iam-me.json b/src/test/resources/sdk-responses/iam-me.json new file mode 100644 index 00000000..ba5cda12 --- /dev/null +++ b/src/test/resources/sdk-responses/iam-me.json @@ -0,0 +1 @@ +{"user_id":42,"role":"USER","tier":"REVERSER","email":"jane.doe@example.com","created_at":"2026-03-02T09:14:27.512843Z","is_active":true,"profile":{"username":"jdoe","first_name":"Jane","last_name":"Doe","time_zone":"Europe/London","default_team_id":12,"hide_example_binaries":false,"hide_ai_decompilation_comments":false,"agent_chat_layout":"floating"},"signs_in_with":"password"} diff --git a/src/test/resources/sdk-responses/matches-status-completed.json b/src/test/resources/sdk-responses/matches-status-completed.json new file mode 100644 index 00000000..f12195fb --- /dev/null +++ b/src/test/resources/sdk-responses/matches-status-completed.json @@ -0,0 +1 @@ +{"status":"COMPLETED","step":"","step_index":0,"steps_total":0,"percent":100,"step_share":0,"messages":[],"completed_at":"2026-11-13T09:30:00.418273Z"} diff --git a/src/test/resources/sdk-responses/matches-status-running.json b/src/test/resources/sdk-responses/matches-status-running.json new file mode 100644 index 00000000..4d8e8246 --- /dev/null +++ b/src/test/resources/sdk-responses/matches-status-running.json @@ -0,0 +1 @@ +{"status":"RUNNING","step":"matching","step_index":1,"steps_total":3,"percent":3,"step_share":85,"messages":[{"timestamp":"2026-11-13T09:29:41.007112Z","step":"resolving_analysis","level":"INFO","text":"Resolving function IDs for the analysis"},{"timestamp":"2026-11-13T09:29:41.552390Z","step":"matching","level":"INFO","text":"Searching for similar functions"}]} diff --git a/src/test/resources/sdk-responses/search-binaries.json b/src/test/resources/sdk-responses/search-binaries.json new file mode 100644 index 00000000..cf1341bb --- /dev/null +++ b/src/test/resources/sdk-responses/search-binaries.json @@ -0,0 +1 @@ +{"status":true,"data":{"results":[{"binary_id":758289,"binary_name":"libstdc++.so.6","analysis_id":948099,"sha_256_hash":"7399e7775c542bf9bd036dccad91e9fea586a383ae2b958facfcdc03749f202e","tags":["linux","stdlib"],"created_at":"2026-10-02T14:21:07.483912Z","model_id":12,"model_name":"binnet-0.7-x86-64-linux","owned_by":"jdoe"}]},"message":null,"errors":null,"meta":{"pagination":{"page_size":10,"page_number":1,"has_next_page":false}}} From b4f3374faab4d256acfe53d7658da454d5b5d6b9 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:24:10 +0000 Subject: [PATCH 50/76] feat(ENG-4563): migrate upload and analysis creation to v3 (#253) --- .../services/api/AnalysisOptionsBuilder.java | 37 +++++++------------ .../services/api/GhidraRevengService.java | 23 ++++++++++++ .../services/api/TypedApiImplementation.java | 28 +++++++++----- .../ai/reveng/AnalysisOptionsDialogTest.java | 6 +-- .../ai/reveng/GhidraRevengServiceTest.java | 26 +++++++++++++ .../api/AnalysisOptionsBuilderTest.java | 23 +++++------- .../services/api/EmptyResponseDataTest.java | 4 +- .../core/services/api/SdkSchemaTest.java | 9 +++-- 8 files changed, 102 insertions(+), 54 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java index 01b49edc..767b522f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java @@ -7,8 +7,7 @@ import ghidra.util.Msg; import org.json.JSONArray; import org.json.JSONObject; -import ai.reveng.model.AnalysisCreateRequest; -import ai.reveng.model.Tag; +import ai.reveng.model.CreateRequest; import java.util.ArrayList; import java.util.List; @@ -102,35 +101,25 @@ public AnalysisOptionsBuilder architecture(String arch) { } /** - * Converts the current AnalysisOptionsBuilder to an AnalysisCreateRequest object - * that can be used with the new API endpoints + * Converts the current AnalysisOptionsBuilder to the v3 create-analysis request. * - * @return AnalysisCreateRequest object populated with the current options + * @return CreateRequest populated with the current options */ - public AnalysisCreateRequest toAnalysisCreateRequest() { - // Create the request with only the core required fields that we know work - var request = new AnalysisCreateRequest() + public CreateRequest toAnalysisCreateRequest() { + var request = new CreateRequest() .filename(options.getString("file_name")) .sha256Hash(options.getString("sha_256_hash")); - // Include tags if any were provided - List tagStrings = getTags(); - if (!tagStrings.isEmpty()) { - // Convert string tags to Tag objects, filtering out any empty/null strings - List tags = tagStrings.stream() - .filter(tagString -> tagString != null && !tagString.trim().isEmpty()) - .map(tagString -> new Tag().name(tagString)) - .toList(); - - // Only set tags if we have valid ones after filtering - if (!tags.isEmpty()) { - request.setTags(tags); - } + List tags = getTags().stream() + .filter(tag -> tag != null && !tag.trim().isEmpty()) + .toList(); + if (!tags.isEmpty()) { + request.setTags(tags); } if (options.has("binary_scope")) { var scope = options.getString("binary_scope"); - request.analysisScope(ai.reveng.model.AnalysisScope.fromValue(scope)); + request.analysisScope(CreateRequest.AnalysisScopeEnum.fromValue(scope)); } if (options.has("symbols")) { @@ -160,7 +149,7 @@ public AnalysisCreateRequest toAnalysisCreateRequest() { request.setSymbols(symbolsModel); } - var analysisConfig = new ai.reveng.model.AnalysisConfig(); + var analysisConfig = new ai.reveng.model.Config(); if (options.has("skip_capabilities")) { analysisConfig.setGenerateCapabilities(!options.getBoolean("skip_capabilities")); @@ -180,7 +169,7 @@ public AnalysisCreateRequest toAnalysisCreateRequest() { request.setBinaryConfig(binaryConfig); - Msg.info(this, "Created AnalysisCreateRequest: " + request); + Msg.info(this, "Created CreateRequest: " + request); return request; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 9c5e1abf..a3cf79ef 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -18,6 +18,8 @@ import ghidra.app.cmd.function.ApplyFunctionSignatureCmd; import ghidra.app.cmd.function.FunctionRenameOption; import ghidra.app.cmd.function.SetFunctionNameCmd; +import ghidra.framework.OperatingSystem; +import ghidra.framework.Platform; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.ServiceProvider; import ghidra.program.model.address.Address; @@ -46,7 +48,10 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; +import java.nio.file.FileSystemException; +import java.nio.file.Files; import java.nio.file.InvalidPathException; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.time.Duration; import java.util.*; @@ -1321,6 +1326,11 @@ public TypedApiInterface.BinaryHash upload(Program program) { // we have to drop the first "/" for the path to be valid filePath = Path.of(program.getExecutablePath().substring(1)); } + // The SDK only reports an unreadable file as an opaque HTTP 0, so check up front. + try (var ignored = Files.newInputStream(filePath)) { + } catch (IOException e) { + throw new RuntimeException(unreadableBinaryMessage(filePath, e), e); + } try { var hash = api.upload(filePath); if (hash.equals(hashOfProgram(program))){ @@ -1339,6 +1349,19 @@ public TypedApiInterface.BinaryHash upload(Program program) { } } + private static String unreadableBinaryMessage(Path path, IOException e) { + String reason = e instanceof NoSuchFileException ? "file not found" + : e instanceof FileSystemException fse && fse.getReason() != null ? fse.getReason() + : e.getMessage(); + String message = "Cannot read %s (%s).".formatted(path, reason); + if (Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.MAC_OS_X + && !(e instanceof NoSuchFileException)) { + message += "\n\nmacOS may be blocking Ghidra from this folder. Grant access in System Settings → " + + "Privacy & Security → Files and Folders, or move the file elsewhere and re-import it."; + } + return message; + } + public TypedApiInterface.BinaryHash upload(Path path) { try { return api.upload(path); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index fe366a5a..98176eae 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -66,7 +66,7 @@ public class TypedApiImplementation implements TypedApiInterface { private final ApiClient apiClient; private final ApiClient uploadClient; - private final AnalysesCoreApi uploadApi; + private final BinariesApi uploadApi; /// Ordinary requests: a page of functions or a batch of signatures, which the server answers quickly. private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(15); @@ -83,7 +83,7 @@ public TypedApiImplementation(String baseUrl, String apiKey) { var apiClient = newClient(baseUrl, apiKey, userAgent, REQUEST_TIMEOUT); this.apiClient = apiClient; this.uploadClient = newClient(baseUrl, apiKey, userAgent, UPLOAD_TIMEOUT); - this.uploadApi = new AnalysesCoreApi(uploadClient); + this.uploadApi = new BinariesApi(uploadClient); this.analysisCoreApi = new AnalysesCoreApi(apiClient); this.searchApi = new SearchApi(apiClient); @@ -160,12 +160,12 @@ public BinaryHash upload(Path binPath) throws FileNotFoundException, ApiExceptio if (!bin.exists()) throw new FileNotFoundException("Binary to upload does not exist"); - var result = this.uploadApi.uploadFile(UploadFileType.fromValue("BINARY"), bin, null, true); + var result = this.uploadApi.v3UploadFile(bin, "BINARY", true); - if (result.getData() == null) { - throw new ApiException("Upload response carried no data"); + if (result.getSha256Hash() == null) { + throw new ApiException("Upload response carried no hash"); } - return new BinaryHash(result.getData().getSha256Hash()); + return new BinaryHash(result.getSha256Hash()); } /// GET /v3/analyses, filtered to one binary hash and paged to exhaustion. @@ -197,14 +197,22 @@ public List search(BinaryHash hash) { return results; } + /// POST /v3/analyses + /// + /// Answers with a long-running operation: the analysis id rides on its metadata while pending + /// and on its response once done. @Override public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { var analysisRequest = options.toAnalysisCreateRequest(); - var result = this.analysisCoreApi.createAnalysis(analysisRequest, null); - if (result.getData() == null) { - throw new ApiException("Analysis creation response carried no data"); + var operation = this.analysisCoreApi.v3CreateAnalysis(analysisRequest, null); + Long analysisId = operation.getMetadata() != null ? operation.getMetadata().getAnalysisId() : null; + if (analysisId == null && operation.getResponse() != null) { + analysisId = operation.getResponse().getAnalysisId(); + } + if (analysisId == null) { + throw new ApiException("Create-analysis operation " + operation.getName() + " carried no analysis id"); } - return new AnalysisID(result.getData().getAnalysisId()); + return new AnalysisID(Math.toIntExact(analysisId)); } @Override diff --git a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java index 87ae690a..19b0461c 100644 --- a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java +++ b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java @@ -22,7 +22,7 @@ import javax.swing.*; -import ai.reveng.model.AnalysisCreateRequest; +import ai.reveng.model.CreateRequest; import ai.reveng.model.User; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.analysiscreation.RevEngAIAnalysisOptionsDialog; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; @@ -71,7 +71,7 @@ public void testBasicOptionsDialog() throws Exception { /** * Pins the analysis configuration the dialog submits. The dialog offers no controls for - * capability generation, advanced analysis, third-party scraping or sandbox execution, so + * capability generation, third-party scraping or sandbox execution, so * every analysis it creates must carry these fixed values. */ @Test @@ -95,7 +95,7 @@ public void testSubmittedAnalysisConfig() throws Exception { var options = dialog.getOptionsFromUI(); assertNotNull(options); - AnalysisCreateRequest request = options.toAnalysisCreateRequest(); + CreateRequest request = options.toAnalysisCreateRequest(); var analysisConfig = request.getAnalysisConfig(); assertNotNull("The request must always carry an analysis config", analysisConfig); diff --git a/src/test/java/ai/reveng/GhidraRevengServiceTest.java b/src/test/java/ai/reveng/GhidraRevengServiceTest.java index 85a1880a..9218b684 100644 --- a/src/test/java/ai/reveng/GhidraRevengServiceTest.java +++ b/src/test/java/ai/reveng/GhidraRevengServiceTest.java @@ -5,6 +5,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.BinaryHash; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; @@ -13,7 +14,10 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; +import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; @@ -44,6 +48,28 @@ public void testKnownProgramLookupIsNetworkFree() throws Exception { statusCallsBefore, mock.statusCalls); } + /// An unreadable binary must fail with the path and reason, not the SDK's raw HTTP 0 dump. + @Test + public void testUploadOfUnreadableFileExplainsWhy() throws Exception { + Path bin = Files.createTempFile("unreadable", ".bin"); + bin.toFile().deleteOnExit(); + Files.setPosixFilePermissions(bin, Set.of()); + var program = newX64Program().getProgram(); + int tx = program.startTransaction("set path"); + program.setExecutablePath(bin.toString()); + program.endTransaction(tx, true); + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public BinaryHash upload(Path binPath) { + throw new RuntimeException(new ApiException("Message: java.io.FileNotFoundException: " + binPath)); + } + }); + + var e = assertThrows(RuntimeException.class, () -> service.upload(program)); + + assertTrue(e.getMessage(), e.getMessage().startsWith("Cannot read " + bin)); + } + @Test public void testStatusPollingGivesUpAfterTenFailures() throws Exception { var statusCalls = new int[1]; diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java index a2e5fb0f..d5f40f35 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java @@ -1,7 +1,6 @@ package ai.reveng.toolkit.ghidra.core.services.api; -import ai.reveng.model.AnalysisCreateRequest; -import ai.reveng.model.Tag; +import ai.reveng.model.CreateRequest; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionBoundary; import org.junit.Test; @@ -22,7 +21,7 @@ public void testToAnalysisCreateRequest_IncludeInAnalysisFlag() { new FunctionBoundary("excluded_fn", 0x1020, 0x1030, false), new FunctionBoundary("default_fn", 0x1040, 0x1050))); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); List boundaries = request.getSymbols().getFunctionBoundaries(); assertEquals("All boundaries are sent regardless of the include flag", 3, boundaries.size()); @@ -47,7 +46,7 @@ public void testToAnalysisCreateRequest_WithNoTags() { .hash(new TypedApiInterface.BinaryHash("a".repeat(64))) .fileName("test.bin"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that tags are either null or empty, but not containing empty tags if (request.getTags() != null) { @@ -64,15 +63,13 @@ public void testToAnalysisCreateRequest_WithValidTags() { .addTag("malware") .addTag("suspicious"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that tags are properly set assertNotNull("Tags should not be null", request.getTags()); assertEquals("Should have 2 tags", 2, request.getTags().size()); - List tagNames = request.getTags().stream() - .map(Tag::getName) - .toList(); + List tagNames = request.getTags(); assertTrue("Should contain 'malware' tag", tagNames.contains("malware")); assertTrue("Should contain 'suspicious' tag", tagNames.contains("suspicious")); @@ -88,12 +85,12 @@ public void testToAnalysisCreateRequest_WithEmptyStringTag() { .addTag(" ") // whitespace only .addTag("valid-tag"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that empty/whitespace tags are filtered out assertNotNull("Tags should not be null", request.getTags()); assertEquals("Should only have 1 valid tag after filtering", 1, request.getTags().size()); - assertEquals("Should only contain the valid tag", "valid-tag", request.getTags().getFirst().getName()); + assertEquals("Should only contain the valid tag", "valid-tag", request.getTags().getFirst()); } @Test @@ -104,7 +101,7 @@ public void testToAnalysisCreateRequest_WithMultipleTags() { .fileName("test.bin") .addTags(Arrays.asList("tag1", "tag2", "tag3")); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that all tags are properly set assertNotNull("Tags should not be null", request.getTags()); @@ -121,7 +118,7 @@ public void testToAnalysisCreateRequest_WithOnlyEmptyTags() { .addTag(" ") .addTag("\t"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that no tags are set when all are empty if (request.getTags() != null) { @@ -139,7 +136,7 @@ public void testToAnalysisCreateRequest_BasicFields() { .hash(new TypedApiInterface.BinaryHash(hash)) .fileName(filename); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); assertEquals("Filename should match", filename, request.getFilename()); assertEquals("SHA256 hash should match", hash, request.getSha256Hash()); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java index 2cb50090..34f6edab 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java @@ -9,10 +9,12 @@ public class EmptyResponseDataTest extends AbstractStubServerTest { private static final String EMPTY = "{\"status\": false, \"data\": null, \"message\": \"nope\"}"; + private static final String OPERATION_WITHOUT_ID = "{\"name\": \"operations/1\", \"done\": false}"; @Override protected void configureStubs(HttpServer server) { server.createContext("/", exchange -> respondJson(exchange, EMPTY)); + server.createContext("/v3/analyses", exchange -> respondJson(exchange, OPERATION_WITHOUT_ID)); } @Test(expected = ApiException.class) @@ -21,7 +23,7 @@ public void statusWithoutDataThrowsApiException() throws Exception { } @Test(expected = ApiException.class) - public void analyseWithoutDataThrowsApiException() throws Exception { + public void analyseWithoutAnalysisIdThrowsApiException() throws Exception { api().analyse(new AnalysisOptionsBuilder() .hash(new TypedApiInterface.BinaryHash("a".repeat(64))) .fileName("test.bin")); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java index 1c60d6d9..8e811834 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java @@ -36,9 +36,10 @@ public void apiClientsExposeMethodsThePluginCalls() { apis.put("ai.reveng.api.CollectionsApi", new String[]{"v3ListCollections"}); apis.put("ai.reveng.api.AuthenticationUsersApi", new String[]{"v3ListUsers"}); apis.put("ai.reveng.api.AnalysesCoreApi", new String[]{ - "uploadFile", "createAnalysis", "getAnalysisStatus", "getAnalysisBasicInfo_0", + "v3CreateAnalysis", "getAnalysisStatus", "getAnalysisBasicInfo_0", "startAnalysisFunctionMatching", "getAnalysisFunctionMatchingStatus", "getAnalysisFunctionMatches", "v3GetAnalysisLogs", "v3ListAnalyses"}); + apis.put("ai.reveng.api.BinariesApi", new String[]{"v3UploadFile"}); apis.put("ai.reveng.api.FunctionsCoreApi", new String[]{ "startFunctionsMatching", "getFunctionsMatchingStatus", "getFunctionsMatches", "listAnalysisFunctions", @@ -120,9 +121,11 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.FunctionSignatureVersion", "getValue", "getUpdatedAt", "getUpdatedBy"); - requireMethods(missing, "ai.reveng.model.AnalysisCreateRequest", + requireMethods(missing, "ai.reveng.model.CreateRequest", "getFilename", "getSha256Hash", "getTags", "getAnalysisScope"); - requireMethods(missing, "ai.reveng.model.Tag", "getName"); + requireMethods(missing, "ai.reveng.model.UploadOutputBody", "getSha256Hash"); + requireMethods(missing, "ai.reveng.model.OperationCreateMetadataCreateResult", + "getMetadata", "getResponse"); requireMethods(missing, "ai.reveng.model.StartMatchingForAnalysisInputBody", "getMinSimilarity", "getResultsPerFunction", "getFilters"); requireMethods(missing, "ai.reveng.model.StartMatchingForFunctionsInputBody", From ca846ff5b83764ee61db31ceb45376fc95961ce5 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:10:03 +0000 Subject: [PATCH 51/76] fix(ENG-4475): treat an empty mangled_name as absent Staging sends mangled_name as "" for functions with no mangled symbol. FunctionInfo only fell back to the function name on null, so it kept the empty string, and the FUN_/sub_ guard in the rename branch never matched it. Fall back on a blank name too. --- .../services/api/TypedApiImplementation.java | 7 +++-- .../api/GetFunctionInfoPaginationTest.java | 28 ++++++++++++++++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 98176eae..98c3e9f4 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -254,8 +254,11 @@ public List getFunctionInfo(AnalysisID analysisID) { new FunctionID(f.getFunctionId()), f.getFunctionName(), // The mangled name is optional here; an unmangled symbol carries none, - // and callers rely on this field being populated. - f.getMangledName() != null ? f.getMangledName() : f.getFunctionName(), + // and callers rely on this field being populated. The server also sends + // it as "" rather than leaving it out, which would otherwise slip past + // the FUN_/sub_ guard on renames. + f.getMangledName() == null || f.getMangledName().isBlank() + ? f.getFunctionName() : f.getMangledName(), f.getFunctionVaddr(), Math.toIntExact(f.getFunctionSize()) ) diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java index 126129da..c4d599c4 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java @@ -92,6 +92,20 @@ public void getFunctionInfo_fallsBackToTheFunctionNameWhenUnmangled() { functions.stream().map(FunctionInfo::functionMangledName).collect(Collectors.toList())); } + /** + * Staging sends mangled_name as "" for functions with no mangled symbol. Kept as-is, an empty + * name never starts with FUN_ or sub_, so the rename guard would let a placeholder through. + */ + @Test + public void getFunctionInfo_treatsAnEmptyMangledNameAsAbsent() { + allFunctionIds = List.of(10L, EMPTY_MANGLED_ID, BLANK_MANGLED_ID); + + List functions = fetch(); + + assertEquals(List.of("mangled_10", "func_" + EMPTY_MANGLED_ID, "func_" + BLANK_MANGLED_ID), + functions.stream().map(FunctionInfo::functionMangledName).collect(Collectors.toList())); + } + private List fetch() { return api().getFunctionInfo(new TypedApiInterface.AnalysisID(ANALYSIS_ID)); } @@ -124,9 +138,21 @@ private static String pageResponse(List functionIds, int totalCount) { /** The id whose entry the stub serves without a mangled_name. */ private static final long UNMANGLED_ID = 99L; + /** The ids whose entries carry an empty and a whitespace-only mangled_name. */ + private static final long EMPTY_MANGLED_ID = 98L; + private static final long BLANK_MANGLED_ID = 97L; private static String functionJson(long id) { - String mangledName = id == UNMANGLED_ID ? "" : "\"mangled_name\":\"mangled_%d\",".formatted(id); + String mangledName; + if (id == UNMANGLED_ID) { + mangledName = ""; + } else if (id == EMPTY_MANGLED_ID) { + mangledName = "\"mangled_name\":\"\","; + } else if (id == BLANK_MANGLED_ID) { + mangledName = "\"mangled_name\":\" \","; + } else { + mangledName = "\"mangled_name\":\"mangled_%d\",".formatted(id); + } return """ {"function_id":%d,"function_name":"func_%d",%s\ "function_vaddr":%d,"function_size":32,"binary_id":7,"debug":false,\ From f1a303c6d8dbfa8bb3e27fc600508e6aaa99e26e Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:43:32 +0000 Subject: [PATCH 52/76] fix(ENG-4484): load analysis details off the EDT before opening Function Matching The matching dialog fetched the analysis' basic info in its constructor, which runs on the Swing thread from the menu actions. The first fetch is uncached and can block the UI for several seconds, and when it failed the constructor returned early and the action still showed a dialog with no work panel. The actions now go through AbstractFunctionMatchingDialog.showWhenLoaded, which fetches the details in a background task and builds the dialog with them, or reports the failure and shows no dialog. The dialogs take the details as a constructor argument. --- .../AbstractFunctionMatchingDialog.java | 56 ++++++-- .../BinaryLevelFunctionMatchingDialog.java | 5 +- .../FunctionLevelFunctionMatchingDialog.java | 5 +- .../plugins/BinarySimilarityPlugin.java | 9 +- ...nctionLevelFunctionMatchingDialogTest.java | 124 +++++++++++++++--- 5 files changed, 163 insertions(+), 36 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index a6b671a8..13391c49 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -1,9 +1,11 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching; +import ai.reveng.invoker.ApiException; import ai.reveng.model.*; import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiImplementation; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.CollectionSelectionPanel; @@ -20,6 +22,8 @@ import ghidra.util.task.TaskBuilder; import ghidra.util.task.TaskMonitor; import ghidra.util.Msg; +import ghidra.util.Swing; +import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import resources.ResourceManager; import generic.theme.GThemeDefaults.Colors.Messages; import generic.theme.GColor; @@ -76,7 +80,8 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone private final JPopupMenu portalPopup = new JPopupMenu(); // Data - protected AnalysisBasicInfoOutputBody analysisBasicInfo; + /// Loaded by {@link #showWhenLoaded} before the dialog is built; the binary filter searches within its model + protected final AnalysisBasicInfoOutputBody analysisBasicInfo; protected final List functionMatchResults; protected final List filteredFunctionMatchResults; @@ -86,24 +91,15 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone protected static final Duration MAX_MATCHING_WAIT = Duration.ofMinutes(30); protected AbstractFunctionMatchingDialog(String title, Boolean isModal, PluginTool tool, - GhidraRevengService.AnalysedProgram analyzedProgram) { + GhidraRevengService.AnalysedProgram analyzedProgram, + AnalysisBasicInfoOutputBody analysisBasicInfo) { super(title, isModal); this.tool = tool; this.revengService = tool.getService(GhidraRevengService.class); this.analyzedProgram = analyzedProgram; this.functionMatchResults = new ArrayList<>(); this.filteredFunctionMatchResults = new ArrayList<>(); - - try { - this.analysisBasicInfo = revengService.getBasicDetailsForAnalysis(analyzedProgram.analysisID()); - } catch (Exception e) { - JOptionPane.showMessageDialog(null, - "Failed to fetch analysis details: " + e.getMessage(), - "Error", - JOptionPane.ERROR_MESSAGE); - close(); - return; - } + this.analysisBasicInfo = analysisBasicInfo; // Initialize UI addDismissButton(); @@ -116,6 +112,40 @@ protected AbstractFunctionMatchingDialog(String title, Boolean isModal, PluginTo statusLabel.setText("Ready: adjust the filters and press Match Functions"); } + /// Fetches the analysis' basic info in a background task, then builds the dialog with it and shows it. The + /// first fetch for an analysis is not cached and can take several seconds, so it must not run on the Swing + /// thread; when it fails the user is told why and no dialog is shown. + public static void showWhenLoaded(PluginTool tool, GhidraRevengService.AnalysedProgram analyzedProgram, + java.util.function.Function dialog) { + var service = tool.getService(GhidraRevengService.class); + tool.execute(new Task("Load RevEng.AI analysis details", true, false, false) { + @Override + public void run(TaskMonitor monitor) { + AnalysisBasicInfoOutputBody basicInfo; + try { + basicInfo = service.getBasicDetailsForAnalysis(analyzedProgram.analysisID()); + } catch (Exception e) { + // The message carries the server's reason; the trace goes to the log, not the dialog + var message = "Failed to fetch the details of analysis %d: %s" + .formatted(analyzedProgram.analysisID().id(), describe(e)); + Msg.warn(AbstractFunctionMatchingDialog.class, message, e); + Msg.showError(AbstractFunctionMatchingDialog.class, tool.getToolFrame(), + ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", message); + return; + } + if (monitor.isCancelled()) { + return; + } + Swing.runLater(() -> tool.showDialog(dialog.apply(basicInfo))); + } + }, 0); + } + + private static String describe(Exception e) { + return e instanceof ApiException api + ? TypedApiImplementation.describeApiException(api) : e.getMessage(); + } + protected void startFunctionMatching() { // All network work runs on a background thread so the UI stays responsive statusLabel.setText("Starting function matching..."); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java index 37af713e..40c24e31 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java @@ -13,9 +13,10 @@ public class BinaryLevelFunctionMatchingDialog extends AbstractFunctionMatchingDialog { - public BinaryLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID) { + public BinaryLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID, + AnalysisBasicInfoOutputBody analysisBasicInfo) { super(ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", true, - tool, programWithBinaryID); + tool, programWithBinaryID, analysisBasicInfo); } @Override diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java index 2f711c0e..aa51f656 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java @@ -15,9 +15,10 @@ public class FunctionLevelFunctionMatchingDialog extends AbstractFunctionMatchingDialog { private final Function function; - public FunctionLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID, Function function) { + public FunctionLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID, + AnalysisBasicInfoOutputBody analysisBasicInfo, Function function) { super(ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", true, - tool, programWithBinaryID); + tool, programWithBinaryID, analysisBasicInfo); this.function = function; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java index 11b49241..09e26778 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java @@ -16,6 +16,7 @@ package ai.reveng.toolkit.ghidra.plugins; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.aidecompiler.AIDecompilationdWindow; +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.AbstractFunctionMatchingDialog; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.BinaryLevelFunctionMatchingDialog; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.FunctionLevelFunctionMatchingDialog; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.SimilarFunctionsWindow; @@ -134,8 +135,8 @@ private void setupActions() { return; } - var functionMatchingDialog = new BinaryLevelFunctionMatchingDialog(tool, knownProgram.get()); - tool.showDialog(functionMatchingDialog); + AbstractFunctionMatchingDialog.showWhenLoaded(tool, knownProgram.get(), + basicInfo -> new BinaryLevelFunctionMatchingDialog(tool, knownProgram.get(), basicInfo)); }) .buildAndInstall(tool); @@ -196,8 +197,8 @@ public void run(TaskMonitor monitor) { var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress()); - var functionMatchingDialog = new FunctionLevelFunctionMatchingDialog(tool, knownProgram, func); - tool.showDialog(functionMatchingDialog); + AbstractFunctionMatchingDialog.showWhenLoaded(tool, knownProgram, + basicInfo -> new FunctionLevelFunctionMatchingDialog(tool, knownProgram, basicInfo, func)); }) .popupMenuPath(new String[] { "Match function" }) .popupMenuIcon(ReaiPluginPackage.REVENG_16) diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index 18ff03ab..a8a10496 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -2,7 +2,9 @@ import ai.reveng.model.*; import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.AbstractFunctionMatchingDialog; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.FunctionLevelFunctionMatchingDialog; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; @@ -13,6 +15,8 @@ import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; import ai.reveng.toolkit.ghidra.plugins.BinarySimilarityPlugin; +import docking.AbstractErrDialog; +import docking.DialogComponentProvider; import docking.DockingWindowManager; import ghidra.program.model.data.Undefined; import ghidra.program.model.symbol.SourceType; @@ -60,7 +64,7 @@ public void testDialogOpensWithMockedService() throws Exception { // Create and show the dialog FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -107,7 +111,7 @@ public void testDialogHasResultsTableConfigured() throws Exception { // Create the dialog FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -142,7 +146,7 @@ public void testAssemblyComparisonPanelExists() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -176,7 +180,7 @@ public void testUserSubmittedDebugSymbolsAlwaysVisibleAndEnabledByParent() throw waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); @@ -217,7 +221,7 @@ public void testFunctionMatchingTriggersAPICall() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -255,7 +259,7 @@ public void testPlatformAndArchitectureTogglesAreSentAsMatchFilters() throws Exc waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); @@ -306,7 +310,7 @@ public void testClickMatchButtonPopulatesResultsTable() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -378,7 +382,7 @@ public void testSelectedMatchFollowsSortOrderNotModelOrder() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); @@ -452,7 +456,7 @@ public GetMatchesOutputBody getFunctionsMatches(List functionIds) { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); @@ -502,7 +506,7 @@ public void testSimilarityAndConfidenceCellsAreColorCoded() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); @@ -548,7 +552,7 @@ public void testRightClickOffersMatchedBinaryInPortal() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); @@ -615,7 +619,7 @@ public void testTransferOnlyRenamesOnThePortalWhatItAppliedLocally() throws Exce sync.attach(program); try { FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); @@ -759,7 +763,7 @@ public GetMatchesStatusOutputBody getFunctionsMatchingStatus(List function waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); @@ -808,7 +812,7 @@ public void testCancelledRunDoesNotHideTheNextRunsProgress() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); @@ -884,6 +888,95 @@ public GetMatchesStatusOutputBody getFunctionsMatchingStatus(List function } } + /// The plugin actions open the dialog through showWhenLoaded, which fetches the analysis details off the + /// Swing thread and builds the dialog with them + @Test + public void testAnalysisDetailsLoadOffTheSwingThreadBeforeTheDialogOpens() throws Exception { + var tool = env.getTool(); + var fetchedOnSwingThread = new java.util.concurrent.atomic.AtomicReference(); + var service = addMockedService(tool, new FunctionMatchingMockApi() { + @Override + public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) + throws ai.reveng.invoker.ApiException { + fetchedOnSwingThread.set(SwingUtilities.isEventDispatchThread()); + return super.getAnalysisBasicInfo(analysisID); + } + }); + env.addPlugin(BinarySimilarityPlugin.class); + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + runSwing(() -> AbstractFunctionMatchingDialog.showWhenLoaded(tool, analysedProgram, + basicInfo -> new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo, testFunction)), false); + + var dialog = awaitDialog(FunctionLevelFunctionMatchingDialog.class); + assertEquals("the details should be fetched, and not on the Swing thread", Boolean.FALSE, fetchedOnSwingThread.get()); + var loaded = (AnalysisBasicInfoOutputBody) getInstanceField("analysisBasicInfo", dialog); + assertEquals("test-model", loaded.getModelName()); + + close(dialog); + waitForSwing(); + } + + /// When the details cannot be fetched the user is told why, and no half-built dialog is shown + @Test + public void testFailedAnalysisDetailsShowAnErrorInsteadOfTheDialog() throws Exception { + setErrorGUIEnabled(true); + var tool = env.getTool(); + var service = addMockedService(tool, new FunctionMatchingMockApi() { + @Override + public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) + throws ai.reveng.invoker.ApiException { + throw new ai.reveng.invoker.ApiException(503, "Service Unavailable"); + } + }); + env.addPlugin(BinarySimilarityPlugin.class); + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + var factoryCalls = new AtomicInteger(); + runSwing(() -> AbstractFunctionMatchingDialog.showWhenLoaded(tool, analysedProgram, basicInfo -> { + factoryCalls.incrementAndGet(); + return new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo, testFunction); + }), false); + + var error = awaitDialog(AbstractErrDialog.class); + assertTrue(error.getMessage(), error.getMessage().contains("Failed to fetch the details of analysis 12345")); + assertTrue(error.getMessage(), error.getMessage().contains("HTTP 503")); + close(error); + waitForSwing(); + + assertEquals("no dialog should be built without the details", 0, factoryCalls.get()); + assertNull(getDialogComponent(FunctionLevelFunctionMatchingDialog.class)); + } + + /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is + /// ignored in favour of Ghidra's 2s default, which a slow CI runner can exceed while a task is still running + private static T awaitDialog(Class type) { + long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); + T dialog; + while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { + sleep(DEFAULT_WAIT_DELAY); + } + assertNotNull("timed out waiting for " + type.getSimpleName(), dialog); + return dialog; + } + + private static AnalysisBasicInfoOutputBody basicInfo(GhidraRevengService service, + GhidraRevengService.AnalysedProgram program) { + try { + return service.getBasicDetailsForAnalysis(program.analysisID()); + } catch (ai.reveng.invoker.ApiException e) { + throw new RuntimeException(e); + } + } + /** * Mock API implementation for function matching dialog tests. * Provides necessary responses for the dialog to function without a real server. @@ -918,7 +1011,8 @@ public List getFunctionInfo(TypedApiInterface.AnalysisID analysisI } @Override - public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) { + public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) + throws ai.reveng.invoker.ApiException { var basic = new AnalysisBasicInfoOutputBody(); basic.setModelId(1L); basic.setModelName("test-model"); From cbafc0426dc45196dc36cfa0db410d99643f7340 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:53:28 +0000 Subject: [PATCH 53/76] test(ENG-4483): pin how a transferred signature reaches the portal The fix itself landed with ENG-4457, which left transferred names to the reactive push and dropped the comment claiming a signature-only transfer had nothing to push. Add the missing coverage: a signature-only transfer pushes the signature once and no rename, and a name-and-signature transfer pushes each once. --- .../ai/reveng/LocalEditSyncScopeTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java index fd5a80e4..22a48856 100644 --- a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java +++ b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java @@ -17,8 +17,11 @@ import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; import ghidra.program.model.address.AddressSet; +import ghidra.program.model.data.FunctionDefinitionDataType; import ghidra.program.model.data.IntegerDataType; import ghidra.program.model.data.LongDataType; +import ghidra.program.model.data.ParameterDefinitionImpl; +import ghidra.program.model.data.PointerDataType; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.LocalVariableImpl; import ghidra.program.model.listing.ParameterImpl; @@ -177,6 +180,60 @@ public void anAppliedMatchPushesItsNameWithoutTheMatchedBinary() throws Exceptio assertEquals("matched_name", api.renameRequests.get(0).getFunctions().get(0).getNewName()); } + /// The matching dialog applies a transfer with no service, so the sync service is what pushes it. A + /// signature-only transfer changes the prototype and nothing else: the signature goes up once, and no + /// rename does. + @Test + public void aSignatureTransferPushesTheSignatureOnceAndNoRename() throws Exception { + var originalName = first.getName(); + edit("transfer the signature", () -> assertTrue(new ApplyMatchCmd(null, analysedProgram, + matchWithSignature(), false, ApplyMatchCmd.Transfer.SIGNATURE).applyTo(program))); + assertEquals(originalName, first.getName()); + assertEquals("buf", first.getParameter(1).getName()); + + waitForCondition(() -> !api.pushedSignatures.isEmpty(), "the transferred signature should be pushed"); + // Past the debounce, so a second push or a rename would have gone up by now + Thread.sleep(1_000); + assertEquals(List.of(new FunctionID(1)), api.pushedSignatures); + assertTrue("renames pushed: " + api.renameRequests, api.renameRequests.isEmpty()); + } + + /// Transferring both pushes each once: one rename, one signature. + @Test + public void aNameAndSignatureTransferPushesEachOnce() throws Exception { + edit("transfer name and signature", () -> assertTrue(new ApplyMatchCmd(null, analysedProgram, + matchWithSignature(), false, ApplyMatchCmd.Transfer.NAME_AND_SIGNATURE).applyTo(program))); + + waitForCondition(() -> !api.pushedSignatures.isEmpty() && !api.renameRequests.isEmpty(), + "the transferred name and signature should be pushed"); + Thread.sleep(1_000); + assertEquals(List.of(new FunctionID(1)), api.pushedSignatures); + assertEquals("renames pushed: " + api.renameRequests, 1, api.renameRequests.size()); + var pushed = api.renameRequests.get(0).getFunctions(); + assertEquals(1, pushed.size()); + assertEquals(Long.valueOf(1), pushed.get(0).getFunctionId()); + assertEquals("matched_name", pushed.get(0).getNewName()); + } + + private GhidraFunctionMatchWithSignature matchWithSignature() { + var signature = new FunctionDefinitionDataType("matched_name"); + signature.setReturnType(IntegerDataType.dataType); + signature.setArguments( + new ParameterDefinitionImpl("len", IntegerDataType.dataType, null), + new ParameterDefinitionImpl("buf", PointerDataType.dataType, null)); + return new GhidraFunctionMatchWithSignature(first, new FunctionMatch( + new FunctionID(1), + new FunctionID(200), + "matched_name", + "matched_name", + "libfoo.so", + new BinaryHash("abc123"), + false, + BigDecimal.valueOf(0.9), + BigDecimal.valueOf(0.9), + null), signature); + } + /// A namespace the analyst made is part of the function's name on the portal. @Test public void aRenameInsideAnAnalystNamespaceKeepsTheNamespace() throws Exception { From 460a42888a265756565b582ee7a56d58a8abdd28 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:12:55 +0000 Subject: [PATCH 54/76] feat(ENG-4587): add cross-platform installation script (#259) --- README.md | 19 ++++++++ install.ps1 | 134 ++++++++++++++++++++++++++++++++++++++++++++++++++++ install.sh | 118 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 271 insertions(+) create mode 100644 install.ps1 create mode 100755 install.sh diff --git a/README.md b/README.md index 03bbe6d2..2c0f44d1 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,25 @@ and use it for Binary Code Similarity to help you Reverse Engineer stripped bina ## Installation +### Install script + +Close Ghidra, then run: + +```sh +# Linux / macOS +curl -fsSL https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.sh | bash +``` + +```powershell +# Windows (PowerShell) +irm https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.ps1 | iex +``` + +The script finds your Ghidra installs (asking which one if several), downloads the matching release, installs it and enables the plugins in the CodeBrowser. +Set `GHIDRA_INSTALL_DIR` to target a specific install, or `REVENG_PLUGIN_VERSION` (e.g. `v1.1.2`) to pin a release. + +### Manual installation + The builds for latest stable version of the RevEng.AI Ghidra plugin for common Ghidra versions can be downloaded from the [Releases](https://github.com/revengai/plugin-ghidra/releases/latest) page. ### Supported Ghidra versions diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 00000000..9d16fc06 --- /dev/null +++ b/install.ps1 @@ -0,0 +1,134 @@ +# Installs the RevEng.AI Ghidra plugin and enables it in the CodeBrowser tool. +# +# irm https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.ps1 | iex +# +# $env:GHIDRA_INSTALL_DIR target this Ghidra install instead of detecting one +# $env:REVENG_PLUGIN_VERSION release tag to install (default: latest) + +& { +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem + +$Repo = 'RevEngAI/plugin-ghidra' +$ExtName = 'plugin-ghidra' +$PluginPackage = 'RevEng.AI' +$SettingsRoot = Join-Path $env:APPDATA 'ghidra' + +function Get-Prop($Ghidra, $Name) { + $line = Get-Content (Join-Path $Ghidra 'Ghidra\application.properties') | + Where-Object { $_ -like "$Name=*" } | Select-Object -First 1 + $line.Substring($Name.Length + 1).Trim() +} + +function Test-Ghidra($Dir) { + $Dir -and (Test-Path -LiteralPath (Join-Path $Dir 'Ghidra\application.properties')) +} + +function Find-Installs { + $candidates = @() + $lastrun = Join-Path $SettingsRoot 'lastrun' + if (Test-Path $lastrun) { $candidates += (Get-Content $lastrun -Raw).Trim() } + $roots = @('C:\', $env:ProgramFiles, ${env:ProgramFiles(x86)}, 'C:\tools', $HOME, + "$HOME\Downloads", "$HOME\Desktop", "$HOME\scoop\apps\ghidra", + "$env:ProgramData\chocolatey\lib\ghidra\tools") + foreach ($root in $roots | Where-Object { $_ -and (Test-Path $_) }) { + foreach ($d in Get-ChildItem $root -Directory -ErrorAction SilentlyContinue) { + if ($d.Name -like 'ghidra*' -or $root -like '*ghidra*') { + $candidates += $d.FullName + $candidates += Get-ChildItem $d.FullName -Directory -Filter 'ghidra*' -ErrorAction SilentlyContinue | + ForEach-Object { $_.FullName } + } + } + } + $candidates | Where-Object { Test-Ghidra $_ } | + ForEach-Object { (Get-Item -LiteralPath $_).FullName.TrimEnd('\') } | Sort-Object -Unique +} + +if ($env:GHIDRA_INSTALL_DIR) { + if (-not (Test-Ghidra $env:GHIDRA_INSTALL_DIR)) { throw "No Ghidra install at $env:GHIDRA_INSTALL_DIR" } + $ghidra = $env:GHIDRA_INSTALL_DIR +} else { + $installs = @(Find-Installs) + if ($installs.Count -eq 0) { throw 'No Ghidra install found; set $env:GHIDRA_INSTALL_DIR to its path' } + if ($installs.Count -eq 1) { + $ghidra = $installs[0] + } else { + Write-Host 'Ghidra installs found:' + for ($i = 0; $i -lt $installs.Count; $i++) { + Write-Host (" {0}) {1} {2}" -f ($i + 1), (Get-Prop $installs[$i] 'application.version'), $installs[$i]) + } + $choice = Read-Host "Install into [1-$($installs.Count)]" + if ($choice -notmatch '^\d+$' -or [int]$choice -lt 1 -or [int]$choice -gt $installs.Count) { throw 'Invalid choice' } + $ghidra = $installs[[int]$choice - 1] + } +} + +$version = Get-Prop $ghidra 'application.version' +$settings = Join-Path $SettingsRoot "ghidra_${version}_$(Get-Prop $ghidra 'application.release.name')" +Write-Host "Ghidra $version at $ghidra" + +$running = Get-CimInstance Win32_Process -Filter "Name LIKE 'java%'" -ErrorAction SilentlyContinue | + Where-Object { $_.CommandLine -match 'ghidra\.GhidraRun' } +if ($running) { throw 'Ghidra is running; close it and rerun' } + +$tmp = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid()) +New-Item -ItemType Directory $tmp | Out-Null +try { + $asset = "ghidra_${version}_$ExtName.zip" + if ($env:REVENG_PLUGIN_VERSION) { + $url = "https://github.com/$Repo/releases/download/$env:REVENG_PLUGIN_VERSION/$asset" + } else { + $url = "https://github.com/$Repo/releases/latest/download/$asset" + } + $zip = Join-Path $tmp $asset + $unpacked = Join-Path $tmp 'x' + Write-Host "Downloading $url" + try { + Invoke-WebRequest $url -OutFile $zip -UseBasicParsing + } catch { + throw "No release build for Ghidra $version; see https://github.com/$Repo#building-your-own-plugin-for-custom-ghidra-forks-and-versions" + } + + [IO.Compression.ZipFile]::ExtractToDirectory($zip, $unpacked) + if (-not (Test-Path (Join-Path (Join-Path $unpacked $ExtName) 'extension.properties'))) { throw 'Unexpected archive layout' } + $extensions = Join-Path $settings 'Extensions' + New-Item -ItemType Directory -Force $extensions | Out-Null + $target = Join-Path $extensions $ExtName + if (Test-Path $target) { Remove-Item -Recurse -Force $target } + Move-Item (Join-Path $unpacked $ExtName) $extensions + Write-Host "Installed to $target" + + $tool = Join-Path (Join-Path $settings 'tools') '_code_browser.tcd' + if (-not (Test-Path $tool)) { + Write-Host 'CodeBrowser not configured yet; Ghidra will offer to enable the plugins when it opens.' + return + } + + $jar = [IO.Compression.ZipFile]::OpenRead((Join-Path (Join-Path $target 'lib') "$ExtName.jar")) + try { + $plugins = $jar.Entries | ForEach-Object { $_.FullName } | + Where-Object { $_ -match '^ai/reveng/toolkit/ghidra/plugins/[^/$]*Plugin\.class$' } | + ForEach-Object { ($_ -replace '\.class$', '') -replace '/', '.' } + } finally { $jar.Dispose() } + if (-not $plugins) { throw "No plugins found in $ExtName.jar" } + + Copy-Item $tool "$tool.bak" -Force + [xml]$xml = Get-Content $tool -Raw + $toolNode = $xml.TOOL_CONFIG.SelectSingleNode('TOOL') + foreach ($old in @($toolNode.SelectNodes("PACKAGE[@NAME='$PluginPackage']"))) { [void]$toolNode.RemoveChild($old) } + $package = $xml.CreateElement('PACKAGE') + $package.SetAttribute('NAME', $PluginPackage) + foreach ($plugin in $plugins) { + $include = $xml.CreateElement('INCLUDE') + $include.SetAttribute('CLASS', $plugin) + [void]$package.AppendChild($include) + } + [void]$toolNode.AppendChild($package) + $xml.Save($tool) + Write-Host "Enabled in CodeBrowser (backup: $tool.bak)" +} finally { + Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue +} +} diff --git a/install.sh b/install.sh new file mode 100755 index 00000000..85d6e496 --- /dev/null +++ b/install.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# Installs the RevEng.AI Ghidra plugin and enables it in the CodeBrowser tool. +# +# curl -fsSL https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.sh | bash +# +# GHIDRA_INSTALL_DIR target this Ghidra install instead of detecting one +# REVENG_PLUGIN_VERSION release tag to install (default: latest) +set -euo pipefail + +REPO="RevEngAI/plugin-ghidra" +EXT_NAME="plugin-ghidra" +PLUGIN_PACKAGE="RevEng.AI" + +die() { echo "error: $*" >&2; exit 1; } + +for cmd in curl unzip; do + command -v "$cmd" >/dev/null || die "'$cmd' is required" +done + +case "$(uname -s)" in + Darwin) SETTINGS_ROOT="$HOME/Library/ghidra" ;; + *) SETTINGS_ROOT="${XDG_CONFIG_HOME:-$HOME/.config}/ghidra" ;; +esac + +prop() { sed -n "s/^$1=//p" "$2/Ghidra/application.properties" | tr -d '\r'; } + +find_installs() { + local d + { + [ -f "$SETTINGS_ROOT/lastrun" ] && cat "$SETTINGS_ROOT/lastrun" && echo + for d in /opt /usr/local /usr/share /usr/lib /Applications "$HOME" "$HOME/Downloads" \ + "$HOME/Desktop" "$HOME/tools" "$HOME/Applications" \ + /opt/homebrew/Caskroom/ghidra/* /usr/local/Caskroom/ghidra/*; do + ls -d "$d"/[Gg]hidra* "$d"/[Gg]hidra*/[Gg]hidra* 2>/dev/null || true + done + ls -d /opt/homebrew/Cellar/ghidra/*/libexec /usr/local/Cellar/ghidra/*/libexec 2>/dev/null || true + } | while IFS= read -r d; do + [ -n "$d" ] && [ -f "$d/Ghidra/application.properties" ] && (cd -P "$d" && pwd) + done | awk '!seen[$0]++' +} + +if [ -n "${GHIDRA_INSTALL_DIR:-}" ]; then + [ -f "$GHIDRA_INSTALL_DIR/Ghidra/application.properties" ] || die "no Ghidra install at $GHIDRA_INSTALL_DIR" + GHIDRA="$GHIDRA_INSTALL_DIR" +else + INSTALLS=() + while IFS= read -r d; do INSTALLS+=("$d"); done < <(find_installs) + [ ${#INSTALLS[@]} -gt 0 ] || die "no Ghidra install found; set GHIDRA_INSTALL_DIR to its path" + if [ ${#INSTALLS[@]} -eq 1 ]; then + GHIDRA="${INSTALLS[0]}" + else + echo "Ghidra installs found:" + for i in "${!INSTALLS[@]}"; do + echo " $((i + 1))) $(prop application.version "${INSTALLS[$i]}") ${INSTALLS[$i]}" + done + # Read from the terminal: stdin is the script itself under `curl | bash`. + read -rp "Install into [1-${#INSTALLS[@]}]: " choice /dev/null && pgrep -f 'ghidra\.GhidraRun' >/dev/null; then + die "Ghidra is running; close it and rerun" +fi + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +ASSET="ghidra_${VERSION}_${EXT_NAME}.zip" +if [ -n "${REVENG_PLUGIN_VERSION:-}" ]; then + URL="https://github.com/$REPO/releases/download/$REVENG_PLUGIN_VERSION/$ASSET" +else + URL="https://github.com/$REPO/releases/latest/download/$ASSET" +fi +echo "Downloading $URL" +curl -fsSL -o "$TMP/$ASSET" "$URL" \ + || die "no release build for Ghidra $VERSION; see https://github.com/$REPO#building-your-own-plugin-for-custom-ghidra-forks-and-versions" + +unzip -q "$TMP/$ASSET" -d "$TMP/x" +[ -f "$TMP/x/$EXT_NAME/extension.properties" ] || die "unexpected archive layout" +mkdir -p "$SETTINGS/Extensions" +rm -rf "${SETTINGS:?}/Extensions/$EXT_NAME" +mv "$TMP/x/$EXT_NAME" "$SETTINGS/Extensions/" +echo "Installed to $SETTINGS/Extensions/$EXT_NAME" + +TOOL="$SETTINGS/tools/_code_browser.tcd" +if [ ! -f "$TOOL" ]; then + echo "CodeBrowser not configured yet; Ghidra will offer to enable the plugins when it opens." + exit 0 +fi + +PLUGINS="$(unzip -Z1 "$SETTINGS/Extensions/$EXT_NAME/lib/$EXT_NAME.jar" \ + | sed -n 's#^\(ai/reveng/toolkit/ghidra/plugins/[^/$]*Plugin\)\.class$#\1#p' | tr /'\n' '. ')" +[ -n "$PLUGINS" ] || die "no plugins found in $EXT_NAME.jar" + +cp "$TOOL" "$TOOL.bak" +awk -v pkg="$PLUGIN_PACKAGE" -v plugins="$PLUGINS" ' + index($0, "/) skip = 1 + next + } + skip { if ($0 ~ /<\/PACKAGE>/) skip = 0; next } + /<\/TOOL>/ && !done { + print " " + n = split(plugins, p, " ") + for (i = 1; i <= n; i++) print " " + print " " + done = 1 + } + { print } +' "$TOOL.bak" > "$TMP/tool.tcd" +mv "$TMP/tool.tcd" "$TOOL" +echo "Enabled in CodeBrowser (backup: $TOOL.bak)" From 044073a701d782597545085c0ce7a9b448ba111b Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:50:18 +0000 Subject: [PATCH 55/76] fix(ENG-4588): stop staging CI flakes in dialog and sync tests TestAnalysisLogComponent waited for its error dialog with waitForDialogComponent(null, OptionDialog.class, 30_000), but Ghidra ignores that timeout and waits only 2s. On a slow runner the chain from the Queued event to the dialog (task, Swing, task, Swing) takes longer, and the test failed with "Timed-out waiting for window". The awaitDialog helper that polls against a 30s deadline moves from FunctionLevelFunctionMatchingDialogTest into the shared base class, and both classes use it. The other waitForDialogComponent calls show their dialog straight from Swing, so the 2s wait is enough for them. RejectedLocalEditsTest woke once the mock had recorded both renames, but the mock records them inside the send, and the unpushed mark is cleared only after the send returns. Asserting the mark right away could race the sync thread, so the test now waits for it to clear. --- .../FunctionLevelFunctionMatchingDialogTest.java | 13 ------------- .../java/ai/reveng/RejectedLocalEditsTest.java | 3 ++- .../RevEngMockableHeadedIntegrationTest.java | 15 +++++++++++++++ .../java/ai/reveng/TestAnalysisLogComponent.java | 8 +++----- 4 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index a8a10496..ae75baf4 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -16,7 +16,6 @@ import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; import ai.reveng.toolkit.ghidra.plugins.BinarySimilarityPlugin; import docking.AbstractErrDialog; -import docking.DialogComponentProvider; import docking.DockingWindowManager; import ghidra.program.model.data.Undefined; import ghidra.program.model.symbol.SourceType; @@ -956,18 +955,6 @@ public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.Analys assertNull(getDialogComponent(FunctionLevelFunctionMatchingDialog.class)); } - /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is - /// ignored in favour of Ghidra's 2s default, which a slow CI runner can exceed while a task is still running - private static T awaitDialog(Class type) { - long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); - T dialog; - while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { - sleep(DEFAULT_WAIT_DELAY); - } - assertNotNull("timed out waiting for " + type.getSimpleName(), dialog); - return dialog; - } - private static AnalysisBasicInfoOutputBody basicInfo(GhidraRevengService service, GhidraRevengService.AnalysedProgram program) { try { diff --git a/src/test/java/ai/reveng/RejectedLocalEditsTest.java b/src/test/java/ai/reveng/RejectedLocalEditsTest.java index abe7f02f..760643f4 100644 --- a/src/test/java/ai/reveng/RejectedLocalEditsTest.java +++ b/src/test/java/ai/reveng/RejectedLocalEditsTest.java @@ -169,7 +169,8 @@ public void aRefusedKeyIsReportedOnceAndResumesWhenAPushSucceeds() throws Except rename(second, "second_name"); waitForCondition(() -> api.renamed.size() == 2, "the earlier rename should follow the one that got through"); assertEquals(Map.of(1L, "first_name_again", 2L, "second_name"), api.renamed); - assertFalse(marked(first)); + // The mock records the rename inside the send, and the mark is cleared only once the send returns. + waitForCondition(() -> !marked(first), "the earlier rename should no longer be marked"); waitForCondition(() -> !statusInfos.isEmpty(), "the edits that followed should be reported"); assertTrue(statusInfos.get(0), statusInfos.get(0).contains("pushed 1 local edit")); } diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index 40e0397f..682b66c8 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -3,6 +3,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.plugins.LoggingPlugin; +import docking.DialogComponentProvider; import generic.jar.ResourceFile; import ghidra.GhidraTestApplicationLayout; import utility.application.ApplicationLayout; @@ -18,9 +19,12 @@ import java.io.File; import java.io.IOException; +import java.time.Duration; import java.util.HashMap; import java.util.Map; +import static org.junit.Assert.assertNotNull; + /// Base class abstract class RevEngMockableHeadedIntegrationTest extends AbstractGhidraHeadedIntegrationTest { protected TestEnv env; @@ -65,6 +69,17 @@ protected ProgramBuilder newX64Program(String name) throws Exception { return new ProgramBuilder(name, ProgramBuilder._X64, this); } + /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is + /// ignored in favour of Ghidra's 2s default, which a slow CI runner can exceed while a task is still running + protected static T awaitDialog(Class type) { + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + T dialog; + while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { + sleep(DEFAULT_WAIT_DELAY); + } + assertNotNull("timed out waiting for " + type.getSimpleName(), dialog); + return dialog; + } /// This method adds a provided mocked service to the tool diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index 7b0dc592..8db87e18 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -224,7 +224,7 @@ public AnalysisStatus status(AnalysisID analysisID) { var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); assertFalse(trackedPrograms.containsKey(program)); // The wait ended in Error, which is reported - pressButtonByText(waitForDialogComponent(null, OptionDialog.class, 30_000), "Keep attached"); + pressButtonByText(awaitDialog(OptionDialog.class), "Keep attached"); } private static final String FAILED_ANALYSIS_LOGS = "Unpacking binary\nDisassembling\nFATAL: worker ran out of memory\n"; @@ -249,9 +249,7 @@ public String getAnalysisLogs(AnalysisID analysisID) { /// fires the Error event (Swing), which starts the log fetch (a task), which shows the dialog (Swing). How many /// rounds that takes varies between machines, so poll for the dialog; the limit only bounds a broken run. private OptionDialog awaitErrorDialog() { - var dialog = waitForDialogComponent(null, OptionDialog.class, 30_000); - assertNotNull("the failed analysis should be reported", dialog); - return dialog; + return awaitDialog(OptionDialog.class); } private String logText(AnalysisLogComponent logComponent) { @@ -326,7 +324,7 @@ public void testReopenedFailedAnalysisIsReportedOnce() throws Exception { service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); env.showTool(program); - var dialog = waitForDialogComponent(null, OptionDialog.class, 30_000); + var dialog = awaitDialog(OptionDialog.class); assertTrue(dialog.getMessage(), dialog.getMessage().contains("FATAL: worker ran out of memory")); pressButtonByText(dialog, "Detach"); waitForSwing(); From 7cec5c90caa745b767145d1480a635a951e3ac70 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:52:56 +0000 Subject: [PATCH 56/76] fix(ENG-4590): stop the analysis wait on Detach and close, ignore stale events Detaching while an analysis was still running left its monitoring task polling, and the program stayed in the log component's tracked map. A new analysis for the same program was then never monitored, and when the old analysis finished its Complete event loaded the old analysis' function IDs into a program whose options pointed at another analysis. Closing the program also left the wait polling, and holding the program, for up to three hours. Each wait now runs on its own cancellable monitor that still shows its progress on the shared TaskMonitorComponent. Detach and programClosed stop the program's wait, and close also drops its stored logs and terminal status line. A status event for a different analysis of an already tracked program replaces the old wait instead of being ignored, and a finished wait only removes its own map entry. The shared component's cancelled state is cleared once no wait uses it, so a Cancel press does not cancel the next wait. The plugin ignores status events, and skips results loads, for a ProgramWithID that is no longer the program's known analysis, so a Complete or Error from a wait that had not yet noticed the detach does nothing. --- .../ui/misc/AnalysisLogComponent.java | 105 ++++++++-- .../plugins/AnalysisManagementPlugin.java | 16 ++ .../ai/reveng/DetachDuringAnalysisTest.java | 195 ++++++++++++++++++ .../ai/reveng/TestAnalysisLogComponent.java | 27 ++- 4 files changed, 323 insertions(+), 20 deletions(-) create mode 100644 src/test/java/ai/reveng/DetachDuringAnalysisTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index aa005bdd..39e8dea9 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -15,6 +15,7 @@ import ghidra.util.task.TaskBuilder; import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitorComponent; +import ghidra.util.task.WrappingTaskMonitor; import javax.swing.*; @@ -27,7 +28,9 @@ public class AnalysisLogComponent extends ComponentProviderAdapter implements An private final JScrollPane scroll; private TaskMonitorComponent taskMonitorComponent; private final JPanel mainPanel; - private final Map trackedPrograms = new ConcurrentHashMap<>(); + /// The task waiting for each program's analysis. At most one per program: a new analysis replaces the + /// wait for an earlier one, which the program is no longer attached to. + private final Map trackedPrograms = new ConcurrentHashMap<>(); private final Map storedLogs = new ConcurrentHashMap<>(); /// How the program's analysis ended, shown below its logs; absent while it runs or when unknown private final Map terminalStatusLines = new ConcurrentHashMap<>(); @@ -76,7 +79,7 @@ public TaskMonitor getTaskMonitor() { public void programActivated(Program program) { // Switch the active log to the given program this.activeProgram = program; - if (trackedPrograms.containsKey(program)) { + if (program != null && trackedPrograms.containsKey(program)) { // If we are tracking this program, show the task monitor taskMonitorComponent.setVisible(true); } else { @@ -117,18 +120,53 @@ public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { if (terminalStatusLines.remove(event.getProgram()) != null) { refreshIfActive(event.getProgram()); } - if (!trackedPrograms.containsKey(event.getProgram())){ - // We aren't tracking this program yet, so we start a new task for it - var task = new AnalysisMonitoringTask(event.getProgramWithBinaryID(), this); - var builder = TaskBuilder.withTask(task); - trackedPrograms.put(event.getProgram(), task); - builder.launchInBackground(getTaskMonitor()); + var tracked = trackedPrograms.get(event.getProgram()); + if (tracked != null && tracked.program.equals(event.getProgramWithBinaryID())) { + // Already waiting for this analysis + return; } + if (tracked != null) { + // Waiting for an analysis the program has since been detached from + tracked.stop(); + } + var task = new AnalysisMonitoringTask(event.getProgramWithBinaryID(), this); + trackedPrograms.put(event.getProgram(), task); + TaskBuilder.withTask(task).launchInBackground(task.waitMonitor); } } } + /// Stop waiting for the program's analysis, e.g. because the program was detached from it. The wait ends + /// without firing any further status events for it. + public void stopMonitoring(Program program) { + var task = trackedPrograms.remove(program); + if (task != null) { + task.stop(); + } + updateMonitorVisibility(); + } + + /// Forget everything about a program that was closed, and stop waiting for its analysis + public void programClosed(Program program) { + stopMonitoring(program); + storedLogs.remove(program); + terminalStatusLines.remove(program); + if (activeProgram == program) { + activeProgram = null; + } + } + + private void updateMonitorVisibility() { + var active = activeProgram; + var show = active != null && trackedPrograms.containsKey(active); + if (!show && trackedPrograms.isEmpty()) { + // Nothing uses the shared monitor any more, so a Cancel pressed on it must not cancel the next wait + taskMonitorComponent.clearCanceled(); + } + taskMonitorComponent.setVisible(show); + } + @Override public void consumeLogs(String logs, GhidraRevengService.ProgramWithID programWithID) { storedLogs.put(programWithID.program(), logs); @@ -181,10 +219,43 @@ public static String unfinishedWaitMessage(StatusPoller.Result r }; } + /// Shows its progress on the shared monitor component, and is cancelled either by the Cancel button there + /// (which cancels every wait shown on it) or on its own, without cancelling the shared component. + private static class StoppableMonitor extends WrappingTaskMonitor { + private volatile boolean stopped; + + StoppableMonitor(TaskMonitor display) { + super(display); + } + + @Override + public boolean isCancelled() { + return stopped || super.isCancelled(); + } + + @Override + public void checkCancelled() throws CancelledException { + if (isCancelled()) { + throw new CancelledException(); + } + } + + @Override + public void cancel() { + stopped = true; + } + + @Override + public void clearCanceled() { + stopped = false; + } + } + class AnalysisMonitoringTask extends Task { private final GhidraRevengService.ProgramWithID program; private final AnalysisLogConsumer logConsumer; + private final StoppableMonitor waitMonitor = new StoppableMonitor(getTaskMonitor()); public AnalysisMonitoringTask(GhidraRevengService.ProgramWithID programWithID, AnalysisLogConsumer logConsumer) { super(programWithID.toString(), true, false, false); @@ -192,12 +263,22 @@ public AnalysisMonitoringTask(GhidraRevengService.ProgramWithID programWithID, A this.logConsumer = logConsumer; } + void stop() { + waitMonitor.cancel(); + } + @Override public void run(TaskMonitor monitor) throws CancelledException { // Wait for the analysis var service = tool.getService(GhidraRevengService.class); + // Logs fetched just before the wait was stopped belong to an analysis the program has left + AnalysisLogConsumer logs = (text, programWithID) -> { + if (!waitMonitor.isCancelled()) { + logConsumer.consumeLogs(text, programWithID); + } + }; try { - var result = service.waitForAnalysis(monitor, program, this.logConsumer, tool); + var result = service.waitForAnalysis(monitor, program, logs, tool); var message = unfinishedWaitMessage(result, program); if (message != null) { tool.getService(ReaiLoggingService.class).warn(message); @@ -206,9 +287,9 @@ public void run(TaskMonitor monitor) throws CancelledException { } finally { /// waitForFinishedAnalysis has already sent the completion event to all plugins /// so this task just needs to clean up the tracked programs map - // Remove ourselves from the tracked programs when done - trackedPrograms.remove(program.program()); - taskMonitorComponent.setVisible(false); + // Remove ourselves from the tracked programs when done, and only our own entry: a newer analysis of the same program may have replaced it + trackedPrograms.remove(program.program(), this); + updateMonitorVisibility(); } } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 71db83b4..ab4277c5 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -305,6 +305,7 @@ private void detach(GhidraRevengService.ProgramWithID knownProgram) { // Stop the background work tied to this analysis first, so none of it runs against the // association while it is being removed, or later against a different analysis. localEditSyncService.detach(program); + analysisLogComponent.stopMonitoring(program); if (autoUnstripSyncService.stopPolling(knownProgram.analysisID())) { var message = "RevEng.AI: stopped waiting for auto-unstrip; the program was detached from " + displayText + "."; @@ -411,6 +412,10 @@ protected void programClosed(Program program) { } // Reopening a program with a failed analysis reports the failure again reportedErrors.removeIf(reported -> reported.program() == program); + if (analysisLogComponent != null) { + // Otherwise the wait keeps polling, and holding the program, until the analysis ends + analysisLogComponent.programClosed(program); + } } @Override @@ -429,6 +434,13 @@ public void processEvent(PluginEvent event) { super.processEvent(event); // Forward the event to the analysis log component if (event instanceof RevEngAIAnalysisStatusChangedEvent analysisEvent) { + if (!isStillAttached(analysisEvent.getProgramWithBinaryID())) { + // From a wait that was still running when the program was detached or closed. Acting on it would + // load the old analysis into a program that is now attached to another one, or to none. + Msg.info(this, "Ignoring status event for an analysis the program is no longer attached to: " + + analysisEvent.getProgramWithBinaryID()); + return; + } analysisLogComponent.processEvent(analysisEvent); if (analysisEvent.getStatus() == AnalysisStatus.Complete) { @@ -451,6 +463,10 @@ private void loadAnalysisResults(GhidraRevengService.ProgramWithID program) { @Override public void run(TaskMonitor monitor) { try { + if (!isStillAttached(program)) { + // Detached or closed since the load was requested + return; + } var analysedProgram = revengService.registerFinishedAnalysisForProgram(program, monitor); localEditSyncService.attach(program.program()); tool.firePluginEvent(new RevEngAIAnalysisResultsLoaded("AnalysisManagementPlugin", analysedProgram)); diff --git a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java new file mode 100644 index 00000000..6ae4128d --- /dev/null +++ b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java @@ -0,0 +1,195 @@ +package ai.reveng; + +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.misc.AnalysisLogComponent; +import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisResultsLoaded; +import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.plugins.AnalysisManagementPlugin; +import docking.DialogComponentProvider; +import docking.widgets.OptionDialog; +import ghidra.app.services.ProgramManager; +import ghidra.framework.plugintool.PluginTool; +import ghidra.program.model.listing.Program; +import ghidra.util.task.Task; +import ghidra.util.task.TaskMonitorComponent; +import org.junit.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; + +/// Detaching or closing a program while its analysis is still being waited on (ENG-4590) +public class DetachDuringAnalysisTest extends RevEngMockableHeadedIntegrationTest { + + private static final TypedApiInterface.AnalysisID OLD = new TypedApiInterface.AnalysisID(1); + private static final TypedApiInterface.AnalysisID NEW = new TypedApiInterface.AnalysisID(2); + + /// Analyses stay Processing until marked finished; function info requests are recorded + private static class RunningAnalysesAPI extends UnimplementedAPI { + final Set finished = ConcurrentHashMap.newKeySet(); + final Map statusCalls = new ConcurrentHashMap<>(); + final AtomicInteger functionInfoCalls = new AtomicInteger(); + + int statusCalls(AnalysisID id) { + return statusCalls.computeIfAbsent(id, k -> new AtomicInteger()).get(); + } + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.computeIfAbsent(analysisID, k -> new AtomicInteger()).incrementAndGet(); + return finished.contains(analysisID) ? AnalysisStatus.Complete : AnalysisStatus.Processing; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + return "logs of analysis " + analysisID.id(); + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + functionInfoCalls.incrementAndGet(); + return List.of(); + } + } + + private record Fixture(PluginTool tool, GhidraRevengService service, RunningAnalysesAPI api, Program program, + AnalysisLogComponent logComponent) { + + @SuppressWarnings("unchecked") + Map trackedPrograms() { + return (Map) getInstanceField("trackedPrograms", logComponent); + } + + /// The analysis the program's wait is for, or empty when nothing waits for it + Optional monitoredAnalysis() { + return Optional.ofNullable(trackedPrograms().get(program)) + .map(task -> (GhidraRevengService.ProgramWithID) getInstanceField("program", task)); + } + + /// As StartAnalysisTask does: attach the program, then report the analysis as queued + GhidraRevengService.ProgramWithID startAnalysis(TypedApiInterface.AnalysisID id) { + var programWithID = service.registerAnalysisForProgram(program, id); + runSwing(() -> tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued))); + return programWithID; + } + + void stopAllWaits() { + ((TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent)).cancel(); + waitForTasks(); + } + } + + private Fixture fixture() throws Exception { + var tool = env.getTool(); + var api = new RunningAnalysesAPI(); + var service = addMockedService(tool, api); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + var logComponent = (AnalysisLogComponent) tool.getComponentProvider(AnalysisLogComponent.NAME); + return new Fixture(tool, service, api, program, logComponent); + } + + /// Detach through the menu action and its confirmation, as the analyst does + private void detach(Fixture fixture) { + performAction(getAction(fixture.tool(), "Detach"), false); + pressButtonByText(awaitDialog(OptionDialog.class), "Detach"); + waitForSwing(); + assertTrue(fixture.service().getKnownProgram(fixture.program()).isEmpty()); + } + + /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is + /// ignored in favour of Ghidra's 2s default + private static T awaitDialog(Class type) { + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + T dialog; + while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { + sleep(DEFAULT_WAIT_DELAY); + } + assertNotNull("timed out waiting for " + type.getSimpleName(), dialog); + return dialog; + } + + private static boolean hasFunctionIds(Program program) { + return program.getUsrPropertyManager().getLongPropertyMap("RevEngAI_FunctionID_Map") != null; + } + + /// Detach stops the wait for the old analysis, and its Complete arriving late loads nothing into the + /// program, which is now attached to another analysis + @Test + public void testLateCompleteAfterDetachIsIgnored() throws Exception { + var fixture = fixture(); + var old = fixture.startAnalysis(OLD); + waitForCondition(() -> fixture.api().statusCalls(OLD) > 0, "the old analysis should be waited on"); + var resultsLoaded = new AtomicBoolean(); + fixture.tool().addEventListener(RevEngAIAnalysisResultsLoaded.class, e -> resultsLoaded.set(true)); + + detach(fixture); + waitForCondition(() -> fixture.monitoredAnalysis().isEmpty(), "detaching should stop the wait"); + // Attached to another analysis, e.g. through Attach to existing + var current = fixture.service().registerAnalysisForProgram(fixture.program(), NEW); + + // The old analysis now finishes, and its Complete arrives from a wait that had not noticed the detach yet + fixture.api().finished.add(OLD); + runSwing(() -> fixture.tool().firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent(null, old, AnalysisStatus.Complete))); + waitForTasks(); + waitForSwing(); + + assertEquals("the old analysis' results should not be fetched", 0, fixture.api().functionInfoCalls.get()); + assertFalse("no function ids should be written", hasFunctionIds(fixture.program())); + assertFalse(resultsLoaded.get()); + assertEquals(Optional.of(current), fixture.service().getKnownProgram(fixture.program())); + } + + /// After Detach, a new analysis of the same program is waited on + @Test + public void testNewAnalysisAfterDetachIsMonitored() throws Exception { + var fixture = fixture(); + fixture.startAnalysis(OLD); + waitForCondition(() -> fixture.monitoredAnalysis().isPresent(), "the old analysis should be waited on"); + + detach(fixture); + var oldCalls = fixture.api().statusCalls(OLD); + var next = fixture.startAnalysis(NEW); + + assertEquals(Optional.of(next), fixture.monitoredAnalysis()); + waitForCondition(() -> fixture.api().statusCalls(NEW) > 0, "the new analysis should be polled"); + // Polling continues for the new analysis only + waitForCondition(() -> fixture.api().statusCalls(NEW) > 1, "the new analysis should keep being polled"); + assertTrue(fixture.api().statusCalls(OLD) <= oldCalls + 1); + + fixture.stopAllWaits(); + assertTrue(fixture.monitoredAnalysis().isEmpty()); + } + + /// Closing the program stops the wait, and forgets the program's logs + @Test + public void testClosingProgramStopsMonitoring() throws Exception { + var fixture = fixture(); + fixture.startAnalysis(OLD); + waitForCondition(() -> fixture.logComponent().getStoredLogs(fixture.program()) != null, + "the analysis logs should arrive"); + + runSwing(() -> fixture.tool().getService(ProgramManager.class).closeProgram(fixture.program(), true)); + waitForTasks(); + + assertTrue(fixture.trackedPrograms().isEmpty()); + assertNull(fixture.logComponent().getStoredLogs(fixture.program())); + var calls = fixture.api().statusCalls(OLD); + sleep(1_500); + assertEquals("the closed program's analysis should no longer be polled", calls, fixture.api().statusCalls(OLD)); + } +} diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index 7b0dc592..6c489014 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -39,6 +39,13 @@ private GhidraRevengService.ProgramWithID getPlaceHolderID() throws Exception{ ); } + /// Attach the program to its analysis, as StartAnalysisTask does before reporting it queued. Status events + /// for an analysis the program is not attached to are ignored. + private static GhidraRevengService.ProgramWithID attach(GhidraRevengService service, + GhidraRevengService.ProgramWithID programWithID) { + return service.registerAnalysisForProgram(programWithID.program(), programWithID.analysisID()); + } + /// If a user starts Ghidra for a program with an associated analysis that is still processing on the server, /// then the analysis log component should show that the analysis is still processing, and automatically /// fetch the logs and fire @@ -47,16 +54,15 @@ private GhidraRevengService.ProgramWithID getPlaceHolderID() throws Exception{ public void testResumeWaitingForProcessingAnalysis() throws Exception{ var defaultTool = env.showTool(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { @Override public AnalysisStatus status(AnalysisID analysisID) { return AnalysisStatus.Processing; } }); -// defaultTool.getService(GhidraRevengService.class); env.addPlugin(AnalysisManagementPlugin.class); - var programWithID = getPlaceHolderID(); + var programWithID = attach(service, getPlaceHolderID()); defaultTool.firePluginEvent( new RevEngAIAnalysisStatusChangedEvent( "Test", @@ -79,7 +85,7 @@ public void testFullAnalysisFlow() throws Exception { var defaultTool = env.showTool(); var programWithID = getPlaceHolderID(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { private final Map statusMap = new HashMap<>(); { @@ -105,6 +111,7 @@ public List getFunctionInfo(AnalysisID analysisID) { } } ); + attach(service, programWithID); env.addPlugin(AnalysisManagementPlugin.class); // Start a new analysis that is queued defaultTool.firePluginEvent( @@ -135,7 +142,7 @@ public void testTransientServerErrorsDoNotStopMonitoring() throws Exception { var statusCalls = new AtomicInteger(); var logCalls = new AtomicInteger(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { @Override public AnalysisStatus status(AnalysisID analysisID) throws ApiException { return switch (statusCalls.incrementAndGet()) { @@ -158,6 +165,7 @@ public List getFunctionInfo(AnalysisID analysisID) { return List.of(); } }); + attach(service, programWithID); env.addPlugin(AnalysisManagementPlugin.class); defaultTool.firePluginEvent( new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) @@ -176,12 +184,13 @@ public void testCancelledMonitoringUntracksProgram() throws Exception { var defaultTool = env.showTool(); var programWithID = getPlaceHolderID(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { @Override public AnalysisStatus status(AnalysisID analysisID) { return AnalysisStatus.Queued; } }); + attach(service, programWithID); env.addPlugin(AnalysisManagementPlugin.class); defaultTool.firePluginEvent( new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) @@ -415,13 +424,14 @@ public void testUnknownStatusIsNotMonitored() throws Exception { var programWithID = getPlaceHolderID(); var statusCalls = new AtomicInteger(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { @Override public AnalysisStatus status(AnalysisID analysisID) { statusCalls.incrementAndGet(); return AnalysisStatus.Unknown; } }); + attach(service, programWithID); env.addPlugin(AnalysisManagementPlugin.class); defaultTool.firePluginEvent( new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Unknown) @@ -442,12 +452,13 @@ public void testWaitEndingOnUnknownStatusStops() throws Exception { var programWithID = getPlaceHolderID(); var statusCalls = new AtomicInteger(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { @Override public AnalysisStatus status(AnalysisID analysisID) { return statusCalls.incrementAndGet() == 1 ? AnalysisStatus.Processing : AnalysisStatus.Unknown; } }); + attach(service, programWithID); env.addPlugin(AnalysisManagementPlugin.class); defaultTool.firePluginEvent( new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) From 2f1cc6e9a4a4eefc448a49d1b9a20fe290e21842 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:55:55 +0000 Subject: [PATCH 57/76] fix(ENG-4589): never push a null data type id The 500-type closure cap was applied to the union of every function in a push batch. Since pushes go out in batches (ENG-4482), a large binary pushed types past the cap without a server id, and the signature and struct-member writes then sent null data_type_ids. Both endpoints replace the stored value in full, so this silently erased the portal's types, and the edits were cleared as if they had gone up. The cap now bounds each function's closure on its own, and the batch passes the union of those closures to AnalysisDataTypesService.ensureTypes, which de-duplicates without capping and already chunks its writes to the endpoints' 100-type limit. Capping per function keeps the bound on a single walk while making a function's ids independent of whatever else shares its batch. A reference that still has no id is never sent as null: a type definition that would name one is withheld, and a function whose signature or reachable types cannot be written in full is not sent. It stays marked as unpushed and is reported like any other edit the portal did not take (UnresolvedDataTypesException, classified REJECTED). Test mocks that answered every create with a generic "pushed" type now echo the requested types, since a signature naming unresolvable types is no longer sent. --- .../api/AnalysisDataTypesService.java | 20 +- .../services/api/GhidraDataTypeEncoder.java | 96 ++++++++- .../services/api/GhidraRevengService.java | 96 +++++++-- .../api/UnresolvedDataTypesException.java | 33 +++ src/test/java/ai/reveng/CreatedDataTypes.java | 38 ++++ .../ai/reveng/GhidraDataTypeEncoderTest.java | 15 ++ .../ai/reveng/LocalEditSyncScopeTest.java | 5 +- .../ai/reveng/LocalEditsDuringSyncTest.java | 5 +- .../ai/reveng/PullSignaturesOnSyncTest.java | 5 +- .../java/ai/reveng/PushFunctionTypesTest.java | 191 +++++++++++++++++- 10 files changed, 458 insertions(+), 46 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java create mode 100644 src/test/java/ai/reveng/CreatedDataTypes.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java index a9e265cb..8d7b368a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java @@ -162,7 +162,25 @@ public Optional get(AnalysisID analysisID, long dataTypeId) { /// Where a type was filed under a different namespace than its category path implies — see /// {@link #storageKey} — that key is present too, pointing at the same id. public Map ensure(AnalysisID analysisID, Collection roots) throws ApiException { - List closure = GhidraDataTypeEncoder.closure(roots); + return ensureTypes(analysisID, GhidraDataTypeEncoder.closure(roots)); + } + + /// As {@link #ensure}, for types the caller has already closed over their dependencies — the + /// union of several functions' {@link GhidraDataTypeEncoder#reachableTypes}, say. They are + /// de-duplicated by key but neither walked again nor capped: each function's closure is bounded + /// on its own, and the writes are chunked to the endpoints' limits however many there are. + /// + /// A type whose definition names a type with no id here — one that lies past the edge of a + /// capped closure — gets an id but no definition write; see + /// {@link GhidraDataTypeEncoder#updateEntry}. + public Map ensureTypes(AnalysisID analysisID, Collection types) throws ApiException { + Map distinct = new LinkedHashMap<>(); + for (DataType type : types) { + if (type != null) { + distinct.putIfAbsent(GhidraDataTypeEncoder.keyOf(type), type); + } + } + List closure = List.copyOf(distinct.values()); if (closure.isEmpty()) { return Map.of(); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java index 974bb46f..852ea945 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java @@ -53,8 +53,13 @@ /// overloads without one keep the derived value. public final class GhidraDataTypeEncoder { - /// Upper bound on transitive dependency resolution, so a pathological type graph cannot make a - /// reactive push walk forever. Also keeps a single push well inside the endpoints' batch limits. + /// Upper bound on one {@link #closure} walk, so a pathological type graph cannot make a reactive + /// push walk forever. + /// + /// It bounds one function's closure, not a whole push: a push of many functions closes each one + /// separately and hands the union to {@link AnalysisDataTypesService#ensureTypes}, which chunks its + /// writes to the endpoints' limits. Capping the union instead made whether a function's types got + /// ids depend on which other functions happened to share its batch. private static final int MAX_TYPES = 500; /// Ghidra's placeholders for "no calling convention recorded", which the API would rather not @@ -64,8 +69,11 @@ public final class GhidraDataTypeEncoder { private GhidraDataTypeEncoder() {} - /// Resolves a referenced type to the analysis' id for it. Absent ids encode as an omitted - /// reference, which the API reads as "unresolved" rather than as an error. + /// Resolves a referenced type to the analysis' id for it. + /// + /// An absent id is never written as a null reference: the write endpoints replace a stored + /// definition in full, so a null `data_type_id` would erase the type the portal had there. A body + /// that would need one is withheld instead — see {@link #updateEntry} and {@link #unresolvedTypes}. @FunctionalInterface public interface Ids { @Nullable @@ -119,6 +127,34 @@ public static List closure(Collection roots) { return List.copyOf(seen.values()); } + /// The names of the types a push of `function` cannot write in full with `ids`, given its + /// `reachable` types ({@link #reachableTypes}). Empty when the signature and every definition + /// it depends on can be sent. + /// + /// A type counts when it has no id itself, or when it refers to a type that has none: the latter + /// is how a closure cut short by {@link #MAX_TYPES} shows up, and {@link #updateEntry} withholds + /// such a definition rather than write a null reference into it. Either way the function's + /// edit has not fully reached the portal. + public static Set unresolvedTypes(Function function, Collection reachable, Ids ids) { + Set unresolved = new LinkedHashSet<>(); + List named = new ArrayList<>(); + named.add(function.getReturnType()); + for (Parameter parameter : function.getParameters()) { + named.add(parameter.getDataType()); + } + for (DataType type : named) { + if (type == null || ids.idOf(keyOf(type)) == null) { + unresolved.add(nameOf(type)); + } + } + for (DataType type : reachable) { + if (ids.idOf(keyOf(type)) == null || !referencesResolve(type, ids)) { + unresolved.add(nameOf(type)); + } + } + return unresolved; + } + /// The server's identity for a Ghidra type. public static TypeKey keyOf(DataType type) { return new TypeKey(namespaceOf(type), nameOf(type), kindOf(type)); @@ -221,6 +257,9 @@ public static ai.reveng.model.CreateDataTypeEntry createEntry(DataType type, Str /// that never carry a definition, and a composite or reference type that is locally a bare /// placeholder. `PUT` replaces a stored type in full, so writing an empty definition would /// erase whatever the server extracted; a push that has nothing to say says nothing. + /// + /// Empty too when any type it refers to has no id in `ids`, for the same reason: a member or + /// parameter written with a null type would replace the portal's type with nothing. public static Optional updateEntry(DataType type, long id, Ids ids) { return updateEntry(type, namespaceOf(type), id, ids); } @@ -232,6 +271,9 @@ public static Optional updateEntry(DataType String namespace, long id, Ids ids) { + if (!referencesResolve(type, ids)) { + return Optional.empty(); + } Long size = sizeOf(type); String name = nameOf(type); return switch (kindOf(type)) { @@ -310,7 +352,11 @@ public static Optional updateEntry(DataType /// The function's local signature as a signature update, with every type named by id. /// /// `PUT .../signature` replaces the stored signature in full, so parameter storage is carried - /// over as well: leaving it out would clear the storage the server extracted. + /// over as well: leaving it out would clear the storage the server extracted. For the same + /// reason a parameter or return type without an id is refused rather than sent as null; callers + /// check {@link #unresolvedTypes} first. + /// + /// @throws IllegalStateException if `ids` has no id for a parameter or the return type public static ai.reveng.model.UpdateFunctionSignatureInputBody signatureOf(Function function, Ids ids) { var body = new ai.reveng.model.UpdateFunctionSignatureInputBody(); @@ -327,16 +373,24 @@ public static ai.reveng.model.UpdateFunctionSignatureInputBody signatureOf(Funct var input = new ai.reveng.model.SignatureParameterInput() .ordinal((long) ordinal) .name(parameter.getName()) - .dataTypeId(ids.idOf(keyOf(parameter.getDataType()))) + .dataTypeId(requireId(parameter.getDataType(), ids)) .bitLength(Math.max(0, parameter.getLength()) * 8L); storageOf(parameter).ifPresent(input::storage); parameters.add(input); } body.setParameters(parameters); - body.setReturnDataTypeId(ids.idOf(keyOf(function.getReturnType()))); + body.setReturnDataTypeId(requireId(function.getReturnType(), ids)); return body; } + private static long requireId(@Nullable DataType type, Ids ids) { + Long id = type == null ? null : ids.idOf(keyOf(type)); + if (id == null) { + throw new IllegalStateException("No data type id for \"%s\"".formatted(nameOf(type))); + } + return id; + } + /// Convenience overload for callers holding the id map {@link AnalysisDataTypesService#ensure} /// returned. public static ai.reveng.model.UpdateFunctionSignatureInputBody signatureOf(Function function, @@ -361,6 +415,26 @@ private static List roots(Function function) { /// The types one type refers to. A pointer's pointee and an array's element count as /// dependencies because they are types in their own right on the server, each with its own id. private static List dependenciesOf(DataType type) { + List dependencies = referencesOf(type); + dependencies.removeIf(java.util.Objects::isNull); + return dependencies; + } + + /// Whether every type `type`'s definition names has an id, so its update body can be written + /// without a null reference. + private static boolean referencesResolve(DataType type, Ids ids) { + for (DataType reference : referencesOf(type)) { + if (reference == null || ids.idOf(keyOf(reference)) == null) { + return false; + } + } + return true; + } + + /// The types `type`'s definition names, one entry per reference. A member or parameter with no + /// type is kept as a null, since its body would carry a null reference; a pointer with no + /// pointee is `void *` and names nothing. + private static List referencesOf(DataType type) { List dependencies = new ArrayList<>(); switch (kindOf(type)) { case STRUCT, UNION -> { @@ -369,7 +443,12 @@ private static List dependenciesOf(DataType type) { } } case TYPEDEF -> dependencies.add(((TypeDef) type).getDataType()); - case POINTER -> dependencies.add(((Pointer) type).getDataType()); + case POINTER -> { + DataType pointee = ((Pointer) type).getDataType(); + if (pointee != null) { + dependencies.add(pointee); + } + } case ARRAY -> dependencies.add(((Array) type).getDataType()); case FUNCTION_DEFINITION -> { FunctionDefinition definition = (FunctionDefinition) type; @@ -381,7 +460,6 @@ private static List dependenciesOf(DataType type) { default -> { } } - dependencies.removeIf(java.util.Objects::isNull); return dependencies; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index a3cf79ef..9a4904e8 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -431,46 +431,81 @@ public enum TypePushOutcome { } /// Push the local signature and variables of a function back to the portal. - public TypePushOutcome pushFunctionTypes(AnalysedProgram analysedProgram, Function function) throws ApiException { + /// + /// @throws UnresolvedDataTypesException if a type the function reaches could not be given an id, + /// so its signature was held back + public TypePushOutcome pushFunctionTypes(AnalysedProgram analysedProgram, Function function) + throws ApiException, UnresolvedDataTypesException { if (analysedProgram.getIDForFunction(function).isEmpty()) { return TypePushOutcome.NOT_MATCHED; } // The function is known to the analysis, so the type pass below ran for it; only the // signature write can still decline. - return pushFunctionTypes(analysedProgram, List.of(function)) > 0 + var push = pushFunctionTypes(analysedProgram, List.of(function)); + var withheld = push.withheld().get(function); + if (withheld != null) { + throw withheld; + } + return push.signaturesWritten() > 0 ? TypePushOutcome.SIGNATURE_WRITTEN : TypePushOutcome.TYPES_ONLY; } - /// Push the local signatures of several functions, and answer with how many the server took. + /// What a push of several functions' types achieved. + /// + /// @param signaturesWritten how many signatures the portal took + /// @param withheld the functions whose signature was not sent because a type they reach + /// has no id, each with the reason; their edits have not gone up + public record TypePush(int signaturesWritten, Map withheld) {} + + /// Push the local signatures of several functions, and answer with how many the server took and + /// which were held back. /// /// The two halves of the write path compose here, and only here. Data-type management is a /// batch affair — the union of everything the functions reach is resolved against the analysis' /// catalogue and created where it is missing, in one pass — while a signature is written one /// function at a time. Running the type pass once for the whole set is the point of keeping the /// two apart: the alternative re-resolves the same closure per function. - public int pushFunctionTypes(AnalysedProgram analysedProgram, Collection functions) throws ApiException { + /// + /// Each function's closure is capped on its own and only the union is handed to the type pass, + /// so how many functions share a batch does not decide which of them get ids. A function that + /// still reaches a type without one is not sent at all: its signature, or a struct it depends + /// on, would otherwise go up with a null type and erase what the portal holds. + public TypePush pushFunctionTypes(AnalysedProgram analysedProgram, Collection functions) + throws ApiException { Map known = new LinkedHashMap<>(); for (Function function : functions) { analysedProgram.getIDForFunction(function) .ifPresent(withId -> known.put(function, withId.functionID())); } if (known.isEmpty()) { - return 0; + return new TypePush(0, Map.of()); } - List roots = new ArrayList<>(); - known.keySet().forEach(function -> roots.addAll(GhidraDataTypeEncoder.reachableTypes(function))); - var ids = analysisDataTypes().ensure(analysedProgram.analysisID(), roots); + Map> reachable = new LinkedHashMap<>(); + List union = new ArrayList<>(); + for (Function function : known.keySet()) { + var types = GhidraDataTypeEncoder.reachableTypes(function); + reachable.put(function, types); + union.addAll(types); + } + var ids = GhidraDataTypeEncoder.Ids.of(analysisDataTypes().ensureTypes(analysedProgram.analysisID(), union)); int pushed = 0; + Map withheld = new LinkedHashMap<>(); for (var entry : known.entrySet()) { - var signature = GhidraDataTypeEncoder.signatureOf(entry.getKey(), ids); + var function = entry.getKey(); + var unresolved = GhidraDataTypeEncoder.unresolvedTypes(function, reachable.get(function), ids); + if (!unresolved.isEmpty()) { + withheld.put(function, new UnresolvedDataTypesException(unresolved)); + continue; + } + var signature = GhidraDataTypeEncoder.signatureOf(function, ids); if (signatures().put(analysedProgram.analysisID(), entry.getValue(), signature)) { pushed++; } } - return pushed; + return new TypePush(pushed, withheld); } /// Breakdown of a bidirectional analysis sync, shown to the user afterwards. @@ -670,7 +705,7 @@ public LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram) { var flush = new FlushTally(); Map renamed = markedFunctions(program, UnpushedEdits.Kind.NAME); sendIsolatingRejections(program, UnpushedEdits.Kind.NAME, renamed, flush, - functions -> pushFunctionRenames(analysedProgram, functions).size(), + functions -> new Sent(pushFunctionRenames(analysedProgram, functions).size(), Map.of()), function -> "rename of \"%s\" at %s".formatted(function.getName(), function.getEntryPoint())); Map retyped = markedFunctions(program, UnpushedEdits.Kind.TYPES); @@ -683,11 +718,11 @@ public LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram) { return unknown; }); // A signature the portal has no extraction for is declined, but its types went up, which is - // all this push can do. + // all this push can do. One held back for want of a type id has not gone up, and stays marked. sendIsolatingRejections(program, UnpushedEdits.Kind.TYPES, retyped, flush, functions -> { - pushFunctionTypes(analysedProgram, functions); - return functions.size(); + var push = pushFunctionTypes(analysedProgram, functions); + return new Sent(functions.size() - push.withheld().size(), Map.copyOf(push.withheld())); }, function -> "types of \"%s\" at %s".formatted(function.getName(), function.getEntryPoint())); return new LocalEditFlush(flush.pushed, flush.unsent, flush.unsentError, List.copyOf(flush.rejected)); @@ -703,9 +738,13 @@ private static final class FlushTally { @FunctionalInterface private interface EditSender { /// Send the edits of these functions and answer with how many went up. - int send(List functions) throws Exception; + Sent send(List functions) throws Exception; } + /// @param pushed how many edits went up + /// @param failed the functions whose edit was held back without failing the rest, with why + private record Sent(int pushed, Map failed) {} + /// The functions with a `kind` edit marked, each with the address it is marked at. A mark whose /// function is gone is cleared, since nothing is left to send. private static Map markedFunctions(Program program, UnpushedEdits.Kind kind) { @@ -734,8 +773,7 @@ private static void sendIsolatingRejections(Program program, UnpushedEdits.Kind } List functions = List.copyOf(marked.keySet()); try { - flush.pushed += sender.send(functions); - marked.values().forEach(entryPoint -> UnpushedEdits.clear(program, kind, entryPoint)); + settle(program, kind, marked, functions, sender.send(functions), flush, describe); return; } catch (Exception e) { if (PushFailure.of(e) != PushFailure.REJECTED || functions.size() == 1) { @@ -745,14 +783,28 @@ private static void sendIsolatingRejections(Program program, UnpushedEdits.Kind } for (Function function : functions) { try { - flush.pushed += sender.send(List.of(function)); - UnpushedEdits.clear(program, kind, marked.get(function)); + settle(program, kind, marked, List.of(function), sender.send(List.of(function)), flush, describe); } catch (Exception e) { record(flush, List.of(function), e, describe); } } } + /// Clear the marks of the `sent` edits that went up, and record the ones held back. + private static void settle(Program program, UnpushedEdits.Kind kind, Map marked, + List functions, Sent sent, FlushTally flush, + java.util.function.Function describe) { + flush.pushed += sent.pushed(); + for (Function function : functions) { + Exception failure = sent.failed().get(function); + if (failure == null) { + UnpushedEdits.clear(program, kind, marked.get(function)); + } else { + record(flush, List.of(function), failure, describe); + } + } + } + private static void record(FlushTally flush, List functions, Exception e, java.util.function.Function describe) { if (PushFailure.of(e) == PushFailure.TRANSIENT) { @@ -982,9 +1034,13 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, } try { // One type pass over the union of every candidate's types, then a signature write each. - int pushed = pushFunctionTypes(analysedProgram, candidates); + var push = pushFunctionTypes(analysedProgram, candidates); + int pushed = push.signaturesWritten(); log.info("Pushed local types for %d of %d functions the portal had none for" .formatted(pushed, candidates.size())); + push.withheld().forEach((function, reason) -> log.warn( + "Did not push the types of \"%s\" at %s: %s" + .formatted(function.getName(), function.getEntryPoint(), reason.getMessage()))); return pushed; } catch (ApiException e) { Msg.warn(this, "Failed to push local types during sync", e); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java new file mode 100644 index 00000000..e51d3b2d --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java @@ -0,0 +1,33 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import java.util.Set; + +/// A function's types could not all be given a portal id, so its signature was not written. +/// +/// Sending the signature anyway would name the missing types as null, and the portal replaces a +/// stored signature in full, so it would lose the types it had. The edit is held back instead and +/// stays unpushed. {@link PushFailure} classifies this as {@link PushFailure#REJECTED}: sending the +/// same edit again gets the same answer. +public final class UnresolvedDataTypesException extends Exception { + + private final Set typeNames; + + public UnresolvedDataTypesException(Set typeNames) { + super(describe(typeNames)); + this.typeNames = Set.copyOf(typeNames); + } + + public Set typeNames() { + return typeNames; + } + + private static String describe(Set typeNames) { + final int shown = 5; + String names = typeNames.stream().limit(shown).map("\"%s\""::formatted) + .collect(java.util.stream.Collectors.joining(", ")); + if (typeNames.size() > shown) { + names += " and %d more".formatted(typeNames.size() - shown); + } + return "no portal id for the data type(s) %s, so the signature was not sent".formatted(names); + } +} diff --git a/src/test/java/ai/reveng/CreatedDataTypes.java b/src/test/java/ai/reveng/CreatedDataTypes.java new file mode 100644 index 00000000..9913c339 --- /dev/null +++ b/src/test/java/ai/reveng/CreatedDataTypes.java @@ -0,0 +1,38 @@ +package ai.reveng; + +import ai.reveng.model.CreateAnalysisDataTypesInputBody; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; + +import java.util.List; +import java.util.function.LongSupplier; + +/// What a mock server answers a data-type create with: each type as it was sent, under a new id. +/// +/// The answer has to name the types it was asked for. A push resolves every type a signature names +/// through the created types' `(namespace, name, kind)`, and a signature with a type it cannot +/// resolve is not sent. +final class CreatedDataTypes { + + private CreatedDataTypes() {} + + static List echo(CreateAnalysisDataTypesInputBody request, LongSupplier nextId) { + return request.getDataTypes().stream() + .map(entry -> { + Object instance = entry.getActualInstance(); + return new ServerDataType(nextId.getAsLong(), string(instance, "getNamespace"), + string(instance, "getName"), + ServerDataType.Kind.fromJson(string(instance, "getKind")), + null, "USER", false, null, null, null); + }) + .toList(); + } + + private static String string(Object target, String method) { + try { + Object value = target.getClass().getMethod(method).invoke(target); + return value == null ? null : value.toString(); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java b/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java index d036c6bf..9c6b38eb 100644 --- a/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java +++ b/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java @@ -307,6 +307,21 @@ public void typesWithNothingToSayProduceNoUpdate() { new PointerDataType(new StructureDataType("Unknown", 4)), 1L, key -> null).isEmpty()); } + /// A struct whose members' types are only partly resolved is withheld whole: writing it would + /// send the rest as null types and erase them on the portal. + @Test + public void aCompositeWithAnUnresolvedMemberProducesNoUpdate() { + var resolved = new StructureDataType("Resolved", 4); + var unresolved = new StructureDataType("Unresolved", 4); + var struct = new StructureDataType("Mixed", 0); + struct.add(resolved, "a", null); + struct.add(unresolved, "b", null); + TypeKey resolvedKey = GhidraDataTypeEncoder.keyOf(resolved); + + assertTrue(GhidraDataTypeEncoder.updateEntry(struct, 1L, + key -> key.equals(resolvedKey) ? 2L : null).isEmpty()); + } + /// The namespace round-trips through the category path, which is how a type the plugin pulled /// from the server resolves back to the same entry instead of being created again. @Test diff --git a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java index 22a48856..a27bc91d 100644 --- a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java +++ b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java @@ -80,10 +80,7 @@ public List listAnalysisDataTypes(AnalysisID analysisID, long of @Override public List createAnalysisDataTypes(AnalysisID analysisID, CreateAnalysisDataTypesInputBody request) { - return request.getDataTypes().stream() - .map(type -> new ServerDataType(nextDataTypeId.getAndIncrement(), "", "pushed", - ServerDataType.Kind.BASE, null, "USER", false, null, null, null)) - .toList(); + return CreatedDataTypes.echo(request, nextDataTypeId::getAndIncrement); } @Override diff --git a/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java index 8bdf5f81..faf98c35 100644 --- a/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java +++ b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java @@ -113,10 +113,7 @@ public List listAnalysisDataTypes(AnalysisID analysisID, long of @Override public synchronized List createAnalysisDataTypes(AnalysisID analysisID, CreateAnalysisDataTypesInputBody request) { - return request.getDataTypes().stream() - .map(type -> new ServerDataType(nextDataTypeId++, "", "pushed", - ServerDataType.Kind.BASE, null, "USER", false, null, null, null)) - .toList(); + return CreatedDataTypes.echo(request, () -> nextDataTypeId++); } @Override diff --git a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java index 8d567aa1..21ec569c 100644 --- a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java +++ b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java @@ -132,10 +132,7 @@ public List listAnalysisDataTypes(AnalysisID analysisID, long of @Override public List createAnalysisDataTypes(AnalysisID analysisID, CreateAnalysisDataTypesInputBody request) { - return request.getDataTypes().stream() - .map(type -> new ServerDataType(nextDataTypeId++, "", "pushed", - ServerDataType.Kind.BASE, null, "USER", false, null, null, null)) - .toList(); + return CreatedDataTypes.echo(request, () -> nextDataTypeId++); } @Override diff --git a/src/test/java/ai/reveng/PushFunctionTypesTest.java b/src/test/java/ai/reveng/PushFunctionTypesTest.java index 9f1cf827..684fbe47 100644 --- a/src/test/java/ai/reveng/PushFunctionTypesTest.java +++ b/src/test/java/ai/reveng/PushFunctionTypesTest.java @@ -5,12 +5,16 @@ import ai.reveng.model.UpdateAnalysisDataTypesInputBody; import ai.reveng.model.UpdateFunctionSignatureInputBody; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.UnresolvedDataTypesException; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; import ghidra.app.cmd.function.CreateFunctionCmd; import ghidra.program.model.data.IntegerDataType; import ghidra.program.model.data.PointerDataType; @@ -21,12 +25,17 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /// Tests how {@link GhidraRevengService#pushFunctionTypes} composes the two halves of the write /// path: batch data-type management, then one signature write per function. @@ -37,9 +46,12 @@ public class PushFunctionTypesTest extends RevEngMockableHeadedIntegrationTest { /// Records every write and assigns ids to created types the way the server does. private static class RecordingApi extends UnimplementedAPI { - final List calls = new ArrayList<>(); - final List signatures = new ArrayList<>(); - final List signedFunctions = new ArrayList<>(); + final List calls = new CopyOnWriteArrayList<>(); + final List signatures = new CopyOnWriteArrayList<>(); + final List signedFunctions = new CopyOnWriteArrayList<>(); + final List updates = new CopyOnWriteArrayList<>(); + /// Types the server leaves out of its create response, so they never get an id. + volatile Set uncreatable = Set.of(); private long nextId = 100; @Override @@ -67,6 +79,9 @@ public List createAnalysisDataTypes(AnalysisID analysisID, List created = new ArrayList<>(); for (var entry : request.getDataTypes()) { Object instance = entry.getActualInstance(); + if (uncreatable.contains(string(instance, "getName"))) { + continue; + } created.add(new ServerDataType(nextId++, string(instance, "getNamespace"), string(instance, "getName"), ServerDataType.Kind.fromJson(string(instance, "getKind")), @@ -79,6 +94,7 @@ public List createAnalysisDataTypes(AnalysisID analysisID, public List updateAnalysisDataTypes(AnalysisID analysisID, UpdateAnalysisDataTypesInputBody request) { calls.add("update"); + updates.add(request); return List.of(); } @@ -144,7 +160,8 @@ private Fixture twoFunctionsSharingAStruct() throws Exception { public void multiFunctionPushResolvesTypesOnceThenWritesEachSignature() throws Exception { var fixture = twoFunctionsSharingAStruct(); - int pushed = fixture.service().pushFunctionTypes(fixture.analysedProgram(), fixture.functions()); + int pushed = fixture.service().pushFunctionTypes(fixture.analysedProgram(), fixture.functions()) + .signaturesWritten(); assertEquals("both signatures written", 2, pushed); assertEquals("one catalogue read for the whole push", 1, count(fixture.api(), "list")); @@ -230,6 +247,172 @@ public void singleFunctionPushReportsAFunctionTheAnalysisDoesNotKnow() throws Ex assertEquals(GhidraRevengService.TypePushOutcome.NOT_MATCHED, outcome); } + /// A function whose parameter points at a struct with `members` members of distinct struct types, + /// so its closure holds a little over `members` types. + private static Function functionReachingStructs(ghidra.program.database.ProgramBuilder builder, String name, + String address, int members) throws Exception { + var state = new StructureDataType(name + "_state", 0); + for (int i = 0; i < members; i++) { + state.add(new StructureDataType(name + "_member_" + i, 4), "m" + i, null); + } + return builder.createEmptyFunction(name, address, 0x100, new IntegerDataType(), + new ParameterImpl("state", new PointerDataType(state), builder.getProgram())); + } + + /// Two functions that each reach about 300 types, under the 500-type closure cap on their own + /// but over it together. Capping the union left some of the second function's types without an + /// id, and its struct then went up with null member types, erasing them on the portal. + @Test + public void aBatchOverTheClosureCapSendsNoNullTypeIds() throws Exception { + var api = new RecordingApi(); + var service = new GhidraRevengService(api); + var builder = newX64Program("push"); + builder.createMemory("code", "0x4000", 0x400); + Function first = functionReachingStructs(builder, "first", "0x4000", 300); + Function second = functionReachingStructs(builder, "second", "0x4200", 300); + var programWithID = service.registerAnalysisForProgram(builder.getProgram(), new AnalysisID(1)); + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + var push = service.pushFunctionTypes(analysedProgram, List.of(first, second)); + + assertEquals("nothing held back: " + push.withheld(), 0, push.withheld().size()); + assertEquals("both signatures written", 2, push.signaturesWritten()); + List referenced = new ArrayList<>(); + java.util.Map stateMembers = new java.util.HashMap<>(); + for (var request : api.updates) { + for (var entry : request.getDataTypes()) { + referenced.addAll(referencedIds(entry.getActualInstance())); + if (entry.getActualInstance() instanceof ai.reveng.model.UpdateStructDataType struct) { + stateMembers.put(struct.getName(), struct.getDefinition().getMembers().size()); + } + } + } + assertEquals("both structs were written in full", + java.util.Map.of("first_state", 300, "second_state", 300), stateMembers); + assertFalse("no type write names a null type", referenced.contains(null)); + for (var signature : api.signatures) { + assertNotNull(signature.getReturnDataTypeId()); + signature.getParameters().forEach(parameter -> assertNotNull(parameter.getDataTypeId())); + } + } + + /// Every `data_type_id` an update body refers to, nulls included. + private static List referencedIds(Object update) { + List ids = new ArrayList<>(); + if (update instanceof ai.reveng.model.UpdateStructDataType struct) { + struct.getDefinition().getMembers().forEach(member -> ids.add(member.getDataTypeId())); + } else if (update instanceof ai.reveng.model.UpdateUnionDataType union) { + union.getDefinition().getMembers().forEach(member -> ids.add(member.getDataTypeId())); + } else if (update instanceof ai.reveng.model.UpdatePointerDataType pointer) { + ids.add(pointer.getDefinition().getPointeeDataTypeId()); + } else if (update instanceof ai.reveng.model.UpdateTypedefDataType typedef) { + ids.add(typedef.getDefinition().getTargetDataTypeId()); + } else if (update instanceof ai.reveng.model.UpdateArrayDataType array) { + ids.add(array.getDefinition().getElementDataTypeId()); + } else if (update instanceof ai.reveng.model.UpdateFunctionDataType function) { + function.getDefinition().getParameters().forEach(parameter -> ids.add(parameter.getDataTypeId())); + ids.add(function.getDefinition().getReturnDataTypeId()); + } + return ids; + } + + /// The first function takes a pointer to a struct the server never gives an id; the second + /// only takes an int. + private Fixture oneFunctionWithAnUnresolvableType() throws Exception { + var api = new RecordingApi(); + api.uncreatable = Set.of("orphan_t"); + var service = new GhidraRevengService(api); + var builder = newX64Program("push"); + builder.createMemory("code", "0x4000", 0x400); + var program = builder.getProgram(); + var orphan = new StructureDataType("orphan_t", 0); + orphan.add(new IntegerDataType(), "count", null); + Function first = builder.createEmptyFunction("first", "0x4000", 0x100, new IntegerDataType(), + new ParameterImpl("state", new PointerDataType(orphan), program)); + Function second = builder.createEmptyFunction("second", "0x4200", 0x100, new IntegerDataType(), + new ParameterImpl("count", new IntegerDataType(), program)); + var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + api.calls.clear(); + return new Fixture(service, api, analysedProgram, List.of(first, second)); + } + + @Test + public void aFunctionReachingATypeWithNoIdIsNotSentAndStaysUnpushed() throws Exception { + var fixture = oneFunctionWithAnUnresolvableType(); + var program = fixture.analysedProgram().program(); + Function first = fixture.functions().get(0); + Function second = fixture.functions().get(1); + fixture.functions().forEach(function -> + UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint())); + + var flush = fixture.service().pushUnpushedEdits(fixture.analysedProgram()); + + assertEquals("only the second signature went up", List.of(new FunctionID(2)), fixture.api().signedFunctions); + assertTrue("the held-back edit is still marked", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, first.getEntryPoint())); + assertFalse("the other one went up", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, second.getEntryPoint())); + assertEquals(1, flush.pushed()); + assertEquals(1, flush.rejected().size()); + var rejected = flush.rejected().get(0); + assertTrue(rejected.edit(), rejected.edit().contains("\"first\"")); + assertTrue(rejected.error().getMessage(), rejected.error().getMessage().contains("orphan_t")); + for (var request : fixture.api().updates) { + for (var entry : request.getDataTypes()) { + assertFalse("no type write names a null type", + referencedIds(entry.getActualInstance()).contains(null)); + } + } + } + + @Test + public void singleFunctionPushThrowsWhenATypeHasNoId() throws Exception { + var fixture = oneFunctionWithAnUnresolvableType(); + try { + fixture.service().pushFunctionTypes(fixture.analysedProgram(), fixture.functions().get(0)); + fail("the push should have been held back"); + } catch (UnresolvedDataTypesException e) { + assertTrue(e.typeNames().toString(), e.typeNames().contains("orphan_t")); + } + assertTrue("no signature was sent", fixture.api().signedFunctions.isEmpty()); + } + + /// The reactive push holds the edit back, keeps it marked, and reports it like any other edit the + /// portal did not take. + @Test + public void aReactiveEditReachingATypeWithNoIdIsReportedAndKept() throws Exception { + var fixture = oneFunctionWithAnUnresolvableType(); + var program = fixture.analysedProgram().program(); + Function second = fixture.functions().get(1); + List warnings = new CopyOnWriteArrayList<>(); + var sync = new LocalEditSyncService(fixture.service(), new ReaiLoggingService() { + @Override public void info(String message) {} + @Override public void warn(String message) {} + @Override public void error(String message) {} + }, (message, warning) -> { + if (warning) { + warnings.add(message); + } + }, List.of(Duration.ofHours(1))); + sync.attach(program); + try { + var orphan = new StructureDataType("orphan_t", 0); + orphan.add(new IntegerDataType(), "count", null); + program.withTransaction("retype", () -> + second.setReturnType(new PointerDataType(orphan), SourceType.USER_DEFINED)); + program.flushEvents(); + + waitForCondition(() -> !warnings.isEmpty(), "the held-back edit should be reported"); + assertTrue(warnings.get(0), warnings.get(0).contains("did not take")); + assertTrue("the edit is kept for the next sync", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, second.getEntryPoint())); + assertFalse("its signature was never sent", fixture.api().signedFunctions.contains(new FunctionID(2))); + } finally { + sync.dispose(); + } + } + private static int count(RecordingApi api, String call) { return (int) api.calls.stream().filter(call::equals).count(); } From 760305c1de633933c85fc27f77d3bb4d5752d67a Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:01:17 +0000 Subject: [PATCH 58/76] fix(ENG-4588): give the matching-status wait its own deadline testUnrecognisedMatchingStatusStopsPolling waits for the dialog to see CANCELLED. The dialog first sleeps its 2s poll interval, and Ghidra's waitForCondition gives up after about the same time, so the test failed on slow runners. It now uses a shared awaitCondition helper with a 30s deadline. awaitDialog also takes an optional failure message. The analysis error dialog wait uses it again to say "the failed analysis should be reported". --- ...nctionLevelFunctionMatchingDialogTest.java | 3 ++- .../RevEngMockableHeadedIntegrationTest.java | 20 ++++++++++++++++++- .../ai/reveng/TestAnalysisLogComponent.java | 2 +- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index ae75baf4..97e69164 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -769,7 +769,8 @@ public GetMatchesStatusOutputBody getFunctionsMatchingStatus(List function JLabel statusLabel = (JLabel) getInstanceField("statusLabel", foundDialog); JButton matchButton = (JButton) getInstanceField("matchButton", foundDialog); - waitForCondition(() -> runSwing(() -> statusLabel.getText().equals("Stopped waiting for function matching") + // The dialog sleeps a 2s poll interval before it sees CANCELLED, as long as waitForCondition's own limit + awaitCondition(() -> runSwing(() -> statusLabel.getText().equals("Stopped waiting for function matching") && getInstanceField("matchingThread", foundDialog) == null && matchButton.getText().equals("Match Functions")), "An unrecognised status should end the matching run"); diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index 682b66c8..759cd678 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -22,8 +22,10 @@ import java.time.Duration; import java.util.HashMap; import java.util.Map; +import java.util.function.BooleanSupplier; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; /// Base class abstract class RevEngMockableHeadedIntegrationTest extends AbstractGhidraHeadedIntegrationTest { @@ -72,15 +74,31 @@ protected ProgramBuilder newX64Program(String name) throws Exception { /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is /// ignored in favour of Ghidra's 2s default, which a slow CI runner can exceed while a task is still running protected static T awaitDialog(Class type) { + return awaitDialog(type, "timed out waiting for " + type.getSimpleName()); + } + + /// As {@link #awaitDialog(Class)}, failing with the given message so a CI timeout says what was expected + protected static T awaitDialog(Class type, String message) { long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); T dialog; while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { sleep(DEFAULT_WAIT_DELAY); } - assertNotNull("timed out waiting for " + type.getSimpleName(), dialog); + assertNotNull(message, dialog); return dialog; } + /// Like waitForCondition, but against this test's own 30s deadline: Ghidra's default limit is about 2s, which + /// a wait that spans a real poll interval (function matching sleeps 2s between polls) can exceed on CI + protected static void awaitCondition(BooleanSupplier condition, String message) { + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + boolean met; + while (!(met = condition.getAsBoolean()) && System.nanoTime() < deadline) { + sleep(DEFAULT_WAIT_DELAY); + } + assertTrue(message, met); + } + /// This method adds a provided mocked service to the tool /// This allows each test to provide its own mocked API responses diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index 8db87e18..3837f287 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -249,7 +249,7 @@ public String getAnalysisLogs(AnalysisID analysisID) { /// fires the Error event (Swing), which starts the log fetch (a task), which shows the dialog (Swing). How many /// rounds that takes varies between machines, so poll for the dialog; the limit only bounds a broken run. private OptionDialog awaitErrorDialog() { - return awaitDialog(OptionDialog.class); + return awaitDialog(OptionDialog.class, "the failed analysis should be reported"); } private String logText(AnalysisLogComponent logComponent) { From b56298431068aeffc58ac23bca6c39b51388b834 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:01:58 +0000 Subject: [PATCH 59/76] fix(ENG-4590): drop a results load the program was detached from mid-load The plugin checked that the program was still attached only before the load started. Loading makes several requests before it writes the function IDs, so a Detach followed by Attach or Create new during those requests still wrote the old analysis' IDs into the program. The function info is now fetched before the load transaction opens, and the service checks the attachment again before writing. If the program was detached during the pull, the function IDs are removed and the transaction is committed, not rolled back, because the Detach's own change joined the same transaction. The plugin treats this as an abandoned load, not a failed one. Also from review: a stopped wait no longer passes its last log line to the shared monitor, the deprecated checkCanceled honours a stop, the shared monitor is updated on the Swing thread, logs for a closed program are dropped, and a Cancel press now stops each running wait so the shared monitor can be reset for the next one. --- .../ui/misc/AnalysisLogComponent.java | 45 ++++++++++++++++--- .../services/api/GhidraRevengService.java | 43 +++++++++++++++--- .../plugins/AnalysisManagementPlugin.java | 3 ++ .../ai/reveng/DetachDuringAnalysisTest.java | 40 ++++++++++++++++- 4 files changed, 117 insertions(+), 14 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index 39e8dea9..7263d38b 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -10,6 +10,7 @@ import ghidra.framework.plugintool.ComponentProviderAdapter; import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Program; +import ghidra.util.Swing; import ghidra.util.exception.CancelledException; import ghidra.util.task.Task; import ghidra.util.task.TaskBuilder; @@ -49,6 +50,10 @@ public AnalysisLogComponent(PluginTool tool) { taskMonitorComponent = new TaskMonitorComponent(false, true); taskMonitorComponent.setIndeterminate(true); taskMonitorComponent.setVisible(false); + // Each wait keeps the cancel to itself, so the shared component can be reset for the next wait without + // resuming one the user cancelled + taskMonitorComponent.addCancelledListener( + () -> trackedPrograms.values().forEach(AnalysisMonitoringTask::stop)); scroll = new JScrollPane(textArea); @@ -129,6 +134,10 @@ public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { // Waiting for an analysis the program has since been detached from tracked.stop(); } + if (taskMonitorComponent.isCancelled()) { + // Left over from a Cancel press; the waits it cancelled have already been stopped + taskMonitorComponent.clearCanceled(); + } var task = new AnalysisMonitoringTask(event.getProgramWithBinaryID(), this); trackedPrograms.put(event.getProgram(), task); TaskBuilder.withTask(task).launchInBackground(task.waitMonitor); @@ -158,17 +167,24 @@ public void programClosed(Program program) { } private void updateMonitorVisibility() { - var active = activeProgram; - var show = active != null && trackedPrograms.containsKey(active); - if (!show && trackedPrograms.isEmpty()) { - // Nothing uses the shared monitor any more, so a Cancel pressed on it must not cancel the next wait - taskMonitorComponent.clearCanceled(); - } - taskMonitorComponent.setVisible(show); + // Also called from the background thread of a wait that has ended + Swing.runIfSwingOrRunLater(() -> { + var active = activeProgram; + var show = active != null && trackedPrograms.containsKey(active); + if (!show && trackedPrograms.isEmpty()) { + // Nothing uses the shared monitor any more, so a Cancel pressed on it must not cancel the next wait + taskMonitorComponent.clearCanceled(); + } + taskMonitorComponent.setVisible(show); + }); } @Override public void consumeLogs(String logs, GhidraRevengService.ProgramWithID programWithID) { + if (programWithID.program().isClosed()) { + // Arrived after programClosed, and would keep the closed program in the map + return; + } storedLogs.put(programWithID.program(), logs); // If this is the currently active program, update the log display @@ -240,6 +256,21 @@ public void checkCancelled() throws CancelledException { } } + @Override + @SuppressWarnings("deprecation") + public void checkCanceled() throws CancelledException { + checkCancelled(); + } + + @Override + public void setMessage(String message) { + // A stopped wait may still report its analysis' last log line, which would replace the message of the + // wait that is now shown + if (!stopped) { + super.setMessage(message); + } + } + @Override public void cancel() { stopped = true; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index a3cf79ef..cf9604a5 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -189,13 +189,26 @@ public AnalysedProgram registerFinishedAnalysisForProgram(ProgramWithID programW // may have arrived. One transaction around the whole load is rolled back when any part of it fails, so the // program is left as it was, the load can be retried, and the undo history holds nothing to bring it back. var program = programWithID.program(); + // Fetched before the transaction opens, so a Detach during the request does not join it + var functionInfo = api.getFunctionInfo(programWithID.analysisID()); + requireStillAttached(programWithID); var transactionId = program.startTransaction("RevEng.AI: Load analysis results"); boolean loaded = false; FunctionAssociation association; try { - association = associateFunctionInfo(programWithID); + association = associateFunctionInfo(programWithID, functionInfo); pullFunctionInfoFromAnalysis(association.analysedProgram(), monitor); monitor.checkCancelled(); + if (!isStillAttached(programWithID)) { + // Detached during the pull. Its change to the options joined this transaction, so rolling back + // would undo the Detach too. Remove the function ids instead, so the program is not taken to + // be analysed by the analysis it has left. + if (!program.isClosed()) { + clearFunctionAssociation(program); + } + loaded = true; + throw new DetachedDuringLoadException(programWithID); + } loaded = true; } finally { // A program closed during the load takes no more transactions, and must not hide why the load failed @@ -207,10 +220,30 @@ public AnalysedProgram registerFinishedAnalysisForProgram(ProgramWithID programW return association.analysedProgram(); } - /// What {@link #associateFunctionInfo(ProgramWithID)} produced, with the summary to show once the + /// What {@link #associateFunctionInfo(ProgramWithID, List)} produced, with the summary to show once the /// rest of the load has succeeded too. private record FunctionAssociation(AnalysedProgram analysedProgram, String summary) {} + /// The program was detached from the analysis, or attached to another one, while its results were loading. + /// The program is left without that analysis' function ids. + public static class DetachedDuringLoadException extends RuntimeException { + public DetachedDuringLoadException(ProgramWithID programWithID) { + super("%s was detached from analysis %d while its results were loading" + .formatted(programWithID.program().getName(), programWithID.analysisID().id())); + } + } + + private boolean isStillAttached(ProgramWithID programWithID) { + return !programWithID.program().isClosed() + && getKnownProgram(programWithID.program()).filter(programWithID::equals).isPresent(); + } + + private void requireStillAttached(ProgramWithID programWithID) { + if (!isStillAttached(programWithID)) { + throw new DetachedDuringLoadException(programWithID); + } + } + private ProgramWithID addAnalysisIDtoProgramOptions(Program program, TypedApiInterface.AnalysisID analysisID){ var transactionId = program.startTransaction("Associate Binary ID with Program"); program.getOptions(ReaiPluginPackage.REAI_OPTIONS_CATEGORY) @@ -251,11 +284,9 @@ private Optional getAnalysisIDFor(Program program) /// /// Any association already on the program is replaced, so an earlier load that stopped part way does /// not block this one. - private FunctionAssociation associateFunctionInfo(ProgramWithID knownProgram) { + private FunctionAssociation associateFunctionInfo(ProgramWithID knownProgram, List functionInfo) { var analysisID = knownProgram.analysisID(); var program = knownProgram.program(); - List functionInfo = null; - functionInfo = api.getFunctionInfo(analysisID); var transactionID = program.startTransaction("Associate Function Info"); clearFunctionAssociation(program); @@ -1082,7 +1113,7 @@ static boolean isInvalidGhidraName(String name) { /// * the type signature of the function /// /// It assumes that the initial load already happened, i.e. the functions have an associated FunctionID already. - /// The initial association happens in {@link #associateFunctionInfo(ProgramWithID)} + /// The initial association happens in {@link #associateFunctionInfo(ProgramWithID, List)} /// public List pullFunctionInfoFromAnalysis(AnalysedProgram analysedProgram, TaskMonitor monitor) { var transactionId = startServerTransaction(analysedProgram.program(), "RevEng.AI: Pull Function Info from Analysis"); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index ab4277c5..32d5211d 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -473,6 +473,9 @@ public void run(TaskMonitor monitor) { // Auto-unstrip runs server-side after the analysis is marked complete, so poll for it // and sync the recovered names / data types once it finishes (PLU-300). autoUnstripSyncService.pollAndSync(analysedProgram, true); + } catch (GhidraRevengService.DetachedDuringLoadException e) { + // The user chose to leave this analysis, so there is nothing to report or retry + Msg.info(AnalysisManagementPlugin.this, e.getMessage()); } catch (CancelledException e) { reportFailedLoad(program, loadCancelledMessage(program), null); } catch (Exception e) { diff --git a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java index 6ae4128d..b69b34ea 100644 --- a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java +++ b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java @@ -24,6 +24,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -40,6 +41,8 @@ private static class RunningAnalysesAPI extends UnimplementedAPI { final Set finished = ConcurrentHashMap.newKeySet(); final Map statusCalls = new ConcurrentHashMap<>(); final AtomicInteger functionInfoCalls = new AtomicInteger(); + /// Holds function info requests until released, when set + volatile CountDownLatch functionInfoGate; int statusCalls(AnalysisID id) { return statusCalls.computeIfAbsent(id, k -> new AtomicInteger()).get(); @@ -59,6 +62,14 @@ public String getAnalysisLogs(AnalysisID analysisID) { @Override public List getFunctionInfo(AnalysisID analysisID) { functionInfoCalls.incrementAndGet(); + var gate = functionInfoGate; + if (gate != null) { + try { + gate.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } return List.of(); } } @@ -154,6 +165,33 @@ public void testLateCompleteAfterDetachIsIgnored() throws Exception { assertEquals(Optional.of(current), fixture.service().getKnownProgram(fixture.program())); } + /// Detach while the finished analysis' results are being fetched: the load writes nothing and reports no failure + @Test + public void testDetachDuringResultsLoadWritesNothing() throws Exception { + var fixture = fixture(); + var gate = new CountDownLatch(1); + fixture.api().functionInfoGate = gate; + fixture.startAnalysis(OLD); + var resultsLoaded = new AtomicBoolean(); + fixture.tool().addEventListener(RevEngAIAnalysisResultsLoaded.class, e -> resultsLoaded.set(true)); + + // The analysis finishes, and its wait starts loading the results + fixture.api().finished.add(OLD); + waitForCondition(() -> fixture.api().functionInfoCalls.get() > 0, "the results should start loading"); + + detach(fixture); + var current = fixture.service().registerAnalysisForProgram(fixture.program(), NEW); + gate.countDown(); + waitForTasks(); + waitForSwing(); + + assertFalse("no function ids should be written", hasFunctionIds(fixture.program())); + assertFalse(resultsLoaded.get()); + assertEquals(Optional.of(current), fixture.service().getKnownProgram(fixture.program())); + assertTrue("an abandoned load is not a failed one", + ((Set) getInstanceField("failedLoads", getPlugin(fixture.tool(), AnalysisManagementPlugin.class))).isEmpty()); + } + /// After Detach, a new analysis of the same program is waited on @Test public void testNewAnalysisAfterDetachIsMonitored() throws Exception { @@ -189,7 +227,7 @@ public void testClosingProgramStopsMonitoring() throws Exception { assertTrue(fixture.trackedPrograms().isEmpty()); assertNull(fixture.logComponent().getStoredLogs(fixture.program())); var calls = fixture.api().statusCalls(OLD); - sleep(1_500); + sleep(500); assertEquals("the closed program's analysis should no longer be polled", calls, fixture.api().statusCalls(OLD)); } } From 97e7ef177ffd43e07480e496adb4e1953e0b5c37 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:07:29 +0000 Subject: [PATCH 60/76] fix(ENG-4589): explain closure-limit holds and quieten their logging A function whose own closure is over the 500-type limit can never be pushed: the types at the edge of the walk refer to ones it never reached, so it is held back rather than written with null ids. The limit stays, because it bounds the walk a single reactive edit can trigger, but the reason now says so. UnresolvedDataTypesException records whether the closure limit was the cause, and its message names the limit instead of implying the portal gave no id. A held-back function is an expected outcome, so the reactive push logs it without a stack trace, and the sync backfill logs one summary line with a few examples instead of one warning per function. Adds a test for a single function over the limit: no null ids, no partial struct write, no signature, and the edit stays marked. The test mock's create answer now reuses CreatedDataTypes.echo. --- .../services/api/GhidraDataTypeEncoder.java | 27 +++++++- .../services/api/GhidraRevengService.java | 23 +++++-- .../api/UnresolvedDataTypesException.java | 19 +++++- .../services/sync/LocalEditSyncService.java | 8 ++- src/test/java/ai/reveng/CreatedDataTypes.java | 21 ++++--- .../java/ai/reveng/PushFunctionTypesTest.java | 62 +++++++++++++------ 6 files changed, 125 insertions(+), 35 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java index 852ea945..84b8159c 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java @@ -60,7 +60,12 @@ public final class GhidraDataTypeEncoder { /// separately and hands the union to {@link AnalysisDataTypesService#ensureTypes}, which chunks its /// writes to the endpoints' limits. Capping the union instead made whether a function's types got /// ids depend on which other functions happened to share its batch. - private static final int MAX_TYPES = 500; + /// + /// A function whose own closure is larger than this cannot be pushed: the types at the edge of + /// the walk refer to types it never reached, which have no id, so the function is held back + /// rather than written with null references. {@link #exceedsClosureLimit} tells that case apart + /// from a type the server gave no id. + public static final int MAX_TYPES = 500; /// Ghidra's placeholders for "no calling convention recorded", which the API would rather not /// have at all than have as a literal. @@ -155,6 +160,26 @@ public static Set unresolvedTypes(Function function, Collection reachable) { + if (reachable.size() < MAX_TYPES) { + return false; + } + Set reached = new java.util.HashSet<>(); + for (DataType type : reachable) { + reached.add(keyOf(type)); + } + for (DataType type : reachable) { + for (DataType dependency : dependenciesOf(type)) { + if (!reached.contains(keyOf(dependency))) { + return true; + } + } + } + return false; + } + /// The server's identity for a Ghidra type. public static TypeKey keyOf(DataType type) { return new TypeKey(namespaceOf(type), nameOf(type), kindOf(type)); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 9a4904e8..fb5991dc 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -497,7 +497,8 @@ public TypePush pushFunctionTypes(AnalysedProgram analysedProgram, Collection withheld) { + if (withheld.isEmpty()) { + return; + } + final int shown = 5; + String examples = withheld.entrySet().stream().limit(shown) + .map(entry -> "\"%s\" at %s (%s)".formatted(entry.getKey().getName(), + entry.getKey().getEntryPoint(), entry.getValue().getMessage())) + .collect(java.util.stream.Collectors.joining("; ")); + if (withheld.size() > shown) { + examples += "; and %d more".formatted(withheld.size() - shown); + } + log.warn("Did not push the types of %d function(s): %s".formatted(withheld.size(), examples)); + } + /// Breakdown of a bidirectional analysis sync, shown to the user afterwards. public record SyncSummary( int matchedFunctions, @@ -1038,9 +1055,7 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, int pushed = push.signaturesWritten(); log.info("Pushed local types for %d of %d functions the portal had none for" .formatted(pushed, candidates.size())); - push.withheld().forEach((function, reason) -> log.warn( - "Did not push the types of \"%s\" at %s: %s" - .formatted(function.getName(), function.getEntryPoint(), reason.getMessage()))); + logWithheld(log, push.withheld()); return pushed; } catch (ApiException e) { Msg.warn(this, "Failed to push local types during sync", e); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java index e51d3b2d..86f59f13 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java @@ -11,16 +11,31 @@ public final class UnresolvedDataTypesException extends Exception { private final Set typeNames; + private final boolean pastClosureLimit; - public UnresolvedDataTypesException(Set typeNames) { - super(describe(typeNames)); + /// @param typeNames the types the function reaches that could not be written in full + /// @param pastClosureLimit whether the function reaches more types than + /// {@link GhidraDataTypeEncoder#MAX_TYPES}, which is then the cause + /// rather than the portal + public UnresolvedDataTypesException(Set typeNames, boolean pastClosureLimit) { + super(pastClosureLimit ? describeLimit() : describe(typeNames)); this.typeNames = Set.copyOf(typeNames); + this.pastClosureLimit = pastClosureLimit; } public Set typeNames() { return typeNames; } + public boolean pastClosureLimit() { + return pastClosureLimit; + } + + private static String describeLimit() { + return ("it reaches more than %d data types, the most the plugin pushes for one function, so " + + "the signature was not sent").formatted(GhidraDataTypeEncoder.MAX_TYPES); + } + private static String describe(Set typeNames) { final int shown = 5; String names = typeNames.stream().limit(shown).map("\"%s\""::formatted) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java index f16f1786..7bbbb1a0 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java @@ -4,6 +4,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService.AnalysedProgram; import ai.reveng.toolkit.ghidra.core.services.api.PushFailure; +import ai.reveng.toolkit.ghidra.core.services.api.UnresolvedDataTypesException; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ghidra.framework.model.DomainObjectChangeRecord; import ghidra.framework.model.DomainObjectListener; @@ -398,7 +399,12 @@ private void pushTypes(Program program, Address entryPoint) { /// portal could not be reached, and otherwise a retry straight away, which sends the marked edits /// one at a time where needed and finds out which ones the portal will not take. private void onPushFailed(Program program, String detail, Exception e) { - Msg.warn(this, "%s: %s".formatted(detail, reasonOf(e)), e); + if (e instanceof UnresolvedDataTypesException) { + // An expected outcome, not a fault: the message says all there is to say. + Msg.warn(this, "%s: %s".formatted(detail, reasonOf(e))); + } else { + Msg.warn(this, "%s: %s".formatted(detail, reasonOf(e)), e); + } if (PushFailure.of(e) == PushFailure.TRANSIENT) { reportOutage(e); scheduleRetry(program, nextDelay(program)); diff --git a/src/test/java/ai/reveng/CreatedDataTypes.java b/src/test/java/ai/reveng/CreatedDataTypes.java index 9913c339..d1aff697 100644 --- a/src/test/java/ai/reveng/CreatedDataTypes.java +++ b/src/test/java/ai/reveng/CreatedDataTypes.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.function.LongSupplier; +import java.util.function.Predicate; /// What a mock server answers a data-type create with: each type as it was sent, under a new id. /// @@ -16,14 +17,20 @@ final class CreatedDataTypes { private CreatedDataTypes() {} static List echo(CreateAnalysisDataTypesInputBody request, LongSupplier nextId) { + return echo(request, nextId, name -> true); + } + + /// As {@link #echo(CreateAnalysisDataTypesInputBody, LongSupplier)}, but leaving out the types + /// whose name `created` rejects, the way a server that will not create a type answers. + static List echo(CreateAnalysisDataTypesInputBody request, LongSupplier nextId, + Predicate created) { return request.getDataTypes().stream() - .map(entry -> { - Object instance = entry.getActualInstance(); - return new ServerDataType(nextId.getAsLong(), string(instance, "getNamespace"), - string(instance, "getName"), - ServerDataType.Kind.fromJson(string(instance, "getKind")), - null, "USER", false, null, null, null); - }) + .map(entry -> (Object) entry.getActualInstance()) + .filter(instance -> created.test(string(instance, "getName"))) + .map(instance -> new ServerDataType(nextId.getAsLong(), string(instance, "getNamespace"), + string(instance, "getName"), + ServerDataType.Kind.fromJson(string(instance, "getKind")), + null, "USER", false, null, null, null)) .toList(); } diff --git a/src/test/java/ai/reveng/PushFunctionTypesTest.java b/src/test/java/ai/reveng/PushFunctionTypesTest.java index 684fbe47..bd3d120e 100644 --- a/src/test/java/ai/reveng/PushFunctionTypesTest.java +++ b/src/test/java/ai/reveng/PushFunctionTypesTest.java @@ -76,18 +76,7 @@ public List listAnalysisDataTypes(AnalysisID analysisID, long of public List createAnalysisDataTypes(AnalysisID analysisID, CreateAnalysisDataTypesInputBody request) { calls.add("create"); - List created = new ArrayList<>(); - for (var entry : request.getDataTypes()) { - Object instance = entry.getActualInstance(); - if (uncreatable.contains(string(instance, "getName"))) { - continue; - } - created.add(new ServerDataType(nextId++, string(instance, "getNamespace"), - string(instance, "getName"), - ServerDataType.Kind.fromJson(string(instance, "getKind")), - null, "USER", false, null, null, null)); - } - return created; + return CreatedDataTypes.echo(request, () -> nextId++, name -> !uncreatable.contains(name)); } @Override @@ -113,14 +102,6 @@ public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID signatures.add(signature); } - private static String string(Object target, String method) { - try { - Object value = target.getClass().getMethod(method).invoke(target); - return value == null ? null : value.toString(); - } catch (ReflectiveOperationException e) { - throw new RuntimeException(e); - } - } } private record Fixture(GhidraRevengService service, @@ -413,6 +394,47 @@ public void aReactiveEditReachingATypeWithNoIdIsReportedAndKept() throws Excepti } } + /// One function whose own closure is over the cap: its struct has more distinct member types + /// than the walk takes. The types at the edge of the walk refer to ones it never reached, so the + /// signature and those definitions would carry null ids; the function is held back instead, and + /// the reason names the limit rather than blaming the portal. + @Test + public void aFunctionOverTheClosureCapOnItsOwnSendsNoNullIdsAndStaysUnpushed() throws Exception { + var api = new RecordingApi(); + var service = new GhidraRevengService(api); + var builder = newX64Program("push"); + builder.createMemory("code", "0x4000", 0x400); + Function big = functionReachingStructs(builder, "first", "0x4000", 600); + var program = builder.getProgram(); + var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + try { + service.pushFunctionTypes(analysedProgram, big); + fail("the push should have been held back"); + } catch (UnresolvedDataTypesException e) { + assertTrue("the limit is the cause", e.pastClosureLimit()); + assertTrue(e.getMessage(), e.getMessage().contains("more than 500 data types")); + } + + UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, big.getEntryPoint()); + var flush = service.pushUnpushedEdits(analysedProgram); + + assertTrue("no signature was sent", api.signedFunctions.isEmpty()); + assertTrue("the edit is still marked", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, big.getEntryPoint())); + assertEquals(1, flush.rejected().size()); + for (var request : api.updates) { + for (var entry : request.getDataTypes()) { + assertFalse("no type write names a null type", + referencedIds(entry.getActualInstance()).contains(null)); + if (entry.getActualInstance() instanceof ai.reveng.model.UpdateStructDataType struct) { + assertFalse("the struct is not written in part", struct.getName().equals("first_state")); + } + } + } + } + private static int count(RecordingApi api, String call) { return (int) api.calls.stream().filter(call::equals).count(); } From f1890b1819f30208d0c0cfc14b8cd81db9baeb12 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:10:21 +0000 Subject: [PATCH 61/76] fix(ENG-4590): use the TaskMonitor names Ghidra 12.2 still has Ghidra 12.2 removed the deprecated checkCanceled and clearCanceled, so the wait monitor failed to compile there. Call and override only clearCancelled and checkCancelled, which every supported version has. --- .../ui/misc/AnalysisLogComponent.java | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index 7263d38b..5b302c0a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -136,7 +136,7 @@ public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { } if (taskMonitorComponent.isCancelled()) { // Left over from a Cancel press; the waits it cancelled have already been stopped - taskMonitorComponent.clearCanceled(); + taskMonitorComponent.clearCancelled(); } var task = new AnalysisMonitoringTask(event.getProgramWithBinaryID(), this); trackedPrograms.put(event.getProgram(), task); @@ -173,7 +173,7 @@ private void updateMonitorVisibility() { var show = active != null && trackedPrograms.containsKey(active); if (!show && trackedPrograms.isEmpty()) { // Nothing uses the shared monitor any more, so a Cancel pressed on it must not cancel the next wait - taskMonitorComponent.clearCanceled(); + taskMonitorComponent.clearCancelled(); } taskMonitorComponent.setVisible(show); }); @@ -256,12 +256,6 @@ public void checkCancelled() throws CancelledException { } } - @Override - @SuppressWarnings("deprecation") - public void checkCanceled() throws CancelledException { - checkCancelled(); - } - @Override public void setMessage(String message) { // A stopped wait may still report its analysis' last log line, which would replace the message of the @@ -276,8 +270,9 @@ public void cancel() { stopped = true; } + // Only the non-deprecated spellings: Ghidra 12.2 removed checkCanceled and clearCanceled @Override - public void clearCanceled() { + public void clearCancelled() { stopped = false; } } From d5191b9c61b966924bf611411f390597d306a938 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:20:29 +0000 Subject: [PATCH 62/76] fix(ENG-4590): drop the duplicate awaitDialog that breaks the test build ENG-4588 moved awaitDialog into RevEngMockableHeadedIntegrationTest while ENG-4590 added a private copy to DetachDuringAnalysisTest. With both on staging, the private static method clashes with the inherited one and compileTestJava fails. The two are identical, so use the shared helper. --- .../java/ai/reveng/DetachDuringAnalysisTest.java | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java index b69b34ea..091fcad0 100644 --- a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java +++ b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java @@ -9,7 +9,6 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.plugins.AnalysisManagementPlugin; -import docking.DialogComponentProvider; import docking.widgets.OptionDialog; import ghidra.app.services.ProgramManager; import ghidra.framework.plugintool.PluginTool; @@ -18,7 +17,6 @@ import ghidra.util.task.TaskMonitorComponent; import org.junit.Test; -import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; @@ -121,18 +119,6 @@ private void detach(Fixture fixture) { assertTrue(fixture.service().getKnownProgram(fixture.program()).isEmpty()); } - /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is - /// ignored in favour of Ghidra's 2s default - private static T awaitDialog(Class type) { - long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); - T dialog; - while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { - sleep(DEFAULT_WAIT_DELAY); - } - assertNotNull("timed out waiting for " + type.getSimpleName(), dialog); - return dialog; - } - private static boolean hasFunctionIds(Program program) { return program.getUsrPropertyManager().getLongPropertyMap("RevEngAI_FunctionID_Map") != null; } From eb1753233ed0086f59e29faed473ed5f36e01ba5 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:20:29 +0000 Subject: [PATCH 63/76] fix(ENG-4590): drop the duplicate awaitDialog that breaks the test build ENG-4588 moved awaitDialog into RevEngMockableHeadedIntegrationTest while ENG-4590 added a private copy to DetachDuringAnalysisTest. With both on staging, the private static method clashes with the inherited one and compileTestJava fails. The two are identical, so use the shared helper. (cherry picked from commit d5191b9c61b966924bf611411f390597d306a938) --- .../java/ai/reveng/DetachDuringAnalysisTest.java | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java index b69b34ea..091fcad0 100644 --- a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java +++ b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java @@ -9,7 +9,6 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.plugins.AnalysisManagementPlugin; -import docking.DialogComponentProvider; import docking.widgets.OptionDialog; import ghidra.app.services.ProgramManager; import ghidra.framework.plugintool.PluginTool; @@ -18,7 +17,6 @@ import ghidra.util.task.TaskMonitorComponent; import org.junit.Test; -import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; @@ -121,18 +119,6 @@ private void detach(Fixture fixture) { assertTrue(fixture.service().getKnownProgram(fixture.program()).isEmpty()); } - /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is - /// ignored in favour of Ghidra's 2s default - private static T awaitDialog(Class type) { - long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); - T dialog; - while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { - sleep(DEFAULT_WAIT_DELAY); - } - assertNotNull("timed out waiting for " + type.getSimpleName(), dialog); - return dialog; - } - private static boolean hasFunctionIds(Program program) { return program.getUsrPropertyManager().getLongPropertyMap("RevEngAI_FunctionID_Map") != null; } From a6867d15dbebae9add087419885d7cebae6ad860 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:33:20 +0000 Subject: [PATCH 64/76] test(ENG-4590): dump thread stacks when awaitDialog times out The error-dialog tests still time out now and then on CI after a full 30s, never locally. Print every thread's stack on a timeout so the next failure shows where the work that leads to the dialog stopped. --- .../RevEngMockableHeadedIntegrationTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index 759cd678..ab79aae5 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -84,10 +84,25 @@ protected static T awaitDialog(Class type while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { sleep(DEFAULT_WAIT_DELAY); } + if (dialog == null) { + // Only seen on CI so far; the stacks show where the work that leads to the dialog stopped + System.err.println("awaitDialog timed out: " + message + "\n" + threadDump()); + } assertNotNull(message, dialog); return dialog; } + private static String threadDump() { + var dump = new StringBuilder(); + Thread.getAllStackTraces().forEach((thread, stack) -> { + dump.append('"').append(thread.getName()).append("\" ").append(thread.getState()).append('\n'); + for (var frame : stack) { + dump.append(" at ").append(frame).append('\n'); + } + }); + return dump.toString(); + } + /// Like waitForCondition, but against this test's own 30s deadline: Ghidra's default limit is about 2s, which /// a wait that spans a real poll interval (function matching sleeps 2s between polls) can exceed on CI protected static void awaitCondition(BooleanSupplier condition, String message) { From ad40ca34f9fdfa742cf769505b6e9fe2c1957d51 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:27:04 +0000 Subject: [PATCH 65/76] fix(ENG-4590): fire analysis status events after the current delivery Ghidra's EventManager drops an event fired while another of the same type and name is being delivered, taking it for an event loop. The analysis wait reports its status from a background thread, so on a slow machine its first status (an Error or a Complete) could arrive while the Queued event that started the wait was still being delivered, and was lost: the failure was never reported, or the results never loaded. This is what made the error-dialog tests time out on CI after a full 30s. Fire status events from background threads with fireLater, which hands them to the Swing thread to be fired once the current delivery is done. --- .../RevEngAIAnalysisStatusChangedEvent.java | 10 +++ .../services/api/GhidraRevengService.java | 2 +- .../ghidra/core/tasks/StartAnalysisTask.java | 7 +- .../plugins/AnalysisManagementPlugin.java | 21 ++---- .../ai/reveng/StatusEventDeliveryTest.java | 67 +++++++++++++++++++ 5 files changed, 86 insertions(+), 21 deletions(-) create mode 100644 src/test/java/ai/reveng/StatusEventDeliveryTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java index 795244f0..ba0c9b30 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java @@ -3,7 +3,9 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ghidra.framework.plugintool.PluginEvent; +import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Program; +import ghidra.util.Swing; /** * Event that is fired when a RevEng.AI analysis result with some program changes. @@ -31,6 +33,14 @@ public RevEngAIAnalysisStatusChangedEvent(String sourceName, GhidraRevengService this.programWithID = programWithID; } + /// Fires the event on the Swing thread, after the event being delivered there (if any) has finished. Ghidra + /// drops an event fired while another of the same type is being delivered, taking it for an event loop, so a + /// status reported from a background thread at that moment was lost: e.g. a wait's Error or Complete arriving + /// while the Queued event that started the wait was still being delivered. + public void fireLater(PluginTool tool) { + Swing.runLater(() -> tool.firePluginEvent(this)); + } + public AnalysisStatus getStatus() { return status; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index cf9604a5..d50d6d0a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1574,7 +1574,7 @@ public StatusPoller.Result waitForAnalysis( if (currentStatus != lastStatus[0]) { lastStatus[0] = currentStatus; if (tool != null) { - tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus)); + new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus).fireLater(tool); } } return switch (currentStatus) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java index 649efde8..9f145d43 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java @@ -75,11 +75,8 @@ public void run(TaskMonitor monitor) throws CancelledException { loggingService.info(successMessage); } - tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent( - "StartAnalysisTask", - programWithID, - AnalysisStatus.Queued) - ); + new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued) + .fireLater(tool); } private void reportFailure(TaskMonitor monitor, diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 32d5211d..33c83b23 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -351,31 +351,22 @@ public void run(TaskMonitor monitor) { } switch (status) { case Complete -> { - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); + new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status) + .fireLater(tool); } case Uploaded, Queued, Processing -> { // This is the same code as above, but it has the implicit assumption that someone /// Currently this is done by {@link AnalysisLogComponent#processEvent(RevEngAIAnalysisStatusChangedEvent)} - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); + new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status) + .fireLater(tool); } case Error -> { // The analysis failed on the server side. Reported through the event, so it is // shown the same way as a failure seen while waiting, see processEvent - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); + new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status) + .fireLater(tool); } case Unknown -> { // Not waited on: an unrecognised status might never change into one that ends the wait diff --git a/src/test/java/ai/reveng/StatusEventDeliveryTest.java b/src/test/java/ai/reveng/StatusEventDeliveryTest.java new file mode 100644 index 00000000..ab0bd15c --- /dev/null +++ b/src/test/java/ai/reveng/StatusEventDeliveryTest.java @@ -0,0 +1,67 @@ +package ai.reveng; + +import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ghidra.framework.plugintool.PluginEvent; +import ghidra.framework.plugintool.PluginTool; +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.BiConsumer; + +import static org.junit.Assert.assertEquals; + +/// Ghidra drops an event fired while another of the same type is being delivered, taking it for an event loop. A wait +/// reports its first status from a background thread, which on a slow machine can be while the Queued event that +/// started it is still being delivered; the Error or Complete it reported was then lost. +public class StatusEventDeliveryTest extends RevEngMockableHeadedIntegrationTest { + + @Test + public void aStatusFiredLaterDuringAnotherStatusDeliveryArrives() throws Exception { + var received = deliverQueuedThenFireFromBackground(RevEngAIAnalysisStatusChangedEvent::fireLater); + + assertEquals(List.of(AnalysisStatus.Queued, AnalysisStatus.Error), received); + } + + /// Documents the Ghidra behaviour fireLater works around, so a Ghidra version that stops dropping these is noticed + @Test + public void aStatusFiredDirectlyDuringAnotherStatusDeliveryIsDropped() throws Exception { + var received = deliverQueuedThenFireFromBackground((event, tool) -> tool.firePluginEvent(event)); + + assertEquals(List.of(AnalysisStatus.Queued), received); + } + + /// Fires Queued; while it is being delivered, a background thread fires Error with {@code fire} and is waited for + private List deliverQueuedThenFireFromBackground( + BiConsumer fire) throws Exception { + var tool = env.getTool(); + var program = newX64Program().getProgram(); + var programWithID = new GhidraRevengService.ProgramWithID(program, new TypedApiInterface.AnalysisID(7)); + List received = new CopyOnWriteArrayList<>(); + + tool.addListenerForAllPluginEvents((PluginEvent event) -> { + if (!(event instanceof RevEngAIAnalysisStatusChangedEvent status)) { + return; + } + received.add(status.getStatus()); + if (status.getStatus() == AnalysisStatus.Queued) { + var waitThread = new Thread(() -> fire.accept( + new RevEngAIAnalysisStatusChangedEvent(null, programWithID, AnalysisStatus.Error), tool)); + waitThread.start(); + try { + waitThread.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); + + runSwing(() -> tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued))); + waitForSwing(); + return List.copyOf(received); + } +} From 6602935761eb299a4ad91d1c4fe634bfc89e3639 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:33:20 +0000 Subject: [PATCH 66/76] test(ENG-4590): dump thread stacks when awaitDialog times out The error-dialog tests still time out now and then on CI after a full 30s, never locally. Print every thread's stack on a timeout so the next failure shows where the work that leads to the dialog stopped. (cherry picked from commit a6867d15dbebae9add087419885d7cebae6ad860) --- .../RevEngMockableHeadedIntegrationTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index 759cd678..ab79aae5 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -84,10 +84,25 @@ protected static T awaitDialog(Class type while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { sleep(DEFAULT_WAIT_DELAY); } + if (dialog == null) { + // Only seen on CI so far; the stacks show where the work that leads to the dialog stopped + System.err.println("awaitDialog timed out: " + message + "\n" + threadDump()); + } assertNotNull(message, dialog); return dialog; } + private static String threadDump() { + var dump = new StringBuilder(); + Thread.getAllStackTraces().forEach((thread, stack) -> { + dump.append('"').append(thread.getName()).append("\" ").append(thread.getState()).append('\n'); + for (var frame : stack) { + dump.append(" at ").append(frame).append('\n'); + } + }); + return dump.toString(); + } + /// Like waitForCondition, but against this test's own 30s deadline: Ghidra's default limit is about 2s, which /// a wait that spans a real poll interval (function matching sleeps 2s between polls) can exceed on CI protected static void awaitCondition(BooleanSupplier condition, String message) { From d8d10b11c9f9369360309db090e9e8650b5db51a Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:27:04 +0000 Subject: [PATCH 67/76] fix(ENG-4590): fire analysis status events after the current delivery Ghidra's EventManager drops an event fired while another of the same type and name is being delivered, taking it for an event loop. The analysis wait reports its status from a background thread, so on a slow machine its first status (an Error or a Complete) could arrive while the Queued event that started the wait was still being delivered, and was lost: the failure was never reported, or the results never loaded. This is what made the error-dialog tests time out on CI after a full 30s. Fire status events from background threads with fireLater, which hands them to the Swing thread to be fired once the current delivery is done. (cherry picked from commit ad40ca34f9fdfa742cf769505b6e9fe2c1957d51) --- .../RevEngAIAnalysisStatusChangedEvent.java | 10 +++ .../services/api/GhidraRevengService.java | 2 +- .../ghidra/core/tasks/StartAnalysisTask.java | 7 +- .../plugins/AnalysisManagementPlugin.java | 21 ++---- .../ai/reveng/StatusEventDeliveryTest.java | 67 +++++++++++++++++++ 5 files changed, 86 insertions(+), 21 deletions(-) create mode 100644 src/test/java/ai/reveng/StatusEventDeliveryTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java index 795244f0..ba0c9b30 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java @@ -3,7 +3,9 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ghidra.framework.plugintool.PluginEvent; +import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Program; +import ghidra.util.Swing; /** * Event that is fired when a RevEng.AI analysis result with some program changes. @@ -31,6 +33,14 @@ public RevEngAIAnalysisStatusChangedEvent(String sourceName, GhidraRevengService this.programWithID = programWithID; } + /// Fires the event on the Swing thread, after the event being delivered there (if any) has finished. Ghidra + /// drops an event fired while another of the same type is being delivered, taking it for an event loop, so a + /// status reported from a background thread at that moment was lost: e.g. a wait's Error or Complete arriving + /// while the Queued event that started the wait was still being delivered. + public void fireLater(PluginTool tool) { + Swing.runLater(() -> tool.firePluginEvent(this)); + } + public AnalysisStatus getStatus() { return status; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index cabbd96a..21800fc1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1645,7 +1645,7 @@ public StatusPoller.Result waitForAnalysis( if (currentStatus != lastStatus[0]) { lastStatus[0] = currentStatus; if (tool != null) { - tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus)); + new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus).fireLater(tool); } } return switch (currentStatus) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java index 649efde8..9f145d43 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java @@ -75,11 +75,8 @@ public void run(TaskMonitor monitor) throws CancelledException { loggingService.info(successMessage); } - tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent( - "StartAnalysisTask", - programWithID, - AnalysisStatus.Queued) - ); + new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued) + .fireLater(tool); } private void reportFailure(TaskMonitor monitor, diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java index 32d5211d..33c83b23 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java @@ -351,31 +351,22 @@ public void run(TaskMonitor monitor) { } switch (status) { case Complete -> { - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); + new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status) + .fireLater(tool); } case Uploaded, Queued, Processing -> { // This is the same code as above, but it has the implicit assumption that someone /// Currently this is done by {@link AnalysisLogComponent#processEvent(RevEngAIAnalysisStatusChangedEvent)} - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); + new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status) + .fireLater(tool); } case Error -> { // The analysis failed on the server side. Reported through the event, so it is // shown the same way as a failure seen while waiting, see processEvent - tool.firePluginEvent( - new RevEngAIAnalysisStatusChangedEvent( - "programOpened", - knownProgram.get(), - status)); + new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status) + .fireLater(tool); } case Unknown -> { // Not waited on: an unrecognised status might never change into one that ends the wait diff --git a/src/test/java/ai/reveng/StatusEventDeliveryTest.java b/src/test/java/ai/reveng/StatusEventDeliveryTest.java new file mode 100644 index 00000000..ab0bd15c --- /dev/null +++ b/src/test/java/ai/reveng/StatusEventDeliveryTest.java @@ -0,0 +1,67 @@ +package ai.reveng; + +import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ghidra.framework.plugintool.PluginEvent; +import ghidra.framework.plugintool.PluginTool; +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.BiConsumer; + +import static org.junit.Assert.assertEquals; + +/// Ghidra drops an event fired while another of the same type is being delivered, taking it for an event loop. A wait +/// reports its first status from a background thread, which on a slow machine can be while the Queued event that +/// started it is still being delivered; the Error or Complete it reported was then lost. +public class StatusEventDeliveryTest extends RevEngMockableHeadedIntegrationTest { + + @Test + public void aStatusFiredLaterDuringAnotherStatusDeliveryArrives() throws Exception { + var received = deliverQueuedThenFireFromBackground(RevEngAIAnalysisStatusChangedEvent::fireLater); + + assertEquals(List.of(AnalysisStatus.Queued, AnalysisStatus.Error), received); + } + + /// Documents the Ghidra behaviour fireLater works around, so a Ghidra version that stops dropping these is noticed + @Test + public void aStatusFiredDirectlyDuringAnotherStatusDeliveryIsDropped() throws Exception { + var received = deliverQueuedThenFireFromBackground((event, tool) -> tool.firePluginEvent(event)); + + assertEquals(List.of(AnalysisStatus.Queued), received); + } + + /// Fires Queued; while it is being delivered, a background thread fires Error with {@code fire} and is waited for + private List deliverQueuedThenFireFromBackground( + BiConsumer fire) throws Exception { + var tool = env.getTool(); + var program = newX64Program().getProgram(); + var programWithID = new GhidraRevengService.ProgramWithID(program, new TypedApiInterface.AnalysisID(7)); + List received = new CopyOnWriteArrayList<>(); + + tool.addListenerForAllPluginEvents((PluginEvent event) -> { + if (!(event instanceof RevEngAIAnalysisStatusChangedEvent status)) { + return; + } + received.add(status.getStatus()); + if (status.getStatus() == AnalysisStatus.Queued) { + var waitThread = new Thread(() -> fire.accept( + new RevEngAIAnalysisStatusChangedEvent(null, programWithID, AnalysisStatus.Error), tool)); + waitThread.start(); + try { + waitThread.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); + + runSwing(() -> tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued))); + waitForSwing(); + return List.copyOf(received); + } +} From 2b80eeeb17d55ce6a50f0f7a09088a1fd53eba28 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:57:42 +0000 Subject: [PATCH 68/76] fix(ENG-4588): don't let a late status from a cancelled wait resume it Since the wait's statuses are fired after the current event delivery (fireLater), the Queued a wait reported can arrive after the wait has been cancelled and has ended. With the program no longer tracked, AnalysisLogComponent took it for a new analysis and started another wait, which cleared the cancel and polled on. This is what failed testCancelledMonitoringUntracksProgram on the release PR. Statuses a wait reports now carry their own source, and never start a wait: only Start Analysis, reopening a program and the like do. --- .../ui/misc/AnalysisLogComponent.java | 5 +++ .../RevEngAIAnalysisStatusChangedEvent.java | 9 +++++ .../services/api/GhidraRevengService.java | 3 +- .../ai/reveng/TestAnalysisLogComponent.java | 36 +++++++++++++++++++ 4 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index 5b302c0a..c1df2822 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -121,6 +121,11 @@ public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { // Unknown: the wait for it has already ended, so starting another would end at once and loop case Unknown -> {} default -> { + if (event.isFromWait()) { + // Progress from a wait, which is tracked already, or has ended since it reported this: starting + // another here would resume a wait the user cancelled + return; + } // A new or resumed analysis: an earlier ending no longer applies if (terminalStatusLines.remove(event.getProgram()) != null) { refreshIfActive(event.getProgram()); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java index ba0c9b30..581d93ea 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java @@ -21,6 +21,9 @@ * (e.g. function info). Use {@link ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisResultsLoaded} for that. */ public class RevEngAIAnalysisStatusChangedEvent extends PluginEvent { + /// The source of the statuses a running wait reports, see {@link #isFromWait()} + public static final String WAIT_SOURCE = "RevEng.AI analysis wait"; + private final AnalysisStatus status; private final GhidraRevengService.ProgramWithID programWithID; @@ -41,6 +44,12 @@ public void fireLater(PluginTool tool) { Swing.runLater(() -> tool.firePluginEvent(this)); } + /// Whether a running wait reported this status. Such a status is delivered later than it was seen (see + /// {@link #fireLater}), so the wait may already have ended, e.g. because it was cancelled. + public boolean isFromWait() { + return WAIT_SOURCE.equals(getSourceName()); + } + public AnalysisStatus getStatus() { return status; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index 21800fc1..b4793517 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1645,7 +1645,8 @@ public StatusPoller.Result waitForAnalysis( if (currentStatus != lastStatus[0]) { lastStatus[0] = currentStatus; if (tool != null) { - new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus).fireLater(tool); + new RevEngAIAnalysisStatusChangedEvent(RevEngAIAnalysisStatusChangedEvent.WAIT_SOURCE, programWithID, currentStatus) + .fireLater(tool); } } return switch (currentStatus) { diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index 65ca33e5..bfda4458 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -207,6 +207,42 @@ public AnalysisStatus status(AnalysisID analysisID) { assertFalse(taskMonitorComponent.isVisible()); } + /// A wait's statuses are delivered after it reported them, so one can arrive once the wait has been cancelled. + /// It must not start the wait again. + @Test + public void testStatusFromACancelledWaitDoesNotResumeIt() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.incrementAndGet(); + return AnalysisStatus.Queued; + } + }); + attach(service, programWithID); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued)); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + ((TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent)).cancel(); + waitForTasks(); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + + // The Queued the cancelled wait reported, arriving late + runSwing(() -> defaultTool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent( + RevEngAIAnalysisStatusChangedEvent.WAIT_SOURCE, programWithID, AnalysisStatus.Queued))); + waitForSwing(); + int callsAfterCancel = statusCalls.get(); + waitForTasks(); + + assertFalse("a late status must not start another wait", trackedPrograms.containsKey(programWithID.program())); + assertEquals("no polling after the cancel", callsAfterCancel, statusCalls.get()); + } + /// An analysis that was still Uploaded when Ghidra closed is waited on again when the program is reopened @Test public void testReopenedUploadedAnalysisIsWaitedOn() throws Exception { From 4b08a451141d23bb61cdc576500bc2d2646b9ed4 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:39:34 +0000 Subject: [PATCH 69/76] ci(ENG-4588): complete a test report check the reporter left in progress dorny/test-reporter creates its check run and updates it with the results a moment later. That update intermittently 404s, because the new check run is not visible to the API yet; continue-on-error keeps the job green, but the check run stays in progress for good, so the PR never shows all checks finished. When the report step fails, find any 'Tests (Ghidra X)' check run for the head commit that is not completed, retrying while it becomes visible, and complete it with the outcome of the Run tests step. Look them up with filter=all: with filter=latest the endpoint returned no runs at all for two of the three stuck checks. --- .github/workflows/build.yml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b2ff3003..250248f9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -66,6 +66,7 @@ jobs: run: $GHIDRA_INSTALL_DIR/support/sleigh $GHIDRA_INSTALL_DIR/Ghidra/Processors/x86/data/languages/x86-64.slaspec - name: Run tests + id: tests run: xvfb-run ./gradlew test - name: Upload test results @@ -76,6 +77,7 @@ jobs: path: build/reports/tests/test/ - name: Publish test report + id: report if: always() # Updating the check run right after creating it intermittently 404s, which failed jobs whose # tests had passed. Failing tests already fail "Run tests", so the report is display only. @@ -85,3 +87,34 @@ jobs: name: Tests (Ghidra ${{ matrix.ghidra }}) path: build/test-results/test/*.xml reporter: java-junit + + - name: Complete a test report left in progress + # When the reporter's update 404s, the check run it created stays "in progress" for good, so the PR never + # shows all checks finished. Complete it with the outcome of the tests. Display only, like the report. + if: always() && steps.report.outcome == 'failure' + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + CHECK_NAME: Tests (Ghidra ${{ matrix.ghidra }}) + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + CONCLUSION: ${{ steps.tests.outcome == 'success' && 'success' || 'failure' }} + run: | + summary="The test reporter could not attach the results to this check (HTTP 404). See the Run tests step and the test-results artifact." + # The check run may not be visible to the API yet, which is what made the reporter's update fail + for attempt in 1 2 3 4 5; do + ids=$(gh api -X GET "repos/$GITHUB_REPOSITORY/commits/$HEAD_SHA/check-runs" \ + -f check_name="$CHECK_NAME" -f filter=all \ + --jq '.check_runs[] | select(.status != "completed") | .id') || ids="" + completed=true + for id in $ids; do + gh api -X PATCH "repos/$GITHUB_REPOSITORY/check-runs/$id" \ + -f status=completed -f conclusion="$CONCLUSION" \ + -f "output[title]=$CHECK_NAME" -f "output[summary]=$summary" >/dev/null || completed=false + done + if [ -n "$ids" ] && [ "$completed" = true ]; then + echo "Completed '$CHECK_NAME' ($ids) as $CONCLUSION" + exit 0 + fi + sleep 5 + done + echo "::warning::Could not find or complete an in-progress '$CHECK_NAME' check" From 102c346f03359ab7c23a281efbaabe7787d04c68 Mon Sep 17 00:00:00 2001 From: Robert Marsal <507871+robertmarsal@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:45:01 +0000 Subject: [PATCH 70/76] chore: bump SDK to 4.77.1 (#266) --- build.gradle | 2 +- .../RevEngAIAnalysisOptionsDialog.java | 6 +++--- .../services/api/TypedApiImplementation.java | 2 +- .../core/services/api/TypedApiInterface.java | 2 +- .../ai/reveng/AnalysisOptionsDialogTest.java | 20 +++++++++---------- .../services/api/SdkRecordedResponseTest.java | 4 ++-- .../core/services/api/SdkSchemaTest.java | 2 +- 7 files changed, 19 insertions(+), 19 deletions(-) diff --git a/build.gradle b/build.gradle index 29e4824a..ca4ff370 100644 --- a/build.gradle +++ b/build.gradle @@ -69,7 +69,7 @@ dependencies { implementation group: 'com.fifesoft', name: 'rsyntaxtextarea', version: '3.5.2' implementation 'org.commonmark:commonmark:0.24.0' implementation 'org.commonmark:commonmark-ext-gfm-tables:0.24.0' - implementation('ai.reveng:sdk:4.75.1-rc.1') + implementation('ai.reveng:sdk:4.77.1') testImplementation('junit:junit:4.13.1') testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.8.2") // Version comes from the junit-bom pulled in by junit-vintage-engine. diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java index 179da617..63422edf 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java @@ -1,7 +1,7 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.analysiscreation; import ai.reveng.model.ConfigResponse; -import ai.reveng.model.User; +import ai.reveng.model.CurrentUser; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; @@ -417,10 +417,10 @@ private void fetchUserTierAsync() { }); } - private void handleUserResponse(@Nullable User user) { + private void handleUserResponse(@Nullable CurrentUser user) { tierResolved = true; - if (user != null && user.getTier() != User.TierEnum.ENTHUSIAST) { + if (user != null && user.getTier() != CurrentUser.TierEnum.ENTHUSIAST) { privateScope.setEnabled(true); privateScope.setToolTipText(null); privateScopePanel.setToolTipText(null); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 98c3e9f4..ea5256f4 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -776,7 +776,7 @@ public ConfigResponse getConfig() { } @Override - public User getMe() { + public CurrentUser getMe() { try { return this.iamUsersApi.getMe(); } catch (ApiException e) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java index afa8d8d1..4a87aba1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java @@ -255,7 +255,7 @@ default ConfigResponse getConfig() throws ApiException { throw new UnsupportedOperationException("getConfig not implemented yet"); } - default User getMe() throws ApiException { + default CurrentUser getMe() throws ApiException { throw new UnsupportedOperationException("getMe not implemented yet"); } } diff --git a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java index 19b0461c..467575f0 100644 --- a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java +++ b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java @@ -23,7 +23,7 @@ import javax.swing.*; import ai.reveng.model.CreateRequest; -import ai.reveng.model.User; +import ai.reveng.model.CurrentUser; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.analysiscreation.RevEngAIAnalysisOptionsDialog; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.mocks.MockApi; @@ -112,8 +112,8 @@ public void testSubmittedAnalysisConfig() throws Exception { public void testPrivateScopeDisabledForEnthusiast() throws Exception { var reService = new GhidraRevengService(new MockApi() { @Override - public User getMe() { - return new User().tier(User.TierEnum.ENTHUSIAST); + public CurrentUser getMe() { + return new CurrentUser().tier(CurrentUser.TierEnum.ENTHUSIAST); } }); var builder = newX64Program(); @@ -150,8 +150,8 @@ public User getMe() { public void testPrivateScopeEnabledForNonEnthusiast() throws Exception { var reService = new GhidraRevengService(new MockApi() { @Override - public User getMe() { - return new User().tier(User.TierEnum.REVERSER); + public CurrentUser getMe() { + return new CurrentUser().tier(CurrentUser.TierEnum.REVERSER); } }); var builder = newX64Program(); @@ -184,7 +184,7 @@ public User getMe() { public void testPrivateScopeDisabledWhenTierFetchFails() throws Exception { var reService = new GhidraRevengService(new MockApi() { @Override - public User getMe() { + public CurrentUser getMe() { throw new RuntimeException("tier lookup failed"); } }); @@ -225,13 +225,13 @@ public void testStartAnalysisBlockedUntilTierResolves() throws Exception { CountDownLatch release = new CountDownLatch(1); var reService = new GhidraRevengService(new MockApi() { @Override - public User getMe() { + public CurrentUser getMe() { try { release.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - return new User().tier(User.TierEnum.REVERSER); + return new CurrentUser().tier(CurrentUser.TierEnum.REVERSER); } }); var builder = newX64Program(); @@ -267,8 +267,8 @@ public User getMe() { public void testGetOptionsIgnoresDisabledPrivateSelection() throws Exception { var reService = new GhidraRevengService(new MockApi() { @Override - public User getMe() { - return new User().tier(User.TierEnum.ENTHUSIAST); + public CurrentUser getMe() { + return new CurrentUser().tier(CurrentUser.TierEnum.ENTHUSIAST); } }); var builder = newX64Program(); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java index aeddb871..9b796976 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java @@ -3,7 +3,7 @@ import ai.reveng.model.DecompilationData; import ai.reveng.model.GetMatchesStatusOutputBody; import ai.reveng.model.ProgressMessage; -import ai.reveng.model.User; +import ai.reveng.model.CurrentUser; import ai.reveng.model.WorkflowProgress; import ai.reveng.toolkit.ghidra.core.services.api.types.AIDecompilationStatus; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; @@ -130,7 +130,7 @@ public void canonicalNamesComeBackKeyedByInput() throws Exception { @Test public void currentUserCarriesTier() { - assertEquals(User.TierEnum.REVERSER, api().getMe().getTier()); + assertEquals(CurrentUser.TierEnum.REVERSER, api().getMe().getTier()); } @Test diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java index df3e3fc8..8da17ab7 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java @@ -211,7 +211,7 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.CanonicalizeNamesOutputBody", "getResults"); requireMethods(missing, "ai.reveng.model.CanonicalName", "getName", "getCanonicalName"); - requireMethods(missing, "ai.reveng.model.User", "getTier"); + requireMethods(missing, "ai.reveng.model.CurrentUser", "getTier"); requireMethods(missing, "ai.reveng.model.BaseResponseConfigResponse", "getData"); requireMethods(missing, "ai.reveng.model.ConfigResponse", "getMaxFileSizeBytes"); From 1edc3bed5cf44a29ed94d95909a5f993b11331ab Mon Sep 17 00:00:00 2001 From: Rob Marsal Date: Tue, 17 Nov 2026 14:57:50 +0000 Subject: [PATCH 71/76] fix(ENG-4379): upload the binary stored in the program when its file is missing --- .../RevEngAIAnalysisOptionsDialog.java | 46 ++++------ .../services/api/GhidraRevengService.java | 27 +++--- .../core/services/api/OriginalBinary.java | 88 +++++++++++++++++++ .../ai/reveng/AnalysisOptionsDialogTest.java | 37 ++++++-- .../ai/reveng/GhidraRevengServiceTest.java | 38 ++++++++ .../RevEngMockableHeadedIntegrationTest.java | 21 +++++ 6 files changed, 210 insertions(+), 47 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/api/OriginalBinary.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java index 63422edf..6e3760aa 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java @@ -5,6 +5,7 @@ import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.OriginalBinary; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisScope; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import docking.widgets.table.GTable; @@ -23,9 +24,8 @@ import javax.swing.table.TableRowSorter; import java.awt.*; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.InvalidPathException; -import java.nio.file.Path; +import java.nio.file.NoSuchFileException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -445,22 +445,24 @@ private void handleUserResponse(@Nullable CurrentUser user) { private void handleConfigResponse(@Nullable ConfigResponse config) { loadingLabel.setVisible(false); - - if (config == null) { - // Config fetch failed, allow upload attempt (server will reject if too large) - fileSizeOk = true; - updateOkButtonState(); - return; - } - - long maxFileSizeBytes = config.getMaxFileSizeBytes().longValue(); - validateFileSize(maxFileSizeBytes); + // Without a config, allow upload attempt (server will reject if too large) + validateFileSize(config == null ? Long.MAX_VALUE : config.getMaxFileSizeBytes().longValue()); } private void validateFileSize(long maxFileSizeBytes) { - long fileSize = getProgramFileSize(); - if (fileSize < 0) { + long fileSize; + try { + fileSize = OriginalBinary.size(program); + } catch (NoSuchFileException e) { + fileSizeWarningLabel.setText("

%s
" + .formatted(OriginalBinary.notFoundMessage(OriginalBinary.importPath(program)))); + fileSizeWarningLabel.setVisible(true); + fileSizeOk = false; + updateOkButtonState(); + return; + } catch (IOException | InvalidPathException e) { // Could not determine file size, allow upload attempt + Msg.warn(this, "Could not determine file size: " + e.getMessage()); fileSizeOk = true; updateOkButtonState(); return; @@ -485,22 +487,6 @@ private void updateOkButtonState() { okButton.setEnabled(fileSizeOk && tierResolved); } - private long getProgramFileSize() { - try { - Path filePath; - try { - filePath = Path.of(program.getExecutablePath()); - } catch (InvalidPathException e) { - // Windows paths may have leading slash like "/C:/file.dll" - filePath = Path.of(program.getExecutablePath().substring(1)); - } - return Files.size(filePath); - } catch (IOException | InvalidPathException e) { - Msg.warn(this, "Could not determine file size: " + e.getMessage()); - return -1; - } - } - private static String formatBytes(long bytes) { if (bytes < 1024) { return bytes + " B"; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index b4793517..bb341f06 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -50,7 +50,6 @@ import java.net.URI; import java.nio.file.FileSystemException; import java.nio.file.Files; -import java.nio.file.InvalidPathException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.time.Duration; @@ -1419,15 +1418,13 @@ public TypedApiInterface.BinaryHash upload(Program program) { // TODO: Check if the program is already uploaded on the server // But this requires a dedicated API to do cleanly - Path filePath; + Path extracted; try { - filePath = Path.of(program.getExecutablePath()); - } catch (InvalidPathException e) { - // For windows the returned String isn't a valid input to Path.of - // because they look like "/C:/vfcompat.dll" - // we have to drop the first "/" for the path to be valid - filePath = Path.of(program.getExecutablePath().substring(1)); + extracted = OriginalBinary.extract(program).orElse(null); + } catch (IOException e) { + throw new RuntimeException("Could not extract the binary stored in the program: " + e.getMessage(), e); } + Path filePath = extracted != null ? extracted : OriginalBinary.importPath(program); // The SDK only reports an unreadable file as an opaque HTTP 0, so check up front. try (var ignored = Files.newInputStream(filePath)) { } catch (IOException e) { @@ -1448,12 +1445,22 @@ public TypedApiInterface.BinaryHash upload(Program program) { throw new RuntimeException(e); } catch (ApiException e) { throw new RuntimeException(TypedApiImplementation.describeApiException(e), e); + } finally { + if (extracted != null) { + try { + OriginalBinary.delete(extracted); + } catch (IOException e) { + Msg.warn(this, "Could not delete " + extracted + ": " + e.getMessage()); + } + } } } private static String unreadableBinaryMessage(Path path, IOException e) { - String reason = e instanceof NoSuchFileException ? "file not found" - : e instanceof FileSystemException fse && fse.getReason() != null ? fse.getReason() + if (e instanceof NoSuchFileException) { + return OriginalBinary.notFoundMessage(path); + } + String reason = e instanceof FileSystemException fse && fse.getReason() != null ? fse.getReason() : e.getMessage(); String message = "Cannot read %s (%s).".formatted(path, reason); if (Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.MAC_OS_X diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/OriginalBinary.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/OriginalBinary.java new file mode 100644 index 00000000..719956b8 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/OriginalBinary.java @@ -0,0 +1,88 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ghidra.program.database.mem.FileBytes; +import ghidra.program.model.listing.Program; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Optional; + +/// The file a program was imported from. +/// +/// Ghidra records the importer's path, which is missing on other machines (e.g. in a shared project), +/// but its loaders also store the file's bytes in the program, which travel with it. +public final class OriginalBinary { + private static final int CHUNK = 1 << 20; + + private OriginalBinary() { + } + + public static Path importPath(Program program) { + try { + return Path.of(program.getExecutablePath()); + } catch (InvalidPathException e) { + // On Windows the path looks like "/C:/vfcompat.dll" + return Path.of(program.getExecutablePath().substring(1)); + } + } + + /// Size of the original file, from the stored bytes if present, else from disk. + public static long size(Program program) throws IOException { + FileBytes stored = stored(program); + return stored != null ? stored.getSize() : Files.size(importPath(program)); + } + + /// Writes the stored bytes to a new temporary directory, under the original file name. + /// Empty if none are stored or they don't hash to the program's SHA-256. + public static Optional extract(Program program) throws IOException { + FileBytes stored = stored(program); + if (stored == null) { + return Optional.empty(); + } + Path name = importPath(program).getFileName(); + Path file = Files.createTempDirectory("reai-upload").resolve(name != null ? name.toString() : program.getName()); + MessageDigest sha256; + try { + sha256 = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + byte[] buffer = new byte[CHUNK]; + try (OutputStream out = Files.newOutputStream(file)) { + for (long offset = 0; offset < stored.getSize(); ) { + int read = stored.getOriginalBytes(offset, buffer, 0, (int) Math.min(CHUNK, stored.getSize() - offset)); + out.write(buffer, 0, read); + sha256.update(buffer, 0, read); + offset += read; + } + } + if (!HexFormat.of().formatHex(sha256.digest()).equalsIgnoreCase(program.getExecutableSHA256())) { + delete(file); + return Optional.empty(); + } + return Optional.of(file); + } + + /// Deletes a file returned by {@link #extract} and its directory. + public static void delete(Path extracted) throws IOException { + Files.deleteIfExists(extracted); + Files.deleteIfExists(extracted.getParent()); + } + + public static String notFoundMessage(Path path) { + return "Original binary not found at %s and not stored in the program. Copy it to that path or re-import it." + .formatted(path); + } + + private static @Nullable FileBytes stored(Program program) { + var all = program.getMemory().getAllFileBytes(); + return all.isEmpty() ? null : all.getFirst(); + } +} diff --git a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java index 467575f0..03df1472 100644 --- a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java +++ b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java @@ -30,6 +30,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisScope; import docking.DockingWindowManager; import ghidra.framework.main.FrontEndTool; +import ghidra.program.database.ProgramBuilder; import org.junit.*; import ghidra.test.TestEnv; @@ -43,11 +44,18 @@ public AnalysisOptionsDialogTest() { super(); } + /// A program holding the bytes of the binary it was imported from, as Ghidra's loaders store them. + private ProgramBuilder newImportedProgram() throws Exception { + var builder = newX64Program(); + importedFrom(builder.getProgram(), "/nonexistent/original.bin", "original binary".getBytes()); + return builder; + } + @Test public void testBasicOptionsDialog() throws Exception { var reService = new GhidraRevengService( new MockApi() {}); - var builder = newX64Program(); + var builder = newImportedProgram(); var program = builder.getProgram(); var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); SwingUtilities.invokeLater(() -> { @@ -77,7 +85,7 @@ public void testBasicOptionsDialog() throws Exception { @Test public void testSubmittedAnalysisConfig() throws Exception { var reService = new GhidraRevengService(new MockApi() {}); - var builder = newX64Program(); + var builder = newImportedProgram(); var program = builder.getProgram(); var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); SwingUtilities.invokeLater(() -> { @@ -116,7 +124,7 @@ public CurrentUser getMe() { return new CurrentUser().tier(CurrentUser.TierEnum.ENTHUSIAST); } }); - var builder = newX64Program(); + var builder = newImportedProgram(); var program = builder.getProgram(); var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); SwingUtilities.invokeLater(() -> { @@ -154,7 +162,7 @@ public CurrentUser getMe() { return new CurrentUser().tier(CurrentUser.TierEnum.REVERSER); } }); - var builder = newX64Program(); + var builder = newImportedProgram(); var program = builder.getProgram(); var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); SwingUtilities.invokeLater(() -> { @@ -188,7 +196,7 @@ public CurrentUser getMe() { throw new RuntimeException("tier lookup failed"); } }); - var builder = newX64Program(); + var builder = newImportedProgram(); var program = builder.getProgram(); var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); SwingUtilities.invokeLater(() -> { @@ -220,6 +228,21 @@ public CurrentUser getMe() { assertEquals(AnalysisScope.PUBLIC, options.getScope()); } + @Test + public void testMissingBinaryWithoutStoredBytesBlocksAnalysis() throws Exception { + var reService = new GhidraRevengService(new MockApi() {}); + var program = newX64Program().getProgram(); + importedFrom(program, "/nonexistent/original.bin", null); + var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); + SwingUtilities.invokeLater(() -> DockingWindowManager.showDialog(null, dialog)); + + JLabel warning = (JLabel) getInstanceField("fileSizeWarningLabel", dialog); + waitFor(warning::isVisible); + JButton okButton = (JButton) getInstanceField("okButton", dialog); + assertTrue(warning.getText(), warning.getText().contains("Original binary not found")); + assertFalse(okButton.isEnabled()); + } + @Test public void testStartAnalysisBlockedUntilTierResolves() throws Exception { CountDownLatch release = new CountDownLatch(1); @@ -234,7 +257,7 @@ public CurrentUser getMe() { return new CurrentUser().tier(CurrentUser.TierEnum.REVERSER); } }); - var builder = newX64Program(); + var builder = newImportedProgram(); var program = builder.getProgram(); var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); SwingUtilities.invokeLater(() -> { @@ -271,7 +294,7 @@ public CurrentUser getMe() { return new CurrentUser().tier(CurrentUser.TierEnum.ENTHUSIAST); } }); - var builder = newX64Program(); + var builder = newImportedProgram(); var program = builder.getProgram(); var dialog = RevEngAIAnalysisOptionsDialog.withModelsFromServer(program, reService); SwingUtilities.invokeLater(() -> { diff --git a/src/test/java/ai/reveng/GhidraRevengServiceTest.java b/src/test/java/ai/reveng/GhidraRevengServiceTest.java index 9218b684..4970b6ed 100644 --- a/src/test/java/ai/reveng/GhidraRevengServiceTest.java +++ b/src/test/java/ai/reveng/GhidraRevengServiceTest.java @@ -14,11 +14,14 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.io.IOException; +import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Set; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -70,6 +73,41 @@ public BinaryHash upload(Path binPath) { assertTrue(e.getMessage(), e.getMessage().startsWith("Cannot read " + bin)); } + /// A shared project records the importer's path, missing on other machines; the bytes Ghidra stored must be uploaded. + @Test + public void testUploadUsesBytesStoredInProgramWhenFileIsMissing() throws Exception { + byte[] content = "original binary".getBytes(); + var program = newX64Program().getProgram(); + importedFrom(program, "/nonexistent/original.bin", content); + var uploaded = new byte[1][]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public BinaryHash upload(Path binPath) { + try { + uploaded[0] = Files.readAllBytes(binPath); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new BinaryHash(program.getExecutableSHA256()); + } + }); + + service.upload(program); + + assertArrayEquals(content, uploaded[0]); + } + + @Test + public void testUploadOfMissingFileWithoutStoredBytesExplainsWhy() throws Exception { + var program = newX64Program().getProgram(); + importedFrom(program, "/nonexistent/original.bin", null); + var service = new GhidraRevengService(new UnimplementedAPI()); + + var e = assertThrows(RuntimeException.class, () -> service.upload(program)); + + assertTrue(e.getMessage(), e.getMessage().startsWith("Original binary not found at /nonexistent/original.bin")); + } + @Test public void testStatusPollingGivesUpAfterTenFailures() throws Exception { var statusCalls = new int[1]; diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index ab79aae5..37a96286 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -12,13 +12,18 @@ import ghidra.framework.plugintool.mgr.ServiceManager; import ghidra.framework.plugintool.util.PluginException; import ghidra.program.database.ProgramBuilder; +import ghidra.program.model.listing.Program; +import generic.hash.HashUtilities; +import ghidra.util.task.TaskMonitor; import ghidra.test.AbstractGhidraHeadedIntegrationTest; import ghidra.test.TestEnv; import org.junit.After; import org.junit.Before; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.time.Duration; import java.util.HashMap; import java.util.Map; @@ -71,6 +76,22 @@ protected ProgramBuilder newX64Program(String name) throws Exception { return new ProgramBuilder(name, ProgramBuilder._X64, this); } + /// Records `program` as imported from `path`, as a shared project does for every machine but the importer's. + /// Ghidra keeps `content` in the program when it is not null, as its loaders do. + protected static void importedFrom(Program program, String path, byte[] content) throws Exception { + int tx = program.startTransaction("import"); + try { + program.setExecutablePath(path); + if (content != null) { + program.setExecutableSHA256(HashUtilities.getHash(HashUtilities.SHA256_ALGORITHM, content)); + program.getMemory().createFileBytes(Path.of(path).getFileName().toString(), 0, content.length, + new ByteArrayInputStream(content), TaskMonitor.DUMMY); + } + } finally { + program.endTransaction(tx, true); + } + } + /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is /// ignored in favour of Ghidra's 2s default, which a slow CI runner can exceed while a task is still running protected static T awaitDialog(Class type) { From 5421cd41033e9aa7320f28414f928c300d1424a1 Mon Sep 17 00:00:00 2001 From: Rob Marsal Date: Tue, 17 Nov 2026 15:02:58 +0000 Subject: [PATCH 72/76] test(ENG-4379): hash fixture bytes with the JDK, HashUtilities is missing before Ghidra 12.1 --- .../java/ai/reveng/RevEngMockableHeadedIntegrationTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index 37a96286..cc8f68b8 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -13,7 +13,6 @@ import ghidra.framework.plugintool.util.PluginException; import ghidra.program.database.ProgramBuilder; import ghidra.program.model.listing.Program; -import generic.hash.HashUtilities; import ghidra.util.task.TaskMonitor; import ghidra.test.AbstractGhidraHeadedIntegrationTest; import ghidra.test.TestEnv; @@ -24,8 +23,10 @@ import java.io.File; import java.io.IOException; import java.nio.file.Path; +import java.security.MessageDigest; import java.time.Duration; import java.util.HashMap; +import java.util.HexFormat; import java.util.Map; import java.util.function.BooleanSupplier; @@ -83,7 +84,7 @@ protected static void importedFrom(Program program, String path, byte[] content) try { program.setExecutablePath(path); if (content != null) { - program.setExecutableSHA256(HashUtilities.getHash(HashUtilities.SHA256_ALGORITHM, content)); + program.setExecutableSHA256(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content))); program.getMemory().createFileBytes(Path.of(path).getFileName().toString(), 0, content.length, new ByteArrayInputStream(content), TaskMonitor.DUMMY); } From da36939a7f0c0e06c04041d3b9bb6cf970f03dc1 Mon Sep 17 00:00:00 2001 From: Rob Marsal Date: Tue, 17 Nov 2026 15:24:41 +0000 Subject: [PATCH 73/76] fix(ENG-4192): read data types without reflective record binding --- build.gradle | 10 ++++ .../api/datatypes/ServerDataTypeReader.java | 55 +++++++++++++------ .../services/api/DataTypeEntryGson29Test.java | 46 ++++++++++++++++ 3 files changed, 93 insertions(+), 18 deletions(-) create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/api/DataTypeEntryGson29Test.java diff --git a/build.gradle b/build.gradle index d3d9cf56..9019031a 100644 --- a/build.gradle +++ b/build.gradle @@ -101,7 +101,17 @@ tasks.register('pruneStaleJars', Delete) { } copyDependencies.dependsOn pruneStaleJars +// Ghidra < 12.1 loads its own Gson 2.9.0 ahead of the plugin's. Tests rerun the data-type reader +// against it to catch code that only works on newer Gson (e.g. reflective record binding). +configurations { + ghidraGson +} +dependencies { + ghidraGson 'com.google.code.gson:gson:2.9.0' +} + test { + systemProperty 'reveng.test.gson29', configurations.ghidraGson.singleFile.path maxParallelForks = 3 useJUnitPlatform() jvmArgs '--add-exports=java.desktop/sun.awt=ALL-UNNAMED' diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java index 72219ee3..1a5a15bf 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java @@ -2,12 +2,11 @@ import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType.*; import com.google.gson.*; -import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; -import java.util.Objects; +import java.util.function.Function; /** * Reads the spec's {@code DataTypeEntry} JSON straight into the flattened {@link ServerDataType}, @@ -33,14 +32,9 @@ */ public final class ServerDataTypeReader implements JsonDeserializer { - private static final Type MEMBERS = new TypeToken>() {}.getType(); - private static final Type VALUES = new TypeToken>() {}.getType(); - private static final Type PARAMETERS = new TypeToken>() {}.getType(); - - /// Snake-case naming binds the nested entries' fields ({@code data_type_id}, {@code is_bitfield}, - /// {@code bit_offset}, ...) reflectively; the entry itself is read by hand below. + /// Everything is read by hand: Ghidra < 12.1 loads its own Gson 2.9.0 ahead of the plugin's, and + /// 2.9.0 cannot bind records reflectively. private static final Gson GSON = new GsonBuilder() - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(ServerDataType.class, new ServerDataTypeReader()) .create(); @@ -83,35 +77,60 @@ public ServerDataType deserialize(JsonElement json, Type type, JsonDeserializati Boolean.TRUE.equals(bool(entry, "has_definition")), number(entry, "source_function_id"), string(entry, "created_at"), - definition(kind, entry.get("definition"), context)); + definition(kind, entry.get("definition"))); } - private static Definition definition(Kind kind, JsonElement raw, JsonDeserializationContext context) { + private static Definition definition(Kind kind, JsonElement raw) { if (raw == null || !raw.isJsonObject()) { return null; } JsonObject def = raw.getAsJsonObject(); return switch (kind) { - case STRUCT -> new StructDefinition(list(def, "members", MEMBERS, context)); - case UNION -> new UnionDefinition(list(def, "members", MEMBERS, context)); - case ENUM -> new EnumDefinition(list(def, "values", VALUES, context)); + case STRUCT -> new StructDefinition(list(def, "members", ServerDataTypeReader::member)); + case UNION -> new UnionDefinition(list(def, "members", ServerDataTypeReader::member)); + case ENUM -> new EnumDefinition(list(def, "values", ServerDataTypeReader::enumValue)); case TYPEDEF -> new TypedefDefinition(number(def, "target_data_type_id")); case POINTER -> new PointerDefinition(number(def, "pointee_data_type_id")); case ARRAY -> new ArrayDefinition(number(def, "count"), number(def, "element_data_type_id")); case FUNCTION_DEFINITION -> new FunctionTypeDefinition( - number(def, "return_data_type_id"), list(def, "parameters", PARAMETERS, context)); + number(def, "return_data_type_id"), list(def, "parameters", ServerDataTypeReader::parameter)); // These kinds never carry a definition; ignore one if the server ever sends it. case BASE, BITFIELD, UNKNOWN -> null; }; } - private static List list(JsonObject owner, String field, Type type, JsonDeserializationContext context) { + private static List list(JsonObject owner, String field, Function read) { JsonElement array = owner.get(field); if (array == null || !array.isJsonArray()) { return List.of(); } - List items = context.deserialize(array, type); - return items == null ? List.of() : items.stream().filter(Objects::nonNull).toList(); + List items = new ArrayList<>(); + for (JsonElement item : array.getAsJsonArray()) { + if (item.isJsonObject()) { + items.add(read.apply(item.getAsJsonObject())); + } + } + return List.copyOf(items); + } + + private static Member member(JsonObject m) { + return new Member(string(m, "name"), primitive(m, "offset"), primitive(m, "size"), + number(m, "data_type_id"), Boolean.TRUE.equals(bool(m, "is_bitfield")), + number(m, "bit_offset"), number(m, "bit_size")); + } + + private static EnumValue enumValue(JsonObject v) { + return new EnumValue(string(v, "name"), string(v, "value")); + } + + private static Parameter parameter(JsonObject p) { + return new Parameter(string(p, "name"), primitive(p, "ordinal"), primitive(p, "size"), + number(p, "data_type_id")); + } + + private static long primitive(JsonObject owner, String field) { + Long value = number(owner, field); + return value == null ? 0L : value; } private static String string(JsonObject owner, String field) { diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/DataTypeEntryGson29Test.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/DataTypeEntryGson29Test.java new file mode 100644 index 00000000..65aaccb1 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/DataTypeEntryGson29Test.java @@ -0,0 +1,46 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataTypeReader; +import org.junit.Test; + +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Reruns {@link ServerDataTypeReader} against Gson 2.9.0, which Ghidra < 12.1 loads ahead of the + * plugin's own Gson. 2.9.0 cannot bind records reflectively. + */ +public class DataTypeEntryGson29Test { + + @Test + public void readsNestedDefinitionsOnGson29() throws Exception { + URL gson = new File(System.getProperty("reveng.test.gson29")).toURI().toURL(); + URL plugin = ServerDataTypeReader.class.getProtectionDomain().getCodeSource().getLocation(); + try (var loader = new URLClassLoader(new URL[]{gson, plugin}, ClassLoader.getPlatformClassLoader())) { + Class parser = loader.loadClass("com.google.gson.JsonParser"); + Class element = loader.loadClass("com.google.gson.JsonElement"); + Object body = parser.getMethod("parseString", String.class).invoke(null, """ + {"items": [ + {"data_type_id": 1, "kind": "STRUCT", "name": "S", "namespace": "", "source_type": "SYSTEM", + "has_definition": true, "definition": {"members": [ + {"name": "a", "offset": 0, "size": 4, "data_type_id": 2, "is_bitfield": false}]}}, + {"data_type_id": 3, "kind": "ENUM", "name": "E", "namespace": "", "source_type": "SYSTEM", + "has_definition": true, "definition": {"values": [{"name": "A", "value": "-1"}]}}, + {"data_type_id": 4, "kind": "FUNCTION_DEFINITION", "name": "F", "namespace": "", + "source_type": "SYSTEM", "has_definition": true, "definition": {"return_data_type_id": 2, + "parameters": [{"name": "p", "ordinal": 0, "size": 8, "data_type_id": 2}]}} + ]}"""); + List types = (List) loader.loadClass(ServerDataTypeReader.class.getName()) + .getMethod("readEntries", element, String.class).invoke(null, body, "items"); + assertEquals(3, types.size()); + String text = types.toString(); + assertEquals(text, true, text.contains("Member[name=a, offset=0, size=4, dataTypeId=2, isBitfield=false")); + assertEquals(text, true, text.contains("EnumValue[name=A, value=-1]")); + assertEquals(text, true, text.contains("Parameter[name=p, ordinal=0, size=8, dataTypeId=2]")); + } + } +} From 2e36633ed556f00812fce3d8567c10e0ef1797a2 Mon Sep 17 00:00:00 2001 From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:15:09 +0000 Subject: [PATCH 74/76] feat(ENG-4705): download plugin updates in the background and install them on restart When a newer release is found, download the build for the running Ghidra version, verify it against GitHub's SHA-256 asset digest and unpack it into reai-plugin-update/ in the user settings folder. A shutdown hook starts ExtensionSwapper in its own JVM, which waits for Ghidra to exit and swaps the staged folder over the installed extension, restoring the old one on failure. Adds an 'Install updates automatically' option; with it off, or when the extension is not in the user's Extensions folder, the existing download prompt is shown. --- README.md | 8 + .../services/update/ExtensionSwapper.java | 102 ++++++++ .../core/services/update/UpdateChecker.java | 10 +- .../core/services/update/UpdateInstaller.java | 246 ++++++++++++++++++ .../ghidra/plugins/ReaiAPIServicePlugin.java | 59 ++++- .../services/update/ExtensionSwapperTest.java | 72 +++++ .../services/update/UpdateCheckerTest.java | 10 +- .../services/update/UpdateInstallerTest.java | 84 ++++++ 8 files changed, 586 insertions(+), 5 deletions(-) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java diff --git a/README.md b/README.md index 2c0f44d1..a68b3c2d 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,14 @@ Set `GHIDRA_INSTALL_DIR` to target a specific install, or `REVENG_PLUGIN_VERSION The builds for latest stable version of the RevEng.AI Ghidra plugin for common Ghidra versions can be downloaded from the [Releases](https://github.com/revengai/plugin-ghidra/releases/latest) page. +### Updating + +The plugin checks GitHub for a new release when Ghidra starts. If it finds one, it downloads the build for your Ghidra version in the background and checks it against the SHA-256 checksum GitHub publishes for the release. It then installs that build when you close Ghidra, so the new version runs the next time you start Ghidra. +The download is kept in `reai-plugin-update/` in your Ghidra user settings folder until it is installed. + +This only works when the plugin is installed in your user `Extensions` folder, which is where the install script and `Install Extensions` put it. +You can turn off the check or the automatic install with `Check for updates` and `Install updates automatically` under `Edit` -> `Tool Options...` -> `RevEngAI Options` in the CodeBrowser. With the automatic install off, the plugin only tells you about new releases and links to the download. + ### Supported Ghidra versions We support all versions compatible with Ghidra 11.4+. Ghidra 11.4 through 12.1.x run on Java 21; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java new file mode 100644 index 00000000..5c9490bf --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java @@ -0,0 +1,102 @@ +package ai.reveng.toolkit.ghidra.core.services.update; + +import java.io.IOException; +import java.nio.file.FileSystemException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Comparator; + +/** + * Moves a staged update into the Extensions folder once Ghidra has exited. + *

+ * Ghidra keeps the installed jars open for as long as it runs (and Windows locks open files), so the + * running plugin cannot replace itself. {@link UpdateInstaller} starts this class in a separate JVM as + * Ghidra shuts down. Its classpath is a copy of the plugin jar and nothing else, so it must only use + * the JDK and must not touch {@link UpdateInstaller} or any Ghidra class. + */ +public final class ExtensionSwapper { + /** Folder name of the extension, both installed and inside the release zip. */ + static final String EXTENSION_DIR = "plugin-ghidra"; + /** Holds the staged release tag. Written last when staging and removed on install or skip. */ + static final String READY_FILE = "ready"; + static final String PREVIOUS_DIR = "previous"; + + private static final int MOVE_ATTEMPTS = 10; + + private ExtensionSwapper() {} + + /** Arguments: Ghidra's process id, the installed extension folder, the staging folder. */ + public static void main(String[] args) throws Exception { + long ghidraPid = Long.parseLong(args[0]); + var installed = Path.of(args[1]); + var staging = Path.of(args[2]); + + ProcessHandle.of(ghidraPid).ifPresent(ghidra -> ghidra.onExit().join()); + try { + System.out.println(Instant.now() + " " + swap(installed, staging)); + } catch (Exception e) { + System.out.println(Instant.now() + " Update failed, the previous version is still installed"); + e.printStackTrace(System.out); + } + } + + /** + * Replaces {@code installed} with the extension staged under {@code staging}, restoring the old + * one if the new one cannot be moved in. Returns a line for the update log. + */ + static String swap(Path installed, Path staging) throws IOException, InterruptedException { + var ready = staging.resolve(READY_FILE); + if (!Files.exists(ready)) { + return "No staged update (skipped by the user)"; + } + var version = Files.readString(ready).strip(); + // Ghidra's uninstall renames extension.properties away; don't bring back what the user removed. + if (!Files.exists(installed.resolve("extension.properties"))) { + Files.delete(ready); + return "Not installing " + version + ": the extension is no longer installed at " + installed; + } + + var previous = staging.resolve(PREVIOUS_DIR); + deleteRecursively(previous); + move(installed, previous); + try { + move(staging.resolve(EXTENSION_DIR), installed); + } catch (IOException e) { + move(previous, installed); + throw e; + } + Files.delete(ready); + deleteRecursively(previous); + return "Installed " + version + " into " + installed; + } + + /** Renames {@code from} to {@code to}, retrying while Windows still holds handles from Ghidra. */ + private static void move(Path from, Path to) throws IOException, InterruptedException { + for (int attempt = 1; ; attempt++) { + try { + Files.move(from, to); + return; + } catch (NoSuchFileException e) { + throw e; + } catch (FileSystemException e) { + if (attempt == MOVE_ATTEMPTS) { + throw e; + } + Thread.sleep(1000); + } + } + } + + static void deleteRecursively(Path path) throws IOException { + if (!Files.exists(path)) { + return; + } + try (var paths = Files.walk(path)) { + for (var p : paths.sorted(Comparator.reverseOrder()).toList()) { + Files.delete(p); + } + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java index 07b4daa5..335e2dbd 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java @@ -22,7 +22,11 @@ public class UpdateChecker { private static final String LATEST_RELEASE_URL = "https://api.github.com/repos/RevEngAI/plugin-ghidra/releases/latest"; - public record UpdateInfo(String version, String releaseUrl, String downloadUrl) {} + /** + * @param sha256 hex SHA-256 of the download, from GitHub's asset digest, or null when the + * release does not carry one + */ + public record UpdateInfo(String version, String releaseUrl, String downloadUrl, String sha256) {} /** * The installed plugin's release tag, or {@link #UNKNOWN_VERSION} for local builds. @@ -69,8 +73,10 @@ static Optional findUpdate(String currentVersion, String ghidraVersi for (int i = 0; i < assets.length(); i++) { var asset = assets.getJSONObject(i); if (assetName.equals(asset.getString("name"))) { + var digest = asset.optString("digest", ""); + var sha256 = digest.startsWith("sha256:") ? digest.substring("sha256:".length()) : null; return Optional.of(new UpdateInfo(latest, release.getString("html_url"), - asset.getString("browser_download_url"))); + asset.getString("browser_download_url"), sha256)); } } } catch (JSONException ignored) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java new file mode 100644 index 00000000..3a0f42aa --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java @@ -0,0 +1,246 @@ +package ai.reveng.toolkit.ghidra.core.services.update; + +import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker.UpdateInfo; +import ghidra.framework.Application; +import ghidra.util.Msg; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.zip.ZipInputStream; + +import static ai.reveng.toolkit.ghidra.core.services.update.ExtensionSwapper.EXTENSION_DIR; +import static ai.reveng.toolkit.ghidra.core.services.update.ExtensionSwapper.READY_FILE; + +/** + * Downloads a plugin release in the background and installs it when Ghidra closes. + *

+ * The release is unpacked into a staging folder in the user settings directory, outside + * {@code Extensions/} so Ghidra does not load it as a second copy. As Ghidra shuts down, a shutdown + * hook starts {@link ExtensionSwapper} in its own JVM, which waits for Ghidra to exit and then moves + * the staged folder over the installed one. + */ +public final class UpdateInstaller { + private static final String STAGING_DIR = "reai-plugin-update"; + private static final String DOWNLOAD_FILE = "download.zip"; + // The swapper runs from a copy, so it doesn't hold the jar it is about to replace open. + private static final String UPDATER_JAR = "updater.jar"; + private static final String LOG_FILE = "update.log"; + private static final String PLUGIN_JAR = "lib/plugin-ghidra.jar"; + + // Every CodeBrowser runs its own update check; these keep it to one download and one hook per JVM. + private static final Map> downloads = new HashMap<>(); + private static boolean startupHandled = false; + private static Thread shutdownHook; + + private UpdateInstaller() {} + + /** + * The folder this plugin runs from, if it is one this user can replace: a {@code plugin-ghidra} + * folder in the user's own {@code Extensions/} directory. Empty for a local build or an + * extension installed into the Ghidra installation. + */ + public static Optional installedExtension() { + try { + var installed = Application.getMyModuleRootDirectory().getFile(false).toPath().toRealPath(); + var extensions = Application.getUserSettingsDirectory().toPath().resolve("Extensions").toRealPath(); + if (extensions.equals(installed.getParent()) + && installed.getFileName().toString().equals(EXTENSION_DIR) + && Files.isRegularFile(installed.resolve(PLUGIN_JAR))) { + return Optional.of(installed); + } + } catch (IOException | RuntimeException e) { + Msg.debug(UpdateInstaller.class, "Cannot locate the installed extension", e); + } + return Optional.empty(); + } + + /** + * Logs the result of the last install and then either keeps a staged release newer than + * {@code currentVersion} (so it installs when this session closes, even offline) or removes + * whatever is staged. Only the first call per JVM does anything. + */ + public static synchronized void handleStartup(String currentVersion, Optional installed) { + if (startupHandled) { + return; + } + startupHandled = true; + var staging = stagingDir(); + try { + var log = staging.resolve(LOG_FILE); + if (Files.exists(log)) { + Msg.info(UpdateInstaller.class, "RevEng.AI plugin update: " + Files.readString(log).strip()); + Files.delete(log); + } + var staged = stagedVersion(staging); + if (installed.isPresent() && staged.isPresent() && UpdateChecker.isNewer(staged.get(), currentVersion)) { + registerShutdownHook(installed.get(), staging); + } else { + ExtensionSwapper.deleteRecursively(staging); + } + } catch (IOException e) { + Msg.warn(UpdateInstaller.class, "Cannot clean up the RevEng.AI update folder " + staging, e); + } + } + + /** + * Downloads, verifies and unpacks {@code update}, then arranges for it to be installed over + * {@code installed} when Ghidra exits. Completes exceptionally if any step fails, leaving + * nothing staged. + */ + public static synchronized CompletableFuture stage(UpdateInfo update, Path installed) { + return downloads.computeIfAbsent(update.version(), version -> CompletableFuture.runAsync(() -> { + var staging = stagingDir(); + try { + if (!stagedVersion(staging).orElse("").equals(version)) { + download(update, installed, staging); + } + } catch (IOException e) { + deleteQuietly(staging); + throw new UncheckedIOException(e); + } catch (InterruptedException e) { + deleteQuietly(staging); + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + registerShutdownHook(installed, staging); + })); + } + + /** Drops the staged release so nothing is installed on exit. */ + public static synchronized void cancel() { + downloads.clear(); + deleteQuietly(stagingDir()); + } + + private static void download(UpdateInfo update, Path installed, Path staging) throws IOException, InterruptedException { + ExtensionSwapper.deleteRecursively(staging); + Files.createDirectories(staging); + + var zip = staging.resolve(DOWNLOAD_FILE); + var request = HttpRequest.newBuilder(URI.create(update.downloadUrl())) + .timeout(Duration.ofMinutes(5)) + .build(); + var response = HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.NORMAL) + .connectTimeout(Duration.ofSeconds(10)) + .build() + .send(request, HttpResponse.BodyHandlers.ofFile(zip)); + if (response.statusCode() != 200) { + throw new IOException("Downloading " + update.downloadUrl() + " returned HTTP " + response.statusCode()); + } + verifySha256(zip, update.sha256()); + extract(zip, staging); + Files.delete(zip); + + Files.copy(installed.resolve(PLUGIN_JAR), staging.resolve(UPDATER_JAR)); + Files.writeString(staging.resolve(READY_FILE), update.version()); + } + + static void verifySha256(Path file, String expected) throws IOException { + if (expected == null) { + throw new IOException("The release does not publish a checksum for " + file.getFileName()); + } + try (var in = Files.newInputStream(file)) { + var digest = MessageDigest.getInstance("SHA-256"); + var buffer = new byte[64 * 1024]; + for (int n; (n = in.read(buffer)) != -1; ) { + digest.update(buffer, 0, n); + } + var actual = HexFormat.of().formatHex(digest.digest()); + if (!actual.equalsIgnoreCase(expected)) { + throw new IOException("Checksum mismatch for " + file.getFileName() + ": expected " + expected + ", got " + actual); + } + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** Unpacks the {@code plugin-ghidra/} folder of a release zip into {@code staging}. */ + static void extract(Path zip, Path staging) throws IOException { + var root = staging.resolve(EXTENSION_DIR).normalize(); + try (var in = new ZipInputStream(Files.newInputStream(zip))) { + for (var entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) { + var target = staging.resolve(entry.getName()).normalize(); + if (!target.startsWith(root)) { + throw new IOException("Unexpected entry in release zip: " + entry.getName()); + } + if (entry.isDirectory()) { + Files.createDirectories(target); + } else { + Files.createDirectories(target.getParent()); + // Release zips list some files twice. + Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING); + } + } + } + if (!Files.isRegularFile(root.resolve("extension.properties")) || !Files.isRegularFile(root.resolve(PLUGIN_JAR))) { + throw new IOException(zip.getFileName() + " is not a " + EXTENSION_DIR + " build"); + } + } + + private static synchronized void registerShutdownHook(Path installed, Path staging) { + if (shutdownHook != null) { + return; + } + shutdownHook = new Thread(() -> launchSwapper(installed, staging), "RevEng.AI plugin update"); + Runtime.getRuntime().addShutdownHook(shutdownHook); + } + + private static void launchSwapper(Path installed, Path staging) { + if (!Files.exists(staging.resolve(READY_FILE))) { + return; + } + var bin = Path.of(System.getProperty("java.home"), "bin"); + // javaw has no console window, so nothing flashes up on Windows after Ghidra closes. + var java = Files.exists(bin.resolve("javaw.exe")) ? bin.resolve("javaw.exe") + : Files.exists(bin.resolve("java.exe")) ? bin.resolve("java.exe") + : bin.resolve("java"); + try { + new ProcessBuilder(java.toString(), "-cp", staging.resolve(UPDATER_JAR).toString(), + ExtensionSwapper.class.getName(), + Long.toString(ProcessHandle.current().pid()), installed.toString(), staging.toString()) + .redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.appendTo(staging.resolve(LOG_FILE).toFile())) + .start(); + } catch (IOException e) { + // Ghidra is shutting down, so stderr is the only place left to report this. + System.err.println("RevEng.AI: cannot start the plugin updater: " + e); + } + } + + private static Path stagingDir() { + return Application.getUserSettingsDirectory().toPath().resolve(STAGING_DIR); + } + + static Optional stagedVersion(Path staging) { + try { + var ready = staging.resolve(READY_FILE); + return Files.exists(ready) ? Optional.of(Files.readString(ready).strip()) : Optional.empty(); + } catch (IOException e) { + return Optional.empty(); + } + } + + private static void deleteQuietly(Path path) { + try { + ExtensionSwapper.deleteRecursively(path); + } catch (IOException e) { + Msg.warn(UpdateInstaller.class, "Cannot delete " + path, e); + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java index 22c8a0c5..30615fec 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java @@ -6,6 +6,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.ApiInfo; import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker; import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker.UpdateInfo; +import ai.reveng.toolkit.ghidra.core.services.update.UpdateInstaller; import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardManager; import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardStateKey; @@ -49,6 +50,7 @@ public class ReaiAPIServicePlugin extends Plugin { public static final String REAI_WIZARD_RUN_PREF = "REAISetupWizardRun"; public static final String CHECK_FOR_UPDATES_PREF = "Check for updates"; public static final String SKIPPED_UPDATE_PREF = "Skipped update version"; + public static final String INSTALL_UPDATES_PREF = "Install updates automatically"; public ReaiAPIServicePlugin(PluginTool tool) { super(tool); @@ -56,6 +58,7 @@ public ReaiAPIServicePlugin(PluginTool tool) { tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(REAI_WIZARD_RUN_PREF, "false", null, "If the setup wizard has been run"); tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(CHECK_FOR_UPDATES_PREF, true, null, "Check GitHub for a newer plugin release on startup"); tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(SKIPPED_UPDATE_PREF, "", null, "Release the user chose not to be prompted about"); + tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(INSTALL_UPDATES_PREF, true, null, "Download new releases in the background and install them when Ghidra closes"); // Try to get API info from config file or tool options Optional apiInfoOpt = getApiInfoFromConfig() @@ -80,12 +83,64 @@ public ReaiAPIServicePlugin(PluginTool tool) { private void checkForUpdates() { var currentVersion = UpdateChecker.currentVersion(); - if (!tool.getOptions(REAI_OPTIONS_CATEGORY).getBoolean(CHECK_FOR_UPDATES_PREF, true) + var options = tool.getOptions(REAI_OPTIONS_CATEGORY); + if (!options.getBoolean(CHECK_FOR_UPDATES_PREF, true) || currentVersion.equals(UpdateChecker.UNKNOWN_VERSION)) { return; } + // Empty when updates can't be installed automatically, which also discards anything staged. + var installed = options.getBoolean(INSTALL_UPDATES_PREF, true) + ? UpdateInstaller.installedExtension() + : Optional.empty(); + UpdateInstaller.handleStartup(currentVersion, installed); UpdateChecker.check(currentVersion, Application.getApplicationVersion()) - .thenAccept(result -> result.ifPresent(u -> Swing.runLater(() -> notifyUpdate(u)))); + .thenAccept(result -> result.ifPresent(u -> Swing.runLater(() -> handleUpdate(u, installed)))); + } + + private void handleUpdate(UpdateInfo u, Optional installed) { + var skipped = u.version().equals(tool.getOptions(REAI_OPTIONS_CATEGORY).getString(SKIPPED_UPDATE_PREF, "")); + if (installed.isEmpty() || u.sha256() == null || skipped) { + notifyUpdate(u); + return; + } + UpdateInstaller.stage(u, installed.get()).whenComplete((ignored, error) -> Swing.runLater(() -> { + if (error != null) { + Msg.warn(this, "Could not download RevEng.AI plugin " + u.version() + ", offering a manual download", error); + notifyUpdate(u); + } else { + notifyUpdateReady(u); + } + })); + } + + private void notifyUpdateReady(UpdateInfo u) { + if (isDisposed()) { + return; + } + update = Optional.of(u); + + var message = "RevEng.AI plugin " + u.version() + " has been downloaded. You have " + UpdateChecker.currentVersion() + + ".\nIt will be installed when you close Ghidra. Restart Ghidra to start using it."; + var action = new ActionBuilder("Update ready", this.toString()) + .withContext(ActionContext.class) + .onAction(context -> Msg.showInfo(this, tool.getToolFrame(), "RevEng.AI update ready", message)) + .menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "Update ready (" + u.version() + ") - restart Ghidra" }) + .menuGroup(REAI_PLUGIN_SETUP_MENU_GROUP, "050") + .buildAndInstall(tool); + tool.setStatusInfo("RevEng.AI plugin " + u.version() + " will be installed when Ghidra restarts"); + + if (updatePromptShown) { + return; + } + updatePromptShown = true; + int choice = OptionDialog.showOptionNoCancelDialog(tool.getToolFrame(), "RevEng.AI update ready", + message, "OK", "Skip this version", OptionDialog.INFORMATION_MESSAGE); + if (choice == OptionDialog.OPTION_TWO) { + UpdateInstaller.cancel(); + tool.getOptions(REAI_OPTIONS_CATEGORY).setString(SKIPPED_UPDATE_PREF, u.version()); + tool.removeAction(action); + tool.setStatusInfo("RevEng.AI plugin " + u.version() + " will not be installed"); + } } private void notifyUpdate(UpdateInfo u) { diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java new file mode 100644 index 00000000..67cf58d6 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java @@ -0,0 +1,72 @@ +package ai.reveng.toolkit.ghidra.core.services.update; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** Unit tests for {@link ExtensionSwapper#swap}. */ +public class ExtensionSwapperTest { + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + private Path installed; + private Path staging; + + @Before + public void setUp() throws IOException { + installed = temp.newFolder("Extensions", "plugin-ghidra").toPath(); + Files.writeString(installed.resolve("extension.properties"), "old"); + staging = temp.newFolder("reai-plugin-update").toPath(); + Files.createDirectories(staging.resolve("plugin-ghidra")); + Files.writeString(staging.resolve("plugin-ghidra/extension.properties"), "new"); + Files.writeString(staging.resolve(ExtensionSwapper.READY_FILE), "v1.3.0"); + } + + @Test + public void installsStagedExtension() throws Exception { + var result = ExtensionSwapper.swap(installed, staging); + + assertTrue(result, result.startsWith("Installed v1.3.0")); + assertEquals("new", Files.readString(installed.resolve("extension.properties"))); + assertFalse(Files.exists(staging.resolve(ExtensionSwapper.READY_FILE))); + assertFalse(Files.exists(staging.resolve(ExtensionSwapper.PREVIOUS_DIR))); + } + + @Test + public void doesNothingWhenSkipped() throws Exception { + Files.delete(staging.resolve(ExtensionSwapper.READY_FILE)); + + ExtensionSwapper.swap(installed, staging); + + assertEquals("old", Files.readString(installed.resolve("extension.properties"))); + } + + @Test + public void doesNotReinstallAnUninstalledExtension() throws Exception { + Files.move(installed.resolve("extension.properties"), installed.resolve("extension.properties.uninstalled")); + + ExtensionSwapper.swap(installed, staging); + + assertFalse(Files.exists(installed.resolve("extension.properties"))); + assertFalse(Files.exists(staging.resolve(ExtensionSwapper.READY_FILE))); + } + + @Test + public void restoresPreviousVersionWhenStagedFolderIsMissing() throws Exception { + ExtensionSwapper.deleteRecursively(staging.resolve("plugin-ghidra")); + + assertThrows(IOException.class, () -> ExtensionSwapper.swap(installed, staging)); + + assertEquals("old", Files.readString(installed.resolve("extension.properties"))); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java index f1d83225..00229e07 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** Unit tests for the pure parts of {@link UpdateChecker}. */ @@ -14,7 +15,8 @@ public class UpdateCheckerTest { "html_url": "https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0", "assets": [ {"name": "ghidra_12.1.3_plugin-ghidra.zip", "browser_download_url": "https://example/12.1.3.zip"}, - {"name": "ghidra_12.2_plugin-ghidra.zip", "browser_download_url": "https://example/12.2.zip"} + {"name": "ghidra_12.2_plugin-ghidra.zip", "browser_download_url": "https://example/12.2.zip", + "digest": "sha256:abc123"} ]} """; @@ -40,6 +42,12 @@ public void findsAssetForGhidraVersion() { assertEquals("v1.2.0", update.version()); assertEquals("https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0", update.releaseUrl()); assertEquals("https://example/12.2.zip", update.downloadUrl()); + assertEquals("abc123", update.sha256()); + } + + @Test + public void missingDigestLeavesChecksumUnset() { + assertNull(UpdateChecker.findUpdate("v1.1.0", "12.1.3", RELEASE).orElseThrow().sha256()); } @Test diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java new file mode 100644 index 00000000..5f25dd92 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java @@ -0,0 +1,84 @@ +package ai.reveng.toolkit.ghidra.core.services.update; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** Unit tests for the file handling in {@link UpdateInstaller}. */ +public class UpdateInstallerTest { + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + private Path zip(String... namesAndContents) throws IOException { + var zip = temp.newFile("release.zip").toPath(); + try (var out = new ZipOutputStream(Files.newOutputStream(zip))) { + for (int i = 0; i < namesAndContents.length; i += 2) { + out.putNextEntry(new ZipEntry(namesAndContents[i])); + out.write(namesAndContents[i + 1].getBytes(StandardCharsets.UTF_8)); + out.closeEntry(); + } + } + return zip; + } + + @Test + public void extractsReleaseZip() throws IOException { + var zip = zip("plugin-ghidra/extension.properties", "name=plugin-ghidra", + "plugin-ghidra/lib/plugin-ghidra.jar", "jar"); + var staging = temp.newFolder("staging").toPath(); + + UpdateInstaller.extract(zip, staging); + + assertEquals("name=plugin-ghidra", Files.readString(staging.resolve("plugin-ghidra/extension.properties"))); + assertEquals("jar", Files.readString(staging.resolve("plugin-ghidra/lib/plugin-ghidra.jar"))); + } + + @Test + public void rejectsEntriesOutsideTheExtension() throws IOException { + var zip = zip("plugin-ghidra/../../escaped.txt", "x"); + var staging = temp.newFolder("staging").toPath(); + + assertThrows(IOException.class, () -> UpdateInstaller.extract(zip, staging)); + assertFalse(Files.exists(staging.getParent().resolve("escaped.txt"))); + } + + @Test + public void rejectsZipWithoutPluginJar() throws IOException { + var zip = zip("plugin-ghidra/extension.properties", "name=plugin-ghidra"); + assertThrows(IOException.class, () -> UpdateInstaller.extract(zip, temp.newFolder("staging").toPath())); + } + + @Test + public void verifiesChecksum() throws Exception { + var file = temp.newFile("download.zip").toPath(); + Files.writeString(file, "release"); + var sha256 = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest("release".getBytes(StandardCharsets.UTF_8))); + + UpdateInstaller.verifySha256(file, sha256); + UpdateInstaller.verifySha256(file, sha256.toUpperCase()); + assertThrows(IOException.class, () -> UpdateInstaller.verifySha256(file, "0".repeat(64))); + assertThrows(IOException.class, () -> UpdateInstaller.verifySha256(file, null)); + } + + @Test + public void readsStagedVersion() throws IOException { + var staging = temp.newFolder("staging").toPath(); + assertTrue(UpdateInstaller.stagedVersion(staging).isEmpty()); + Files.writeString(staging.resolve(ExtensionSwapper.READY_FILE), "v1.3.0\n"); + assertEquals("v1.3.0", UpdateInstaller.stagedVersion(staging).orElseThrow()); + } +} From 9336b6bf79bc8fff7cd30c6ebe979628a051b47e Mon Sep 17 00:00:00 2001 From: Rob Marsal Date: Fri, 20 Nov 2026 15:08:25 +0000 Subject: [PATCH 75/76] feat(ENG-3917): link AI decompilation lines to disassembly --- .../aidecompiler/AIDecompilationdWindow.java | 207 ++++++++++++++++++ .../ui/aidecompiler/LineAttributions.java | 108 +++++++++ .../services/api/TypedApiImplementation.java | 8 + .../core/services/api/TypedApiInterface.java | 8 + .../ai/reveng/AIDecompilerComponentTest.java | 120 ++++++++++ .../ui/aidecompiler/LineAttributionsTest.java | 65 ++++++ .../core/services/api/SdkSchemaTest.java | 3 + 7 files changed, 519 insertions(+) create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributions.java create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributionsTest.java diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java index 704d738f..489a865f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java @@ -17,11 +17,21 @@ import docking.action.DockingAction; import docking.action.ToolBarData; import docking.widgets.dialogs.InputDialog; +import docking.widgets.fieldpanel.FieldPanel; +import generic.theme.GColor; import generic.theme.GIcon; +import ghidra.app.events.ProgramHighlightPluginEvent; +import ghidra.app.services.CodeViewerService; +import ghidra.app.util.viewer.listingpanel.ListingPanel; import ghidra.framework.plugintool.ComponentProviderAdapter; import ghidra.framework.plugintool.PluginTool; +import ghidra.program.model.address.Address; +import ghidra.program.model.address.AddressSet; +import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.Program; import ghidra.program.util.ProgramLocation; +import ghidra.program.util.ProgramSelection; import ghidra.util.Msg; import ghidra.util.exception.CancelledException; import ghidra.util.task.*; @@ -35,6 +45,7 @@ import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import java.math.BigInteger; import java.time.Duration; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; @@ -70,6 +81,18 @@ public class AIDecompilationdWindow extends ComponentProviderAdapter { /// completed decompilation is shown. private RenderModel currentRenderModel; + private static final Color ATTRIBUTED_LINE = new GColor("color.bg.highlight"); + + /// Line attributions per function, fetched once its decompilation completes. Cleared with the + /// decompilation on refresh and regenerate. + private final Map attributions = new java.util.concurrent.ConcurrentHashMap<>(); + private final java.util.Set inFlightAttributions = java.util.concurrent.ConcurrentHashMap.newKeySet(); + + /// Last listing location, so attributions arriving later can light the line under the cursor. + private ProgramLocation lastLocation; + /// Program the listing highlight was set on, so only a highlight of ours is cleared. + private Program highlightedProgram; + private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_]\\w*"); @@ -231,6 +254,8 @@ private JComponent buildComponent() { textArea = new RSyntaxTextArea(20, 60); textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_C); textArea.setEditable(false); + // The highlight colour marks attributed lines; a current-line tint would read as one. + textArea.setHighlightCurrentLine(false); // The view stays read-only; edits are driven through double-click (rename) and the // right-click context menu (comments) so they can be synced back to RevEng.AI. textArea.setPopupMenu(null); @@ -239,6 +264,8 @@ private JComponent buildComponent() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) { handleDoubleClick(e.getPoint()); + } else if (e.getClickCount() == 1 && SwingUtilities.isLeftMouseButton(e)) { + highlightFromDecompilation(e.getPoint()); } } @@ -305,6 +332,8 @@ public void setDisplayedValuesBasedOnStatus(Function function, AIDecompilationSt switch (status.status()) { case COMPLETED -> { setCode(renderWithMap(status.decompilation(), status.inlineComments())); + loadAttributions(function); + highlightFromListing(lastLocation); descriptionArea.setText("%s".formatted(status.summary() == null ? "" : status.summary())); String predictedName = status.predictedFunctionName(); @@ -441,12 +470,14 @@ private static String leadingWhitespace(String line) { private void setCode(String code) { String text = code; + textArea.removeAllLineHighlights(); textArea.setText(text); } private void clear() { this.function = null; this.currentRenderModel = null; + clearListingHighlight(); setCode(""); descriptionArea.setText(""); predictedNamePanel.setVisible(false); @@ -504,6 +535,10 @@ public void locationChanged(ProgramLocation loc) { function = newFuncLocation; var functionWithID = analyzedProgram.get().getIDForFunction(function); functionWithID.ifPresent(this::refresh); + + lastLocation = loc; + clearListingHighlight(); + highlightFromListing(loc); } /** @@ -517,6 +552,7 @@ private void refreshCurrentFunction() { return; } cache.remove(target); + attributions.remove(target); currentRenderModel = null; var service = tool.getService(GhidraRevengService.class); var analysed = service.getAnalysedProgram(target.getProgram()); @@ -540,6 +576,7 @@ private void regenerateCurrentFunction() { return; } cache.remove(target); + attributions.remove(target); currentRenderModel = null; tool.getService(ReaiLoggingService.class).info("Regenerating the AI Decompilation for function %s".formatted(target.getName())); setCode(""); @@ -549,6 +586,176 @@ private void regenerateCurrentFunction() { contextChanged(); } + // --- Line attribution highlighting --------------------------------------------------------- + + /// Fetch {@code target}'s line attributions in the background, once. A failure is cached as + /// empty, so a decompilation re-rendered on every poll does not refetch; Refresh retries. + private void loadAttributions(Function target) { + if (target == null || attributions.containsKey(target) || !inFlightAttributions.add(target)) { + return; + } + FunctionID functionID = resolveFunctionId(target); + if (functionID == null) { + inFlightAttributions.remove(target); + return; + } + var service = tool.getService(GhidraRevengService.class); + tool.execute(new Task("Fetch AI decompilation line attributions", false, false, false) { + @Override + public void run(TaskMonitor monitor) { + LineAttributions result = LineAttributions.EMPTY; + try { + var raw = service.getApi().getAIDecompilationLineAttributions(functionID); + if (!raw.isEmpty()) { + result = LineAttributions.of(raw, service.getApi().getAssembly(functionID)); + } + } catch (Exception e) { + Msg.warn(AIDecompilationdWindow.this, + "Failed to fetch line attributions for %s: %s".formatted(target.getName(), e.getMessage())); + } finally { + attributions.put(target, result); + inFlightAttributions.remove(target); + } + SwingUtilities.invokeLater(() -> { + if (isCurrentFunction(target)) { + highlightFromListing(lastLocation); + } + }); + } + }, 0); + } + + /// Light the decompilation lines the instruction at {@code loc} fed, and bring the first into view. + private void highlightFromListing(ProgramLocation loc) { + textArea.removeAllLineHighlights(); + RenderModel model = currentRenderModel; + Function target = this.function; + if (loc == null || model == null || target == null || !target.getBody().contains(loc.getAddress())) { + return; + } + LineAttributions lines = attributions.get(target); + if (lines == null) { + return; + } + CodeUnit codeUnit = loc.getProgram().getListing().getCodeUnitContaining(loc.getAddress()); + Address instruction = codeUnit == null ? loc.getAddress() : codeUnit.getMinAddress(); + var decompilationLines = lines.decompilationLinesFor(instruction.getOffset()); + int first = highlightDecompilationLines(model, decompilationLines); + if (first >= 0) { + try { + var view = textArea.modelToView2D(textArea.getLineStartOffset(first)); + if (view != null) { + textArea.scrollRectToVisible(view.getBounds()); + } + } catch (BadLocationException e) { + // The line went away with a re-render; nothing to scroll to. + } + } + } + + /// Light the clicked decompilation line and the instructions that fed it, and scroll the listing + /// to them. The cursor stays put, so every attributed instruction shows the same colour. + /// A line the model attributed nothing to lights nothing. + private void highlightFromDecompilation(Point point) { + textArea.removeAllLineHighlights(); + clearListingHighlight(); + RenderModel model = currentRenderModel; + Function target = this.function; + LineAttributions lines = target == null ? null : attributions.get(target); + if (model == null || lines == null) { + return; + } + Integer sourceLine; + try { + int offset = textArea.viewToModel2D(point); + sourceLine = offset < 0 ? null : model.sourceLine(textArea.getLineOfOffset(offset)); + } catch (BadLocationException e) { + return; + } + if (sourceLine == null) { + return; + } + var addresses = lines.addressesFor(sourceLine - 1); + if (addresses.isEmpty()) { + return; + } + highlightDecompilationLines(model, List.of(sourceLine - 1)); + + Program program = target.getProgram(); + var space = program.getAddressFactory().getDefaultAddressSpace(); + var set = new AddressSet(); + for (long offset : addresses) { + Address address = space.getAddress(offset); + CodeUnit codeUnit = program.getListing().getCodeUnitAt(address); + if (codeUnit == null) { + set.add(address); + } else { + set.add(codeUnit.getMinAddress(), codeUnit.getMaxAddress()); + } + } + highlightedProgram = program; + tool.firePluginEvent(new ProgramHighlightPluginEvent(getName(), new ProgramSelection(set), program)); + + CodeViewerService codeViewer = tool.getService(CodeViewerService.class); + if (codeViewer != null) { + scrollListing(codeViewer.getListingPanel(), program, target.getEntryPoint(), set.getMinAddress()); + } + } + + /// Put the function's top at the top of the listing when {@code first} still fits on screen + /// below it; otherwise scroll to {@code first}, so the highlight is never off screen. + private static void scrollListing(ListingPanel listing, Program program, Address top, Address first) { + var indexes = listing.getAddressIndexMap(); + BigInteger topIndex = indexes.getIndex(top); + BigInteger firstIndex = indexes.getIndex(first); + FieldPanel fieldPanel = listing.getFieldPanel(); + if (topIndex != null && firstIndex != null && topIndex.compareTo(firstIndex) <= 0) { + int available = fieldPanel.getVisibleRect().height; + int needed = 0; + for (BigInteger i = topIndex; i != null && i.compareTo(firstIndex) <= 0 && needed <= available; + i = fieldPanel.getLayoutModel().getIndexAfter(i)) { + needed += fieldPanel.getHeight(i); + } + if (needed <= available) { + fieldPanel.setViewerPosition(topIndex, 0, 0); + return; + } + } + listing.scrollTo(new ProgramLocation(program, first)); + } + + /// Light every code line rendered from one of the 0-based {@code decompilationLines}. + /// @return the first display line lit, or -1 + private int highlightDecompilationLines(RenderModel model, List decompilationLines) { + int first = -1; + if (decompilationLines.isEmpty()) { + return first; + } + for (int displayLine = 0; displayLine < model.displaySource.size(); displayLine++) { + if (model.isCodeLine(displayLine) && decompilationLines.contains(model.displaySource.get(displayLine) - 1)) { + try { + textArea.addLineHighlight(displayLine, ATTRIBUTED_LINE); + } catch (BadLocationException e) { + continue; + } + if (first < 0) { + first = displayLine; + } + } + } + return first; + } + + private void clearListingHighlight() { + if (highlightedProgram == null) { + return; + } + if (!highlightedProgram.isClosed()) { + tool.firePluginEvent(new ProgramHighlightPluginEvent(getName(), new ProgramSelection(), highlightedProgram)); + } + highlightedProgram = null; + } + // --- Rename / comment editing ------------------------------------------------------------- private void handleDoubleClick(Point point) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributions.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributions.java new file mode 100644 index 00000000..bac3f754 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributions.java @@ -0,0 +1,108 @@ +package ai.reveng.toolkit.ghidra.binarysimilarity.ui.aidecompiler; + +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; + +/// Which instructions fed which AI decompilation lines, as read from +/// `GET /v3/functions/{function_id}/ai-decompilation/line-attributions`. +/// +/// The endpoint numbers both sides by line, 0-based, many-to-many in both directions. Disassembly +/// lines are resolved here to instruction addresses, so the listing can be lit without knowing how +/// the portal laid the assembly out. +/// +/// Mirrors the portal: the model numbered the sequencer trace, which runs one line ahead of the +/// blocks' assembly, so disassembly line `n` is assembly line `n + 1`. +public final class LineAttributions { + + static final int DISASSEMBLY_ROW_OFFSET = 1; + + public static final LineAttributions EMPTY = new LineAttributions(Map.of(), Map.of()); + + private final Map> addressesByDecompilationLine; + private final Map> decompilationLinesByAddress; + + private LineAttributions(Map> addressesByDecompilationLine, + Map> decompilationLinesByAddress) { + this.addressesByDecompilationLine = addressesByDecompilationLine; + this.decompilationLinesByAddress = decompilationLinesByAddress; + } + + /// @param disassemblyToDecompilation the endpoint's map, keyed by disassembly line + /// @param assembly the function's assembly, each line led by its address (`0x401000\tPUSH RBP`) + public static LineAttributions of(Map> disassemblyToDecompilation, List assembly) { + if (disassemblyToDecompilation == null || assembly == null) { + return EMPTY; + } + var byDecompilationLine = new TreeMap>(); + var byAddress = new TreeMap>(); + disassemblyToDecompilation.forEach((rawLine, decompilationLines) -> { + Long address = addressOfRow(assembly, parseLine(rawLine)); + if (address == null || decompilationLines == null) { + return; + } + for (Long decompilationLine : decompilationLines) { + if (decompilationLine == null) { + continue; + } + int line = decompilationLine.intValue(); + byDecompilationLine.computeIfAbsent(line, k -> new TreeSet<>()).add(address); + byAddress.computeIfAbsent(address, k -> new TreeSet<>()).add(line); + } + }); + var addresses = new TreeMap>(); + byDecompilationLine.forEach((line, set) -> addresses.put(line, List.copyOf(set))); + var lines = new TreeMap>(); + byAddress.forEach((address, set) -> lines.put(address, List.copyOf(set))); + return new LineAttributions(addresses, lines); + } + + /// Addresses of the instructions that fed the 0-based decompilation line, ascending. + public List addressesFor(int decompilationLine) { + return addressesByDecompilationLine.getOrDefault(decompilationLine, List.of()); + } + + /// 0-based decompilation lines the instruction at {@code address} fed, ascending. + public List decompilationLinesFor(long address) { + return decompilationLinesByAddress.getOrDefault(address, List.of()); + } + + public boolean isEmpty() { + return addressesByDecompilationLine.isEmpty(); + } + + private static Integer parseLine(String rawLine) { + try { + return Integer.parseInt(rawLine); + } catch (NumberFormatException e) { + return null; + } + } + + private static Long addressOfRow(List assembly, Integer disassemblyLine) { + if (disassemblyLine == null) { + return null; + } + int row = disassemblyLine + DISASSEMBLY_ROW_OFFSET; + if (row < 0 || row >= assembly.size()) { + return null; + } + return parseAddress(assembly.get(row)); + } + + static Long parseAddress(String assemblyLine) { + if (assemblyLine == null) { + return null; + } + String head = assemblyLine.strip().split("\\s+", 2)[0]; + if (!head.startsWith("0x") && !head.startsWith("0X")) { + return null; + } + try { + return Long.parseUnsignedLong(head.substring(2), 16); + } catch (NumberFormatException e) { + return null; + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index ea5256f4..eb6716e2 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -556,6 +556,14 @@ public GetTokensResponse getAIDecompilationTokens(FunctionID functionID) throws return functionsAiDecompilationApi.v3GetAiDecompilationTokens(functionID.value()); } + @Override + public java.util.Map> getAIDecompilationLineAttributions(FunctionID functionID) throws ApiException { + // GET /v3/functions/{function_id}/ai-decompilation/line-attributions + var data = functionsAiDecompilationApi.v3GetAiDecompilationLineAttributions(functionID.value()); + var attributions = data == null ? null : data.getDisassemblyLineNumberToAiDecompilationLineNumbers(); + return attributions == null ? java.util.Map.of() : attributions; + } + @Override public UpsertOverridesData applyAIDecompilationOverrides(FunctionID functionID, java.util.Map overrides) throws ApiException { // PUT /v3/functions/{function_id}/ai-decompilation/overrides diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java index 4a87aba1..eb50c153 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java @@ -118,6 +118,14 @@ default GetTokensResponse getAIDecompilationTokens(FunctionID functionID) throws throw new UnsupportedOperationException("getAIDecompilationTokens not implemented yet"); } + /** + * Each 0-based disassembly line of the function mapped to the 0-based AI decompilation lines it + * fed. Empty when no completed run produced a correspondence. + */ + default java.util.Map> getAIDecompilationLineAttributions(FunctionID functionID) throws ApiException { + throw new UnsupportedOperationException("getAIDecompilationLineAttributions not implemented yet"); + } + /** * Override the display names of variables/types keyed by their tokens. The server re-renders * the decompilation with the overrides applied. diff --git a/src/test/java/ai/reveng/AIDecompilerComponentTest.java b/src/test/java/ai/reveng/AIDecompilerComponentTest.java index ad975e91..1ece7dcb 100644 --- a/src/test/java/ai/reveng/AIDecompilerComponentTest.java +++ b/src/test/java/ai/reveng/AIDecompilerComponentTest.java @@ -677,4 +677,124 @@ public void popupActionsAreDisabledForContextWithoutAddress() throws Exception { assertFalse(name, getAction(tool, name).isEnabledForContext(context)); } } + + /// Moving in the listing lights the decompilation lines an instruction fed; clicking a + /// decompilation line lights its instructions in the listing. + @Test + public void lineAttributionsLinkListingAndDecompilation() throws Exception { + var tool = env.getTool(); + var service = addMockedService(tool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { + return new AnalysisID(1); + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of(new FunctionInfo(new FunctionID(1), "portal_func_1", "portal_func_1_mangled", 0x1000L, 0xf1)); + } + + @Override + public AIDecompilationStatus pollAIDecompileStatus(FunctionID functionID) { + return new AIDecompilationStatus( + DecompilationData.StatusEnum.COMPLETED, + "int func1() {\n int a = 1;\n return a;\n}", + null, + null, + WorkflowProgress.StatusEnum.COMPLETED, + WorkflowProgress.StatusEnum.COMPLETED, + List.of(), + null); + } + + @Override + public Map> getAIDecompilationLineAttributions(FunctionID functionID) { + return Map.of("0", List.of(1L), "1", List.of(2L), "2", List.of(3L)); + } + + @Override + public List getAssembly(FunctionID functionID) { + return List.of("0x1000\tPUSH RBP", "0x1001\tMOV EAX,0x1", "0x1006\tRET", "0x10f0\tRET"); + } + }); + + var codeBrowser = env.addPlugin(ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin.class); + env.addPlugin(BinarySimilarityPlugin.class); + var builder = newX64Program(); + builder.createMemory(".text", "0x1000", 0x100); + // PUSH RBP; MOV EAX,0x1; RET + builder.setBytes("0x1000", "55 b8 01 00 00 00 c3", true); + // A RET far enough down that the function header and it cannot share the screen + builder.setBytes("0x10f0", "c3", true); + var func1 = builder.createEmptyFunction(null, "0x1000", 0xf1, Undefined.getUndefinedDataType(4)); + var programWithID = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + var program = programWithID.program(); + env.showTool(program); + // Room for the function header and its first few instructions + runSwing(() -> tool.getToolFrame().setSize(1200, 1000)); + waitForSwing(); + + var aiDecompComponent = getComponentProvider(AIDecompilationdWindow.class); + RSyntaxTextArea textArea = (RSyntaxTextArea) getInstanceField("textArea", aiDecompComponent); + var action = getAction(tool, "AI Decompilation"); + performAction(action, new ProgramLocationActionContext(null, program, + new ProgramLocation(program, func1.getEntryPoint()), null, null), true); + waitForTasks(); + waitForSwing(); + + goTo(tool, program, program.getAddressFactory().getDefaultAddressSpace().getAddress(0x1001)); + waitForSwing(); + assertEquals(List.of(1), highlightedLines(textArea)); + + goTo(tool, program, func1.getEntryPoint()); + waitForSwing(); + assertEquals(List.of(), highlightedLines(textArea)); + + // Scroll the function header off screen, so the click has to bring it back + goTo(tool, program, program.getAddressFactory().getDefaultAddressSpace().getAddress(0x10f0)); + waitForSwing(); + + var cursor = codeBrowser.getCurrentAddress(); + var lineTwo = textArea.modelToView2D(textArea.getLineStartOffset(2)).getBounds(); + clickMouse(textArea, java.awt.event.MouseEvent.BUTTON1, lineTwo.x + 1, lineTwo.y + 1, 1, 0); + waitForSwing(); + var highlight = codeBrowser.getProvider().getHighlight(); + var space = program.getAddressFactory().getDefaultAddressSpace(); + assertTrue(highlight.contains(space.getAddress(0x1006))); + assertFalse(highlight.contains(space.getAddress(0x1001))); + assertEquals("the cursor must stay put", cursor, codeBrowser.getCurrentAddress()); + assertEquals(List.of(2), highlightedLines(textArea)); + assertFalse(textArea.getHighlightCurrentLine()); + var listing = codeBrowser.getProvider().getListingPanel(); + var indexes = listing.getAddressIndexMap(); + assertEquals("a nearby instruction leaves the function header on top", + indexes.getIndex(func1.getEntryPoint()), listing.getFieldPanel().getViewerPosition().getIndex()); + + var lineThree = textArea.modelToView2D(textArea.getLineStartOffset(3)).getBounds(); + clickMouse(textArea, java.awt.event.MouseEvent.BUTTON1, lineThree.x + 1, lineThree.y + 1, 1, 0); + waitForSwing(); + var farIndex = indexes.getIndex(space.getAddress(0x10f0)); + assertTrue("a distant instruction is scrolled into view", listing.getFieldPanel().getVisibleLayouts() + .stream().anyMatch(layout -> layout.getIndex().equals(farIndex))); + assertNotEquals(indexes.getIndex(func1.getEntryPoint()), listing.getFieldPanel().getViewerPosition().getIndex()); + } + + @SuppressWarnings("unchecked") + private static List highlightedLines(RSyntaxTextArea textArea) throws Exception { + Object manager = invokeInstanceMethod("getLineHighlightManager", textArea); + if (manager == null) { + return List.of(); + } + var lines = new java.util.ArrayList(); + for (Object tag : (List) invokeInstanceMethod("getCurrentLineHighlightTags", manager)) { + lines.add(textArea.getLineOfOffset((int) invokeInstanceMethod("getOffset", tag))); + } + java.util.Collections.sort(lines); + return lines; + } } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributionsTest.java b/src/test/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributionsTest.java new file mode 100644 index 00000000..e984d71a --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/LineAttributionsTest.java @@ -0,0 +1,65 @@ +package ai.reveng.toolkit.ghidra.binarysimilarity.ui.aidecompiler; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; + +public class LineAttributionsTest { + + private static final List ASSEMBLY = List.of( + "0x401000\tPUSH RBP", + "0x401001\tMOV RBP,RSP", + "0x401004\tMOV EAX,0x1", + "0x401009\tPOP RBP", + "0x40100a\tRET"); + + @Test + public void disassemblyLinesAreOneRowBehindTheAssembly() { + var attributions = LineAttributions.of(Map.of("0", List.of(2L)), ASSEMBLY); + + assertEquals(List.of(0x401001L), attributions.addressesFor(2)); + assertEquals(List.of(2), attributions.decompilationLinesFor(0x401001L)); + assertEquals(List.of(), attributions.decompilationLinesFor(0x401000L)); + } + + @Test + public void manyToManyInBothDirections() { + var attributions = LineAttributions.of(Map.of( + "1", List.of(3L, 4L), + "2", List.of(4L)), ASSEMBLY); + + assertEquals(List.of(0x401004L, 0x401009L), attributions.addressesFor(4)); + assertEquals(List.of(0x401004L), attributions.addressesFor(3)); + assertEquals(List.of(3, 4), attributions.decompilationLinesFor(0x401004L)); + } + + @Test + public void unresolvableEntriesAreSkipped() { + var raw = new HashMap>(); + raw.put("x", List.of(1L)); + raw.put("4", List.of(1L)); // row 5, past the end + raw.put("-2", List.of(1L)); // row -1 + raw.put("3", null); + var attributions = LineAttributions.of(raw, ASSEMBLY); + + assertTrue(attributions.isEmpty()); + } + + @Test + public void assemblyWithoutAnAddressContributesNothing() { + var attributions = LineAttributions.of(Map.of("0", List.of(1L)), List.of("PUSH RBP", "MOV RBP,RSP")); + + assertTrue(attributions.isEmpty()); + } + + @Test + public void addressesPastLongMaxParse() { + assertEquals(Long.valueOf(0xffffffff80001000L), LineAttributions.parseAddress("0xffffffff80001000\tNOP")); + assertEquals(Long.valueOf(0x140001000L), LineAttributions.parseAddress("0x140001000 PUSH RBP")); + assertNull(LineAttributions.parseAddress("label:")); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java index 8da17ab7..49758b15 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java @@ -65,6 +65,7 @@ public void apiClientsExposeMethodsThePluginCalls() { apis.put("ai.reveng.api.FunctionsAiDecompilationApi", new String[]{ "createAiDecompilation", "getAiDecompilation", "getAiDecompilationStatus", "v3GetAiDecompilationTokens", "v3UpsertAiDecompilationOverrides", + "v3GetAiDecompilationLineAttributions", "getAiDecompilationSummary", "getAiDecompilationSummaryStatus", "getAiDecompilationInlineComments", "getAiDecompilationInlineCommentsStatus", "patchAiDecompilationInlineComment", "deleteAiDecompilationInlineComment", @@ -194,6 +195,8 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.RenderedToken", "getValue", "getDataTypeId", "getFunctionId", "getImportedFunctionId"); requireMethods(missing, "ai.reveng.model.Token", "getValue"); + requireMethods(missing, "ai.reveng.model.LineAttributionsData", + "getDisassemblyLineNumberToAiDecompilationLineNumbers"); requireMethods(missing, "ai.reveng.model.UpsertOverridesInputBody", "getOverrides"); // The AI decompilation poll: the decompilation itself, its pipeline progress while it runs, From 0bdd2b07a0862e1f8e9685d226dda97c877c4ab5 Mon Sep 17 00:00:00 2001 From: Rob Marsal Date: Mon, 23 Nov 2026 12:29:04 +0000 Subject: [PATCH 76/76] feat(ENG-3917): light disassembly on any caret move --- .../aidecompiler/AIDecompilationdWindow.java | 39 +++++++++++++------ .../ai/reveng/AIDecompilerComponentTest.java | 13 +++++++ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java index 489a865f..d4ff8610 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java @@ -92,6 +92,8 @@ public class AIDecompilationdWindow extends ComponentProviderAdapter { private ProgramLocation lastLocation; /// Program the listing highlight was set on, so only a highlight of ours is cleared. private Program highlightedProgram; + private boolean settingCode; + private int caretLine = -1; private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_]\\w*"); @@ -264,8 +266,6 @@ private JComponent buildComponent() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) { handleDoubleClick(e.getPoint()); - } else if (e.getClickCount() == 1 && SwingUtilities.isLeftMouseButton(e)) { - highlightFromDecompilation(e.getPoint()); } } @@ -285,6 +285,20 @@ private void maybeShowPopup(MouseEvent e) { } } }); + textArea.addCaretListener(e -> { + if (settingCode) { + return; + } + try { + int line = textArea.getLineOfOffset(e.getDot()); + if (line != caretLine) { + caretLine = line; + highlightFromDecompilation(line); + } + } catch (BadLocationException ignored) { + // The caret outran a re-render; the next move lights its line. + } + }); sp = new RTextScrollPane(textArea); component.add(sp, BorderLayout.CENTER); @@ -471,7 +485,13 @@ private static String leadingWhitespace(String line) { private void setCode(String code) { String text = code; textArea.removeAllLineHighlights(); - textArea.setText(text); + settingCode = true; + try { + textArea.setText(text); + } finally { + settingCode = false; + } + caretLine = -1; } private void clear() { @@ -628,6 +648,7 @@ public void run(TaskMonitor monitor) { /// Light the decompilation lines the instruction at {@code loc} fed, and bring the first into view. private void highlightFromListing(ProgramLocation loc) { textArea.removeAllLineHighlights(); + caretLine = -1; RenderModel model = currentRenderModel; Function target = this.function; if (loc == null || model == null || target == null || !target.getBody().contains(loc.getAddress())) { @@ -653,10 +674,10 @@ private void highlightFromListing(ProgramLocation loc) { } } - /// Light the clicked decompilation line and the instructions that fed it, and scroll the listing + /// Light the caret's decompilation line and the instructions that fed it, and scroll the listing /// to them. The cursor stays put, so every attributed instruction shows the same colour. /// A line the model attributed nothing to lights nothing. - private void highlightFromDecompilation(Point point) { + private void highlightFromDecompilation(int displayLine) { textArea.removeAllLineHighlights(); clearListingHighlight(); RenderModel model = currentRenderModel; @@ -665,13 +686,7 @@ private void highlightFromDecompilation(Point point) { if (model == null || lines == null) { return; } - Integer sourceLine; - try { - int offset = textArea.viewToModel2D(point); - sourceLine = offset < 0 ? null : model.sourceLine(textArea.getLineOfOffset(offset)); - } catch (BadLocationException e) { - return; - } + Integer sourceLine = model.sourceLine(displayLine); if (sourceLine == null) { return; } diff --git a/src/test/java/ai/reveng/AIDecompilerComponentTest.java b/src/test/java/ai/reveng/AIDecompilerComponentTest.java index 1ece7dcb..b0882343 100644 --- a/src/test/java/ai/reveng/AIDecompilerComponentTest.java +++ b/src/test/java/ai/reveng/AIDecompilerComponentTest.java @@ -782,6 +782,19 @@ public List getAssembly(FunctionID functionID) { assertTrue("a distant instruction is scrolled into view", listing.getFieldPanel().getVisibleLayouts() .stream().anyMatch(layout -> layout.getIndex().equals(farIndex))); assertNotEquals(indexes.getIndex(func1.getEntryPoint()), listing.getFieldPanel().getViewerPosition().getIndex()); + + runSwing(() -> { + try { + textArea.setCaretPosition(textArea.getLineStartOffset(1)); + } catch (javax.swing.text.BadLocationException e) { + throw new RuntimeException(e); + } + }); + waitForSwing(); + highlight = codeBrowser.getProvider().getHighlight(); + assertTrue("moving the caret by keyboard lights its instructions", highlight.contains(space.getAddress(0x1001))); + assertFalse(highlight.contains(space.getAddress(0x1006))); + assertEquals(List.of(1), highlightedLines(textArea)); } @SuppressWarnings("unchecked")