From 9336b6bf79bc8fff7cd30c6ebe979628a051b47e Mon Sep 17 00:00:00 2001 From: Rob Marsal Date: Fri, 20 Nov 2026 15:08:25 +0000 Subject: [PATCH] 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,