items = context.deserialize(array, type);
- return items == null ? List.of() : items;
+ return items == null ? List.of() : items.stream().filter(Objects::nonNull).toList();
}
private static String string(JsonObject owner, String field) {
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java
index 037e3600..70969fd2 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfo.java
@@ -15,7 +15,12 @@ public record ApiInfo(
String apiKey
) {
public ApiInfo(String hostURI, String portalURI, String apiKey) {
- this(URI.create(hostURI), URI.create(portalURI), apiKey);
+ this(URI.create(normaliseHost(hostURI)), URI.create(normaliseHost(portalURI)), apiKey);
+ }
+
+ public static String normaliseHost(String host) {
+ var normalised = host.strip().replaceAll("/+$", "");
+ return normalised.isEmpty() || normalised.contains("://") ? normalised : "https://" + normalised;
}
public static ApiInfo fromConfig(Path configFilePath) throws FileNotFoundException {
@@ -27,6 +32,9 @@ public static ApiInfo fromConfig(Path configFilePath) throws FileNotFoundExcepti
} catch (java.io.IOException e) {
throw new RuntimeException("Failed to read config file: " + configFilePath, e);
}
+ if (config == null || config.getPluginSettings() == null) {
+ throw new JSONException("Invalid config file: pluginSettings missing");
+ }
var apikey = config.getPluginSettings().getApiKey();
var hostname = config.getPluginSettings().getHostname();
var portalHostname = config.getPluginSettings().getPortalHostname();
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java
index 14ce1906..6c042552 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/FunctionMatch.java
@@ -22,7 +22,8 @@ public record FunctionMatch(
TypedApiInterface.BinaryHash nearest_neighbor_sha_256_hash,
Boolean nearest_neighbor_debug,
BigDecimal similarity,
- BigDecimal confidence
+ BigDecimal confidence,
+ @Nullable TypedApiInterface.AnalysisID nearest_neighbor_analysis_id
) {
@@ -36,7 +37,8 @@ public static FunctionMatch fromMatchedFunctionAPIType(MatchedFunction matchedFu
new TypedApiInterface.BinaryHash(matchedFunction.getSha256Hash()),
matchedFunction.getDebug(),
matchedFunction.getSimilarity() == null ? null : BigDecimal.valueOf(matchedFunction.getSimilarity()),
- matchedFunction.getConfidence() == null ? null : BigDecimal.valueOf(matchedFunction.getConfidence())
+ matchedFunction.getConfidence() == null ? null : BigDecimal.valueOf(matchedFunction.getConfidence()),
+ matchedFunction.getAnalysisId() == null ? null : new TypedApiInterface.AnalysisID(Math.toIntExact(matchedFunction.getAnalysisId()))
);
}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java
index 5a572744..d16bd4e0 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndName.java
@@ -2,6 +2,8 @@
import ghidra.program.model.data.CategoryPath;
+import java.util.Arrays;
+
/// A scoped type name split into its Ghidra {@link CategoryPath} and its leaf name.
///
/// The server reports a type's scope in a `namespace` field, using `::` as the separator, e.g.
@@ -20,7 +22,10 @@ public record TypePathAndName(
public static TypePathAndName fromString(String str){
// split into path and name on "::"
if (str.contains("::")) {
- String[] pathPlusType = str.split("::");
+ String[] pathPlusType = Arrays.stream(str.split("::", -1)).filter(s -> !s.isEmpty()).toArray(String[]::new);
+ if (pathPlusType.length == 0) {
+ return new TypePathAndName("", new String[0]);
+ }
var baseType = pathPlusType[pathPlusType.length - 1];
String[] parts = new String[pathPlusType.length - 1];
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java
index 4c518469..178088d1 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/AutoUnstripSyncService.java
@@ -3,12 +3,14 @@
import ai.reveng.invoker.ApiException;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService.AnalysedProgram;
+import ai.reveng.toolkit.ghidra.core.services.api.PushFailure;
import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID;
import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AutoUnstripStatus;
import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService;
import ghidra.util.Msg;
-import ghidra.util.task.TaskMonitor;
+import ghidra.util.task.TaskMonitorAdapter;
+import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
@@ -24,25 +26,50 @@
* pull and would otherwise only appear after a manual refresh.
*
* Mirrors the IDA plugin's {@code AutoUnstripStatusService} + {@code AutoUnstripStatusCoordinator}:
- * a background thread polls the status endpoint every {@link #POLL_INTERVAL_SECONDS} seconds and, on
+ * a background thread polls the status endpoint every {@link #DEFAULT_POLL_INTERVAL} and, on
* completion, runs the same reconciliation the "Sync With Portal" action uses.
+ *
+ *
Polling stops when auto-unstrip completes or fails, when {@link #stopPolling} is called (even
+ * if a poll or the sync is running at that moment), after {@link #DEFAULT_MAX_POLL_DURATION}, or on
+ * an error a retry cannot fix. A transient error (no connection, timeout, 5xx) backs off and retries
+ * within that time limit. Every way of giving up is reported in the log and the status bar, except
+ * for an analysis whose auto-unstrip never starts within {@link #NOT_STARTED_GRACE}: that is not a
+ * failure, so polling ends quietly.
*/
public class AutoUnstripSyncService {
- private static final long POLL_INTERVAL_SECONDS = 5;
+ public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5);
+ public static final Duration DEFAULT_MAX_POLL_DURATION = Duration.ofMinutes(30);
+ /// How long an analysis may report auto-unstrip as not started (UNINITIALISED or UNKNOWN) before
+ /// polling assumes it will never run. Capped by the overall time limit.
+ public static final Duration NOT_STARTED_GRACE = Duration.ofMinutes(5);
+ /// Longest wait between polls while the status endpoint keeps failing transiently.
+ private static final Duration MAX_BACKOFF = Duration.ofSeconds(60);
private final GhidraRevengService revengService;
private final ReaiLoggingService loggingService;
/// Surfaces a progress message to the user (text, isWarning); wired to the tool status bar in the plugin.
private final BiConsumer statusNotifier;
+ private final long pollIntervalMillis;
+ private final Duration maxPollDuration;
+ private final Duration notStartedGrace;
private final ScheduledExecutorService scheduler;
- private final Map> pollers = new ConcurrentHashMap<>();
+ private final Map pollers = new ConcurrentHashMap<>();
public AutoUnstripSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService,
BiConsumer statusNotifier) {
+ this(revengService, loggingService, statusNotifier, DEFAULT_POLL_INTERVAL, DEFAULT_MAX_POLL_DURATION);
+ }
+
+ public AutoUnstripSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService,
+ BiConsumer statusNotifier,
+ Duration pollInterval, Duration maxPollDuration) {
this.revengService = revengService;
this.loggingService = loggingService;
this.statusNotifier = statusNotifier;
+ this.pollIntervalMillis = pollInterval.toMillis();
+ this.maxPollDuration = maxPollDuration;
+ this.notStartedGrace = NOT_STARTED_GRACE.compareTo(maxPollDuration) < 0 ? NOT_STARTED_GRACE : maxPollDuration;
this.scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
var thread = new Thread(runnable, "RevEng.AI-AutoUnstripSync");
thread.setDaemon(true);
@@ -60,75 +87,240 @@ public AutoUnstripSyncService(GhidraRevengService revengService, ReaiLoggingServ
* and is not re-synced.
*/
public void pollAndSync(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete) {
- stopPolling(analysedProgram.analysisID());
- schedule(analysedProgram, resyncIfAlreadyComplete, true, 0);
+ var poller = new Poller(analysedProgram, resyncIfAlreadyComplete);
+ var previous = pollers.put(analysedProgram.analysisID(), poller);
+ if (previous != null) {
+ previous.cancel();
+ }
+ poller.schedule(0);
}
- public void stopPolling(AnalysisID analysisID) {
+ /// Stop polling for the given analysis. A poll that is running right now neither reschedules
+ /// nor starts a sync afterwards, and a sync that is running is cancelled and rolls back.
+ ///
+ /// @return whether polling was still active for the analysis
+ public boolean stopPolling(AnalysisID analysisID) {
var existing = pollers.remove(analysisID);
if (existing != null) {
- existing.cancel(false);
+ existing.cancel();
+ return true;
}
+ return false;
}
public void dispose() {
- pollers.values().forEach(future -> future.cancel(false));
+ pollers.values().forEach(Poller::cancel);
pollers.clear();
scheduler.shutdownNow();
}
- private void schedule(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete,
- boolean firstPoll, long delaySeconds) {
- var future = scheduler.schedule(
- () -> poll(analysedProgram, resyncIfAlreadyComplete, firstPoll),
- delaySeconds, TimeUnit.SECONDS);
- pollers.put(analysedProgram.analysisID(), future);
- }
+ /// One polling run for one analysis. Cancelling it is final, so a replaced or stopped run can
+ /// never put itself back on the schedule.
+ private final class Poller {
+ private final AnalysedProgram analysedProgram;
+ private final boolean resyncIfAlreadyComplete;
+ private final long startNanos = System.nanoTime();
+ /// Cancelled together with the poller, so a sync that is running stops and rolls back.
+ private final TaskMonitorAdapter syncMonitor = new TaskMonitorAdapter(true);
+ private boolean firstPoll = true;
+ private boolean started = false;
+ private int consecutiveFailures = 0;
+ private String lastFailure;
+ /// Guarded by {@code this}
+ private boolean cancelled = false;
+ /// Guarded by {@code this}
+ private ScheduledFuture> future;
- private void poll(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete, boolean firstPoll) {
- AutoUnstripStatus status;
- try {
- status = revengService.getAutoUnstripStatus(analysedProgram.analysisID());
- } catch (ApiException e) {
- pollers.remove(analysedProgram.analysisID());
- loggingService.warn("Failed to poll auto-unstrip status: " + e.getMessage());
- return;
+ Poller(AnalysedProgram analysedProgram, boolean resyncIfAlreadyComplete) {
+ this.analysedProgram = analysedProgram;
+ this.resyncIfAlreadyComplete = resyncIfAlreadyComplete;
}
- switch (status) {
- case COMPLETED -> {
- pollers.remove(analysedProgram.analysisID());
- if (firstPoll && !resyncIfAlreadyComplete) {
+ synchronized void cancel() {
+ cancelled = true;
+ syncMonitor.cancel();
+ if (future != null) {
+ future.cancel(false);
+ }
+ }
+
+ synchronized boolean isCancelled() {
+ return cancelled;
+ }
+
+ synchronized void schedule(long delayMillis) {
+ if (!cancelled) {
+ future = scheduler.schedule(this::pollSafely, delayMillis, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ /// Leave the map, unless a newer run for the same analysis has already replaced this one.
+ void finish() {
+ pollers.remove(analysedProgram.analysisID(), this);
+ }
+
+ private void pollSafely() {
+ try {
+ poll();
+ } catch (RuntimeException e) {
+ finish();
+ Msg.warn(AutoUnstripSyncService.this, "Auto-unstrip polling failed", e);
+ if (!isCancelled()) {
+ announce("RevEng.AI: stopped waiting for auto-unstrip after an unexpected error (%s). "
+ .formatted(e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName())
+ + "Use Sync With Portal to pull the recovered names later.", true);
+ }
+ }
+ }
+
+ private void poll() {
+ if (isCancelled()) {
+ return;
+ }
+ AutoUnstripStatus status;
+ try {
+ status = revengService.getAutoUnstripStatus(analysedProgram.analysisID());
+ } catch (ApiException | RuntimeException e) {
+ // The typed API wraps some ApiExceptions in a RuntimeException; PushFailure finds them.
+ if (isCancelled()) {
+ return;
+ }
+ var failure = PushFailure.of(e);
+ if (failure != PushFailure.TRANSIENT) {
+ finish();
+ var remedy = failure == PushFailure.AUTH
+ ? "Check the RevEng.AI API key in the plugin configuration."
+ : "Use Sync With Portal to pull the recovered names later.";
+ announce("RevEng.AI: stopped waiting for auto-unstrip, the status check failed (%s). "
+ .formatted(describe(e)) + remedy, true);
return;
}
- runSync(analysedProgram);
+ consecutiveFailures++;
+ lastFailure = describe(e);
+ if (consecutiveFailures == 1) {
+ // Logged once per outage, so a portal that is down for a while does not flood the log.
+ loggingService.warn("Checking the auto-unstrip status failed (%s); retrying with back-off."
+ .formatted(lastFailure));
+ }
+ rescheduleOrGiveUp(backoffMillis());
+ return;
+ }
+ if (isCancelled()) {
+ return;
+ }
+ if (consecutiveFailures > 0) {
+ loggingService.info("Checking the auto-unstrip status works again.");
+ consecutiveFailures = 0;
}
- case FAILED -> {
- pollers.remove(analysedProgram.analysisID());
- announce("RevEng.AI auto-unstrip failed; recovered names were not synced.", true);
+
+ switch (status) {
+ case COMPLETED -> {
+ if (firstPoll && !resyncIfAlreadyComplete) {
+ finish();
+ return;
+ }
+ // Stays in the map while syncing, so stopPolling (e.g. Detach) can still cancel it.
+ try {
+ runSync();
+ } finally {
+ finish();
+ }
+ }
+ case FAILED -> {
+ finish();
+ if (!isCancelled()) {
+ announce("RevEng.AI auto-unstrip failed; recovered names were not synced.", true);
+ }
+ }
+ case UNINITIALISED, UNKNOWN -> {
+ firstPoll = false;
+ if (!started && Duration.ofNanos(System.nanoTime() - startNanos).compareTo(notStartedGrace) >= 0) {
+ // Auto-unstrip never started for this analysis; there is nothing to wait for or report.
+ finish();
+ loggingService.info("Auto-unstrip has not started for analysis %d; not waiting for it."
+ .formatted(analysedProgram.analysisID().id()));
+ return;
+ }
+ rescheduleOrGiveUp(pollIntervalMillis);
+ }
+ default -> {
+ if (!started) {
+ announce("RevEng.AI: waiting for auto-unstrip to finish before syncing recovered "
+ + "function names and data types…", false);
+ }
+ started = true;
+ firstPoll = false;
+ rescheduleOrGiveUp(pollIntervalMillis);
+ }
}
- default -> {
- if (firstPoll) {
- announce("RevEng.AI: waiting for auto-unstrip to finish before syncing recovered "
- + "function names and data types…", false);
+ }
+
+ private long backoffMillis() {
+ int doublings = Math.min(consecutiveFailures, 16);
+ return Math.min(pollIntervalMillis << doublings, Math.max(MAX_BACKOFF.toMillis(), pollIntervalMillis));
+ }
+
+ private void rescheduleOrGiveUp(long delayMillis) {
+ var elapsed = Duration.ofNanos(System.nanoTime() - startNanos);
+ if (elapsed.plusMillis(delayMillis).compareTo(maxPollDuration) > 0) {
+ finish();
+ if (!isCancelled()) {
+ var cause = consecutiveFailures > 0
+ ? "the auto-unstrip status could not be checked for %s (%s)".formatted(describe(maxPollDuration), lastFailure)
+ : "auto-unstrip has not finished after %s".formatted(describe(maxPollDuration));
+ announce("RevEng.AI: %s; stopped waiting. Use Sync With Portal to pull the recovered names later."
+ .formatted(cause), true);
}
- schedule(analysedProgram, resyncIfAlreadyComplete, false, POLL_INTERVAL_SECONDS);
+ return;
+ }
+ schedule(delayMillis);
+ }
+
+ private void runSync() {
+ // The program may have been detached, or attached to another analysis, since polling began.
+ var current = revengService.getAnalysedProgram(analysedProgram.program());
+ if (isCancelled()) {
+ loggingService.info("Auto-unstrip finished for analysis %d, but polling for it was stopped; not syncing."
+ .formatted(analysedProgram.analysisID().id()));
+ return;
+ }
+ if (current.isEmpty() || !current.get().analysisID().equals(analysedProgram.analysisID())) {
+ loggingService.info("Auto-unstrip finished for analysis %d, but the program is no longer attached to it; not syncing."
+ .formatted(analysedProgram.analysisID().id()));
+ return;
+ }
+ announce("RevEng.AI: auto-unstrip finished; syncing recovered function names and data types…", false);
+ try {
+ var summary = revengService.syncAnalysisUpdates(current.get(), syncMonitor, loggingService);
+ if (isCancelled()) {
+ loggingService.info("Stopped the auto-unstrip sync for analysis %d; its changes were rolled back."
+ .formatted(analysedProgram.analysisID().id()));
+ return;
+ }
+ announce(("RevEng.AI: auto-unstrip sync applied %d recovered name(s) and %d signature(s), "
+ + "and pushed %d local type set(s).")
+ .formatted(summary.namesModifiedRemotely(), summary.appliedSignatures(),
+ summary.pushedTypeSets()), false);
+ } catch (Exception e) {
+ Msg.warn(AutoUnstripSyncService.this, "Failed to sync analysis after auto-unstrip", e);
+ if (isCancelled()) {
+ // Stopped mid-sync (e.g. detached); the failure is a consequence of that, not something to report.
+ return;
+ }
+ announce("RevEng.AI: failed to sync analysis after auto-unstrip: " + e.getMessage(), true);
}
}
}
- private void runSync(AnalysedProgram analysedProgram) {
- announce("RevEng.AI: auto-unstrip finished; syncing recovered function names and data types…", false);
- try {
- var summary = revengService.syncAnalysisUpdates(analysedProgram, TaskMonitor.DUMMY, loggingService);
- announce(("RevEng.AI: auto-unstrip sync applied %d recovered name(s) and %d signature(s), "
- + "and pushed %d local type set(s).")
- .formatted(summary.namesModifiedRemotely(), summary.appliedSignatures(),
- summary.pushedTypeSets()), false);
- } catch (Exception e) {
- Msg.warn(this, "Failed to sync analysis after auto-unstrip", e);
- announce("RevEng.AI: failed to sync analysis after auto-unstrip: " + e.getMessage(), true);
+ private static String describe(Exception e) {
+ if (e instanceof ApiException api && api.getCode() > 0) {
+ return "HTTP " + api.getCode();
}
+ return e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
+ }
+
+ private static String describe(Duration duration) {
+ return duration.toMinutes() >= 1 ? duration.toMinutes() + " minute(s)" : duration.toSeconds() + " second(s)";
}
/// Record a message in the plugin log and surface it to the user (status bar).
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java
index 1f19e354..7bbbb1a0 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/LocalEditSyncService.java
@@ -1,9 +1,10 @@
package ai.reveng.toolkit.ghidra.core.services.sync;
-import ai.reveng.invoker.ApiException;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraDataTypeEncoder;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService.AnalysedProgram;
+import ai.reveng.toolkit.ghidra.core.services.api.PushFailure;
+import ai.reveng.toolkit.ghidra.core.services.api.UnresolvedDataTypesException;
import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService;
import ghidra.framework.model.DomainObjectChangeRecord;
import ghidra.framework.model.DomainObjectListener;
@@ -20,7 +21,14 @@
import ghidra.program.util.ProgramEvent;
import ghidra.util.Msg;
+import javax.annotation.Nullable;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -30,30 +38,88 @@
/**
* Reactive push-back of local edits to the portal (PLU-322). Registers a {@link DomainObjectListener}
- * on analysed programs and, when the user renames a function or edits its signature / variables,
- * pushes that change back to the portal in the background.
+ * on analysed programs and, when the user renames a function or edits its signature (return type,
+ * parameters, calling convention, or a data type those use), pushes that change back to the portal
+ * in the background. Local variables are not pushed: the portal's signature holds only the
+ * parameters and return type, so an edit to a local has nothing to send.
*
* Mirrors the IDA plugin's {@code hooks/reactive.py} + {@code hooks/artifacts.py}: edits are
- * coalesced per function (debounced) and pushes are suppressed while the plugin is applying
- * server-sourced changes locally (see {@link GhidraRevengService#isPushbackSuppressed()}), so
- * sync-applied changes are not echoed straight back.
+ * debounced, renames per program and sent as one batch (a script renaming hundreds of functions makes
+ * one request, not hundreds), signature edits per function. Type edits are ignored while the plugin is writing
+ * server-sourced changes into that program (see {@link GhidraRevengService#isApplyingServerChanges}),
+ * so sync-applied changes are not echoed straight back. Renames need no such guard: the plugin only
+ * ever writes {@link SourceType#ANALYSIS} names, and only {@link SourceType#USER_DEFINED} ones are
+ * pushed, so an analyst's rename is pushed even when it lands in the middle of a sync.
+ *
+ *
A push that fails leaves the edit marked in {@link UnpushedEdits} until a push succeeds, and
+ * "Sync with portal" sends whatever is marked. What happens in between depends on the failure — see
+ * {@link PushFailure}:
+ *
+ * - When the portal could not be reached, the program's marked edits are retried in the background,
+ * backing off through {@link #RETRY_DELAYS}. The outage is reported once, in the plugin log and the
+ * status bar, however many pushes fail, and once more when the edits have gone up.
+ * - When the portal turned an edit down, the marked edits are sent again at once, one at a time
+ * where a batch was refused, so the ones it does take go up. Each edit it will not take is reported
+ * once and not retried automatically.
+ * - When the portal refused the API key, that is reported once and nothing is retried until a
+ * push succeeds again.
+ *
+ * Each failure is also logged to Ghidra's console.
*/
public class LocalEditSyncService {
/// Coalesce rapid successive edits to the same function before pushing, matching IDA's debounce.
private static final long DEBOUNCE_MS = 400;
+ /// The waits before each automatic retry of a program's unpushed edits; the last one repeats.
+ public static final List RETRY_DELAYS = List.of(
+ Duration.ofSeconds(30), Duration.ofMinutes(1), Duration.ofMinutes(2), Duration.ofMinutes(5));
+
private final GhidraRevengService revengService;
private final ReaiLoggingService loggingService;
+ /// Shows a message in the status bar; the flag marks it as a warning.
+ private final BiConsumer statusNotifier;
private final ScheduledExecutorService scheduler;
private final Map listeners = new ConcurrentHashMap<>();
- private final Map> pendingRenames = new ConcurrentHashMap<>();
- private final Map> pendingTypes = new ConcurrentHashMap<>();
- private final Map> pendingDataTypeScans = new ConcurrentHashMap<>();
+ private final Map> pendingRenames = new ConcurrentHashMap<>();
+ /// The functions renamed in each program since its last rename push. Guarded by itself.
+ private final Map> dueRenames = new HashMap<>();
+ private final Map, ScheduledFuture>> pendingTypes = new ConcurrentHashMap<>();
+ private final Map, ScheduledFuture>> pendingDataTypeScans = new ConcurrentHashMap<>();
+ private final List retryDelays;
+ /// The programs whose unpushed edits wait for an automatic retry.
+ private final Map> pendingRetries = new ConcurrentHashMap<>();
+ /// How many retries have failed in a row, per program, which picks the next wait.
+ private final Map failedRetries = new ConcurrentHashMap<>();
+ // The outage state below is only touched on the scheduler thread.
+ /// Whether the analyst has been told that pushes are failing, for want of an answer or a key.
+ private boolean outageReported;
+ /// Edits the retries have pushed since the outage was reported.
+ private int pushedSinceOutage;
+ /// Whether the analyst has been told the API key was refused; cleared when a push succeeds.
+ private boolean authReported;
+ /// The programs whose retries stopped on a refused API key, to resume when a push succeeds.
+ private final Set stoppedOnAuth = ConcurrentHashMap.newKeySet();
+ /// The rejected edits already reported, per program, so each is reported once.
+ private final Map> reportedRejections = new ConcurrentHashMap<>();
+
+ /// A debounce key. One service handles every open program, and two programs can have functions at
+ /// the same address (two versions of one binary, or any two PEs with code at `0x140001000`), so an
+ /// address or type path alone would let an edit in one program cancel the other's pending push.
+ private record InProgram(Program program, K key) {}
+
+ public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService,
+ BiConsumer statusNotifier) {
+ this(revengService, loggingService, statusNotifier, RETRY_DELAYS);
+ }
- public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService) {
+ /// @param retryDelays the waits before each automatic retry; the last one repeats
+ public LocalEditSyncService(GhidraRevengService revengService, ReaiLoggingService loggingService,
+ BiConsumer statusNotifier, List retryDelays) {
this.revengService = revengService;
this.loggingService = loggingService;
+ this.statusNotifier = statusNotifier;
+ this.retryDelays = List.copyOf(retryDelays);
this.scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
var thread = new Thread(runnable, "RevEng.AI-LocalEditSync");
thread.setDaemon(true);
@@ -76,6 +142,20 @@ public void detach(Program program) {
if (listener != null) {
program.removeListener(listener);
}
+ // Its edits stay marked, so the next sync of it still sends them.
+ var retry = pendingRetries.remove(program);
+ if (retry != null) {
+ retry.cancel(false);
+ }
+ failedRetries.remove(program);
+ stoppedOnAuth.remove(program);
+ reportedRejections.remove(program);
+ scheduler.execute(() -> {
+ if (pendingRetries.isEmpty() && stoppedOnAuth.isEmpty()) {
+ outageReported = false;
+ pushedSinceOutage = 0;
+ }
+ });
}
public void dispose() {
@@ -86,12 +166,12 @@ public void dispose() {
private DomainObjectListener buildListener(Program program) {
return new DomainObjectListenerBuilder(this)
- .ignoreWhen(revengService::isPushbackSuppressed)
.each(ProgramEvent.SYMBOL_RENAMED).call(record -> onSymbolRenamed(program, record))
// Renaming a decompiler-inferred variable commits it to the database as a new symbol,
// which fires SYMBOL_ADDED rather than SYMBOL_RENAMED, so we react to both.
.each(ProgramEvent.SYMBOL_ADDED).call(record -> onVariableSymbolChanged(program, record))
.each(ProgramEvent.FUNCTION_CHANGED).call(record -> onFunctionChanged(program, record))
+ .each(ProgramEvent.FUNCTION_ADDED).call(record -> onFunctionAdded(program, record))
// Editing a data type definition (rename a struct, change its fields, ...) does not
// fire a function event, so we react to the data-type events and push every server-known
// function that references the edited type — the portal stores types per function.
@@ -116,15 +196,19 @@ private void onSymbolRenamed(Program program, DomainObjectChangeRecord record) {
}
private void onVariableSymbolChanged(Program program, DomainObjectChangeRecord record) {
+ // Applying a portal signature adds parameter symbols.
+ if (revengService.isApplyingServerChanges(program)) {
+ return;
+ }
var symbol = symbolOf(record);
if (symbol != null) {
scheduleTypesForVariable(program, symbol);
}
}
- /// Push the containing function's types when a local variable or parameter symbol changed.
+ /// Push the containing function's signature when one of its parameter symbols changed.
private void scheduleTypesForVariable(Program program, Symbol symbol) {
- if (symbol.getSymbolType() != SymbolType.LOCAL_VAR && symbol.getSymbolType() != SymbolType.PARAMETER) {
+ if (symbol.getSymbolType() != SymbolType.PARAMETER) {
return;
}
if (symbol.getParentNamespace() instanceof Function function && isSyncable(function)) {
@@ -145,19 +229,34 @@ private void onFunctionChanged(Program program, DomainObjectChangeRecord record)
return;
}
var function = functionChange.getFunction();
- if (!isSyncable(function)) {
+ if (!isSyncable(function) || revengService.isApplyingServerChanges(program)) {
return;
}
- // Modifier-only changes (inline/no-return/thunk/...) carry no type information to sync.
- // Everything else (return type, parameters, variable types) is pushed; sync-applied changes
- // are already excluded by the ignoreWhen(isPushbackSuppressed) guard on the listener.
- if (functionChange.isFunctionModifierChange()) {
+ // Only the return type and parameters reach the portal. Ghidra reports any other change —
+ // a local variable added, removed or retyped, the stack frame, an inline or no-return flag —
+ // without one of these two types, and pushing for it would resend an unchanged signature.
+ if (!functionChange.isFunctionSignatureChange()) {
return;
}
scheduleTypes(program, function.getEntryPoint());
}
+ /// A function deleted and created again keeps its server id, because the id map is keyed by
+ /// address, but not its tag; put the tag back so it still shows as synced.
+ private void onFunctionAdded(Program program, DomainObjectChangeRecord record) {
+ if (record instanceof ProgramChangeRecord programChange) {
+ var function = program.getFunctionManager().getFunctionAt(programChange.getStart());
+ if (isSyncable(function)) {
+ revengService.restoreSyncedTag(function);
+ }
+ }
+ }
+
private void onDataTypeChanged(Program program, DomainObjectChangeRecord record) {
+ // Applying a portal signature updates the data types it names in place.
+ if (revengService.isApplyingServerChanges(program)) {
+ return;
+ }
DataType dataType = null;
if (record.getNewValue() instanceof DataType changed) {
dataType = changed;
@@ -165,7 +264,7 @@ private void onDataTypeChanged(Program program, DomainObjectChangeRecord record)
dataType = previous;
}
if (dataType != null) {
- scheduleDataTypeScan(program, dataType.getName());
+ scheduleDataTypeScan(program, dataType);
}
}
@@ -174,25 +273,37 @@ private static boolean isSyncable(Function function) {
}
private void scheduleRename(Program program, Address entryPoint) {
- schedule(pendingRenames, entryPoint, () -> pushRename(program, entryPoint));
+ UnpushedEdits.mark(program, UnpushedEdits.Kind.NAME, entryPoint);
+ synchronized (dueRenames) {
+ dueRenames.computeIfAbsent(program, p -> new LinkedHashSet<>()).add(entryPoint);
+ }
+ schedule(pendingRenames, program, program, () -> pushRenames(program));
}
private void scheduleTypes(Program program, Address entryPoint) {
- schedule(pendingTypes, entryPoint, () -> pushTypes(program, entryPoint));
+ UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, entryPoint);
+ schedule(pendingTypes, new InProgram<>(program, entryPoint), program, () -> pushTypes(program, entryPoint));
}
- private void scheduleDataTypeScan(Program program, String typeName) {
- schedule(pendingDataTypeScans, typeName, () -> pushFunctionsReferencingType(program, typeName));
+ private void scheduleDataTypeScan(Program program, DataType dataType) {
+ var typeName = dataType.getName();
+ schedule(pendingDataTypeScans, new InProgram<>(program, dataType.getPathName()), program,
+ () -> pushFunctionsReferencingType(program, typeName));
}
- private void schedule(Map> pending, K key, Runnable task) {
+ private void schedule(Map> pending, K key, Program program, Runnable task) {
var existing = pending.get(key);
if (existing != null) {
existing.cancel(false);
}
pending.put(key, scheduler.schedule(() -> {
pending.remove(key);
- task.run();
+ // Nothing reads the future, so anything thrown here would vanish with it.
+ try {
+ task.run();
+ } catch (Exception e) {
+ onPushFailed(program, "Could not push a local edit", e);
+ }
}, DEBOUNCE_MS, TimeUnit.MILLISECONDS));
}
@@ -216,16 +327,43 @@ private void pushFunctionsReferencingType(Program program, String typeName) {
}
}
- private void pushRename(Program program, Address entryPoint) {
- withAnalysedFunction(program, entryPoint, (analysedProgram, function) -> {
- try {
- revengService.pushFunctionRename(analysedProgram, function).ifPresent(pushedName ->
- loggingService.info("Pushed rename of function at %s to \"%s\" to the RevEng.AI portal"
- .formatted(entryPoint, pushedName)));
- } catch (ApiException e) {
- Msg.warn(this, "Failed to push rename for %s to portal".formatted(function.getName()), e);
+ /// Push every rename made in `program` since its last push, in one request.
+ private void pushRenames(Program program) {
+ Set entryPoints;
+ synchronized (dueRenames) {
+ entryPoints = dueRenames.remove(program);
+ }
+ var analysedProgram = revengService.getAnalysedProgram(program);
+ if (entryPoints == null || analysedProgram.isEmpty()) {
+ return;
+ }
+ List functions = new ArrayList<>();
+ for (Address entryPoint : entryPoints) {
+ var function = program.getFunctionManager().getFunctionAt(entryPoint);
+ if (isSyncable(function)) {
+ functions.add(function);
}
- });
+ }
+ try {
+ var pushed = revengService.pushFunctionRenames(analysedProgram.get(), functions);
+ if (pushed.size() == 1) {
+ var only = pushed.entrySet().iterator().next();
+ loggingService.info("Pushed rename of function at %s to \"%s\" to the RevEng.AI portal"
+ .formatted(only.getKey().getEntryPoint(), only.getValue()));
+ } else if (!pushed.isEmpty()) {
+ loggingService.info("Pushed renames of %d functions to the RevEng.AI portal".formatted(pushed.size()));
+ }
+ // Every one, including those that were gone or unknown to the portal: nothing is left to send.
+ entryPoints.forEach(entryPoint -> UnpushedEdits.clear(program, UnpushedEdits.Kind.NAME, entryPoint));
+ onPushSucceeded(program);
+ } catch (Exception e) {
+ // Marked again in case a push that started earlier succeeded and cleared them meanwhile.
+ entryPoints.forEach(entryPoint -> UnpushedEdits.mark(program, UnpushedEdits.Kind.NAME, entryPoint));
+ var what = functions.size() == 1
+ ? "the rename of \"%s\"".formatted(functions.get(0).getName())
+ : "the renames of %d functions".formatted(functions.size());
+ onPushFailed(program, "Could not push " + what, e);
+ }
}
private void pushTypes(Program program, Address entryPoint) {
@@ -246,12 +384,167 @@ private void pushTypes(Program program, Address entryPoint) {
// Not part of the analysis, so there was nothing to push.
}
}
- } catch (ApiException e) {
- Msg.warn(this, "Failed to push types for %s to portal".formatted(function.getName()), e);
+ UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, entryPoint);
+ onPushSucceeded(program);
+ } catch (Exception e) {
+ UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, entryPoint);
+ onPushFailed(program, "Could not push the types of \"%s\"".formatted(function.getName()), e);
}
});
}
+ // Everything from here on runs on the scheduler thread.
+
+ /// Log the failure to Ghidra's console and decide what comes next: a retry after a wait when the
+ /// portal could not be reached, and otherwise a retry straight away, which sends the marked edits
+ /// one at a time where needed and finds out which ones the portal will not take.
+ private void onPushFailed(Program program, String detail, Exception e) {
+ if (e instanceof UnresolvedDataTypesException) {
+ // An expected outcome, not a fault: the message says all there is to say.
+ Msg.warn(this, "%s: %s".formatted(detail, reasonOf(e)));
+ } else {
+ Msg.warn(this, "%s: %s".formatted(detail, reasonOf(e)), e);
+ }
+ if (PushFailure.of(e) == PushFailure.TRANSIENT) {
+ reportOutage(e);
+ scheduleRetry(program, nextDelay(program));
+ } else {
+ scheduleRetry(program, Duration.ZERO);
+ }
+ }
+
+ /// A push got through, so the portal is likely back and the key good: retry the program's other
+ /// edits now rather than at the end of the current wait.
+ private void onPushSucceeded(Program program) {
+ authReported = false;
+ var waiting = pendingRetries.get(program);
+ if (waiting != null && waiting.cancel(false)) {
+ pendingRetries.remove(program);
+ scheduleRetry(program, Duration.ZERO);
+ } else if (stoppedOnAuth.remove(program)) {
+ scheduleRetry(program, Duration.ZERO);
+ }
+ }
+
+ private Duration nextDelay(Program program) {
+ return retryDelays.get(Math.min(failedRetries.getOrDefault(program, 0), retryDelays.size() - 1));
+ }
+
+ private void scheduleRetry(Program program, Duration delay) {
+ if (pendingRetries.containsKey(program) || !listeners.containsKey(program)) {
+ return;
+ }
+ pendingRetries.put(program, scheduler.schedule(() -> retry(program), delay.toMillis(), TimeUnit.MILLISECONDS));
+ }
+
+ private void retry(Program program) {
+ pendingRetries.remove(program);
+ var analysedProgram = revengService.getAnalysedProgram(program);
+ if (!listeners.containsKey(program) || analysedProgram.isEmpty()) {
+ failedRetries.remove(program);
+ endOutageIfOver();
+ return;
+ }
+ GhidraRevengService.LocalEditFlush flush;
+ try {
+ flush = revengService.pushUnpushedEdits(analysedProgram.get());
+ } catch (Exception e) {
+ flush = PushFailure.of(e) == PushFailure.TRANSIENT
+ ? new GhidraRevengService.LocalEditFlush(0, 1, e, List.of())
+ : new GhidraRevengService.LocalEditFlush(0, 0, null,
+ List.of(new GhidraRevengService.RejectedEdit("local edits", e)));
+ }
+ pushedSinceOutage += flush.pushed();
+ if (flush.pushed() > 0) {
+ authReported = false;
+ }
+ if (flush.unsent() > 0) {
+ Msg.warn(this, "Retry of %d unpushed local edit(s) failed: %s"
+ .formatted(flush.unsent(), reasonOf(flush.unsentError())), flush.unsentError());
+ reportOutage(flush.unsentError());
+ failedRetries.merge(program, 1, Integer::sum);
+ scheduleRetry(program, nextDelay(program));
+ return;
+ }
+ failedRetries.remove(program);
+ reportRejections(program, flush.rejected());
+ endOutageIfOver();
+ }
+
+ private void reportOutage(Exception e) {
+ if (!outageReported) {
+ outageReported = true;
+ announce(("RevEng.AI: could not push local edits to the portal (%s). They are kept and will be "
+ + "retried automatically.").formatted(reasonOf(e)), true);
+ }
+ }
+
+ /// Report the edits that will not be retried automatically: a refused API key once until a push
+ /// succeeds, and each edit the portal turned down once.
+ private void reportRejections(Program program, List rejected) {
+ var refusedKey = rejected.stream().filter(edit -> edit.failure() == PushFailure.AUTH).findFirst();
+ if (refusedKey.isPresent()) {
+ stoppedOnAuth.add(program);
+ if (!authReported) {
+ authReported = true;
+ // So the edits that go up once the key works are reported, as after an outage.
+ outageReported = true;
+ announce(("RevEng.AI: the portal refused the API key (%s), so local edits are not being pushed. "
+ + "Check the key in the RevEng.AI settings; the edits are kept and will be sent on the next "
+ + "Sync with portal.").formatted(reasonOf(refusedKey.get().error())), true);
+ }
+ }
+ List turnedDown = rejected.stream()
+ .filter(edit -> edit.failure() != PushFailure.AUTH)
+ .toList();
+ // Every marked edit was just sent, so this is the whole set the portal will not take; one that
+ // has since gone up drops out of it.
+ Set reported = reportedRejections.computeIfAbsent(program, p -> ConcurrentHashMap.newKeySet());
+ Set current = new LinkedHashSet<>();
+ turnedDown.forEach(edit -> current.add(edit.edit()));
+ reported.retainAll(current);
+ var fresh = turnedDown.stream().filter(edit -> !reported.contains(edit.edit())).toList();
+ if (fresh.isEmpty()) {
+ return;
+ }
+ for (var edit : fresh) {
+ reported.add(edit.edit());
+ loggingService.warn("RevEng.AI: the portal did not take the %s: %s".formatted(edit.edit(), reasonOf(edit.error())));
+ }
+ announce(("RevEng.AI: the portal did not take %d local edit(s) (%s). They will not be retried "
+ + "automatically; the RevEng.AI log lists them, and they are kept for the next Sync with portal.")
+ .formatted(fresh.size(), reasonOf(fresh.get(0).error())), true);
+ }
+
+ /// Once no program has edits waiting for a retry or a working key, say that the outage is over,
+ /// once.
+ private void endOutageIfOver() {
+ if (!outageReported || !pendingRetries.isEmpty() || !stoppedOnAuth.isEmpty()) {
+ return;
+ }
+ outageReported = false;
+ if (pushedSinceOutage > 0) {
+ announce("RevEng.AI: pushed %d local edit(s) that had failed earlier.".formatted(pushedSinceOutage), false);
+ }
+ pushedSinceOutage = 0;
+ }
+
+ private void announce(String message, boolean warning) {
+ if (warning) {
+ loggingService.warn(message);
+ } else {
+ loggingService.info(message);
+ }
+ statusNotifier.accept(message, warning);
+ }
+
+ private static String reasonOf(@Nullable Exception e) {
+ if (e == null) {
+ return "unknown error";
+ }
+ return e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
+ }
+
private void withAnalysedFunction(Program program, Address entryPoint,
BiConsumer action) {
var analysedProgram = revengService.getAnalysedProgram(program);
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/UnpushedEdits.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/UnpushedEdits.java
new file mode 100644
index 00000000..2f9a8893
--- /dev/null
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/sync/UnpushedEdits.java
@@ -0,0 +1,72 @@
+package ai.reveng.toolkit.ghidra.core.services.sync;
+
+import ghidra.program.model.address.Address;
+import ghidra.program.model.listing.Program;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/// The functions whose local edits have not reached the portal yet.
+///
+/// An edit is marked here when its push is scheduled and cleared only once a push succeeds, so a push
+/// that fails, or never runs because Ghidra closed first, is still known about and "Sync with portal"
+/// sends it. Sync cannot find these edits by itself: it leaves user-defined local names alone, because
+/// it cannot tell an edit that never went up from one the portal has since overwritten.
+///
+/// The marks live in the program's user data, which is saved with the program but sits outside its
+/// undo history and does not mark the program as changed.
+public final class UnpushedEdits {
+
+ private static final String OWNER = "RevEng.AI";
+
+ public enum Kind {
+ NAME("Unpushed function names"),
+ TYPES("Unpushed function types");
+
+ private final String propertyName;
+
+ Kind(String propertyName) {
+ this.propertyName = propertyName;
+ }
+ }
+
+ private UnpushedEdits() {}
+
+ public static synchronized void mark(Program program, Kind kind, Address entryPoint) {
+ var userData = program.getProgramUserData();
+ int tx = userData.startTransaction();
+ try {
+ userData.getBooleanProperty(OWNER, kind.propertyName, true).add(entryPoint);
+ } finally {
+ userData.endTransaction(tx);
+ }
+ }
+
+ public static synchronized void clear(Program program, Kind kind, Address entryPoint) {
+ var userData = program.getProgramUserData();
+ int tx = userData.startTransaction();
+ try {
+ var marks = userData.getBooleanProperty(OWNER, kind.propertyName, false);
+ if (marks != null) {
+ marks.remove(entryPoint);
+ }
+ } finally {
+ userData.endTransaction(tx);
+ }
+ }
+
+ public static synchronized boolean isMarked(Program program, Kind kind, Address entryPoint) {
+ var marks = program.getProgramUserData().getBooleanProperty(OWNER, kind.propertyName, false);
+ return marks != null && marks.hasProperty(entryPoint);
+ }
+
+ /// The entry points marked for `kind`, in address order.
+ public static synchronized List marked(Program program, Kind kind) {
+ var marks = program.getProgramUserData().getBooleanProperty(OWNER, kind.propertyName, false);
+ List entryPoints = new ArrayList<>();
+ if (marks != null) {
+ marks.getPropertyIterator().forEach(entryPoints::add);
+ }
+ return entryPoints;
+ }
+}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java
new file mode 100644
index 00000000..07b4daa5
--- /dev/null
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java
@@ -0,0 +1,110 @@
+package ai.reveng.toolkit.ghidra.core.services.update;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import resources.ResourceManager;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * Checks GitHub for a plugin release newer than the installed one.
+ */
+public class UpdateChecker {
+ public static final String UNKNOWN_VERSION = "unknown";
+ private static final String LATEST_RELEASE_URL =
+ "https://api.github.com/repos/RevEngAI/plugin-ghidra/releases/latest";
+
+ public record UpdateInfo(String version, String releaseUrl, String downloadUrl) {}
+
+ /**
+ * The installed plugin's release tag, or {@link #UNKNOWN_VERSION} for local builds.
+ */
+ public static String currentVersion() {
+ // This resource is written by the release workflow, so it is absent from a local build
+ // and the stream is then null.
+ try (var inputStream = ResourceManager.getResourceAsStream("reai_ghidra_plugin_version.txt")) {
+ if (inputStream != null) {
+ return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8).trim();
+ }
+ } catch (IOException e) {
+ // ignore — fall back to "unknown"
+ }
+ return UNKNOWN_VERSION;
+ }
+
+ /**
+ * Fetches the latest release. Completes empty when up to date, when no build exists for
+ * {@code ghidraVersion}, or on any failure.
+ */
+ public static CompletableFuture> check(String currentVersion, String ghidraVersion) {
+ var request = HttpRequest.newBuilder(URI.create(LATEST_RELEASE_URL))
+ .header("Accept", "application/vnd.github+json")
+ .timeout(Duration.ofSeconds(10))
+ .build();
+ return HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build()
+ .sendAsync(request, HttpResponse.BodyHandlers.ofString())
+ .thenApply(response -> response.statusCode() == 200
+ ? findUpdate(currentVersion, ghidraVersion, response.body())
+ : Optional.empty())
+ .exceptionally(e -> Optional.empty());
+ }
+
+ static Optional findUpdate(String currentVersion, String ghidraVersion, String releaseJson) {
+ try {
+ var release = new JSONObject(releaseJson);
+ var latest = release.getString("tag_name");
+ if (!isNewer(latest, currentVersion)) {
+ return Optional.empty();
+ }
+ var assetName = "ghidra_" + ghidraVersion + "_plugin-ghidra.zip";
+ var assets = release.getJSONArray("assets");
+ for (int i = 0; i < assets.length(); i++) {
+ var asset = assets.getJSONObject(i);
+ if (assetName.equals(asset.getString("name"))) {
+ return Optional.of(new UpdateInfo(latest, release.getString("html_url"),
+ asset.getString("browser_download_url")));
+ }
+ }
+ } catch (JSONException ignored) {
+ }
+ return Optional.empty();
+ }
+
+ static boolean isNewer(String candidate, String current) {
+ var a = parse(candidate);
+ var b = parse(current);
+ if (a.isEmpty() || b.isEmpty()) {
+ return false;
+ }
+ for (int i = 0; i < 3; i++) {
+ if (a.get()[i] != b.get()[i]) {
+ return a.get()[i] > b.get()[i];
+ }
+ }
+ return false;
+ }
+
+ private static Optional parse(String version) {
+ var parts = version.strip().replaceFirst("^v", "").split("\\.");
+ if (parts.length != 3) {
+ return Optional.empty();
+ }
+ try {
+ var numbers = new int[3];
+ for (int i = 0; i < 3; i++) {
+ numbers[i] = Integer.parseInt(parts[i]);
+ }
+ return Optional.of(numbers);
+ } catch (NumberFormatException e) {
+ return Optional.empty();
+ }
+ }
+}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java
index 8296937f..9f145d43 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTask.java
@@ -5,6 +5,7 @@
import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent;
import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService;
+import ai.reveng.toolkit.ghidra.core.services.api.TypedApiImplementation;
import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus;
import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService;
import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage;
@@ -74,11 +75,8 @@ public void run(TaskMonitor monitor) throws CancelledException {
loggingService.info(successMessage);
}
- tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent(
- "StartAnalysisTask",
- programWithID,
- AnalysisStatus.Queued)
- );
+ new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued)
+ .fireLater(tool);
}
private void reportFailure(TaskMonitor monitor,
@@ -96,15 +94,13 @@ private void reportFailure(TaskMonitor monitor,
message, error);
}
- private static String describe(Throwable error) {
+ static String describe(Throwable error) {
Throwable cause = error;
if (!(cause instanceof ApiException) && cause.getCause() instanceof ApiException) {
cause = cause.getCause();
}
if (cause instanceof ApiException apiException) {
- String body = apiException.getResponseBody();
- String detail = (body != null && !body.isBlank()) ? body : apiException.getMessage();
- return "HTTP " + apiException.getCode() + " — " + detail;
+ return TypedApiImplementation.describeApiException(apiException);
}
return cause.getMessage() != null ? cause.getMessage() : cause.toString();
}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowser.java b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowser.java
new file mode 100644
index 00000000..607c45f9
--- /dev/null
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowser.java
@@ -0,0 +1,36 @@
+package ai.reveng.toolkit.ghidra.core.ui;
+
+import ghidra.framework.OperatingSystem;
+import ghidra.framework.Platform;
+import ghidra.util.Msg;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.List;
+
+/// Opens URLs in the user's default browser via the OS launcher. Ghidra's BrowserLoader goes through
+/// the manual-viewer option, whose macOS default in 12.2 is `anaconda-navigator`; java.awt.Desktop
+/// frequently no-ops or is reported unsupported inside Ghidra's JVM.
+public final class WebBrowser {
+
+ private WebBrowser() {
+ }
+
+ public static void open(URI uri) {
+ try {
+ new ProcessBuilder(command(Platform.CURRENT_PLATFORM.getOperatingSystem(), uri)).start();
+ } catch (IOException e) {
+ Msg.showError(WebBrowser.class, null, "URI Opening Failed",
+ "Browsing to URI %s failed".formatted(uri), e);
+ }
+ }
+
+ static List command(OperatingSystem os, URI uri) {
+ String url = uri.toString();
+ return switch (os) {
+ case MAC_OS_X -> List.of("open", url);
+ case WINDOWS -> List.of("rundll32", "url.dll,FileProtocolHandler", url);
+ default -> List.of("xdg-open", url);
+ };
+ }
+}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java
index 1bf4bc06..36aea5ce 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/ui/wizard/panels/UserCredentialsPanel.java
@@ -247,8 +247,8 @@ public void leavePanel(WizardState state) {
public void updateStateObjectWithPanelInfo(WizardState state) {
// Save the entered information into the state object
state.put(SetupWizardStateKey.API_KEY, tfApiKey.getText());
- state.put(SetupWizardStateKey.HOSTNAME, tfApiHostname.getText());
- state.put(SetupWizardStateKey.PORTAL_HOSTNAME, tfPortalHostname.getText());
+ state.put(SetupWizardStateKey.HOSTNAME, ApiInfo.normaliseHost(tfApiHostname.getText()));
+ state.put(SetupWizardStateKey.PORTAL_HOSTNAME, ApiInfo.normaliseHost(tfPortalHostname.getText()));
state.put(SetupWizardStateKey.CREDENTIALS_VALIDATED, credentialsValidated);
}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java
index 579c5e6e..cc382900 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AgentChatPlugin.java
@@ -30,11 +30,19 @@
//@formatter:on
public class AgentChatPlugin extends ProgramPlugin {
- private final AgentChatWindow chatWindow;
+ private AgentChatWindow chatWindow;
public AgentChatPlugin(PluginTool tool) {
super(tool);
- chatWindow = new AgentChatWindow(tool, getName(), new ConversationsApiChatService());
+ }
+
+ @Override
+ protected void init() {
+ // Required services are only resolved by now
+ super.init();
+ var revengService = tool.getService(GhidraRevengService.class);
+ chatWindow = new AgentChatWindow(tool, getName(),
+ new ConversationsApiChatService(revengService::apiClient));
chatWindow.addToTool();
setupActions();
}
@@ -55,7 +63,9 @@ protected void locationChanged(ProgramLocation location) {
@Override
protected void dispose() {
- chatWindow.dispose();
+ if (chatWindow != null) {
+ chatWindow.dispose();
+ }
super.dispose();
}
}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java
index e850e755..33c83b23 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPlugin.java
@@ -38,6 +38,8 @@
import ghidra.program.model.listing.Program;
import ghidra.program.util.GhidraProgramUtilities;
import ghidra.util.Msg;
+import ghidra.util.exception.CancelledException;
+import javax.annotation.Nullable;
import ghidra.util.task.Task;
import ghidra.util.task.TaskBuilder;
import ghidra.util.task.TaskMonitor;
@@ -46,6 +48,10 @@
import org.slf4j.LoggerFactory;
import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
/**
* CorePlugin for accessing the RevEng.AI Platform
@@ -80,9 +86,20 @@ public class AnalysisManagementPlugin extends ProgramPlugin {
private AnalysisLogComponent analysisLogComponent;
private LocalEditSyncService localEditSyncService;
private AutoUnstripSyncService autoUnstripSyncService;
+ /// Programs whose analysis results failed to load, for the Retry action. Touched from tasks and the Swing thread.
+ private final Set failedLoads = ConcurrentHashMap.newKeySet();
+ private static final String RETRY_HINT =
+ "The program was left unchanged. Retry now, or later from RevEng.AI > Analysis > Retry loading results.";
private PluginTool tool;
+ /// Failed analyses whose error has been shown, so each failure is reported once while the program is open
+ private final Set reportedErrors = ConcurrentHashMap.newKeySet();
+
+ /// How many of the last log lines the error dialog shows
+ static final int ERROR_LOG_TAIL_LINES = 15;
+ /// Longer log lines are cut, so one line cannot stretch the dialog
+ static final int ERROR_LOG_LINE_LENGTH = 200;
public AnalysisManagementPlugin(PluginTool tool) {
super(tool);
@@ -99,9 +116,10 @@ public void init() {
tool.addComponentProvider(analysisLogComponent, false);
revengService = Objects.requireNonNull(tool.getService(GhidraRevengService.class));
- localEditSyncService = new LocalEditSyncService(revengService, loggingService);
- autoUnstripSyncService = new AutoUnstripSyncService(revengService, loggingService,
- (message, warning) -> SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, warning)));
+ BiConsumer statusNotifier =
+ (message, warning) -> SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, warning));
+ localEditSyncService = new LocalEditSyncService(revengService, loggingService, statusNotifier);
+ autoUnstripSyncService = new AutoUnstripSyncService(revengService, loggingService, statusNotifier);
setupActions();
@@ -202,13 +220,7 @@ private void setupActions() {
"Detach",
OptionDialog.QUESTION_MESSAGE);
if (result == OptionDialog.YES_OPTION) {
- // For now this is the only place to trigger the removal of the association
- // If this changes, the RevEngAIAnalysisStatusChanged event should be changed to accommodate
- // this kind of event
- program.withTransaction("Undo binary association", () -> revengService.removeProgramAssociation(program));
-
- // Refresh action states after detaching
- tool.contextChanged(null);
+ detach(knownProgram.get());
}
})
@@ -238,7 +250,7 @@ public void run(TaskMonitor monitor) {
SwingUtilities.invokeLater(() -> {
analysisLogComponent.setLogs(logs);
Msg.showInfo(AnalysisManagementPlugin.this, null, ReaiPluginPackage.WINDOW_PREFIX + "Check status",
- "Status of analysis " + knownProgram + ": " + status);
+ checkStatusMessage(status));
});
} catch (Exception e) {
Msg.error(AnalysisManagementPlugin.this, "Failed to check analysis status: " + e.getMessage(), e);
@@ -250,6 +262,19 @@ public void run(TaskMonitor monitor) {
.menuGroup(REAI_ANALYSIS_MANAGEMENT_MENU_GROUP, "400")
.buildAndInstall(tool);
+ new ActionBuilder("Retry loading results", this.getName())
+ .enabledWhen(context -> {
+ var currentProgram = tool.getService(ProgramManager.class).getCurrentProgram();
+ return currentProgram != null && failedLoads.contains(currentProgram);
+ })
+ .onAction(context -> {
+ var currentProgram = tool.getService(ProgramManager.class).getCurrentProgram();
+ revengService.getKnownProgram(currentProgram).ifPresent(this::loadAnalysisResults);
+ })
+ .menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "Analysis", "Retry loading results" })
+ .menuGroup(REAI_ANALYSIS_MANAGEMENT_MENU_GROUP, "250")
+ .buildAndInstall(tool);
+
new ActionBuilder("View in portal", this.getName())
.enabledWhen(context -> {
var currentProgram = tool.getService(ProgramManager.class).getCurrentProgram();
@@ -269,6 +294,31 @@ public void run(TaskMonitor monitor) {
.buildAndInstall(tool);
}
+ /// Remove the program's association with its analysis. The Detach action and the analysis error dialog
+ /// both end here, so they do the same thing.
+ private void detach(GhidraRevengService.ProgramWithID knownProgram) {
+ var program = knownProgram.program();
+ var displayText = "analysis " + knownProgram.analysisID().id();
+ // For now these are the only places to trigger the removal of the association
+ // If this changes, the RevEngAIAnalysisStatusChanged event should be changed to accommodate
+ // this kind of event
+ // Stop the background work tied to this analysis first, so none of it runs against the
+ // association while it is being removed, or later against a different analysis.
+ localEditSyncService.detach(program);
+ analysisLogComponent.stopMonitoring(program);
+ if (autoUnstripSyncService.stopPolling(knownProgram.analysisID())) {
+ var message = "RevEng.AI: stopped waiting for auto-unstrip; the program was detached from "
+ + displayText + ".";
+ tool.getService(ReaiLoggingService.class).info(message);
+ tool.setStatusInfo(message);
+ }
+ program.withTransaction("Undo binary association", () -> revengService.removeProgramAssociation(program));
+ reportedErrors.remove(knownProgram);
+
+ // Refresh action states after detaching
+ tool.contextChanged(null);
+ }
+
@Override
protected void programOpened(Program program) {
super.programOpened(program);
@@ -287,32 +337,46 @@ protected void programOpened(Program program) {
// This can happen if the analysis was started in a previous session but hadn't finished when closing Ghidra
// Either the analysis is finished already now, or we want to actively wait for it to finish
log.info("Detected known program that hasn't been fully loaded yet: {}", knownProgram.get());
- var status = revengService.status(knownProgram.get());
- switch (status) {
- case Complete -> {
- tool.firePluginEvent(
- new RevEngAIAnalysisStatusChangedEvent(
- "programOpened",
- knownProgram.get(),
- status));
- }
- case Queued, Processing -> {
- // This is the same code as above, but it has the implicit assumption that someone
- /// Currently this is done by {@link AnalysisLogComponent#processEvent(RevEngAIAnalysisStatusChangedEvent)}
- tool.firePluginEvent(
- new RevEngAIAnalysisStatusChangedEvent(
- "programOpened",
- knownProgram.get(),
- status));
- }
-
-
- case Error -> {
- // The analysis failed on the server side
- Msg.showError(this, null, "Analysis Error",
- "The RevEng.AI analysis for the program " + knownProgram.get() + " is in error state on the server side.");
+ // Off the Swing thread: programs are opened on it, and without network the request blocks until it times out
+ tool.execute(new Task("Check RevEng.AI analysis status", false, false, false) {
+ @Override
+ public void run(TaskMonitor monitor) {
+ AnalysisStatus status;
+ try {
+ status = revengService.status(knownProgram.get());
+ } catch (Exception e) {
+ Msg.warn(AnalysisManagementPlugin.this,
+ "Could not check the RevEng.AI analysis status for " + knownProgram.get() + ": " + e.getMessage());
+ return;
+ }
+ switch (status) {
+ case Complete -> {
+ new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status)
+ .fireLater(tool);
+ }
+ case Uploaded, Queued, Processing -> {
+ // This is the same code as above, but it has the implicit assumption that someone
+ /// Currently this is done by {@link AnalysisLogComponent#processEvent(RevEngAIAnalysisStatusChangedEvent)}
+ new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status)
+ .fireLater(tool);
+ }
+
+
+ case Error -> {
+ // The analysis failed on the server side. Reported through the event, so it is
+ // shown the same way as a failure seen while waiting, see processEvent
+ new RevEngAIAnalysisStatusChangedEvent("programOpened", knownProgram.get(), status)
+ .fireLater(tool);
+ }
+ case Unknown -> {
+ // Not waited on: an unrecognised status might never change into one that ends the wait
+ var message = unknownStatusOnOpenMessage(knownProgram.get());
+ tool.getService(ReaiLoggingService.class).warn(message);
+ SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, true));
+ }
+ }
}
- }
+ }, 0);
}
} else {
log.info("Opened unknown program: {}", program.getName());
@@ -329,6 +393,7 @@ protected void programActivated(Program program) {
@Override
protected void programClosed(Program program) {
super.programClosed(program);
+ failedLoads.remove(program);
if (localEditSyncService != null) {
localEditSyncService.detach(program);
}
@@ -336,6 +401,12 @@ protected void programClosed(Program program) {
revengService.getKnownProgram(program)
.ifPresent(known -> autoUnstripSyncService.stopPolling(known.analysisID()));
}
+ // Reopening a program with a failed analysis reports the failure again
+ reportedErrors.removeIf(reported -> reported.program() == program);
+ if (analysisLogComponent != null) {
+ // Otherwise the wait keeps polling, and holding the program, until the analysis ends
+ analysisLogComponent.programClosed(program);
+ }
}
@Override
@@ -354,28 +425,198 @@ public void processEvent(PluginEvent event) {
super.processEvent(event);
// Forward the event to the analysis log component
if (event instanceof RevEngAIAnalysisStatusChangedEvent analysisEvent) {
+ if (!isStillAttached(analysisEvent.getProgramWithBinaryID())) {
+ // From a wait that was still running when the program was detached or closed. Acting on it would
+ // load the old analysis into a program that is now attached to another one, or to none.
+ Msg.info(this, "Ignoring status event for an analysis the program is no longer attached to: "
+ + analysisEvent.getProgramWithBinaryID());
+ return;
+ }
analysisLogComponent.processEvent(analysisEvent);
if (analysisEvent.getStatus() == AnalysisStatus.Complete) {
Msg.info(this, "Received analysis complete event for " + analysisEvent.getProgramWithBinaryID());
// If the analysis is complete, we refresh the function signatures from the server
- var program = analysisEvent.getProgramWithBinaryID();
+ loadAnalysisResults(analysisEvent.getProgramWithBinaryID());
+ } else if (analysisEvent.getStatus() == AnalysisStatus.Error) {
+ reportAnalysisError(analysisEvent.getProgramWithBinaryID());
+ }
+ }
+ }
+
+ private void loadAnalysisResults(GhidraRevengService.ProgramWithID program) {
+ failedLoads.remove(program.program());
+ // Disables the Retry action straight away, so a second click cannot start a second load
+ tool.contextChanged(null);
+ // Events arrive on the Swing thread, and loading the results makes several requests
+ tool.execute(new Task("Load RevEng.AI analysis results", true, false, false) {
+ @Override
+ public void run(TaskMonitor monitor) {
try {
- // TODO: Can we get a better taskmonitor here?
- // Or should we never do something here that warrants a monitor in the first place?
- var analysedProgram = revengService.registerFinishedAnalysisForProgram(program, TaskMonitor.DUMMY);
+ if (!isStillAttached(program)) {
+ // Detached or closed since the load was requested
+ return;
+ }
+ var analysedProgram = revengService.registerFinishedAnalysisForProgram(program, monitor);
localEditSyncService.attach(program.program());
tool.firePluginEvent(new RevEngAIAnalysisResultsLoaded("AnalysisManagementPlugin", analysedProgram));
// Auto-unstrip runs server-side after the analysis is marked complete, so poll for it
// and sync the recovered names / data types once it finishes (PLU-300).
autoUnstripSyncService.pollAndSync(analysedProgram, true);
+ } catch (GhidraRevengService.DetachedDuringLoadException e) {
+ // The user chose to leave this analysis, so there is nothing to report or retry
+ Msg.info(AnalysisManagementPlugin.this, e.getMessage());
+ } catch (CancelledException e) {
+ reportFailedLoad(program, loadCancelledMessage(program), null);
} catch (Exception e) {
- Msg.error(this, "Error registering finished analysis for program " + program, e);
- return;
+ Msg.error(AnalysisManagementPlugin.this, "Error registering finished analysis for program " + program, e);
+ reportFailedLoad(program, loadFailedMessage(program, e), e);
}
}
+ }, 0);
+ }
+
+ /// Tell the user that the analysis failed on the server, with the end of its log, and offer to detach it so
+ /// they can create a new analysis or attach to another one. Shown once per failure while the program is open.
+ private void reportAnalysisError(GhidraRevengService.ProgramWithID failed) {
+ if (!reportedErrors.add(failed)) {
+ return;
}
+ Msg.info(this, "Received analysis error event for " + failed);
+ // Events arrive on the Swing thread, and fetching the log is a request
+ tool.execute(new Task("Fetch RevEng.AI analysis log", false, false, false) {
+ @Override
+ public void run(TaskMonitor monitor) {
+ var fetchedLogs = fetchAnalysisLog(failed);
+ var logs = fetchedLogs != null ? fetchedLogs : analysisLogComponent.getStoredLogs(failed.program());
+ var message = analysisErrorMessage(failed.analysisID().id(), failed.program().getName(),
+ logTail(logs, ERROR_LOG_TAIL_LINES, ERROR_LOG_LINE_LENGTH));
+ tool.getService(ReaiLoggingService.class).error(
+ "RevEng.AI: analysis %d failed on the server".formatted(failed.analysisID().id()));
+ SwingUtilities.invokeLater(() -> {
+ if (fetchedLogs != null) {
+ // Show the same log in the panel, e.g. when the failure was found on opening the program
+ analysisLogComponent.consumeLogs(fetchedLogs, failed);
+ }
+ offerDetachAfterError(failed, message);
+ });
+ }
+ }, 0);
+ }
+
+ /// The service leaves the program as it was before the load, so it can simply be loaded again: from the
+ /// dialog straight away, or later from the Retry action.
+ private void reportFailedLoad(GhidraRevengService.ProgramWithID program, String message, @Nullable Exception error) {
+ var loggingService = tool.getService(ReaiLoggingService.class);
+ if (loggingService != null) {
+ loggingService.error(message);
+ }
+ // On the Swing thread, like programClosed, so a program closed during the load cannot be added after it
+ SwingUtilities.invokeLater(() -> {
+ if (program.program().isClosed()) {
+ // Closed during the load, which is likely why it failed. There is nothing left to retry on.
+ return;
+ }
+ failedLoads.add(program.program());
+ tool.setStatusInfo(message, true);
+ tool.contextChanged(null);
+ if (error == null) {
+ // Cancelled by the analyst, who needs no dialog to learn about it
+ return;
+ }
+ var choice = OptionDialog.showOptionDialog(tool.getToolFrame(),
+ ReaiPluginPackage.WINDOW_PREFIX + "Load analysis results", message + "\n\n" + RETRY_HINT,
+ "Retry", OptionDialog.ERROR_MESSAGE);
+ if (choice == OptionDialog.OPTION_ONE && failedLoads.contains(program.program())) {
+ loadAnalysisResults(program);
+ }
+ });
+ }
+
+ private static String loadFailedMessage(GhidraRevengService.ProgramWithID program, Exception error) {
+ // The API wraps its exceptions as `new RuntimeException(cause)`, whose message is the cause's class name
+ // followed by its message. The analyst only needs the message.
+ Throwable shown = error.getCause() != null && Objects.equals(error.getMessage(), error.getCause().toString())
+ ? error.getCause() : error;
+ var reason = shown.getMessage() != null ? shown.getMessage() : shown.getClass().getSimpleName();
+ return "Could not load the results of RevEng.AI analysis %d into %s: %s"
+ .formatted(program.analysisID().id(), program.program().getName(), reason);
+ }
+
+ private static String loadCancelledMessage(GhidraRevengService.ProgramWithID program) {
+ return "Loading the results of RevEng.AI analysis %d into %s was cancelled"
+ .formatted(program.analysisID().id(), program.program().getName());
+ }
+
+ /// The analysis log, or null when it could not be fetched
+ private String fetchAnalysisLog(GhidraRevengService.ProgramWithID failed) {
+ try {
+ return revengService.getAnalysisLog(failed.analysisID());
+ } catch (Exception e) {
+ // The log only adds detail; the failure is reported with what was received while waiting
+ Msg.warn(this, "Could not fetch the log of failed analysis " + failed, e);
+ return null;
+ }
+ }
+
+ private void offerDetachAfterError(GhidraRevengService.ProgramWithID failed, String message) {
+ if (!isStillAttached(failed)) {
+ // Closed or detached while the log was fetched: there is nothing left to offer
+ return;
+ }
+ var choice = OptionDialog.showOptionNoCancelDialog(
+ tool.getToolFrame(),
+ ReaiPluginPackage.WINDOW_PREFIX + "Analysis failed",
+ message,
+ "Detach",
+ "Keep attached",
+ OptionDialog.ERROR_MESSAGE);
+ // The dialog is modal, but check again: the association is what Detach removes
+ if (choice == OptionDialog.OPTION_ONE && isStillAttached(failed)) {
+ detach(failed);
+ }
+ }
+
+ private boolean isStillAttached(GhidraRevengService.ProgramWithID failed) {
+ return !failed.program().isClosed()
+ && revengService.getKnownProgram(failed.program()).filter(failed::equals).isPresent();
+ }
+
+ /// The last {@code maxLines} non-blank lines of the log, each cut to {@code maxLineLength}; empty when
+ /// there is no log
+ static String logTail(String logs, int maxLines, int maxLineLength) {
+ if (logs == null || logs.isBlank()) {
+ return "";
+ }
+ var lines = logs.lines().map(String::stripTrailing).filter(line -> !line.isBlank()).toList();
+ return lines.subList(Math.max(0, lines.size() - maxLines), lines.size()).stream()
+ .map(line -> line.length() <= maxLineLength ? line : line.substring(0, maxLineLength) + "...")
+ .collect(Collectors.joining("\n"));
+ }
+
+ static String analysisErrorMessage(int analysisId, String programName, String logTail) {
+ var message = new StringBuilder("The RevEng.AI analysis %d of %s failed on the server."
+ .formatted(analysisId, programName));
+ if (logTail.isEmpty()) {
+ message.append("\n\nNo analysis log is available.");
+ } else {
+ message.append("\n\nEnd of the analysis log:\n").append(logTail);
+ }
+ message.append("\n\nDetach the program to create a new analysis or attach to an existing one. "
+ + "Keep it attached to look into the failure with View in portal; you can detach it later from "
+ + ReaiPluginPackage.MENU_GROUP_NAME + " > Analysis > Detach.");
+ return message.toString();
+ }
+
+ static String unknownStatusOnOpenMessage(GhidraRevengService.ProgramWithID program) {
+ return ("RevEng.AI: analysis %d of %s reports a status this plugin does not recognise; not waiting for it. "
+ + "Reopen the program to check it again, or use View in portal.")
+ .formatted(program.analysisID().id(), program.program().getName());
+ }
+
+ static String checkStatusMessage(AnalysisStatus status) {
+ return "Analysis status: " + status;
}
}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java
index f797b076..09e26778 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/BinarySimilarityPlugin.java
@@ -16,6 +16,7 @@
package ai.reveng.toolkit.ghidra.plugins;
import ai.reveng.toolkit.ghidra.binarysimilarity.ui.aidecompiler.AIDecompilationdWindow;
+import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.AbstractFunctionMatchingDialog;
import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.BinaryLevelFunctionMatchingDialog;
import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.FunctionLevelFunctionMatchingDialog;
import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.SimilarFunctionsWindow;
@@ -134,8 +135,8 @@ private void setupActions() {
return;
}
- var functionMatchingDialog = new BinaryLevelFunctionMatchingDialog(tool, knownProgram.get());
- tool.showDialog(functionMatchingDialog);
+ AbstractFunctionMatchingDialog.showWhenLoaded(tool, knownProgram.get(),
+ basicInfo -> new BinaryLevelFunctionMatchingDialog(tool, knownProgram.get(), basicInfo));
})
.buildAndInstall(tool);
@@ -181,7 +182,7 @@ public void run(TaskMonitor monitor) {
.withContext(ProgramLocationActionContext.class)
.enabledWhen(context -> {
var apiService = getApiService();
- if (apiService == null) return false;
+ if (apiService == null || context.getAddress() == null) return false;
var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress());
return func != null
// Exclude thunks and external functions because we do not support them in the portal
@@ -196,8 +197,8 @@ public void run(TaskMonitor monitor) {
var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress());
- var functionMatchingDialog = new FunctionLevelFunctionMatchingDialog(tool, knownProgram, func);
- tool.showDialog(functionMatchingDialog);
+ AbstractFunctionMatchingDialog.showWhenLoaded(tool, knownProgram,
+ basicInfo -> new FunctionLevelFunctionMatchingDialog(tool, knownProgram, basicInfo, func));
})
.popupMenuPath(new String[] { "Match function" })
.popupMenuIcon(ReaiPluginPackage.REVENG_16)
@@ -209,7 +210,7 @@ public void run(TaskMonitor monitor) {
.withContext(ProgramLocationActionContext.class)
.enabledWhen(context -> {
var apiService = getApiService();
- if (apiService == null) return false;
+ if (apiService == null || context.getAddress() == null) return false;
var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress());
return func != null
// Exclude thunks and external functions because we do not support them in the portal
@@ -243,7 +244,7 @@ public void run(TaskMonitor monitor) {
.withContext(ProgramLocationActionContext.class)
.enabledWhen(context -> {
var apiService = getApiService();
- if (apiService == null) return false;
+ if (apiService == null || context.getAddress() == null) return false;
var func = context.getProgram().getFunctionManager().getFunctionContaining(context.getAddress());
return func != null
&& apiService.getAnalysedProgram(context.getProgram()).isPresent();
@@ -283,7 +284,7 @@ public void run(TaskMonitor monitor) {
}
private static String formatSyncSummary(GhidraRevengService.SyncSummary summary) {
- return ("Synced %d matched function(s) with the portal.\n" +
+ var text = new StringBuilder(("Synced %d matched function(s) with the portal.\n" +
"Applied %d remote name(s) and %d remote signature(s); canonicalized %d and de-duplicated %d.\n" +
"Pushed %d name(s) and %d type set(s) back to the portal.").formatted(
summary.matchedFunctions(),
@@ -292,7 +293,21 @@ private static String formatSyncSummary(GhidraRevengService.SyncSummary summary)
summary.canonicalizedNames(),
summary.dedupedNames(),
summary.pushedNames(),
- summary.pushedTypeSets());
+ summary.pushedTypeSets()));
+ if (summary.pushedLocalEdits() > 0) {
+ text.append("\nPushed %d local edit(s) that had not reached the portal yet."
+ .formatted(summary.pushedLocalEdits()));
+ }
+ if (summary.failedLocalEdits() > 0) {
+ text.append("\n%d local edit(s) still could not be pushed; the RevEng.AI log says why, and they are kept for the next sync."
+ .formatted(summary.failedLocalEdits()));
+ }
+ if (summary.nameConflicts() > 0 || summary.signatureConflicts() > 0) {
+ text.append(("\n%d name(s) and %d signature(s) differ between Ghidra and the portal and were left "
+ + "as they are locally; the RevEng.AI log lists them.")
+ .formatted(summary.nameConflicts(), summary.signatureConflicts()));
+ }
+ return text.toString();
}
@Override
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java
index 9a4c49db..22c8a0c5 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java
@@ -4,21 +4,28 @@
import ai.reveng.toolkit.ghidra.binarysimilarity.ui.help.HelpDialog;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService;
import ai.reveng.toolkit.ghidra.core.services.api.types.ApiInfo;
+import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker;
+import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker.UpdateInfo;
+import ai.reveng.toolkit.ghidra.core.ui.WebBrowser;
import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardManager;
import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardStateKey;
import docking.ActionContext;
import docking.action.builder.ActionBuilder;
+import docking.widgets.OptionDialog;
import docking.wizard.WizardManager;
import docking.wizard.WizardState;
import ghidra.app.plugin.PluginCategoryNames;
+import ghidra.framework.Application;
import ghidra.framework.plugintool.Plugin;
import ghidra.framework.plugintool.PluginInfo;
import ghidra.framework.plugintool.PluginTool;
import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.util.Msg;
+import ghidra.util.Swing;
import org.json.JSONException;
import java.io.FileNotFoundException;
+import java.net.URI;
import java.nio.file.Path;
import java.util.Optional;
@@ -34,14 +41,21 @@
)
public class ReaiAPIServicePlugin extends Plugin {
private GhidraRevengService revengService;
+ private Optional update = Optional.empty();
+ // One startup prompt per Ghidra session, even with several tools open.
+ private static boolean updatePromptShown = false;
private static final String REAI_PLUGIN_SETUP_MENU_GROUP = "RevEng.AI Setup";
public static final String REAI_WIZARD_RUN_PREF = "REAISetupWizardRun";
+ public static final String CHECK_FOR_UPDATES_PREF = "Check for updates";
+ public static final String SKIPPED_UPDATE_PREF = "Skipped update version";
public ReaiAPIServicePlugin(PluginTool tool) {
super(tool);
tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(REAI_WIZARD_RUN_PREF, "false", null, "If the setup wizard has been run");
+ tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(CHECK_FOR_UPDATES_PREF, true, null, "Check GitHub for a newer plugin release on startup");
+ tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(SKIPPED_UPDATE_PREF, "", null, "Release the user chose not to be prompted about");
// Try to get API info from config file or tool options
Optional apiInfoOpt = getApiInfoFromConfig()
@@ -61,6 +75,47 @@ public ReaiAPIServicePlugin(PluginTool tool) {
registerServiceProvided(GhidraRevengService.class, revengService);
setupActions();
+ checkForUpdates();
+ }
+
+ private void checkForUpdates() {
+ var currentVersion = UpdateChecker.currentVersion();
+ if (!tool.getOptions(REAI_OPTIONS_CATEGORY).getBoolean(CHECK_FOR_UPDATES_PREF, true)
+ || currentVersion.equals(UpdateChecker.UNKNOWN_VERSION)) {
+ return;
+ }
+ UpdateChecker.check(currentVersion, Application.getApplicationVersion())
+ .thenAccept(result -> result.ifPresent(u -> Swing.runLater(() -> notifyUpdate(u))));
+ }
+
+ private void notifyUpdate(UpdateInfo u) {
+ // The check can outlive the tool.
+ if (isDisposed()) {
+ return;
+ }
+ update = Optional.of(u);
+
+ new ActionBuilder("Update available", this.toString())
+ .withContext(ActionContext.class)
+ .onAction(context -> WebBrowser.open(URI.create(u.downloadUrl())))
+ .menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "Update available (" + u.version() + ")" })
+ .menuGroup(REAI_PLUGIN_SETUP_MENU_GROUP, "050")
+ .buildAndInstall(tool);
+ tool.setStatusInfo("RevEng.AI plugin " + u.version() + " is available");
+
+ var options = tool.getOptions(REAI_OPTIONS_CATEGORY);
+ if (updatePromptShown || u.version().equals(options.getString(SKIPPED_UPDATE_PREF, ""))) {
+ return;
+ }
+ updatePromptShown = true;
+ int choice = OptionDialog.showOptionNoCancelDialog(tool.getToolFrame(), "RevEng.AI update available",
+ "RevEng.AI plugin " + u.version() + " is available. You have " + UpdateChecker.currentVersion() + ".",
+ "Download", "Later", "Skip this version", OptionDialog.INFORMATION_MESSAGE);
+ if (choice == OptionDialog.OPTION_ONE) {
+ WebBrowser.open(URI.create(u.downloadUrl()));
+ } else if (choice == OptionDialog.OPTION_THREE) {
+ options.setString(SKIPPED_UPDATE_PREF, u.version());
+ }
}
/**
@@ -114,7 +169,7 @@ private void setupActions() {
new ActionBuilder("About", this.toString())
.withContext(ActionContext.class)
.onAction(context -> {
- var aboutDialog = new AboutDialog(tool);
+ var aboutDialog = new AboutDialog(tool, update);
tool.showDialog(aboutDialog);
})
.menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "About" })
@@ -160,6 +215,17 @@ protected void runSetupWizard() {
SetupWizardManager setupManager = new SetupWizardManager(wizardState, getTool());
WizardManager wizardManager = new WizardManager("RevEng.AI: Configuration", true, setupManager);
wizardManager.showWizard(tool.getToolFrame());
+
+ // The wizard is modal, so it has finished or been cancelled by now. Finishing stores the new
+ // credentials in the tool options; the running service has to follow them, or it keeps
+ // talking to the old host with the old key until Ghidra restarts.
+ if (revengService != null) {
+ getApiInfoFromToolOptions().ifPresent(apiInfo -> {
+ if (revengService.reconfigure(apiInfo)) {
+ Msg.info(this, "RevEng.AI service now uses " + apiInfo.hostURI());
+ }
+ });
+ }
}
}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java
index d83404bb..54dda60f 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiPluginPackage.java
@@ -1,7 +1,7 @@
package ai.reveng.toolkit.ghidra.plugins;
+import generic.theme.GIcon;
import ghidra.framework.plugintool.util.PluginPackage;
-import resources.ResourceManager;
import javax.swing.*;
import java.nio.file.Path;
@@ -32,13 +32,13 @@ public class ReaiPluginPackage extends PluginPackage {
@Deprecated
public static final Integer INVALID_ANALYSIS_ID = -1;
- public static final Icon REVENG_16 = ResourceManager.loadImage("images/reveng_16.png");
+ public static final Icon REVENG_16 = new GIcon("icon.reveng.mark.16");
/**
* Create a Top Level Plugin Package that uses the RevEng.AI logo
*/
public ReaiPluginPackage() {
- super(NAME, ResourceManager.loadImage("images/icon.png"), "AI Assisted Binary Analysis");
+ super(NAME, new GIcon("icon.reveng.mark.large"), "AI Assisted Binary Analysis");
}
}
\ No newline at end of file
diff --git a/src/main/java/docking/wizard/WizardManager.java b/src/main/java/docking/wizard/WizardManager.java
index e53edad3..b5640158 100644
--- a/src/main/java/docking/wizard/WizardManager.java
+++ b/src/main/java/docking/wizard/WizardManager.java
@@ -23,6 +23,7 @@
import javax.swing.*;
import javax.swing.border.TitledBorder;
+import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider;
import docking.DockingWindowManager;
import docking.ReusableDialogComponentProvider;
import docking.widgets.EmptyBorderButton;
@@ -33,7 +34,6 @@
import help.Help;
import help.HelpService;
import resources.Icons;
-import resources.ResourceManager;
/**
* A dialog that controls the panels for going to "Next" and "Previous" in some
@@ -221,41 +221,12 @@ public void componentResized(ComponentEvent e) {
}
});
- // Load custom icon from resources if wizardIcon is null
- if (wizardIcon == null) {
- try {
- wizardIcon = ResourceManager.loadImage("images/icon_50.png");
- } catch (Exception e) {
- // If loading fails, fall back to no icon
- wizardIcon = null;
- }
- }
-
- // Create title label without icon - icon will be handled separately
titleLabel = new GDLabel(INIT_TITLE);
- // Make the title text bold
- Font currentFont = titleLabel.getFont();
- titleLabel.setFont(currentFont.deriveFont(Font.BOLD));
-
- JPanel titlePanel = new JPanel(new BorderLayout());
- titlePanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
- BorderFactory.createEmptyBorder(5, 5, 5, 5)));
-
- // Add icon to the left if available
+ JPanel titlePanel = RevEngDialogComponentProvider.createTitlePanel(titleLabel);
if (wizardIcon != null) {
- JLabel iconLabel = new JLabel(wizardIcon);
- titlePanel.add(iconLabel, BorderLayout.WEST);
+ titleLabel.setIcon(wizardIcon);
}
- // Create a centered panel for the title text
- JPanel centerPanel = new JPanel();
- centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
- centerPanel.add(Box.createHorizontalGlue());
- centerPanel.add(titleLabel);
- centerPanel.add(Box.createHorizontalGlue());
-
- titlePanel.add(centerPanel, BorderLayout.CENTER);
-
mainJPanel = new JPanel(new BorderLayout());
mainJPanel.add(titlePanel, BorderLayout.NORTH);
mainJPanel.add(scrollPane, BorderLayout.CENTER);
diff --git a/src/main/resources/images/icon.png b/src/main/resources/images/icon.png
index ae04979a..ade1fefb 100644
Binary files a/src/main/resources/images/icon.png and b/src/main/resources/images/icon.png differ
diff --git a/src/main/resources/images/icon_50.png b/src/main/resources/images/icon_50.png
deleted file mode 100644
index d4baed04..00000000
Binary files a/src/main/resources/images/icon_50.png and /dev/null differ
diff --git a/src/main/resources/images/icon_dark.png b/src/main/resources/images/icon_dark.png
new file mode 100644
index 00000000..b95f8cff
Binary files /dev/null and b/src/main/resources/images/icon_dark.png differ
diff --git a/src/main/resources/images/reveng_16.png b/src/main/resources/images/reveng_16.png
index d822d7b2..b58f038b 100644
Binary files a/src/main/resources/images/reveng_16.png and b/src/main/resources/images/reveng_16.png differ
diff --git a/src/main/resources/images/reveng_16_dark.png b/src/main/resources/images/reveng_16_dark.png
new file mode 100644
index 00000000..0938614f
Binary files /dev/null and b/src/main/resources/images/reveng_16_dark.png differ
diff --git a/src/main/resources/images/reveng_24.png b/src/main/resources/images/reveng_24.png
new file mode 100644
index 00000000..781deae0
Binary files /dev/null and b/src/main/resources/images/reveng_24.png differ
diff --git a/src/main/resources/images/reveng_24_dark.png b/src/main/resources/images/reveng_24_dark.png
new file mode 100644
index 00000000..15c1c1c8
Binary files /dev/null and b/src/main/resources/images/reveng_24_dark.png differ
diff --git a/src/main/resources/images/reveng_32.png b/src/main/resources/images/reveng_32.png
deleted file mode 100644
index 0f6aca5f..00000000
Binary files a/src/main/resources/images/reveng_32.png and /dev/null differ
diff --git a/src/test/java/ai/reveng/AIDecompilerComponentTest.java b/src/test/java/ai/reveng/AIDecompilerComponentTest.java
index c5e1d637..ad975e91 100644
--- a/src/test/java/ai/reveng/AIDecompilerComponentTest.java
+++ b/src/test/java/ai/reveng/AIDecompilerComponentTest.java
@@ -429,6 +429,165 @@ public void triggerAIDecompilationInlineComments(FunctionID functionID) {
assertEquals("summary trigger must be retried after a 409", 2, summaryTriggers.get());
}
+ /// A summary trigger that fails with anything but 409 ends the wait: the summary will never arrive
+ @Test
+ public void testSummaryTriggerFailureStopsPolling() throws Exception {
+ var tool = env.getTool();
+ var summaryTriggers = new AtomicInteger();
+ var polls = new AtomicInteger();
+
+ var service = addMockedService(tool, new UnimplementedAPI() {
+ @Override
+ public AnalysisStatus status(AnalysisID analysisID) {
+ return AnalysisStatus.Complete;
+ }
+
+ @Override
+ public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException {
+ return new AnalysisID(1);
+ }
+
+ @Override
+ public List getFunctionInfo(AnalysisID analysisID) {
+ return List.of(new FunctionInfo(new FunctionID(1), "portal_func_1", "portal_func_1_mangled", 0x1000L, 10));
+ }
+
+ @Override
+ public AIDecompilationStatus pollAIDecompileStatus(FunctionID functionID) {
+ polls.incrementAndGet();
+ return new AIDecompilationStatus(
+ DecompilationData.StatusEnum.COMPLETED,
+ "void func1() { return; }",
+ null,
+ null,
+ WorkflowProgress.StatusEnum.UNINITIALISED,
+ WorkflowProgress.StatusEnum.UNINITIALISED,
+ List.of(),
+ null);
+ }
+
+ @Override
+ public void triggerAIDecompilationSummary(FunctionID functionID) {
+ summaryTriggers.incrementAndGet();
+ throw new RuntimeException("Failed to trigger AI decompilation summary",
+ new ApiException(402, "Insufficient credits"));
+ }
+ });
+
+ env.addPlugin(BinarySimilarityPlugin.class);
+ var builder = newX64Program();
+ var func1 = builder.createEmptyFunction(null, "0x1000", 10, Undefined.getUndefinedDataType(4));
+ var programWithID = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY);
+ env.showTool(programWithID.program());
+
+ var aiDecompComponent = getComponentProvider(AIDecompilationdWindow.class);
+ aiDecompComponent.setVisible(true);
+ RSyntaxTextArea textArea = (RSyntaxTextArea) getInstanceField("textArea", aiDecompComponent);
+
+ var action = getAction(tool, "AI Decompilation");
+ var context = new ProgramLocationActionContext(
+ null,
+ programWithID.program(),
+ new ProgramLocation(programWithID.program(), func1.getEntryPoint()),
+ null, null);
+ performAction(action, context, true);
+ waitForTasks();
+ waitForSwing();
+
+ assertEquals(1, summaryTriggers.get());
+ // The status check before triggering, and the one poll that saw the decompilation completed
+ assertEquals(2, polls.get());
+ assertEquals("void func1() { return; }", textArea.getText());
+ }
+
+ /// A FAILED decompilation can be run again with the Regenerate action; Refresh alone only re-reads the failure
+ @Test
+ public void testRegenerateFailedDecompilation() throws Exception {
+ var tool = env.getTool();
+ var triggers = new AtomicInteger();
+
+ var service = addMockedService(tool, new UnimplementedAPI() {
+ @Override
+ public AnalysisStatus status(AnalysisID analysisID) {
+ return AnalysisStatus.Complete;
+ }
+
+ @Override
+ public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException {
+ return new AnalysisID(1);
+ }
+
+ @Override
+ public List getFunctionInfo(AnalysisID analysisID) {
+ return List.of(new FunctionInfo(new FunctionID(1), "portal_func_1", "portal_func_1_mangled", 0x1000L, 10));
+ }
+
+ @Override
+ public AIDecompilationStatus pollAIDecompileStatus(FunctionID functionID) {
+ if (triggers.get() == 0) {
+ return new AIDecompilationStatus(
+ DecompilationData.StatusEnum.FAILED, "", null, null, null, null, List.of(), null);
+ }
+ return new AIDecompilationStatus(
+ DecompilationData.StatusEnum.COMPLETED,
+ "void func1() { return; }",
+ "Mocked Description Summary",
+ null,
+ WorkflowProgress.StatusEnum.COMPLETED,
+ WorkflowProgress.StatusEnum.COMPLETED,
+ List.of(),
+ null);
+ }
+
+ @Override
+ public boolean triggerAIDecompilationForFunctionID(FunctionID functionID) {
+ triggers.incrementAndGet();
+ return true;
+ }
+ });
+
+ env.addPlugin(BinarySimilarityPlugin.class);
+ var builder = newX64Program();
+ var func1 = builder.createEmptyFunction(null, "0x1000", 10, Undefined.getUndefinedDataType(4));
+ var programWithID = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY);
+ env.showTool(programWithID.program());
+
+ var aiDecompComponent = getComponentProvider(AIDecompilationdWindow.class);
+ aiDecompComponent.setVisible(true);
+ RSyntaxTextArea textArea = (RSyntaxTextArea) getInstanceField("textArea", aiDecompComponent);
+ javax.swing.JEditorPane descriptionArea =
+ (javax.swing.JEditorPane) getInstanceField("descriptionArea", aiDecompComponent);
+
+ var action = getAction(tool, "AI Decompilation");
+ var context = new ProgramLocationActionContext(
+ null,
+ programWithID.program(),
+ new ProgramLocation(programWithID.program(), func1.getEntryPoint()),
+ null, null);
+ performAction(action, context, true);
+ waitForTasks();
+ waitForSwing();
+
+ assertEquals("a FAILED decompilation must not be re-triggered on its own", 0, triggers.get());
+ assertTrue(descriptionArea.getText(), descriptionArea.getText().contains("Regenerate"));
+
+ performAction(getLocalAction(aiDecompComponent, "Refresh AI Decompilation"));
+ waitForTasks();
+ waitForSwing();
+ assertEquals("Refresh only re-reads the result", 0, triggers.get());
+
+ var regenerate = getLocalAction(aiDecompComponent, "Regenerate AI Decompilation");
+ assertTrue(runSwing(() -> regenerate.isEnabledForContext(aiDecompComponent.getActionContext(null))));
+ performAction(regenerate);
+ waitForTasks();
+ waitForSwing();
+
+ assertEquals(1, triggers.get());
+ assertEquals("void func1() { return; }", textArea.getText());
+ assertFalse("Regenerate is only offered for a failed decompilation",
+ runSwing(() -> regenerate.isEnabledForContext(aiDecompComponent.getActionContext(null))));
+ }
+
static class RatingsAPI extends UnimplementedAPI {
String lastFeedback;
String lastReason;
@@ -504,4 +663,18 @@ public void aiDecompRating(FunctionID functionID, String rating, String reason)
super.aiDecompRating(functionID, rating, reason);
}
}
+
+ /// The Decompiler reports a context without an address when the cursor is on a blank line.
+ @Test
+ public void popupActionsAreDisabledForContextWithoutAddress() throws Exception {
+ var tool = env.getTool();
+ addMockedService(tool, new UnimplementedAPI());
+ env.addPlugin(BinarySimilarityPlugin.class);
+ var program = newX64Program().getProgram();
+
+ var context = new ProgramLocationActionContext(null, program, null, null, null);
+ for (String name : List.of("Match function", "AI Decompilation", "View function in portal")) {
+ assertFalse(name, getAction(tool, name).isEnabledForContext(context));
+ }
+ }
}
diff --git a/src/test/java/ai/reveng/AgentChatWindowTest.java b/src/test/java/ai/reveng/AgentChatWindowTest.java
index 10f02c58..96bc0e38 100644
--- a/src/test/java/ai/reveng/AgentChatWindowTest.java
+++ b/src/test/java/ai/reveng/AgentChatWindowTest.java
@@ -12,6 +12,7 @@
import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus;
import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo;
import ai.reveng.toolkit.ghidra.plugins.AgentChatPlugin;
+import ai.reveng.toolkit.ghidra.plugins.LoggingPlugin;
import ghidra.program.model.data.Undefined;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Program;
@@ -157,4 +158,18 @@ public List getFunctionInfo(AnalysisID analysisID) {
assertEquals("agent rename must overwrite the existing local name",
"renamed_by_agent", func.getName());
}
+
+ /// Plugins are constructed in list order, before services are resolved, so the chat must not
+ /// capture the logging service until it is available.
+ @Test
+ public void capturesLoggingServiceWhenLoadedBeforeLoggingPlugin() throws Exception {
+ var tool = env.getTool();
+ addMockedService(tool, new UnimplementedAPI());
+ tool.removePlugins(List.of(env.getPlugin(LoggingPlugin.class)));
+
+ tool.addPlugins(List.of(AgentChatPlugin.class.getName(), LoggingPlugin.class.getName()));
+
+ var controller = getInstanceField("controller", getComponentProvider(AgentChatWindow.class));
+ assertNotNull(getInstanceField("log", controller));
+ }
}
diff --git a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java
index af3c4fda..467575f0 100644
--- a/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java
+++ b/src/test/java/ai/reveng/AnalysisOptionsDialogTest.java
@@ -22,8 +22,8 @@
import javax.swing.*;
-import ai.reveng.model.AnalysisCreateRequest;
-import ai.reveng.model.User;
+import ai.reveng.model.CreateRequest;
+import ai.reveng.model.CurrentUser;
import ai.reveng.toolkit.ghidra.binarysimilarity.ui.analysiscreation.RevEngAIAnalysisOptionsDialog;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService;
import ai.reveng.toolkit.ghidra.core.services.api.mocks.MockApi;
@@ -71,7 +71,7 @@ public void testBasicOptionsDialog() throws Exception {
/**
* Pins the analysis configuration the dialog submits. The dialog offers no controls for
- * capability generation, advanced analysis, third-party scraping or sandbox execution, so
+ * capability generation, third-party scraping or sandbox execution, so
* every analysis it creates must carry these fixed values.
*/
@Test
@@ -95,12 +95,11 @@ public void testSubmittedAnalysisConfig() throws Exception {
var options = dialog.getOptionsFromUI();
assertNotNull(options);
- AnalysisCreateRequest request = options.toAnalysisCreateRequest();
+ CreateRequest request = options.toAnalysisCreateRequest();
var analysisConfig = request.getAnalysisConfig();
assertNotNull("The request must always carry an analysis config", analysisConfig);
assertEquals("Capabilities are never generated", Boolean.FALSE, analysisConfig.getGenerateCapabilities());
- assertEquals("Advanced analysis is never requested", Boolean.FALSE, analysisConfig.getAdvancedAnalysis());
assertNull("Third-party scraping is never requested", analysisConfig.getScrapeThirdPartyConfig());
assertNull("Sandbox execution is never requested", analysisConfig.getSandboxConfig());
@@ -113,8 +112,8 @@ public void testSubmittedAnalysisConfig() throws Exception {
public void testPrivateScopeDisabledForEnthusiast() throws Exception {
var reService = new GhidraRevengService(new MockApi() {
@Override
- public User getMe() {
- return new User().tier(User.TierEnum.ENTHUSIAST);
+ public CurrentUser getMe() {
+ return new CurrentUser().tier(CurrentUser.TierEnum.ENTHUSIAST);
}
});
var builder = newX64Program();
@@ -151,8 +150,8 @@ public User getMe() {
public void testPrivateScopeEnabledForNonEnthusiast() throws Exception {
var reService = new GhidraRevengService(new MockApi() {
@Override
- public User getMe() {
- return new User().tier(User.TierEnum.REVERSER);
+ public CurrentUser getMe() {
+ return new CurrentUser().tier(CurrentUser.TierEnum.REVERSER);
}
});
var builder = newX64Program();
@@ -185,7 +184,7 @@ public User getMe() {
public void testPrivateScopeDisabledWhenTierFetchFails() throws Exception {
var reService = new GhidraRevengService(new MockApi() {
@Override
- public User getMe() {
+ public CurrentUser getMe() {
throw new RuntimeException("tier lookup failed");
}
});
@@ -226,13 +225,13 @@ public void testStartAnalysisBlockedUntilTierResolves() throws Exception {
CountDownLatch release = new CountDownLatch(1);
var reService = new GhidraRevengService(new MockApi() {
@Override
- public User getMe() {
+ public CurrentUser getMe() {
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
- return new User().tier(User.TierEnum.REVERSER);
+ return new CurrentUser().tier(CurrentUser.TierEnum.REVERSER);
}
});
var builder = newX64Program();
@@ -268,8 +267,8 @@ public User getMe() {
public void testGetOptionsIgnoresDisabledPrivateSelection() throws Exception {
var reService = new GhidraRevengService(new MockApi() {
@Override
- public User getMe() {
- return new User().tier(User.TierEnum.ENTHUSIAST);
+ public CurrentUser getMe() {
+ return new CurrentUser().tier(CurrentUser.TierEnum.ENTHUSIAST);
}
});
var builder = newX64Program();
diff --git a/src/test/java/ai/reveng/ApplyMatchCmdTest.java b/src/test/java/ai/reveng/ApplyMatchCmdTest.java
index bade3af4..1c69876c 100644
--- a/src/test/java/ai/reveng/ApplyMatchCmdTest.java
+++ b/src/test/java/ai/reveng/ApplyMatchCmdTest.java
@@ -3,6 +3,7 @@
import ai.reveng.invoker.ApiException;
import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd;
import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder;
+import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService;
import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID;
import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.BinaryHash;
import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID;
@@ -11,18 +12,28 @@
import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo;
import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch;
import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature;
+import ghidra.program.model.data.FunctionDefinitionDataType;
+import ghidra.program.model.data.IntegerDataType;
+import ghidra.program.model.data.ParameterDefinitionImpl;
+import ghidra.program.model.data.PointerDataType;
import ghidra.program.model.data.Undefined;
+import ghidra.program.model.listing.Function;
import ghidra.util.task.TaskMonitor;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ApplyMatchCmdTest extends RevEngMockableHeadedIntegrationTest {
+ private GhidraRevengService.AnalysedProgram analysedProgram;
+
@Test
public void testFailedServerRenameDoesNotLeakTransaction() throws Exception {
var tool = env.getTool();
@@ -43,7 +54,8 @@ public void testFailedServerRenameDoesNotLeakTransaction() throws Exception {
new BinaryHash("abc123"),
false,
BigDecimal.valueOf(0.9),
- BigDecimal.valueOf(0.9));
+ BigDecimal.valueOf(0.9),
+ null);
var ghidraMatch = new GhidraFunctionMatchWithSignature(func1, match, null);
var cmd = new ApplyMatchCmd(service, analysedProgram, ghidraMatch, true);
@@ -58,6 +70,98 @@ public void testFailedServerRenameDoesNotLeakTransaction() throws Exception {
program.getCurrentTransactionInfo());
}
+ @Test
+ public void testTransferNameLeavesSignatureAlone() throws Exception {
+ var function = setUpFunction();
+
+ assertTrue(apply(function, matchWithSignature(function), ApplyMatchCmd.Transfer.NAME));
+
+ assertEquals("renamed_func", function.getName());
+ assertEquals("the signature must not be transferred", 0, function.getParameterCount());
+ }
+
+ @Test
+ public void testTransferSignatureKeepsName() throws Exception {
+ var function = setUpFunction();
+ var originalName = function.getName();
+
+ assertTrue(apply(function, matchWithSignature(function), ApplyMatchCmd.Transfer.SIGNATURE));
+
+ assertEquals("the name must not be transferred", originalName, function.getName());
+ assertEquals("the function must stay in its namespace",
+ function.getProgram().getGlobalNamespace(), function.getParentNamespace());
+ assertEquals(2, function.getParameterCount());
+ assertEquals(IntegerDataType.dataType.getName(), function.getReturnType().getName());
+ assertEquals("buf", function.getParameter(1).getName());
+ }
+
+ @Test
+ public void testTransferNameAndSignature() throws Exception {
+ var function = setUpFunction();
+
+ assertTrue(apply(function, matchWithSignature(function), ApplyMatchCmd.Transfer.NAME_AND_SIGNATURE));
+
+ assertEquals("renamed_func", function.getName());
+ assertEquals(2, function.getParameterCount());
+ assertEquals("buf", function.getParameter(1).getName());
+ }
+
+ @Test
+ public void testTransferSignatureWithoutOneDoesNothing() throws Exception {
+ var function = setUpFunction();
+ var originalName = function.getName();
+ var match = new GhidraFunctionMatchWithSignature(function, functionMatch(), null);
+
+ assertFalse(apply(function, match, ApplyMatchCmd.Transfer.SIGNATURE));
+ assertEquals(originalName, function.getName());
+ }
+
+ private Function setUpFunction() throws Exception {
+ var service = addMockedService(env.getTool(), new RenameFailsAPI());
+ var builder = newX64Program();
+ var function = builder.createEmptyFunction(null, "0x1000", 10, Undefined.getUndefinedDataType(4));
+ service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY);
+ analysedProgram = service.getAnalysedProgram(builder.getProgram()).orElseThrow();
+ return function;
+ }
+
+ /// Applied without a service, as the matching dialog does, so nothing is pushed to the portal
+ private boolean apply(Function function, GhidraFunctionMatchWithSignature match, ApplyMatchCmd.Transfer transfer) {
+ var program = function.getProgram();
+ var cmd = new ApplyMatchCmd(null, analysedProgram, match, false, transfer);
+ var tx = program.startTransaction("test");
+ boolean applied = false;
+ try {
+ applied = cmd.applyTo(program);
+ } finally {
+ program.endTransaction(tx, applied);
+ }
+ return applied;
+ }
+
+ private static FunctionMatch functionMatch() {
+ return new FunctionMatch(
+ new FunctionID(1),
+ new FunctionID(2),
+ "renamed_func",
+ "renamed_func_mangled",
+ "libfoo.so",
+ new BinaryHash("abc123"),
+ false,
+ BigDecimal.valueOf(0.9),
+ BigDecimal.valueOf(0.9),
+ null);
+ }
+
+ private static GhidraFunctionMatchWithSignature matchWithSignature(Function function) {
+ var signature = new FunctionDefinitionDataType("renamed_func");
+ signature.setReturnType(IntegerDataType.dataType);
+ signature.setArguments(
+ new ParameterDefinitionImpl("len", IntegerDataType.dataType, null),
+ new ParameterDefinitionImpl("buf", PointerDataType.dataType, null));
+ return new GhidraFunctionMatchWithSignature(function, functionMatch(), signature);
+ }
+
static class RenameFailsAPI extends UnimplementedAPI {
@Override
public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException {
diff --git a/src/test/java/ai/reveng/AutoUnstripSyncTest.java b/src/test/java/ai/reveng/AutoUnstripSyncTest.java
index 5385195c..b16a12c1 100644
--- a/src/test/java/ai/reveng/AutoUnstripSyncTest.java
+++ b/src/test/java/ai/reveng/AutoUnstripSyncTest.java
@@ -1,5 +1,6 @@
package ai.reveng;
+import ai.reveng.invoker.ApiException;
import ai.reveng.model.BatchRenameInputBody;
import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService;
import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface;
@@ -15,12 +16,19 @@
import ghidra.util.task.TaskMonitor;
import org.junit.Test;
+import java.time.Duration;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch;
@@ -41,7 +49,10 @@ private static class UnstripApi extends UnimplementedAPI {
final List renameCalls = new ArrayList<>();
final Deque unstripStatuses = new ArrayDeque<>();
List functions = List.of();
- int getFunctionInfoCalls = 0;
+ volatile int getFunctionInfoCalls = 0;
+ /// When set, a function info fetch (the start of a sync) blocks until it is released.
+ volatile CountDownLatch inSync;
+ volatile CountDownLatch releaseSync;
@Override
public AnalysisStatus status(TypedApiInterface.AnalysisID analysisID) {
@@ -51,6 +62,14 @@ public AnalysisStatus status(TypedApiInterface.AnalysisID analysisID) {
@Override
public List getFunctionInfo(TypedApiInterface.AnalysisID analysisID) {
getFunctionInfoCalls++;
+ if (inSync != null) {
+ inSync.countDown();
+ try {
+ releaseSync.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
return functions;
}
@@ -61,16 +80,63 @@ public FunctionSignatureBatch listFunctionSignatures(List failures = new ArrayDeque<>();
+ final AtomicInteger statusCalls = new AtomicInteger();
+ /// When set, a status poll blocks until it is released.
+ volatile CountDownLatch inPoll;
+ volatile CountDownLatch releasePoll;
+
@Override
- public AutoUnstripStatus getAutoUnstripStatus(TypedApiInterface.AnalysisID analysisID) {
+ public AutoUnstripStatus getAutoUnstripStatus(TypedApiInterface.AnalysisID analysisID) throws ApiException {
+ statusCalls.incrementAndGet();
+ if (inPoll != null) {
+ inPoll.countDown();
+ try {
+ releasePoll.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ var failure = failures.poll();
+ if (failure instanceof WrappedApiException wrapped) {
+ throw wrapped.apiException;
+ }
+ if (failure != null) {
+ throw failure;
+ }
return unstripStatuses.size() > 1 ? unstripStatuses.poll() : unstripStatuses.peek();
}
}
+ /// Lets an {@link ApiException} sit in the failure script next to runtime exceptions.
+ private static class WrappedApiException extends RuntimeException {
+ final ApiException apiException;
+
+ WrappedApiException(int code) {
+ this.apiException = new ApiException(code, "HTTP " + code);
+ }
+ }
+
+ /// Records every message the service surfaces to the user.
+ private static class Announcements implements BiConsumer {
+ final List warnings = new CopyOnWriteArrayList<>();
+ final List all = new CopyOnWriteArrayList<>();
+
+ @Override
+ public void accept(String message, Boolean warning) {
+ all.add(message);
+ if (warning) {
+ warnings.add(message);
+ }
+ }
+ }
+
private record Fixture(GhidraRevengService service, GhidraRevengService.AnalysedProgram analysed, Function function) {}
private Fixture setUp(UnstripApi api) throws Exception {
@@ -147,4 +213,243 @@ public void syncsAfterUnstripTransitionsToComplete() throws Exception {
syncService.dispose();
}
}
+
+ private static AutoUnstripSyncService fastService(Fixture fixture, BiConsumer notifier,
+ Duration maxPollDuration) {
+ return new AutoUnstripSyncService(fixture.service(), NOOP_LOG, notifier,
+ Duration.ofMillis(50), maxPollDuration);
+ }
+
+ @Test
+ public void stopPollingDuringAPollEndsPolling() throws Exception {
+ var api = new UnstripApi();
+ api.unstripStatuses.add(AutoUnstripStatus.RUNNING);
+ api.inPoll = new CountDownLatch(1);
+ api.releasePoll = new CountDownLatch(1);
+ var fixture = setUp(api);
+
+ var syncService = fastService(fixture, (m, w) -> {}, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue(api.inPoll.await(5, TimeUnit.SECONDS));
+ assertTrue(syncService.stopPolling(fixture.analysed().analysisID()));
+ api.inPoll = null;
+ api.releasePoll.countDown();
+ Thread.sleep(500);
+ assertEquals("a poll running when polling stops must not schedule another", 1, api.statusCalls.get());
+ assertFalse("polling is no longer active", syncService.stopPolling(fixture.analysed().analysisID()));
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void givesUpAndWarnsWhenUnstripNeverFinishes() throws Exception {
+ var api = new UnstripApi();
+ api.unstripStatuses.add(AutoUnstripStatus.RUNNING);
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMillis(400));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue("running out of time is reported", waitUntil(() -> !announcements.warnings.isEmpty(), 5000));
+ int calls = api.statusCalls.get();
+ Thread.sleep(300);
+ assertEquals("no polls after giving up", calls, api.statusCalls.get());
+ assertTrue(announcements.warnings.get(0).contains("stopped waiting"));
+ assertEquals(1, announcements.warnings.size());
+ assertEquals(0, api.getFunctionInfoCalls);
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void retriesServerErrorsAndSyncsOnceUnstripCompletes() throws Exception {
+ var api = new UnstripApi();
+ api.failures.add(new WrappedApiException(503));
+ api.failures.add(new WrappedApiException(502));
+ api.unstripStatuses.add(AutoUnstripStatus.COMPLETED);
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue("a 5xx is retried and the later completion syncs",
+ waitUntil(() -> api.getFunctionInfoCalls > 0, 5000));
+ assertEquals(3, api.statusCalls.get());
+ assertTrue("a transient error is not shown as a failure", announcements.warnings.isEmpty());
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void stopsAndWarnsOnClientError() throws Exception {
+ var api = new UnstripApi();
+ api.failures.add(new WrappedApiException(404));
+ api.unstripStatuses.add(AutoUnstripStatus.COMPLETED);
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue(waitUntil(() -> !announcements.warnings.isEmpty(), 5000));
+ assertTrue(announcements.warnings.get(0).contains("HTTP 404"));
+ Thread.sleep(300);
+ assertEquals("a 4xx is not retried", 1, api.statusCalls.get());
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void reportsUnexpectedErrorsInsteadOfDyingSilently() throws Exception {
+ var api = new UnstripApi();
+ api.failures.add(new IllegalArgumentException("malformed body"));
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue("an unexpected error is reported", waitUntil(() -> !announcements.warnings.isEmpty(), 5000));
+ assertTrue(announcements.warnings.get(0).contains("malformed body"));
+ assertFalse(syncService.stopPolling(fixture.analysed().analysisID()));
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void doesNotSyncAProgramDetachedWhilePolling() throws Exception {
+ var api = new UnstripApi();
+ api.unstripStatuses.add(AutoUnstripStatus.COMPLETED);
+ api.inPoll = new CountDownLatch(1);
+ api.releasePoll = new CountDownLatch(1);
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue(api.inPoll.await(5, TimeUnit.SECONDS));
+ var program = fixture.analysed().program();
+ program.withTransaction("detach", () -> fixture.service().removeProgramAssociation(program));
+ api.releasePoll.countDown();
+ Thread.sleep(500);
+ assertEquals("a detached program is not synced", 0, api.getFunctionInfoCalls);
+ assertTrue("nothing is reported as failed", announcements.warnings.isEmpty());
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void detachDuringTheSyncCancelsItWithoutAWarning() throws Exception {
+ var api = new UnstripApi();
+ api.unstripStatuses.add(AutoUnstripStatus.COMPLETED);
+ var fixture = setUp(api);
+ api.inSync = new CountDownLatch(1);
+ api.releaseSync = new CountDownLatch(1);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue(api.inSync.await(5, TimeUnit.SECONDS));
+ // What the Detach action does while the sync is running.
+ assertTrue("a running sync can still be stopped", syncService.stopPolling(fixture.analysed().analysisID()));
+ var program = fixture.analysed().program();
+ program.withTransaction("detach", () -> fixture.service().removeProgramAssociation(program));
+ api.releaseSync.countDown();
+ Thread.sleep(500);
+ assertTrue("a sync stopped by Detach is not reported as failed", announcements.warnings.isEmpty());
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void doesNotSyncAProgramReattachedToAnotherAnalysisWhilePolling() throws Exception {
+ var api = new UnstripApi();
+ api.unstripStatuses.add(AutoUnstripStatus.COMPLETED);
+ api.inPoll = new CountDownLatch(1);
+ api.releasePoll = new CountDownLatch(1);
+ var fixture = setUp(api);
+
+ var syncService = fastService(fixture, (m, w) -> {}, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue(api.inPoll.await(5, TimeUnit.SECONDS));
+ var program = fixture.analysed().program();
+ program.withTransaction("detach", () -> fixture.service().removeProgramAssociation(program));
+ var reattached = fixture.service().registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(2));
+ fixture.service().registerFinishedAnalysisForProgram(reattached, TaskMonitor.DUMMY);
+ api.getFunctionInfoCalls = 0;
+ api.releasePoll.countDown();
+ Thread.sleep(500);
+ assertEquals("the old analysis is not synced into the re-attached program", 0, api.getFunctionInfoCalls);
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void stopsQuietlyWhenUnstripNeverStarts() throws Exception {
+ var api = new UnstripApi();
+ api.unstripStatuses.add(AutoUnstripStatus.UNINITIALISED);
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMillis(400));
+ try {
+ syncService.pollAndSync(fixture.analysed(), false);
+ assertTrue("polling ends", waitUntil(() -> !syncService.stopPolling(fixture.analysed().analysisID()), 5000));
+ assertTrue("an unstrip that never started is neither announced nor reported", announcements.all.isEmpty());
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void pointsAtTheApiKeyWhenTheStatusCheckIsRefused() throws Exception {
+ var api = new UnstripApi();
+ api.failures.add(new WrappedApiException(401));
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMinutes(1));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue(waitUntil(() -> !announcements.warnings.isEmpty(), 5000));
+ assertTrue(announcements.warnings.get(0).contains("API key"));
+ } finally {
+ syncService.dispose();
+ }
+ }
+
+ @Test
+ public void namesTheOutageWhenTheTimeLimitIsSpentRetrying() throws Exception {
+ var api = new UnstripApi();
+ for (int i = 0; i < 100; i++) {
+ api.failures.add(new WrappedApiException(503));
+ }
+ api.unstripStatuses.add(AutoUnstripStatus.COMPLETED);
+ var fixture = setUp(api);
+ var announcements = new Announcements();
+
+ var syncService = fastService(fixture, announcements, Duration.ofMillis(400));
+ try {
+ syncService.pollAndSync(fixture.analysed(), true);
+ assertTrue(waitUntil(() -> !announcements.warnings.isEmpty(), 5000));
+ assertTrue(announcements.warnings.get(0).contains("could not be checked"));
+ assertTrue(announcements.warnings.get(0).contains("HTTP 503"));
+ } finally {
+ syncService.dispose();
+ }
+ }
}
diff --git a/src/test/java/ai/reveng/CreatedDataTypes.java b/src/test/java/ai/reveng/CreatedDataTypes.java
new file mode 100644
index 00000000..d1aff697
--- /dev/null
+++ b/src/test/java/ai/reveng/CreatedDataTypes.java
@@ -0,0 +1,45 @@
+package ai.reveng;
+
+import ai.reveng.model.CreateAnalysisDataTypesInputBody;
+import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType;
+
+import java.util.List;
+import java.util.function.LongSupplier;
+import java.util.function.Predicate;
+
+/// What a mock server answers a data-type create with: each type as it was sent, under a new id.
+///
+/// The answer has to name the types it was asked for. A push resolves every type a signature names
+/// through the created types' `(namespace, name, kind)`, and a signature with a type it cannot
+/// resolve is not sent.
+final class CreatedDataTypes {
+
+ private CreatedDataTypes() {}
+
+ static List