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/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/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java index 704d738f..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 @@ -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,20 @@ 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 boolean settingCode; + private int caretLine = -1; + private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_]\\w*"); @@ -231,6 +256,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); @@ -258,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); @@ -305,6 +346,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 +484,20 @@ private static String leadingWhitespace(String line) { private void setCode(String code) { String text = code; - textArea.setText(text); + textArea.removeAllLineHighlights(); + settingCode = true; + try { + textArea.setText(text); + } finally { + settingCode = false; + } + caretLine = -1; } private void clear() { this.function = null; this.currentRenderModel = null; + clearListingHighlight(); setCode(""); descriptionArea.setText(""); predictedNamePanel.setVisible(false); @@ -504,6 +555,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 +572,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 +596,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 +606,171 @@ 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(); + caretLine = -1; + 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 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(int displayLine) { + 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 = model.sourceLine(displayLine); + 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/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/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/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/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/AIDecompilerComponentTest.java b/src/test/java/ai/reveng/AIDecompilerComponentTest.java index ad975e91..b0882343 100644 --- a/src/test/java/ai/reveng/AIDecompilerComponentTest.java +++ b/src/test/java/ai/reveng/AIDecompilerComponentTest.java @@ -677,4 +677,137 @@ 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()); + + 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") + 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/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..cc8f68b8 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -12,15 +12,21 @@ import ghidra.framework.plugintool.mgr.ServiceManager; import ghidra.framework.plugintool.util.PluginException; import ghidra.program.database.ProgramBuilder; +import ghidra.program.model.listing.Program; +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.security.MessageDigest; import java.time.Duration; import java.util.HashMap; +import java.util.HexFormat; import java.util.Map; import java.util.function.BooleanSupplier; @@ -71,6 +77,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(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); + } + } 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) { 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/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]")); + } + } +} 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, 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()); + } +}