Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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("<html><center>%s</center></html>"
.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;
Expand All @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Path> 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();
}
}
37 changes: 30 additions & 7 deletions src/test/java/ai/reveng/AnalysisOptionsDialogTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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(() -> {
Expand Down Expand Up @@ -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(() -> {
Expand Down Expand Up @@ -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(() -> {
Expand Down Expand Up @@ -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(() -> {
Expand Down Expand Up @@ -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(() -> {
Expand Down Expand Up @@ -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);
Expand All @@ -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(() -> {
Expand Down Expand Up @@ -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(() -> {
Expand Down
38 changes: 38 additions & 0 deletions src/test/java/ai/reveng/GhidraRevengServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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];
Expand Down
Loading
Loading