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 63422ed..6e3760a 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 b479351..bb341f0 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 0000000..719956b --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/OriginalBinary.java @@ -0,0 +1,88 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ghidra.program.database.mem.FileBytes; +import ghidra.program.model.listing.Program; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Optional; + +/// The file a program was imported from. +/// +/// Ghidra records the importer's path, which is missing on other machines (e.g. in a shared project), +/// but its loaders also store the file's bytes in the program, which travel with it. +public final class OriginalBinary { + private static final int CHUNK = 1 << 20; + + private OriginalBinary() { + } + + public static Path importPath(Program program) { + try { + return Path.of(program.getExecutablePath()); + } catch (InvalidPathException e) { + // On Windows the path looks like "/C:/vfcompat.dll" + return Path.of(program.getExecutablePath().substring(1)); + } + } + + /// Size of the original file, from the stored bytes if present, else from disk. + public static long size(Program program) throws IOException { + FileBytes stored = stored(program); + return stored != null ? stored.getSize() : Files.size(importPath(program)); + } + + /// Writes the stored bytes to a new temporary directory, under the original file name. + /// Empty if none are stored or they don't hash to the program's SHA-256. + public static Optional extract(Program program) throws IOException { + FileBytes stored = stored(program); + if (stored == null) { + return Optional.empty(); + } + Path name = importPath(program).getFileName(); + Path file = Files.createTempDirectory("reai-upload").resolve(name != null ? name.toString() : program.getName()); + MessageDigest sha256; + try { + sha256 = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + byte[] buffer = new byte[CHUNK]; + try (OutputStream out = Files.newOutputStream(file)) { + for (long offset = 0; offset < stored.getSize(); ) { + int read = stored.getOriginalBytes(offset, buffer, 0, (int) Math.min(CHUNK, stored.getSize() - offset)); + out.write(buffer, 0, read); + sha256.update(buffer, 0, read); + offset += read; + } + } + if (!HexFormat.of().formatHex(sha256.digest()).equalsIgnoreCase(program.getExecutableSHA256())) { + delete(file); + return Optional.empty(); + } + return Optional.of(file); + } + + /// Deletes a file returned by {@link #extract} and its directory. + public static void delete(Path extracted) throws IOException { + Files.deleteIfExists(extracted); + Files.deleteIfExists(extracted.getParent()); + } + + public static String notFoundMessage(Path path) { + return "Original binary not found at %s and not stored in the program. Copy it to that path or re-import it." + .formatted(path); + } + + private static @Nullable FileBytes stored(Program program) { + var all = program.getMemory().getAllFileBytes(); + return all.isEmpty() ? null : all.getFirst(); + } +} diff --git a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java index 467575f..03df147 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 9218b68..4970b6e 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 ab79aae..cc8f68b 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) {