diff --git a/.github/scripts/bump_revengai.py b/.github/scripts/bump_revengai.py deleted file mode 100644 index 1361bbf1..00000000 --- a/.github/scripts/bump_revengai.py +++ /dev/null @@ -1,67 +0,0 @@ -from __future__ import annotations - -import re -import sys -import urllib.request -import xml.etree.ElementTree as ET -from pathlib import Path - -from packaging.version import Version - -BUILD_GRADLE = Path(__file__).resolve().parents[2] / "build.gradle" -MAVEN_METADATA_URL = "https://repo1.maven.org/maven2/ai/reveng/sdk/maven-metadata.xml" - -# The pin can be a staging release candidate (4.74.4-rc.1), which the qualifier puts below -# the plain 4.74.4 on Maven Central. Capturing only the digits would both read it as the -# already-released 4.74.4 and leave the "-rc.1" behind on rewrite. -SDK_PIN_RE = re.compile(r"ai\.reveng:sdk:([\w.\-]+)") -STABLE_RE = re.compile(r"^\d+\.\d+\.\d+$") - - -def fetch_latest_maven_version() -> str: - with urllib.request.urlopen(MAVEN_METADATA_URL, timeout=30) as resp: - root = ET.parse(resp).getroot() - versions = [ - (el.text or "").strip() - for el in root.findall("./versioning/versions/version") - if el.text and STABLE_RE.match(el.text.strip()) - ] - if not versions: - raise RuntimeError("no stable ai.reveng:sdk versions found on Maven Central") - return max(versions, key=Version) - - -def emit(key: str, value: str) -> None: - print(f"{key}={value}") - - -def main() -> int: - text = BUILD_GRADLE.read_text() - - sdk_match = SDK_PIN_RE.search(text) - if not sdk_match: - print("error: could not find ai.reveng:sdk pin in build.gradle", file=sys.stderr) - return 1 - current_sdk = sdk_match.group(1) - - latest_sdk = fetch_latest_maven_version() - - emit("current_sdk", current_sdk) - emit("new_sdk", latest_sdk) - - if Version(latest_sdk) <= Version(current_sdk): - emit("changed", "false") - return 0 - - new_text = text.replace( - f"ai.reveng:sdk:{current_sdk}", - f"ai.reveng:sdk:{latest_sdk}", - ) - BUILD_GRADLE.write_text(new_text) - - emit("changed", "true") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9e1a6082..250248f9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,7 +2,7 @@ name: build on: pull_request: - branches: [ "main" ] + branches: [ "main", "staging" ] jobs: build: @@ -66,6 +66,7 @@ jobs: run: $GHIDRA_INSTALL_DIR/support/sleigh $GHIDRA_INSTALL_DIR/Ghidra/Processors/x86/data/languages/x86-64.slaspec - name: Run tests + id: tests run: xvfb-run ./gradlew test - name: Upload test results @@ -76,9 +77,44 @@ jobs: path: build/reports/tests/test/ - name: Publish test report + id: report if: always() + # Updating the check run right after creating it intermittently 404s, which failed jobs whose + # tests had passed. Failing tests already fail "Run tests", so the report is display only. + continue-on-error: true uses: dorny/test-reporter@d61b558e8df85cb60d09ca3e5b09653b4477cea7 # v1 with: name: Tests (Ghidra ${{ matrix.ghidra }}) path: build/test-results/test/*.xml reporter: java-junit + + - name: Complete a test report left in progress + # When the reporter's update 404s, the check run it created stays "in progress" for good, so the PR never + # shows all checks finished. Complete it with the outcome of the tests. Display only, like the report. + if: always() && steps.report.outcome == 'failure' + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + CHECK_NAME: Tests (Ghidra ${{ matrix.ghidra }}) + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + CONCLUSION: ${{ steps.tests.outcome == 'success' && 'success' || 'failure' }} + run: | + summary="The test reporter could not attach the results to this check (HTTP 404). See the Run tests step and the test-results artifact." + # The check run may not be visible to the API yet, which is what made the reporter's update fail + for attempt in 1 2 3 4 5; do + ids=$(gh api -X GET "repos/$GITHUB_REPOSITORY/commits/$HEAD_SHA/check-runs" \ + -f check_name="$CHECK_NAME" -f filter=all \ + --jq '.check_runs[] | select(.status != "completed") | .id') || ids="" + completed=true + for id in $ids; do + gh api -X PATCH "repos/$GITHUB_REPOSITORY/check-runs/$id" \ + -f status=completed -f conclusion="$CONCLUSION" \ + -f "output[title]=$CHECK_NAME" -f "output[summary]=$summary" >/dev/null || completed=false + done + if [ -n "$ids" ] && [ "$completed" = true ]; then + echo "Completed '$CHECK_NAME' ($ids) as $CONCLUSION" + exit 0 + fi + sleep 5 + done + echo "::warning::Could not find or complete an in-progress '$CHECK_NAME' check" diff --git a/.github/workflows/bump-revengai-sdk.yaml b/.github/workflows/bump-revengai-sdk.yaml deleted file mode 100644 index b95ba831..00000000 --- a/.github/workflows/bump-revengai-sdk.yaml +++ /dev/null @@ -1,101 +0,0 @@ -name: Bump revengai SDK - -on: - schedule: - - cron: '0 9 * * *' - workflow_dispatch: - -permissions: - contents: write - pull-requests: write - -env: - BUMP_BRANCH: chore/auto-bump-revengai - -jobs: - bump: - runs-on: ubuntu-latest - steps: - - name: Generate a token - id: generate-token - uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1 - with: - app-id: ${{ secrets.REVENG_APP_ID }} - private-key: ${{ secrets.REVENG_APP_PRIVATE_KEY }} - owner: ${{ github.repository_owner }} - repositories: | - plugin-ghidra - - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 - with: - token: ${{ steps.generate-token.outputs.token }} - - - name: Set up Python - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 - with: - python-version: '3.14' - - - name: Install packaging - run: pip install packaging - - - name: Inspect existing bump PR - id: existing - env: - GH_TOKEN: ${{ steps.generate-token.outputs.token }} - run: | - set -euo pipefail - pr_num=$(gh pr list --state open --head "$BUMP_BRANCH" \ - --json number --jq '.[0].number // empty') - if [ -z "$pr_num" ]; then - echo "exists=false" >> "$GITHUB_OUTPUT" - echo "human_commits=0" >> "$GITHUB_OUTPUT" - exit 0 - fi - # Count non-bot commits. Commits with a null author (email not linked - # to a GitHub user) are conservatively counted as human so we don't - # clobber an in-flight fix. - human=$(gh api "repos/${{ github.repository }}/pulls/$pr_num/commits" \ - --jq '[.[] | select(.author == null or .author.type != "Bot")] | length') - echo "exists=true" >> "$GITHUB_OUTPUT" - echo "pr_num=$pr_num" >> "$GITHUB_OUTPUT" - echo "human_commits=$human" >> "$GITHUB_OUTPUT" - - - name: Skip when open PR has human commits - if: steps.existing.outputs.exists == 'true' && steps.existing.outputs.human_commits != '0' - run: | - echo "PR #${{ steps.existing.outputs.pr_num }} has human commits; leaving it alone." - echo "ABORT=true" >> "$GITHUB_ENV" - - - name: Compute version bump - if: env.ABORT != 'true' - id: bump - run: python .github/scripts/bump_revengai.py >> "$GITHUB_OUTPUT" - - - name: Already up to date - if: env.ABORT != 'true' && steps.bump.outputs.changed != 'true' - run: echo "ai.reveng:sdk is already at ${{ steps.bump.outputs.current_sdk }}; nothing to do." - - - name: Open or update bump PR - if: env.ABORT != 'true' && steps.bump.outputs.changed == 'true' - uses: peter-evans/create-pull-request@22a9089034f40e5a961c8808d113e2c98fb63676 # v7.0.11 - with: - token: ${{ steps.generate-token.outputs.token }} - branch: ${{ env.BUMP_BRANCH }} - base: main - commit-message: "chore: bump ai.reveng:sdk to ${{ steps.bump.outputs.new_sdk }}" - title: "chore: bump ai.reveng:sdk to ${{ steps.bump.outputs.new_sdk }}" - body: | - Auto-generated by `.github/workflows/bump-revengai-sdk.yaml`. - - **SDK:** `ai.reveng:sdk` `${{ steps.bump.outputs.current_sdk }}` → `${{ steps.bump.outputs.new_sdk }}` - - - Release notes: https://github.com/RevEngAI/sdk-java/releases/tag/v${{ steps.bump.outputs.new_sdk }} - - Changelog: https://github.com/RevEngAI/sdk-java/compare/v${{ steps.bump.outputs.current_sdk }}...v${{ steps.bump.outputs.new_sdk }} - - This is a rolling PR. - - Review for schema/breaking changes before merging. - labels: | - dependencies - automated - delete-branch: true diff --git a/README.md b/README.md index 03bbe6d2..2c0f44d1 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,25 @@ and use it for Binary Code Similarity to help you Reverse Engineer stripped bina ## Installation +### Install script + +Close Ghidra, then run: + +```sh +# Linux / macOS +curl -fsSL https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.sh | bash +``` + +```powershell +# Windows (PowerShell) +irm https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.ps1 | iex +``` + +The script finds your Ghidra installs (asking which one if several), downloads the matching release, installs it and enables the plugins in the CodeBrowser. +Set `GHIDRA_INSTALL_DIR` to target a specific install, or `REVENG_PLUGIN_VERSION` (e.g. `v1.1.2`) to pin a release. + +### Manual installation + The builds for latest stable version of the RevEng.AI Ghidra plugin for common Ghidra versions can be downloaded from the [Releases](https://github.com/revengai/plugin-ghidra/releases/latest) page. ### Supported Ghidra versions diff --git a/build.gradle b/build.gradle index d218f62c..d3d9cf56 100644 --- a/build.gradle +++ b/build.gradle @@ -69,11 +69,13 @@ dependencies { implementation group: 'com.fifesoft', name: 'rsyntaxtextarea', version: '3.5.2' implementation 'org.commonmark:commonmark:0.24.0' implementation 'org.commonmark:commonmark-ext-gfm-tables:0.24.0' - implementation('ai.reveng:sdk:4.75.0') + implementation('ai.reveng:sdk:4.77.1') testImplementation('junit:junit:4.13.1') testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.8.2") // Version comes from the junit-bom pulled in by junit-vintage-engine. testRuntimeOnly('org.junit.platform:junit-platform-launcher') + // Compile-time API for ForkTempDir; matches the runtime version above. + testCompileOnly('org.junit.platform:junit-platform-launcher:1.8.2') // https://mvnrepository.com/artifact/org.jetbrains/annotations implementation group: 'org.jetbrains', name: 'annotations', version: '26.0.2' @@ -84,9 +86,6 @@ dependencies { // Maven repository: // // ./gradlew buildExtension -PrevengSdkVersion= -// -// The pin in the dependencies block stays the literal default so that -// .github/scripts/bump_revengai.py can still find and rewrite it. if (project.hasProperty('revengSdkVersion')) { configurations.all { resolutionStrategy.force "ai.reveng:sdk:${project.revengSdkVersion}" @@ -107,6 +106,10 @@ test { useJUnitPlatform() jvmArgs '--add-exports=java.desktop/sun.awt=ALL-UNNAMED' systemProperty "ghidra.test.property.batch.mode", 'true' + // Parent of the per-fork Ghidra temp dirs created by ForkTempDir. + def forkTempRoot = layout.buildDirectory.dir('tmp/ghidra-test-forks').get().asFile + systemProperty 'reveng.test.fork.tmproot', forkTempRoot.path + doFirst { forkTempRoot.mkdirs() } // Ghidra 12.1+ installs a serial filter factory during application initialization. The JVM // only allows this if no ObjectInputStream has been constructed yet, but Gradle's test diff --git a/data/reveng.theme.properties b/data/reveng.theme.properties new file mode 100644 index 00000000..b3c52318 --- /dev/null +++ b/data/reveng.theme.properties @@ -0,0 +1,38 @@ +[Defaults] + +color.bg.reveng.tag = rgba(14,169,104,.08) +color.border.reveng.tag = rgba(14,169,104,.35) +color.border.reveng.title = [color]laf.color.Separator.foreground + +color.fg.reveng.similarity.critical = #b31d1d +color.fg.reveng.similarity.high = #ac3f09 +color.fg.reveng.similarity.medium = #985a04 +color.fg.reveng.similarity.low = #137236 + +color.bg.reveng.diff.deleted = rgba(201,55,55,.15) +color.bg.reveng.diff.inserted = rgba(14,169,104,.15) +color.bg.reveng.diff.changed = rgba(184,108,0,.15) +color.bg.reveng.diff.placeholder = rgba(7,9,13,.04) + +icon.reveng.mark.16 = images/reveng_16.png +icon.reveng.mark.24 = images/reveng_24.png +icon.reveng.mark.large = images/icon.png + +[Dark Defaults] + +color.bg.reveng.tag = rgba(92,240,163,.06) +color.border.reveng.tag = rgba(92,240,163,.3) + +color.fg.reveng.similarity.critical = #f26d6d +color.fg.reveng.similarity.high = #f08b3c +color.fg.reveng.similarity.medium = #f5c04a +color.fg.reveng.similarity.low = #47d17a + +color.bg.reveng.diff.deleted = rgba(255,107,107,.15) +color.bg.reveng.diff.inserted = rgba(92,240,163,.15) +color.bg.reveng.diff.changed = rgba(255,180,84,.15) +color.bg.reveng.diff.placeholder = rgba(255,255,255,.03) + +icon.reveng.mark.16 = images/reveng_16_dark.png +icon.reveng.mark.24 = images/reveng_24_dark.png +icon.reveng.mark.large = images/icon_dark.png diff --git a/docs/FEATURE_STANDARD.md b/docs/FEATURE_STANDARD.md index 04f04c81..7da74c87 100644 --- a/docs/FEATURE_STANDARD.md +++ b/docs/FEATURE_STANDARD.md @@ -16,7 +16,7 @@ Feature support is declared in [`scripts/emit_features.py`](../scripts/emit_feat - `build_manifest()` merges the two. `.revengai/features.json` is generated from this script — never edit the JSON by hand. The -script is build tooling (a small Python script, like `.github/scripts/bump_revengai.py`) +script is build tooling (a small Python script) and is not part of the Ghidra extension under `src/`. ## Status values diff --git a/ghidra_scripts/RevEngExamplePostScript.java b/ghidra_scripts/RevEngExamplePostScript.java index e9ee7c40..29351d41 100644 --- a/ghidra_scripts/RevEngExamplePostScript.java +++ b/ghidra_scripts/RevEngExamplePostScript.java @@ -8,6 +8,10 @@ public class RevEngExamplePostScript extends GhidraScript { @Override protected void run() throws Exception { + if (currentProgram == null) { + printerr("No program open"); + return; + } // Services are not available in headless mode, so we have to instantiate it ourselves var ghidraRevengService = new GhidraRevengService(ApiInfo.fromConfig(ReaiPluginPackage.DEFAULT_CONFIG_PATH)); diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 00000000..9d16fc06 --- /dev/null +++ b/install.ps1 @@ -0,0 +1,134 @@ +# Installs the RevEng.AI Ghidra plugin and enables it in the CodeBrowser tool. +# +# irm https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.ps1 | iex +# +# $env:GHIDRA_INSTALL_DIR target this Ghidra install instead of detecting one +# $env:REVENG_PLUGIN_VERSION release tag to install (default: latest) + +& { +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem + +$Repo = 'RevEngAI/plugin-ghidra' +$ExtName = 'plugin-ghidra' +$PluginPackage = 'RevEng.AI' +$SettingsRoot = Join-Path $env:APPDATA 'ghidra' + +function Get-Prop($Ghidra, $Name) { + $line = Get-Content (Join-Path $Ghidra 'Ghidra\application.properties') | + Where-Object { $_ -like "$Name=*" } | Select-Object -First 1 + $line.Substring($Name.Length + 1).Trim() +} + +function Test-Ghidra($Dir) { + $Dir -and (Test-Path -LiteralPath (Join-Path $Dir 'Ghidra\application.properties')) +} + +function Find-Installs { + $candidates = @() + $lastrun = Join-Path $SettingsRoot 'lastrun' + if (Test-Path $lastrun) { $candidates += (Get-Content $lastrun -Raw).Trim() } + $roots = @('C:\', $env:ProgramFiles, ${env:ProgramFiles(x86)}, 'C:\tools', $HOME, + "$HOME\Downloads", "$HOME\Desktop", "$HOME\scoop\apps\ghidra", + "$env:ProgramData\chocolatey\lib\ghidra\tools") + foreach ($root in $roots | Where-Object { $_ -and (Test-Path $_) }) { + foreach ($d in Get-ChildItem $root -Directory -ErrorAction SilentlyContinue) { + if ($d.Name -like 'ghidra*' -or $root -like '*ghidra*') { + $candidates += $d.FullName + $candidates += Get-ChildItem $d.FullName -Directory -Filter 'ghidra*' -ErrorAction SilentlyContinue | + ForEach-Object { $_.FullName } + } + } + } + $candidates | Where-Object { Test-Ghidra $_ } | + ForEach-Object { (Get-Item -LiteralPath $_).FullName.TrimEnd('\') } | Sort-Object -Unique +} + +if ($env:GHIDRA_INSTALL_DIR) { + if (-not (Test-Ghidra $env:GHIDRA_INSTALL_DIR)) { throw "No Ghidra install at $env:GHIDRA_INSTALL_DIR" } + $ghidra = $env:GHIDRA_INSTALL_DIR +} else { + $installs = @(Find-Installs) + if ($installs.Count -eq 0) { throw 'No Ghidra install found; set $env:GHIDRA_INSTALL_DIR to its path' } + if ($installs.Count -eq 1) { + $ghidra = $installs[0] + } else { + Write-Host 'Ghidra installs found:' + for ($i = 0; $i -lt $installs.Count; $i++) { + Write-Host (" {0}) {1} {2}" -f ($i + 1), (Get-Prop $installs[$i] 'application.version'), $installs[$i]) + } + $choice = Read-Host "Install into [1-$($installs.Count)]" + if ($choice -notmatch '^\d+$' -or [int]$choice -lt 1 -or [int]$choice -gt $installs.Count) { throw 'Invalid choice' } + $ghidra = $installs[[int]$choice - 1] + } +} + +$version = Get-Prop $ghidra 'application.version' +$settings = Join-Path $SettingsRoot "ghidra_${version}_$(Get-Prop $ghidra 'application.release.name')" +Write-Host "Ghidra $version at $ghidra" + +$running = Get-CimInstance Win32_Process -Filter "Name LIKE 'java%'" -ErrorAction SilentlyContinue | + Where-Object { $_.CommandLine -match 'ghidra\.GhidraRun' } +if ($running) { throw 'Ghidra is running; close it and rerun' } + +$tmp = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid()) +New-Item -ItemType Directory $tmp | Out-Null +try { + $asset = "ghidra_${version}_$ExtName.zip" + if ($env:REVENG_PLUGIN_VERSION) { + $url = "https://github.com/$Repo/releases/download/$env:REVENG_PLUGIN_VERSION/$asset" + } else { + $url = "https://github.com/$Repo/releases/latest/download/$asset" + } + $zip = Join-Path $tmp $asset + $unpacked = Join-Path $tmp 'x' + Write-Host "Downloading $url" + try { + Invoke-WebRequest $url -OutFile $zip -UseBasicParsing + } catch { + throw "No release build for Ghidra $version; see https://github.com/$Repo#building-your-own-plugin-for-custom-ghidra-forks-and-versions" + } + + [IO.Compression.ZipFile]::ExtractToDirectory($zip, $unpacked) + if (-not (Test-Path (Join-Path (Join-Path $unpacked $ExtName) 'extension.properties'))) { throw 'Unexpected archive layout' } + $extensions = Join-Path $settings 'Extensions' + New-Item -ItemType Directory -Force $extensions | Out-Null + $target = Join-Path $extensions $ExtName + if (Test-Path $target) { Remove-Item -Recurse -Force $target } + Move-Item (Join-Path $unpacked $ExtName) $extensions + Write-Host "Installed to $target" + + $tool = Join-Path (Join-Path $settings 'tools') '_code_browser.tcd' + if (-not (Test-Path $tool)) { + Write-Host 'CodeBrowser not configured yet; Ghidra will offer to enable the plugins when it opens.' + return + } + + $jar = [IO.Compression.ZipFile]::OpenRead((Join-Path (Join-Path $target 'lib') "$ExtName.jar")) + try { + $plugins = $jar.Entries | ForEach-Object { $_.FullName } | + Where-Object { $_ -match '^ai/reveng/toolkit/ghidra/plugins/[^/$]*Plugin\.class$' } | + ForEach-Object { ($_ -replace '\.class$', '') -replace '/', '.' } + } finally { $jar.Dispose() } + if (-not $plugins) { throw "No plugins found in $ExtName.jar" } + + Copy-Item $tool "$tool.bak" -Force + [xml]$xml = Get-Content $tool -Raw + $toolNode = $xml.TOOL_CONFIG.SelectSingleNode('TOOL') + foreach ($old in @($toolNode.SelectNodes("PACKAGE[@NAME='$PluginPackage']"))) { [void]$toolNode.RemoveChild($old) } + $package = $xml.CreateElement('PACKAGE') + $package.SetAttribute('NAME', $PluginPackage) + foreach ($plugin in $plugins) { + $include = $xml.CreateElement('INCLUDE') + $include.SetAttribute('CLASS', $plugin) + [void]$package.AppendChild($include) + } + [void]$toolNode.AppendChild($package) + $xml.Save($tool) + Write-Host "Enabled in CodeBrowser (backup: $tool.bak)" +} finally { + Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue +} +} diff --git a/install.sh b/install.sh new file mode 100755 index 00000000..85d6e496 --- /dev/null +++ b/install.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# Installs the RevEng.AI Ghidra plugin and enables it in the CodeBrowser tool. +# +# curl -fsSL https://raw.githubusercontent.com/RevEngAI/plugin-ghidra/main/install.sh | bash +# +# GHIDRA_INSTALL_DIR target this Ghidra install instead of detecting one +# REVENG_PLUGIN_VERSION release tag to install (default: latest) +set -euo pipefail + +REPO="RevEngAI/plugin-ghidra" +EXT_NAME="plugin-ghidra" +PLUGIN_PACKAGE="RevEng.AI" + +die() { echo "error: $*" >&2; exit 1; } + +for cmd in curl unzip; do + command -v "$cmd" >/dev/null || die "'$cmd' is required" +done + +case "$(uname -s)" in + Darwin) SETTINGS_ROOT="$HOME/Library/ghidra" ;; + *) SETTINGS_ROOT="${XDG_CONFIG_HOME:-$HOME/.config}/ghidra" ;; +esac + +prop() { sed -n "s/^$1=//p" "$2/Ghidra/application.properties" | tr -d '\r'; } + +find_installs() { + local d + { + [ -f "$SETTINGS_ROOT/lastrun" ] && cat "$SETTINGS_ROOT/lastrun" && echo + for d in /opt /usr/local /usr/share /usr/lib /Applications "$HOME" "$HOME/Downloads" \ + "$HOME/Desktop" "$HOME/tools" "$HOME/Applications" \ + /opt/homebrew/Caskroom/ghidra/* /usr/local/Caskroom/ghidra/*; do + ls -d "$d"/[Gg]hidra* "$d"/[Gg]hidra*/[Gg]hidra* 2>/dev/null || true + done + ls -d /opt/homebrew/Cellar/ghidra/*/libexec /usr/local/Cellar/ghidra/*/libexec 2>/dev/null || true + } | while IFS= read -r d; do + [ -n "$d" ] && [ -f "$d/Ghidra/application.properties" ] && (cd -P "$d" && pwd) + done | awk '!seen[$0]++' +} + +if [ -n "${GHIDRA_INSTALL_DIR:-}" ]; then + [ -f "$GHIDRA_INSTALL_DIR/Ghidra/application.properties" ] || die "no Ghidra install at $GHIDRA_INSTALL_DIR" + GHIDRA="$GHIDRA_INSTALL_DIR" +else + INSTALLS=() + while IFS= read -r d; do INSTALLS+=("$d"); done < <(find_installs) + [ ${#INSTALLS[@]} -gt 0 ] || die "no Ghidra install found; set GHIDRA_INSTALL_DIR to its path" + if [ ${#INSTALLS[@]} -eq 1 ]; then + GHIDRA="${INSTALLS[0]}" + else + echo "Ghidra installs found:" + for i in "${!INSTALLS[@]}"; do + echo " $((i + 1))) $(prop application.version "${INSTALLS[$i]}") ${INSTALLS[$i]}" + done + # Read from the terminal: stdin is the script itself under `curl | bash`. + read -rp "Install into [1-${#INSTALLS[@]}]: " choice /dev/null && pgrep -f 'ghidra\.GhidraRun' >/dev/null; then + die "Ghidra is running; close it and rerun" +fi + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +ASSET="ghidra_${VERSION}_${EXT_NAME}.zip" +if [ -n "${REVENG_PLUGIN_VERSION:-}" ]; then + URL="https://github.com/$REPO/releases/download/$REVENG_PLUGIN_VERSION/$ASSET" +else + URL="https://github.com/$REPO/releases/latest/download/$ASSET" +fi +echo "Downloading $URL" +curl -fsSL -o "$TMP/$ASSET" "$URL" \ + || die "no release build for Ghidra $VERSION; see https://github.com/$REPO#building-your-own-plugin-for-custom-ghidra-forks-and-versions" + +unzip -q "$TMP/$ASSET" -d "$TMP/x" +[ -f "$TMP/x/$EXT_NAME/extension.properties" ] || die "unexpected archive layout" +mkdir -p "$SETTINGS/Extensions" +rm -rf "${SETTINGS:?}/Extensions/$EXT_NAME" +mv "$TMP/x/$EXT_NAME" "$SETTINGS/Extensions/" +echo "Installed to $SETTINGS/Extensions/$EXT_NAME" + +TOOL="$SETTINGS/tools/_code_browser.tcd" +if [ ! -f "$TOOL" ]; then + echo "CodeBrowser not configured yet; Ghidra will offer to enable the plugins when it opens." + exit 0 +fi + +PLUGINS="$(unzip -Z1 "$SETTINGS/Extensions/$EXT_NAME/lib/$EXT_NAME.jar" \ + | sed -n 's#^\(ai/reveng/toolkit/ghidra/plugins/[^/$]*Plugin\)\.class$#\1#p' | tr /'\n' '. ')" +[ -n "$PLUGINS" ] || die "no plugins found in $EXT_NAME.jar" + +cp "$TOOL" "$TOOL.bak" +awk -v pkg="$PLUGIN_PACKAGE" -v plugins="$PLUGINS" ' + index($0, "/) skip = 1 + next + } + skip { if ($0 ~ /<\/PACKAGE>/) skip = 0; next } + /<\/TOOL>/ && !done { + print " " + n = split(plugins, p, " ") + for (i = 1; i <= n; i++) print " " + print " " + done = 1 + } + { print } +' "$TOOL.bak" > "$TMP/tool.tcd" +mv "$TMP/tool.tcd" "$TOOL" +echo "Enabled in CodeBrowser (backup: $TOOL.bak)" diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java index 08a3c2b3..6cedbf1b 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/cmds/ApplyMatchCmd.java @@ -3,8 +3,11 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; import ghidra.app.cmd.function.ApplyFunctionSignatureCmd; +import ghidra.app.cmd.function.FunctionRenameOption; import ghidra.app.cmd.label.RenameLabelCmd; import ghidra.framework.cmd.Command; +import ghidra.program.model.data.DataTypeConflictHandler; +import ghidra.program.model.data.FunctionDefinitionDataType; import ghidra.program.model.listing.CircularDependencyException; import ghidra.program.model.listing.Program; import ghidra.program.model.symbol.Namespace; @@ -20,14 +23,41 @@ /// The central command to apply a function match to a {@link Program} /// It centralizes product design decisions about how to apply a match, like moving it to a namespace, /// renaming it, applying the signature, etc. -/// It will apply the function signature if available, otherwise it will just rename the function +/// What it transfers is chosen by {@link Transfer}: the matched name, the matched signature (its data +/// types), or both. A signature is only transferred when the match has one. /// There are various considerations when ap public class ApplyMatchCmd implements Command { + /// The parts of a match that can be transferred onto the local function, as offered in the portal + public enum Transfer { + NAME("Name"), + SIGNATURE("Signature"), + NAME_AND_SIGNATURE("Name and Signature"); + + private final String label; + + Transfer(String label) { + this.label = label; + } + + public String label() { + return label; + } + + public boolean includesName() { + return this != SIGNATURE; + } + + public boolean includesSignature() { + return this != NAME; + } + } + private final GhidraRevengService.AnalysedProgram analyzedProgram; private final GhidraFunctionMatchWithSignature match; @Nullable private final GhidraRevengService service; private final Boolean includeBinaryNameInNameSpace; + private final Transfer transfer; public ApplyMatchCmd( @Nullable GhidraRevengService service, @@ -35,27 +65,44 @@ public ApplyMatchCmd( @NotNull GhidraFunctionMatchWithSignature match, Boolean includeBinaryNameInNameSpace + ) { + this(service, program, match, includeBinaryNameInNameSpace, Transfer.NAME_AND_SIGNATURE); + } + + public ApplyMatchCmd( + @Nullable GhidraRevengService service, + @NotNull GhidraRevengService.AnalysedProgram program, + @NotNull GhidraFunctionMatchWithSignature match, + Boolean includeBinaryNameInNameSpace, + @NotNull Transfer transfer ) { super(); this.analyzedProgram = program; this.match = match; this.service = service; this.includeBinaryNameInNameSpace = includeBinaryNameInNameSpace; + this.transfer = transfer; } private boolean shouldApplyMatch() { var func = match.function(); - return func != null && - // Do not override user-defined function names - func.getSymbol().getSource() != SourceType.USER_DEFINED && + if (func == null || // Exclude thunks and external functions - !func.isThunk() && - !func.isExternal() && + func.isThunk() || + func.isExternal() || + // Only apply if the function ID is known (boundaries matched) + analyzedProgram.getIDForFunction(func).isEmpty()) { + return false; + } + if (transfer == Transfer.SIGNATURE) { + // The name is left alone, so only a signature to apply matters + return match.signature() != null; + } + // Do not override user-defined function names + return func.getSymbol().getSource() != SourceType.USER_DEFINED && // Only accept valid names (no spaces) !match.functionMatch().nearest_neighbor_mangled_function_name().contains(" ") && - !match.functionMatch().nearest_neighbor_function_name().contains(" ") - // Only rename if the function ID is known (boundaries matched) - && analyzedProgram.getIDForFunction(func).map(id -> id.functionID() != match.functionMatch().origin_function_id()).orElse(false); + !match.functionMatch().nearest_neighbor_function_name().contains(" "); } @Override @@ -68,8 +115,14 @@ public boolean applyTo(Program obj) { return false; } - var nameSpace = includeBinaryNameInNameSpace ? getLibraryNameSpaceForName(match.functionMatch().nearest_neighbor_binary_name()): getRevEngAINameSpace(); var function = match.function(); + var signature = match.signature(); + if (transfer == Transfer.SIGNATURE) { + // Keep the function's own name: only the prototype and its data types come across + return applySignature(signature); + } + + var nameSpace = includeBinaryNameInNameSpace ? getLibraryNameSpaceForName(match.functionMatch().nearest_neighbor_binary_name()): getRevEngAINameSpace(); try { function.setParentNamespace(nameSpace); } catch (DuplicateNameException e) { @@ -82,15 +135,12 @@ public boolean applyTo(Program obj) { this.analyzedProgram.setMangledNameForFunction(function, match.functionMatch().nearest_neighbor_mangled_function_name()); - var signature = match.signature(); - if (signature != null) { - var cmd = new ApplyFunctionSignatureCmd(function.getEntryPoint(), signature, SourceType.USER_DEFINED); - cmd.applyTo(analyzedProgram.program()); - } - else { - var renameCmd = new RenameLabelCmd(match.function().getSymbol(), match.functionMatch().name(), SourceType.USER_DEFINED); - renameCmd.applyTo(analyzedProgram.program()); + if (transfer.includesSignature() && signature != null) { + // The name is set explicitly below: left to the signature command, it would only replace a default name + applySignature(signature); } + var renameCmd = new RenameLabelCmd(function.getSymbol(), match.functionMatch().name(), SourceType.USER_DEFINED); + renameCmd.applyTo(analyzedProgram.program()); // If we have a service then push the name. If not then it was explicitly not provided, i.e. the caller // is responsible for pushing the names in batch if (service != null) { @@ -105,6 +155,13 @@ public boolean applyTo(Program obj) { return true; } + /// Applies the prototype and its data types, leaving the function's name to the caller + private boolean applySignature(FunctionDefinitionDataType signature) { + var cmd = new ApplyFunctionSignatureCmd(match.function().getEntryPoint(), signature, SourceType.USER_DEFINED, + false, false, DataTypeConflictHandler.DEFAULT_HANDLER, FunctionRenameOption.NO_CHANGE); + return cmd.applyTo(analyzedProgram.program()); + } + public void applyWithTransaction() { var program = this.analyzedProgram.program(); var tID = program.startTransaction("RevEng.AI: Apply Match"); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java index c7de3e9e..d9c2f935 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/about/AboutDialog.java @@ -1,42 +1,30 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.about; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; +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.plugins.ReaiPluginPackage; import ghidra.framework.plugintool.PluginTool; -import resources.ResourceManager; import javax.swing.*; import java.awt.*; -import java.io.IOException; -import java.nio.charset.StandardCharsets; +import java.net.URI; +import java.util.Optional; import ai.reveng.invoker.Configuration; /** * Shows a dialog with about information. */ public class AboutDialog extends RevEngDialogComponentProvider { - public AboutDialog(PluginTool tool) { - super(ReaiPluginPackage.WINDOW_PREFIX + "About", true); + private final Optional update; - buildInterface(getPluginVersion()); - setPreferredSize(300, 210); - } + public AboutDialog(PluginTool tool, Optional update) { + super(ReaiPluginPackage.WINDOW_PREFIX + "About", true); + this.update = update; - private String getPluginVersion() { - String pluginVersion = "unknown"; - try { - // This resource is written by the release workflow, so it is absent from a local build - // and the stream is then null. - var inputStream = ResourceManager.getResourceAsStream("reai_ghidra_plugin_version.txt"); - if (inputStream != null) { - pluginVersion = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8).trim(); - inputStream.close(); - } - } catch (IOException e) { - // ignore — fall back to "unknown" - } - - return pluginVersion; + buildInterface(UpdateChecker.currentVersion()); + setPreferredSize(300, update.isPresent() ? 250 : 210); } private void buildInterface(String pluginVersion) { @@ -73,6 +61,14 @@ private JPanel createAboutContent(String pluginVersion) { sdkLabel.setAlignmentX(Component.CENTER_ALIGNMENT); panel.add(sdkLabel); + update.ifPresent(u -> { + panel.add(Box.createVerticalStrut(10)); + JButton updateButton = new JButton("Update available: " + u.version()); + updateButton.setAlignmentX(Component.CENTER_ALIGNMENT); + updateButton.addActionListener(e -> WebBrowser.open(URI.create(u.releaseUrl()))); + panel.add(updateButton); + }); + return panel; } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java index c1cbc082..704d738f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/aidecompiler/AIDecompilationdWindow.java @@ -7,6 +7,7 @@ import ai.reveng.model.RenderedToken; import ai.reveng.model.WorkflowProgress; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; import ai.reveng.toolkit.ghidra.core.services.api.types.AIDecompilationStatus; @@ -27,12 +28,14 @@ import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RTextScrollPane; +import generic.theme.Gui; import javax.swing.*; import javax.swing.text.BadLocationException; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import java.time.Duration; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; @@ -55,7 +58,7 @@ public class AIDecompilationdWindow extends ComponentProviderAdapter { private JComponent component; private Function function; private TaskMonitorComponent taskMonitorComponent; - private final Map cache = new java.util.HashMap<>(); + private final Map cache = new java.util.concurrent.ConcurrentHashMap<>(); /// Function IDs with a decompilation task currently running. Several functions can decompile /// concurrently in the background; this guards against launching a second task for a function @@ -132,6 +135,32 @@ public void actionPerformed(ActionContext context) { refreshCurrentFunction(); } }); + + addLocalAction(new DockingAction("Regenerate AI Decompilation", getName()) { + { + setToolBarData(new ToolBarData(new GIcon("icon.redo"), null)); + setDescription("Run the failed AI decompilation of the current function again"); + } + + @Override + public void actionPerformed(ActionContext context) { + regenerateCurrentFunction(); + } + + @Override + public boolean isEnabledForContext(ActionContext context) { + return canRegenerate(function); + } + }); + } + + /// Whether {@code target}'s last AI decompilation failed + private boolean canRegenerate(Function target) { + if (target == null) { + return false; + } + var cachedStatus = cache.get(target); + return cachedStatus != null && cachedStatus.status() == DecompilationData.StatusEnum.FAILED; } private void sendFeedbackInBackground(Function target, String rating, String reason) { @@ -179,7 +208,7 @@ private JComponent buildComponent() { descriptionArea.setContentType("text/html"); descriptionArea.setEditable(false); descriptionArea.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); - descriptionArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + descriptionArea.setFont(Gui.getFont("font.monospaced")); descriptionArea.setText("No function selected or binary not analysed yet with RevEng.AI"); headerPanel.add(descriptionArea); @@ -290,7 +319,7 @@ public void setDisplayedValuesBasedOnStatus(Function function, AIDecompilationSt currentRenderModel = null; String detail = status.decompilation(); setCode(detail != null && !detail.isBlank() ? detail : ""); - descriptionArea.setText("AI Decompilation failed"); + descriptionArea.setText("AI Decompilation failed. Use Regenerate AI Decompilation in the toolbar to try again."); predictedNamePanel.setVisible(false); } case UNINITIALISED, PENDING, RUNNING -> { @@ -304,6 +333,8 @@ public void setDisplayedValuesBasedOnStatus(Function function, AIDecompilationSt // Unknown status — leave existing UI state untouched. } } + // Regenerate is only offered for a failed decompilation + contextChanged(); } private static final DateTimeFormatter PROGRESS_TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); @@ -439,16 +470,21 @@ public void refresh(GhidraRevengService.FunctionWithID function) { // Start a background task unless this function is already being decompiled. Multiple // functions decompile in parallel in the background; a running task updates the view // when it polls, so revisiting an in-flight function just shows this placeholder. - if (inFlightDecompilations.add(function.functionID().value())) { - taskMonitorComponent.setVisible(true); - var task = new AIDecompTask(tool, function); - var builder = TaskBuilder.withTask(task); - builder.launchInBackground(taskMonitorComponent); - } + startDecompilation(function, false); } } } + /// Start a background decompilation task, unless the function already has one running + private void startDecompilation(GhidraRevengService.FunctionWithID function, boolean regenerate) { + if (inFlightDecompilations.add(function.functionID().value())) { + taskMonitorComponent.setVisible(true); + var task = new AIDecompTask(tool, function, regenerate); + var builder = TaskBuilder.withTask(task); + builder.launchInBackground(taskMonitorComponent); + } + } + public void locationChanged(ProgramLocation loc) { var service = tool.getService(GhidraRevengService.class); var analyzedProgram = service.getAnalysedProgram(loc.getProgram()); @@ -490,6 +526,29 @@ private void refreshCurrentFunction() { analysed.get().getIDForFunction(target).ifPresent(this::refresh); } + /// Start a new AI decompilation for the current function, whose last one failed. Refresh alone + /// only re-reads the failed result, because the task triggers a decompilation only when none exists. + private void regenerateCurrentFunction() { + Function target = this.function; + if (!canRegenerate(target)) { + return; + } + var service = tool.getService(GhidraRevengService.class); + var functionWithID = service.getAnalysedProgram(target.getProgram()) + .flatMap(analysed -> analysed.getIDForFunction(target)); + if (functionWithID.isEmpty()) { + return; + } + cache.remove(target); + currentRenderModel = null; + tool.getService(ReaiLoggingService.class).info("Regenerating the AI Decompilation for function %s".formatted(target.getName())); + setCode(""); + descriptionArea.setText("Decompiling %s ...".formatted(target.getName())); + predictedNamePanel.setVisible(false); + startDecompilation(functionWithID.get(), true); + contextChanged(); + } + // --- Rename / comment editing ------------------------------------------------------------- private void handleDoubleClick(Point point) { @@ -916,6 +975,17 @@ private void reportDecompFailure(Function failedFunction, Exception e) { }); } + /// Polling for {@code stoppedFunction} ended without a result; say why in the log and the window. + private void reportDecompStopped(Function stoppedFunction, String reason) { + var logger = tool.getService(ReaiLoggingService.class); + logger.warn("Stopped waiting for the AI Decompilation of %s: %s".formatted(stoppedFunction.getName(), reason)); + SwingUtilities.invokeLater(() -> { + if (isCurrentFunction(stoppedFunction)) { + descriptionArea.setText("Stopped waiting for the AI Decompilation: " + reason); + } + }); + } + /** * Maps each display line of the rendered decompilation back to its source line, so a click in * the text area can be resolved to the line/identifier to rename or comment on. @@ -948,13 +1018,22 @@ boolean isCodeLine(int displayLine) { class AIDecompTask extends Task { + // Poll every second, slowing to every 5 while nothing changes, for at most 15 minutes in all + // (decompilation, summary and inline comments) + private static final Duration POLL_INTERVAL = Duration.ofSeconds(1); + private static final Duration MAX_POLL_INTERVAL = Duration.ofSeconds(5); + private static final Duration MAX_DECOMPILATION_WAIT = Duration.ofMinutes(15); + private final GhidraRevengService service; private final GhidraRevengService.FunctionWithID functionWithID; + private final boolean regenerate; - public AIDecompTask(PluginTool tool, GhidraRevengService.FunctionWithID functionWithID) { + /// @param regenerate also start a new decompilation when the last one FAILED + public AIDecompTask(PluginTool tool, GhidraRevengService.FunctionWithID functionWithID, boolean regenerate) { super("AI Decomp task", true, false, false); service = tool.getService(GhidraRevengService.class); this.functionWithID = functionWithID; + this.regenerate = regenerate; } @Override @@ -962,7 +1041,9 @@ public void run(TaskMonitor monitor) throws CancelledException { try { var fID = functionWithID.functionID(); // Check if there is an existing process already, because the trigger API will fail with 400 if there is - if (service.getApi().pollAIDecompileStatus(fID).status() == DecompilationData.StatusEnum.UNINITIALISED) { + var current = service.getApi().pollAIDecompileStatus(fID).status(); + if (current == DecompilationData.StatusEnum.UNINITIALISED + || (regenerate && current == DecompilationData.StatusEnum.FAILED)) { // Trigger the decompilation service.getApi().triggerAIDecompilationForFunctionID(fID); } @@ -974,18 +1055,53 @@ public void run(TaskMonitor monitor) throws CancelledException { reportDecompFailure(functionWithID.function(), e); } finally { inFlightDecompilations.remove(functionWithID.functionID().value()); + SwingUtilities.invokeLater(() -> { + if (inFlightDecompilations.isEmpty()) { + taskMonitorComponent.setVisible(false); + } + contextChanged(); + }); } } - private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) throws CancelledException { - var logger = tool.getService(ReaiLoggingService.class); + private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) throws Exception { var api = service.getApi(); - AIDecompilationStatus lastDecompStatus = null; - boolean inlineCommentsTriggered = false; - boolean summaryTriggered = false; - while (true) { - var newStatus = api.pollAIDecompileStatus(id); + var function = functionWithID.function(); + var step = new DecompPollStep(id); + var result = new StatusPoller(POLL_INTERVAL, MAX_POLL_INTERVAL, MAX_DECOMPILATION_WAIT) + .poll(() -> api.pollAIDecompileStatus(id), status -> step.next(status, monitor), monitor::isCancelled); + switch (result.ending()) { + case CANCELLED -> monitor.checkCancelled(); + case UNRECOGNISED -> { + // Not cached, so selecting the function again checks the server afresh. + cache.remove(function); + reportDecompStopped(function, "the server reported a status this plugin does not recognise"); + } + case TIMED_OUT -> { + cache.remove(function); + reportDecompStopped(function, "it has not finished after %s; use Refresh to check again" + .formatted(StatusPoller.describe(result.waited()))); + } + case DONE -> {} + } + } + + /// Acts on each polled status: shows it, and once the decompilation is done starts the summary + /// and then the inline comments, which the server no longer runs on its own. + private final class DecompPollStep { + private final TypedApiInterface.FunctionID id; + private AIDecompilationStatus lastDecompStatus = null; + private boolean inlineCommentsTriggered = false; + private boolean summaryTriggered = false; + + DecompPollStep(TypedApiInterface.FunctionID id) { + this.id = id; + } + + StatusPoller.Verdict next(AIDecompilationStatus newStatus, TaskMonitor monitor) { + var logger = tool.getService(ReaiLoggingService.class); + var api = service.getApi(); if (lastDecompStatus == null || !Objects.equals(newStatus.status(), lastDecompStatus.status()) || !Objects.equals(newStatus.summaryStatus(), lastDecompStatus.summaryStatus()) @@ -996,28 +1112,21 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) newStatusForFunction(functionWithID.function(), newStatus); } monitor.setMessage("Waiting for AI Decompilation for %s ... Current status: %s".formatted(functionWithID.function().getName(), lastDecompStatus.status())); - monitor.checkCancelled(); switch (newStatus.status()) { case PENDING: case RUNNING: case UNINITIALISED: - try { - // Wait a second before polling again. We don't want to spam the API with requests too often - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - break; + return StatusPoller.Verdict.WAIT; case COMPLETED: monitor.setProgress(monitor.getMaximum()); // Decompilation is done; now wait for inline comments to land before stopping. var commentsStatus = newStatus.inlineCommentsStatus(); if (commentsStatus == WorkflowProgress.StatusEnum.COMPLETED) { - return; + return StatusPoller.Verdict.DONE; } if (commentsStatus == WorkflowProgress.StatusEnum.FAILED) { logger.error("Inline comments generation failed for function %s".formatted(functionWithID.function().getName())); - return; + return StatusPoller.Verdict.DONE; } var summaryStatus = newStatus.summaryStatus(); if (!summaryTriggered) { @@ -1031,7 +1140,9 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) if (e.getCause() instanceof ApiException apiException && apiException.getCode() == 409) { summaryTriggered = false; } else { + // Without a summary there are no inline comments either, so there is nothing left to wait for. logger.error("Failed to trigger summary: %s".formatted(e.getMessage())); + return StatusPoller.Verdict.DONE; } } } @@ -1039,7 +1150,7 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) // Server requires a summary to exist before inline comments can be generated; // if the summary failed there's no point triggering comments. logger.error("Summary generation failed for function %s; skipping inline comments".formatted(functionWithID.function().getName())); - return; + return StatusPoller.Verdict.DONE; } if (summaryStatus == WorkflowProgress.StatusEnum.COMPLETED && !inlineCommentsTriggered) { // Gate the inline-comments POST on summary completion — the server rejects it @@ -1049,22 +1160,16 @@ private void waitForDecomp(TypedApiInterface.FunctionID id, TaskMonitor monitor) api.triggerAIDecompilationInlineComments(id); } catch (RuntimeException e) { logger.error("Failed to trigger inline comments: %s".formatted(e.getMessage())); - return; + return StatusPoller.Verdict.DONE; } } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - break; + return StatusPoller.Verdict.WAIT; case FAILED: logger.error("Decompilation failed: %s".formatted(newStatus.decompilation())); - return; + return StatusPoller.Verdict.DONE; default: - throw new RuntimeException("Unknown status: %s".formatted(newStatus.status())); + return StatusPoller.Verdict.UNRECOGNISED; } - } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java index 79a3b39c..63422edf 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/analysiscreation/RevEngAIAnalysisOptionsDialog.java @@ -1,7 +1,7 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.analysiscreation; import ai.reveng.model.ConfigResponse; -import ai.reveng.model.User; +import ai.reveng.model.CurrentUser; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; @@ -13,6 +13,7 @@ import ghidra.program.model.listing.Program; import ghidra.util.Msg; import ghidra.util.Swing; +import generic.theme.GThemeDefaults.Colors.Messages; import javax.annotation.Nullable; import javax.swing.*; @@ -73,13 +74,9 @@ private void buildInterface() { var workPanel = new JPanel(); workPanel.setLayout(new BoxLayout(workPanel, BoxLayout.Y_AXIS)); - // Create title panel - JPanel titlePanel = createTitlePanel("Create new analysis for this binary"); - workPanel.add(titlePanel, BorderLayout.NORTH); - // File size warning label (hidden by default) fileSizeWarningLabel = new JLabel(); - fileSizeWarningLabel.setForeground(Color.RED); + fileSizeWarningLabel.setForeground(Messages.ERROR); fileSizeWarningLabel.setHorizontalAlignment(SwingConstants.CENTER); fileSizeWarningLabel.setAlignmentX(Component.CENTER_ALIGNMENT); fileSizeWarningLabel.setVisible(false); @@ -143,16 +140,23 @@ private void buildInterface() { // Loading indicator (shown while fetching config) loadingLabel = new JLabel("Checking file size limits..."); - loadingLabel.setForeground(Color.GRAY); + loadingLabel.setForeground(Messages.HINT); loadingLabel.setHorizontalAlignment(SwingConstants.CENTER); loadingLabel.setAlignmentX(Component.CENTER_ALIGNMENT); loadingLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); workPanel.add(loadingLabel); + var optionsColumn = new JPanel(new BorderLayout()); + optionsColumn.add(workPanel, BorderLayout.NORTH); + var contentPanel = new JPanel(new BorderLayout(12, 0)); - contentPanel.add(workPanel, BorderLayout.WEST); + contentPanel.add(optionsColumn, BorderLayout.WEST); contentPanel.add(buildFunctionSelectionPanel(), BorderLayout.CENTER); - addWorkPanel(contentPanel); + + var rootPanel = new JPanel(new BorderLayout()); + rootPanel.add(createTitlePanel("Create new analysis for this binary"), BorderLayout.NORTH); + rootPanel.add(contentPanel, BorderLayout.CENTER); + addWorkPanel(rootPanel); addCancelButton(); addOKButton(); @@ -169,10 +173,9 @@ private void buildInterface() { var options = AnalysisOptionsBuilder.forProgram(program, function -> includedEntryPoints.contains(function.getEntryPoint())); - // Capability generation and advanced analysis are not offered by this dialog and are - // always off for analyses the plugin creates. + // Capability generation is not offered by this dialog and is always off for analyses + // the plugin creates. options.skipCapabilities(true); - options.advancedAnalysis(false); if (privateScope.isSelected() && privateScope.isEnabled()) { options.scope(AnalysisScope.PRIVATE); @@ -414,10 +417,10 @@ private void fetchUserTierAsync() { }); } - private void handleUserResponse(@Nullable User user) { + private void handleUserResponse(@Nullable CurrentUser user) { tierResolved = true; - if (user != null && user.getTier() != User.TierEnum.ENTHUSIAST) { + if (user != null && user.getTier() != CurrentUser.TierEnum.ENTHUSIAST) { privateScope.setEnabled(true); privateScope.setToolTipText(null); privateScopePanel.setToolTipText(null); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java index 67343ce8..d1a8e73e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/ItemSelectionPanel.java @@ -1,5 +1,6 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.components; +import generic.theme.GColor; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; @@ -17,6 +18,7 @@ public class ItemSelectionPanel extends JPanel { private SimpleAutocompleteField autocompleteField; private JPanel selectedItemsPanel; + private JScrollPane tagsScrollPane; private final Set selectedItems; private final List listeners; private Function>> dynamicItemLoader; @@ -41,29 +43,35 @@ public ItemSelectionPanel(Function addSelectedItem()); @@ -107,7 +116,7 @@ private void addSelectedItem() { private void addItemTag(SelectableItem item) { JPanel tagPanel = new JPanel(new BorderLayout()); tagPanel.setBorder(createTagBorder()); - tagPanel.setBackground(new Color(230, 240, 250)); + tagPanel.setBackground(new GColor("color.bg.reveng.tag")); JLabel label = new JLabel(item.getName()); // Display name to user label.setBorder(BorderFactory.createEmptyBorder(2, 6, 2, 6)); @@ -116,21 +125,26 @@ private void addItemTag(SelectableItem item) { removeButton.setPreferredSize(new Dimension(20, 20)); removeButton.setFont(removeButton.getFont().deriveFont(Font.BOLD, 12f)); removeButton.setMargin(new Insets(0, 0, 0, 0)); - removeButton.setBackground(Color.WHITE); - removeButton.setBorder(BorderFactory.createRaisedBevelBorder()); + removeButton.setBorder(BorderFactory.createEmptyBorder()); + removeButton.setContentAreaFilled(false); removeButton.addActionListener(e -> removeItem(item, tagPanel)); tagPanel.add(label, BorderLayout.CENTER); tagPanel.add(removeButton, BorderLayout.EAST); selectedItemsPanel.add(tagPanel); - selectedItemsPanel.revalidate(); - selectedItemsPanel.repaint(); + updateTagsVisibility(); + } + + private void updateTagsVisibility() { + tagsScrollPane.setVisible(!selectedItems.isEmpty()); + revalidate(); + repaint(); } private Border createTagBorder() { return BorderFactory.createCompoundBorder( - BorderFactory.createRaisedBevelBorder(), + BorderFactory.createLineBorder(new GColor("color.border.reveng.tag")), BorderFactory.createEmptyBorder(2, 2, 2, 2) ); } @@ -138,8 +152,7 @@ private Border createTagBorder() { private void removeItem(SelectableItem item, JPanel tagPanel) { selectedItems.remove(item); selectedItemsPanel.remove(tagPanel); - selectedItemsPanel.revalidate(); - selectedItemsPanel.repaint(); + updateTagsVisibility(); notifyListeners(); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java index 20560e8a..46f4c4a1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/SimpleAutocompleteField.java @@ -1,5 +1,7 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.components; +import docking.widgets.textfield.HintTextField; + import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; @@ -19,7 +21,7 @@ * Uses dynamic API-based collection fetching only. */ public class SimpleAutocompleteField extends JPanel { - private JTextField textField; + private HintTextField textField; private JList suggestionsList; private JScrollPane suggestionsScrollPane; private JPopupMenu suggestionsPopup; @@ -45,7 +47,7 @@ private void initializeComponents() { setLayout(new BorderLayout()); // Create text field - textField = new JTextField(); + textField = new HintTextField(""); textField.setPreferredSize(new Dimension(250, textField.getPreferredSize().height)); add(textField, BorderLayout.CENTER); @@ -234,6 +236,11 @@ public void setText(String text) { textField.setText(text); } + /// Greyed-out text shown while the field is empty + public void setHint(String hint) { + textField.setHint(hint); + } + public void clear() { textField.setText(""); hideSuggestions(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/UserSelectionPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/UserSelectionPanel.java new file mode 100644 index 00000000..b63a13d4 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/components/UserSelectionPanel.java @@ -0,0 +1,35 @@ +package ai.reveng.toolkit.ghidra.binarysimilarity.ui.components; + +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.List; + +/** + * A component that allows multiple selection of users with autocomplete support. + * This is a specialized version of ItemSelectionPanel for users. + */ +public class UserSelectionPanel extends ItemSelectionPanel { + + /** + * @param dynamicUserLoader Function that takes a query string and returns matching users + * @param minimumQueryLength Minimum characters before triggering API calls (the users endpoint needs 3) + */ + public UserSelectionPanel(Function>> dynamicUserLoader, int minimumQueryLength) { + super(dynamicUserLoader, minimumQueryLength, "User"); + } + + /** + * Gets the IDs of currently selected users + */ + public Set getSelectedUserIds() { + return getSelectedItemIds(); + } + + /** + * Gets the names of currently selected users + */ + public Set getSelectedUserNames() { + return getSelectedItemNames(); + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java index b3da6e7d..ac7582cd 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/dialog/RevEngDialogComponentProvider.java @@ -2,7 +2,8 @@ import docking.DialogComponentProvider; import docking.widgets.label.GDLabel; -import resources.ResourceManager; +import generic.theme.GColor; +import generic.theme.GIcon; import javax.swing.*; import java.awt.*; @@ -13,39 +14,19 @@ public RevEngDialogComponentProvider(String title, boolean isModal) { } protected JPanel createTitlePanel(String title) { - // Load icon from resources - Icon dialogIcon = null; - try { - dialogIcon = ResourceManager.loadImage("images/icon_50.png"); - } catch (Exception e) { - // If loading fails, fall back to no icon - } + return createTitlePanel(new GDLabel(title)); + } - // Create title label - JLabel titleLabel = new GDLabel(title); - // Make the title text bold - Font currentFont = titleLabel.getFont(); - titleLabel.setFont(currentFont.deriveFont(Font.BOLD)); + public static JPanel createTitlePanel(JLabel titleLabel) { + titleLabel.setIcon(new GIcon("icon.reveng.mark.24")); + titleLabel.setIconTextGap(8); + titleLabel.setFont(titleLabel.getFont().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 - if (dialogIcon != null) { - JLabel iconLabel = new JLabel(dialogIcon); - titlePanel.add(iconLabel, BorderLayout.WEST); - } - - // 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); - + titlePanel.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(0, 0, 1, 0, new GColor("color.border.reveng.title")), + BorderFactory.createEmptyBorder(8, 12, 8, 12))); + titlePanel.add(titleLabel, BorderLayout.CENTER); return titlePanel; } -} \ No newline at end of file +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java index 8f31caa8..13391c49 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AbstractFunctionMatchingDialog.java @@ -1,35 +1,50 @@ package ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching; +import ai.reveng.invoker.ApiException; import ai.reveng.model.*; import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiImplementation; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.dialog.RevEngDialogComponentProvider; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.CollectionSelectionPanel; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.BinarySelectionPanel; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.SelectableItem; +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.UserSelectionPanel; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; +import docking.widgets.textfield.HintTextField; +import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Function; import ghidra.util.task.Task; import ghidra.util.task.TaskBuilder; import ghidra.util.task.TaskMonitor; -import ghidra.util.task.TaskMonitorComponent; import ghidra.util.Msg; +import ghidra.util.Swing; +import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import resources.ResourceManager; +import generic.theme.GThemeDefaults.Colors.Messages; +import generic.theme.GColor; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.time.Duration; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.function.Consumer; import java.util.stream.Collectors; public abstract class AbstractFunctionMatchingDialog extends RevEngDialogComponentProvider { + protected final PluginTool tool; protected final GhidraRevengService revengService; protected final GhidraRevengService.AnalysedProgram analyzedProgram; @@ -44,44 +59,47 @@ public abstract class AbstractFunctionMatchingDialog extends RevEngDialogCompone protected JLabel thresholdValueLabel; protected JCheckBox debugSymbolsCheckBox; protected JCheckBox userSubmittedDebugSymbolsCheckBox; + protected UserSelectionPanel userSelector; + // Nothing ticked means any platform / architecture, as in the portal + protected final Map platformCheckBoxes = new LinkedHashMap<>(); + protected final Map architectureCheckBoxes = new LinkedHashMap<>(); protected JLabel statusLabel; + protected JProgressBar matchingProgressBar; + protected JButton matchButton; + private Icon matchIcon; + protected JLabel resultsCountLabel; protected JTextArea errorArea; protected JScrollPane errorScrollPane; - protected final TaskMonitorComponent taskMonitorComponent; - protected volatile boolean matchingCancelled; - protected Thread matchingThread; - protected JPanel renameButtonsPanel; + /// The thread of the current matching run; null when idle or cancelled. A run whose thread is no + /// longer this one has been superseded, and must not touch the UI. + protected volatile Thread matchingThread; + protected JPanel transferButtonsPanel; // Assembly comparison panel protected AssemblyDiffPanel assemblyDiffPanel; + private final JPopupMenu portalPopup = new JPopupMenu(); // Data - protected AnalysisBasicInfoOutputBody analysisBasicInfo; + /// Loaded by {@link #showWhenLoaded} before the dialog is built; the binary filter searches within its model + protected final AnalysisBasicInfoOutputBody analysisBasicInfo; protected final List functionMatchResults; protected final List filteredFunctionMatchResults; - // Polling configuration - protected static final int POLL_INTERVAL_MS = 2000; // Poll every 2 seconds + // Polling configuration: every 2 seconds, slowing to every 10 while nothing changes, for at most 30 minutes + protected static final Duration POLL_INTERVAL = Duration.ofSeconds(2); + protected static final Duration MAX_POLL_INTERVAL = Duration.ofSeconds(10); + protected static final Duration MAX_MATCHING_WAIT = Duration.ofMinutes(30); - protected AbstractFunctionMatchingDialog(String title, Boolean isModal, GhidraRevengService revengService, - GhidraRevengService.AnalysedProgram analyzedProgram) { + protected AbstractFunctionMatchingDialog(String title, Boolean isModal, PluginTool tool, + GhidraRevengService.AnalysedProgram analyzedProgram, + AnalysisBasicInfoOutputBody analysisBasicInfo) { super(title, isModal); - this.revengService = revengService; + this.tool = tool; + this.revengService = tool.getService(GhidraRevengService.class); this.analyzedProgram = analyzedProgram; - this.taskMonitorComponent = new TaskMonitorComponent(false, true); this.functionMatchResults = new ArrayList<>(); this.filteredFunctionMatchResults = new ArrayList<>(); - - try { - this.analysisBasicInfo = revengService.getBasicDetailsForAnalysis(analyzedProgram.analysisID()); - } catch (Exception e) { - JOptionPane.showMessageDialog(null, - "Failed to fetch analysis details: " + e.getMessage(), - "Error", - JOptionPane.ERROR_MESSAGE); - close(); - return; - } + this.analysisBasicInfo = analysisBasicInfo; // Initialize UI addDismissButton(); @@ -91,23 +109,71 @@ protected AbstractFunctionMatchingDialog(String title, Boolean isModal, GhidraRe setPreferredSize(1200, 1000); // Don't start function matching automatically - wait for user to click Match button - statusLabel.setText("Ready - adjust filters and click 'Match Functions' to begin search"); - taskMonitorComponent.setVisible(false); + statusLabel.setText("Ready: adjust the filters and press Match Functions"); + } + + /// Fetches the analysis' basic info in a background task, then builds the dialog with it and shows it. The + /// first fetch for an analysis is not cached and can take several seconds, so it must not run on the Swing + /// thread; when it fails the user is told why and no dialog is shown. + public static void showWhenLoaded(PluginTool tool, GhidraRevengService.AnalysedProgram analyzedProgram, + java.util.function.Function dialog) { + var service = tool.getService(GhidraRevengService.class); + tool.execute(new Task("Load RevEng.AI analysis details", true, false, false) { + @Override + public void run(TaskMonitor monitor) { + AnalysisBasicInfoOutputBody basicInfo; + try { + basicInfo = service.getBasicDetailsForAnalysis(analyzedProgram.analysisID()); + } catch (Exception e) { + // The message carries the server's reason; the trace goes to the log, not the dialog + var message = "Failed to fetch the details of analysis %d: %s" + .formatted(analyzedProgram.analysisID().id(), describe(e)); + Msg.warn(AbstractFunctionMatchingDialog.class, message, e); + Msg.showError(AbstractFunctionMatchingDialog.class, tool.getToolFrame(), + ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", message); + return; + } + if (monitor.isCancelled()) { + return; + } + Swing.runLater(() -> tool.showDialog(dialog.apply(basicInfo))); + } + }, 0); + } + + private static String describe(Exception e) { + return e instanceof ApiException api + ? TypedApiImplementation.describeApiException(api) : e.getMessage(); } protected void startFunctionMatching() { - // Show initial status. All network work runs on a background thread so the UI stays responsive; - // the bar is indeterminate (animated) until/unless the server reports step counters. + // All network work runs on a background thread so the UI stays responsive statusLabel.setText("Starting function matching..."); - taskMonitorComponent.initialize(100); - taskMonitorComponent.setIndeterminate(true); + matchingProgressBar.setIndeterminate(true); + setMatchingInProgress(true); - matchingCancelled = false; matchingThread = new Thread(this::runMatchingLoop, "RevEngAI function matching"); matchingThread.setDaemon(true); matchingThread.start(); } + /// Shows or hides the progress bar, and turns the Match button into Cancel while a run is going + protected void setMatchingInProgress(boolean inProgress) { + matchingProgressBar.setVisible(inProgress); + matchButton.setText(inProgress ? "Cancel" : "Match Functions"); + matchButton.setIcon(inProgress ? null : matchIcon); + } + + /// Runs {@code update} on the EDT, unless the run on {@code self} has been cancelled or superseded + /// by the time it gets there + private void onEdtIfCurrent(Thread self, Runnable update) { + SwingUtilities.invokeLater(() -> { + if (matchingThread == self) { + update.run(); + } + }); + } + /// Normalised view of the v3 matching progress, shared by the start and status responses protected record MatchingProgress(String status, String step, Long stepIndex, Long stepsTotal, String errorMessage) {} @@ -121,62 +187,98 @@ protected record MatchingProgress(String status, String step, Long stepIndex, Lo protected abstract List fetchMatches() throws ai.reveng.invoker.ApiException; private void runMatchingLoop() { + final Thread self = Thread.currentThread(); try { - MatchingProgress progress = startMatching(); - while (!matchingCancelled) { - final MatchingProgress current = progress; - SwingUtilities.invokeLater(() -> updateProgressUI(current)); - - if ("FAILED".equals(progress.status())) { - String errorMsg = progress.errorMessage() != null && !progress.errorMessage().isEmpty() - ? progress.errorMessage() - : "Function matching returned an error status"; - SwingUtilities.invokeLater(() -> { - statusLabel.setText("Function matching failed"); - handleError(errorMsg); - }); - return; - } - if ("COMPLETED".equals(progress.status())) { - break; - } - Thread.sleep(POLL_INTERVAL_MS); - if (matchingCancelled) return; - progress = pollMatchingStatus(); + boolean[] started = {false}; + var result = new StatusPoller(POLL_INTERVAL, MAX_POLL_INTERVAL, MAX_MATCHING_WAIT).poll( + () -> { + if (!started[0]) { + started[0] = true; + return startMatching(); + } + return pollMatchingStatus(); + }, + current -> { + onEdtIfCurrent(self, () -> updateProgressUI(current)); + return classifyMatchingStatus(current.status()); + }, + () -> matchingThread != self); + if (matchingThread != self) return; + String stopped = switch (result.ending()) { + case UNRECOGNISED -> "The server reported a function matching status this plugin does not recognise " + + "(the matching may have been cancelled). Press Match Functions to start it again."; + case TIMED_OUT -> "Function matching has not finished after %s; stopped waiting. Press Match Functions to start it again." + .formatted(StatusPoller.describe(result.waited())); + default -> null; + }; + if (stopped != null) { + onEdtIfCurrent(self, () -> { + handleError(stopped); + statusLabel.setText("Stopped waiting for function matching"); + }); + return; } - if (matchingCancelled) return; + var progress = result.status(); + if ("FAILED".equals(progress.status())) { + String errorMsg = progress.errorMessage() != null && !progress.errorMessage().isEmpty() + ? progress.errorMessage() + : "Function matching returned an error status"; + onEdtIfCurrent(self, () -> { + handleError(errorMsg); + statusLabel.setText("Function matching failed"); + }); + return; + } + if (matchingThread != self) return; // Resolving type signatures fires many requests, so keep it off the EDT too - SwingUtilities.invokeLater(() -> { - taskMonitorComponent.setIndeterminate(true); - taskMonitorComponent.setMessage("Loading type information..."); + onEdtIfCurrent(self, () -> { + matchingProgressBar.setIndeterminate(true); statusLabel.setText("Loading type information..."); }); - var matches = fetchMatches(); - if (matchingCancelled) return; - processFunctionMatchingResults(matches); - // The status label is the only thing that says what this dialog is doing, and nothing - // used to write to it again after the "Loading type information..." above. The work - // finished, the bar went away, and the label sat there claiming to still be loading — - // indistinguishable from a request that never returned. - SwingUtilities.invokeLater(() -> statusLabel.setText( - "Matching complete: %d match(es)".formatted(functionMatchResults.size()))); + var built = buildMatchResults(fetchMatches()); + // The status label is the only thing that says what this dialog is doing, so it has to be + // told the work finished, or it sits there claiming to still be loading. + onEdtIfCurrent(self, () -> { + functionMatchResults.clear(); + functionMatchResults.addAll(built); + // Apply any existing function filter, which also refreshes the table + onFunctionFilterChanged(); + statusLabel.setText("Matching complete: %d match(es)".formatted(functionMatchResults.size())); + }); } catch (InterruptedException e) { // matching was cancelled, nothing to report } catch (Throwable t) { // Throwable rather than Exception: an Error thrown in here — a clash between a bundled // jar and Ghidra's own, or a large binary's type closure exhausting the heap — killed - // this thread without a word and left the progress message up for ever. Whatever it is, + // this thread without a word and left the progress bar up for ever. Whatever it is, // the user is told. - SwingUtilities.invokeLater(() -> { - Msg.error(this, "Function matching failed: " + t, t); + Msg.error(this, "Function matching failed: " + t, t); + onEdtIfCurrent(self, () -> { handleError("Function matching failed: " + t); statusLabel.setText("Function matching failed"); }); } finally { - // No path out of here may leave the progress bar spinning. - SwingUtilities.invokeLater(() -> taskMonitorComponent.setVisible(false)); + // No path out of here may leave the progress bar spinning. A cancelled run has already + // been reset by stopPolling, and must not hide the bar of the run that replaced it. + onEdtIfCurrent(self, () -> { + matchingThread = null; + setMatchingInProgress(false); + }); + } + } + + /// How a v3 matching status (as its wire value) bears on the wait. The SDK turns a status it does + /// not model, such as CANCELLED, into an "unknown" value; that and a missing status end the wait. + protected static StatusPoller.Verdict classifyMatchingStatus(String status) { + if (status == null) { + return StatusPoller.Verdict.UNRECOGNISED; } + return switch (status) { + case "COMPLETED", "FAILED" -> StatusPoller.Verdict.DONE; + case "UNINITIALISED", "PENDING", "RUNNING" -> StatusPoller.Verdict.WAIT; + default -> StatusPoller.Verdict.UNRECOGNISED; + }; } /// Joins the error-level {@link ProgressMessage}s of a v3 matching response into a single string @@ -212,10 +314,9 @@ protected static List flattenMatches(List response) { + /// Builds the result rows. This resolves type signatures, which is the expensive part, so it is + /// expected to run off the EDT and does not touch Swing. + protected List buildMatchResults(List response) { List matches = new ArrayList<>(); final Map functionMap = analyzedProgram.getFunctionMap(); @@ -240,34 +341,34 @@ protected void processFunctionMatchingResults(List respon var sig = ghidraResultsWithSignatures.get(match); built.add(new GhidraFunctionMatchWithSignature(match.function(), match.functionMatch(), sig)); } - - SwingUtilities.invokeLater(() -> { - functionMatchResults.clear(); - functionMatchResults.addAll(built); - // Apply any existing function filter, which also refreshes the table - onFunctionFilterChanged(); - }); + return built; } protected void updateProgressUI(MatchingProgress progress) { if (progress == null) return; - // Update progress bar from the v3 step counters when present; otherwise show an animated - // (indeterminate) bar so the user can see that matching is still running. + // A determinate bar when the server reports step counters (step_index is zero-based, so the bar + // fills by completed steps); otherwise an animated one so the user can see it is still running. + // The step itself goes in the status text: painted on the bar it overlaps the thin macOS track. + String step = progress.step() != null && !progress.step().isBlank() ? progress.step() : null; if (progress.stepsTotal() != null && progress.stepsTotal() > 0 && progress.stepIndex() != null) { - int percent = (int) Math.min(100, Math.max(0, progress.stepIndex() * 100 / progress.stepsTotal())); - taskMonitorComponent.setIndeterminate(false); - taskMonitorComponent.setProgress(percent); - taskMonitorComponent.setMessage(progress.step() != null ? progress.step() : percent + "%"); + int total = (int) Math.min(Integer.MAX_VALUE, progress.stepsTotal()); + int index = (int) Math.max(0, Math.min(total, progress.stepIndex())); + matchingProgressBar.setIndeterminate(false); + matchingProgressBar.setMaximum(total); + matchingProgressBar.setValue(index); + if (step != null) { + step = "%s (step %d of %d)".formatted(step, Math.min(index + 1, total), total); + } } else { - taskMonitorComponent.setIndeterminate(true); - taskMonitorComponent.setMessage(progress.step() != null ? progress.step() : "Matching functions..."); + matchingProgressBar.setIndeterminate(true); } - // Update status - if (progress.status() != null) { - statusLabel.setText("Status: " + getFriendlyStatusMessage(progress.status())); + if (step != null) { + statusLabel.setText(step); + } else if (progress.status() != null) { + statusLabel.setText(getFriendlyStatusMessage(progress.status())); } // Handle error message - dynamically add/remove error panel @@ -276,9 +377,6 @@ protected void updateProgressUI(MatchingProgress progress) { } else { hideError(); } - - // Update results table - updateResultsTable(); } /// The results that back the table model, in model-row order: all results when no function filter @@ -304,22 +402,18 @@ public boolean isCellEditable(int row, int column) { } resultsTable.setModel(model); - // Update the dynamic title with filtered count + // Show how many of the matches the results filter lets through int totalMatchCount = functionMatchResults.size(); int displayedMatchCount = resultsToShow.size(); - String title; - if (filterText.isEmpty()) { - title = getTableTitle() + " (" + totalMatchCount + " matches found)"; - } else { - title = getTableTitle() + " (" + displayedMatchCount + " of " + totalMatchCount + " matches shown)"; - } - resultsScrollPane.setBorder(BorderFactory.createTitledBorder(title)); + resultsCountLabel.setText(filterText.isEmpty() + ? "%d match%s".formatted(totalMatchCount, totalMatchCount == 1 ? "" : "es") + : "%d of %d shown".formatted(displayedMatchCount, totalMatchCount)); - // Show/hide rename buttons based on whether we have results + // Show/hide transfer buttons based on whether we have results boolean hasResults = displayedMatchCount > 0; - renameButtonsPanel.setVisible(hasResults); + transferButtonsPanel.setVisible(hasResults); - // Enable table selection model for rename operations + // Enable table selection model for transfer operations if (hasResults) { resultsTable.setSelectionMode(getTableSelectionMode()); resultsTable.setRowSelectionAllowed(true); @@ -336,7 +430,6 @@ public boolean isCellEditable(int row, int column) { protected abstract String[] getTableColumnNames(); protected abstract Object[] getTableRowData(GhidraFunctionMatchWithSignature result); - protected abstract String getTableTitle(); protected abstract int getTableSelectionMode(); protected abstract void configureTableColumns(); @@ -349,12 +442,12 @@ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - if (value instanceof String percentageStr) { - Color textColor = getColorForPercentage(percentageStr); + if (value instanceof java.math.BigDecimal percentage) { + Color textColor = getColorForPercentage(percentage.toPlainString()); if (!isSelected) { // Set text color based on percentage value - c.setForeground(textColor); + c.setForeground(textColor != null ? textColor : table.getForeground()); // Keep default background color c.setBackground(table.getBackground()); } else { @@ -367,54 +460,41 @@ public Component getTableCellRendererComponent(JTable table, Object value, return c; } + private static final Color SIMILARITY_CRITICAL = new GColor("color.fg.reveng.similarity.critical"); + private static final Color SIMILARITY_HIGH = new GColor("color.fg.reveng.similarity.high"); + private static final Color SIMILARITY_MEDIUM = new GColor("color.fg.reveng.similarity.medium"); + private static final Color SIMILARITY_LOW = new GColor("color.fg.reveng.similarity.low"); + /** - * Get the text color based on percentage value + * Get the text color based on percentage value, or null for the table's default */ private Color getColorForPercentage(String percentageStr) { try { // Remove the % symbol and parse as double String numStr = percentageStr.replace("%", "").trim(); if (numStr.equals("N/A")) { - return Color.BLACK; // Default color for N/A values + return null; } double percentage = Double.parseDouble(numStr); - if (percentage >= 0 && percentage <= 1) { - return new Color(255, 0, 0); // Red - } else if (percentage > 1 && percentage <= 50) { - return new Color(128, 0, 128); // Purple + if (percentage >= 0 && percentage <= 50) { + return SIMILARITY_CRITICAL; } else if (percentage > 50 && percentage <= 70) { - return new Color(255, 165, 0); // Orange + return SIMILARITY_HIGH; } else if (percentage > 70 && percentage <= 90) { - return new Color(200, 140, 0); // Darker yellow for better visibility - } else if (percentage > 90 && percentage <= 95) { - return new Color(34, 139, 34); // Forest Green - } else if (percentage > 95 && percentage <= 100) { - return new Color(0, 100, 0); // Dark Green + return SIMILARITY_MEDIUM; + } else if (percentage > 90 && percentage <= 100) { + return SIMILARITY_LOW; } else { - return Color.BLACK; // Default for out-of-range values + return null; } } catch (NumberFormatException e) { - return Color.BLACK; // Default color for unparseable values + return null; } } } - /** - * Parse a percentage string (e.g., "95.50%") into a double value for sorting - */ - protected Double parsePercentage(String percentageStr) { - if (percentageStr == null || percentageStr.equals("N/A")) { - return -1.0; // Sort N/A values to the bottom - } - try { - return Double.parseDouble(percentageStr.replace("%", "").trim()); - } catch (NumberFormatException e) { - return -1.0; // Sort unparseable values to the bottom - } - } - /** * Configure custom comparators for percentage columns to enable proper numerical sorting * @param similarityColumnIndex the index of the similarity column @@ -423,11 +503,7 @@ protected Double parsePercentage(String percentageStr) { protected void configurePercentageColumnSorting(int similarityColumnIndex, int confidenceColumnIndex) { if (resultsTable.getRowSorter() != null) { javax.swing.table.TableRowSorter sorter = (javax.swing.table.TableRowSorter) resultsTable.getRowSorter(); - java.util.Comparator percentageComparator = (s1, s2) -> { - Double val1 = parsePercentage(s1); - Double val2 = parsePercentage(s2); - return val1.compareTo(val2); - }; + java.util.Comparator percentageComparator = java.math.BigDecimal::compareTo; sorter.setComparator(similarityColumnIndex, percentageComparator); sorter.setComparator(confidenceColumnIndex, percentageComparator); } @@ -442,19 +518,18 @@ protected String getFriendlyStatusMessage(String apiStatus) { } return switch (apiStatus) { - case "UNINITIALISED", "PENDING" -> "starting function matching..."; - case "RUNNING" -> "running function matching..."; - case "COMPLETED" -> "completed function matching"; - case "FAILED" -> "function matching failed"; + case "UNINITIALISED", "PENDING" -> "Starting function matching..."; + case "RUNNING" -> "Running function matching..."; + case "COMPLETED" -> "Completed function matching"; + case "FAILED" -> "Function matching failed"; default -> apiStatus; // Fallback to original if unknown }; } protected void handleError(String message) { Msg.error(this, message); - statusLabel.setText("An error occurred, press 'Match Functions' again to retry"); + statusLabel.setText("An error occurred, press Match Functions again to retry"); showError(message); - taskMonitorComponent.setMessage("Error"); } protected void showError(String message) { @@ -477,10 +552,13 @@ protected void hideError() { } protected void stopPolling() { - matchingCancelled = true; - if (matchingThread != null) { - matchingThread.interrupt(); - matchingThread = null; + Thread running = matchingThread; + matchingThread = null; + if (running != null) { + running.interrupt(); + } + if (matchingProgressBar != null) { + setMatchingInProgress(false); } } @@ -493,36 +571,34 @@ protected JComponent buildMainPanel() { // Create content panel contentPanel = new JPanel(new BorderLayout()); + contentPanel.setBorder(BorderFactory.createEmptyBorder(12, 16, 12, 16)); - // Create top panel with progress and filters - JPanel topPanel = new JPanel(new BorderLayout()); - - // Progress panel at the top - JPanel progressPanel = createProgressPanel(); - topPanel.add(progressPanel, BorderLayout.NORTH); + // Top half: the filters sent with the matching request, then status and the Match button + JPanel searchSection = new JPanel(new BorderLayout(0, 10)); + searchSection.add(createSectionHeading("Filter Search"), BorderLayout.NORTH); + searchSection.add(createFilterPanel(), BorderLayout.CENTER); + searchSection.add(createMatchActionPanel(), BorderLayout.SOUTH); + contentPanel.add(searchSection, BorderLayout.NORTH); - // Create filter panel - JPanel filterPanel = createFilterPanel(); - topPanel.add(filterPanel, BorderLayout.CENTER); - contentPanel.add(topPanel, BorderLayout.NORTH); + // Bottom half: narrowing down the results that came back + JPanel resultsHeader = new JPanel(new BorderLayout(0, 10)); + resultsHeader.setBorder(BorderFactory.createEmptyBorder(18, 0, 0, 0)); + resultsHeader.add(createSectionHeading("Filter Results"), BorderLayout.NORTH); + resultsHeader.add(createFunctionFilterPanel(), BorderLayout.CENTER); - // Match button panel and function filter - JPanel buttonAndFilterPanel = createButtonAndFilterPanel(); - - // Create a center panel to hold the button and results - JPanel centerPanel = new JPanel(new BorderLayout()); - centerPanel.add(buttonAndFilterPanel, BorderLayout.NORTH); + JPanel centerPanel = new JPanel(new BorderLayout(0, 8)); + centerPanel.add(resultsHeader, BorderLayout.NORTH); // Initialize error area but don't add it to the panel yet errorArea = new JTextArea(5, 60); errorArea.setLineWrap(true); errorArea.setWrapStyleWord(true); errorArea.setEditable(false); - errorArea.setBackground(Color.PINK); + errorArea.setForeground(Messages.ERROR); errorArea.setBorder(BorderFactory.createTitledBorder("Error Details")); errorScrollPane = new JScrollPane(errorArea); - // Results table with rename buttons container + // Results table with transfer buttons container JPanel resultsContainer = createResultsContainer(); centerPanel.add(resultsContainer, BorderLayout.CENTER); @@ -534,70 +610,102 @@ protected JComponent buildMainPanel() { protected abstract String getDialogDescription(); - protected JPanel createFilterPanel() { - JPanel filterPanel = new JPanel(new GridBagLayout()); + /// A bold heading followed by a rule across the rest of the row, splitting the dialog into sections + protected static JComponent createSectionHeading(String text) { + JLabel label = new JLabel(text); + label.setFont(label.getFont().deriveFont(Font.BOLD, label.getFont().getSize2D() + 1f)); + + JPanel heading = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridy = 0; + gbc.anchor = GridBagConstraints.WEST; + heading.add(label, gbc); + + gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.weighty = 0; + gbc.insets = new Insets(0, 8, 0, 0); + heading.add(new JSeparator(), gbc); + return heading; + } - // Row 0, Col 0: Collection selector (50% width) - gbc.gridx = 0; - gbc.gridy = 0; - gbc.gridwidth = 1; - gbc.weightx = 0.5; - gbc.insets = new Insets(10, 0, 10, 10); - filterPanel.add(createCollectionSelectorPanel(), gbc); + protected JPanel createFilterPanel() { + JPanel filterPanel = new JPanel(); + filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS)); + + filterPanel.add(createFilterRow(createCollectionSelectorPanel(), createBinarySelectorPanel())); + filterPanel.add(Box.createVerticalStrut(12)); + filterPanel.add(createFilterRow( + createField("Minimum similarity", createThresholdPanel()), + createField("Debug symbols", createDebugSymbolsPanel()))); + filterPanel.add(Box.createVerticalStrut(12)); + filterPanel.add(createFilterRow( + createField("Platform & architecture", createPlatformArchitecturePanel()), + createUserSelectorPanel())); - // Row 0, Col 1: Binary selector (50% width) - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 0.5; - gbc.insets = new Insets(10, 0, 10, 0); - filterPanel.add(createBinarySelectorPanel(), gbc); + return filterPanel; + } - // Row 1, Col 0: Threshold panel (50% width) - gbc.gridx = 0; - gbc.gridy = 1; - gbc.weightx = 0.5; - gbc.insets = new Insets(0, 0, 0, 10); - filterPanel.add(createThresholdPanel(), gbc); + /// Two filters side by side in equal-width columns, top-aligned + private static JPanel createFilterRow(JComponent left, JComponent right) { + JPanel row = new JPanel(new GridLayout(1, 2, 24, 0)); + row.add(topAligned(left)); + row.add(topAligned(right)); + row.setAlignmentX(Component.LEFT_ALIGNMENT); + return row; + } - // Row 1, Col 1: Debug symbols toggle (50% width) - gbc.gridx = 1; - gbc.gridy = 1; - gbc.weightx = 0.5; - gbc.insets = new Insets(0, 0, 0, 0); - filterPanel.add(createDebugSymbolsPanel(), gbc); + private static JPanel topAligned(JComponent component) { + JPanel wrapper = new JPanel(new BorderLayout()); + wrapper.add(component, BorderLayout.NORTH); + return wrapper; + } - return filterPanel; + /// A bold caption above a filter's controls + protected static JPanel createField(String caption, JComponent control) { + JLabel label = new JLabel(caption); + label.setFont(label.getFont().deriveFont(Font.BOLD)); + + JPanel field = new JPanel(new BorderLayout(0, 4)); + field.add(label, BorderLayout.NORTH); + field.add(control, BorderLayout.CENTER); + return field; } - protected JPanel createButtonAndFilterPanel() { - // Match button panel - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); - JButton matchButton = new JButton("Match Functions"); + /// Status on the left; progress and the Match button right-aligned beneath the filters they apply + protected JPanel createMatchActionPanel() { + JPanel panel = new JPanel(new BorderLayout(12, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0)); + + statusLabel = new JLabel("Initializing..."); + panel.add(statusLabel, BorderLayout.CENTER); + + matchingProgressBar = new JProgressBar(); + matchingProgressBar.setPreferredSize(new Dimension(220, matchingProgressBar.getPreferredSize().height)); + matchingProgressBar.setVisible(false); + + matchButton = new JButton("Match Functions"); // Add magnifying glass icon to the button try { - Icon icon = ResourceManager.loadImage("images/magnifier.png"); - matchButton.setIcon(icon); + matchIcon = ResourceManager.loadImage("images/magnifier.png"); + matchButton.setIcon(matchIcon); } catch (Exception e) { // If icon loading fails, button will just show text without icon } matchButton.addActionListener(e -> onMatchButtonClicked()); - buttonPanel.add(matchButton); - - // Function filter panel - JPanel functionFilterPanel = createFunctionFilterPanel(); - - // Create a combined panel for button and function filter - JPanel buttonAndFilterPanel = new JPanel(new BorderLayout()); - buttonAndFilterPanel.add(buttonPanel, BorderLayout.NORTH); - buttonAndFilterPanel.add(functionFilterPanel, BorderLayout.CENTER); + // The button sets the row's height, so showing or hiding the bar beside it moves nothing + JPanel actions = new JPanel(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridy = 0; + gbc.insets = new Insets(0, 0, 0, 10); + actions.add(matchingProgressBar, gbc); + gbc.insets = new Insets(0, 0, 0, 0); + actions.add(matchButton, gbc); + panel.add(actions, BorderLayout.EAST); - return buttonAndFilterPanel; + return panel; } protected JPanel createResultsContainer() { @@ -606,8 +714,11 @@ protected JPanel createResultsContainer() { // Results table resultsTable = new JTable(); resultsTable.setAutoCreateRowSorter(true); + resultsTable.setFillsViewportHeight(true); + resultsTable.setRowHeight(resultsTable.getRowHeight() + 4); + resultsTable.setShowVerticalLines(false); resultsScrollPane = new JScrollPane(resultsTable); - resultsScrollPane.setBorder(BorderFactory.createTitledBorder("Function Matching Results")); + resultsScrollPane.setPreferredSize(new Dimension(0, 200)); // Add selection listener for assembly comparison resultsTable.getSelectionModel().addListSelectionListener(e -> { @@ -616,22 +727,47 @@ protected JPanel createResultsContainer() { } }); - // Create assembly comparison panel + // Consuming the right-click keeps the dialog's docking popup, with its tool-wide actions, from appearing + JMenuItem openInPortalItem = new JMenuItem("Open in Portal"); + openInPortalItem.addActionListener(e -> { + var analysisID = getSelectedMatchedAnalysisID(); + if (analysisID != null) { + revengService.openPortalFor(tool, analysisID); + } + }); + portalPopup.add(openInPortalItem); + resultsTable.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + showPortalPopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + showPortalPopup(e); + } + }); + + // Create assembly comparison panel; its two halves are titled, so it needs no box of its own here assemblyDiffPanel = new AssemblyDiffPanel(); + assemblyDiffPanel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); + // Its default 300px left the table only a few rows in a dialog of the default size + assemblyDiffPanel.setPreferredSize(new Dimension(0, 200)); - // Create vertical split pane with results table on top and assembly comparison below + // Create vertical split pane with results table on top and assembly comparison below, + // sized from their preferred heights and sharing any extra room JSplitPane mainSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); mainSplitPane.setTopComponent(resultsScrollPane); mainSplitPane.setBottomComponent(assemblyDiffPanel); - mainSplitPane.setResizeWeight(0.4); - mainSplitPane.setDividerLocation(250); + mainSplitPane.setResizeWeight(0.5); + mainSplitPane.setBorder(null); resultsContainer.add(mainSplitPane, BorderLayout.CENTER); - // Rename buttons panel - renameButtonsPanel = createRenameButtonsPanel(); - renameButtonsPanel.setVisible(false); - resultsContainer.add(renameButtonsPanel, BorderLayout.SOUTH); + // Transfer buttons panel + transferButtonsPanel = createTransferButtonsPanel(); + transferButtonsPanel.setVisible(false); + resultsContainer.add(transferButtonsPanel, BorderLayout.SOUTH); return resultsContainer; } @@ -656,41 +792,45 @@ protected void onTableSelectionChanged() { assemblyDiffPanel.showAssemblyFor(selectedMatch, revengService); } - protected JPanel createRenameButtonsPanel() { - JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); - - JButton renameAllButton = new JButton("Rename All"); - renameAllButton.addActionListener(e -> onRenameAllButtonClicked()); - panel.add(renameAllButton); + private void showPortalPopup(MouseEvent e) { + if (!e.isPopupTrigger()) { + return; + } + e.consume(); + int row = resultsTable.rowAtPoint(e.getPoint()); + if (row >= 0) { + resultsTable.setRowSelectionInterval(row, row); + portalPopup.getComponent(0).setEnabled(getSelectedMatchedAnalysisID() != null); + portalPopup.show(resultsTable, e.getX(), e.getY()); + } + } - JButton renameSelectedButton = new JButton("Rename Selected"); - renameSelectedButton.addActionListener(e -> onRenameSelectedButtonClicked()); - panel.add(renameSelectedButton); + private TypedApiInterface.AnalysisID getSelectedMatchedAnalysisID() { + var selected = getSelectedMatches(); + return selected.size() == 1 ? selected.get(0).functionMatch().nearest_neighbor_analysis_id() : null; + } + protected JPanel createTransferButtonsPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); + panel.add(createTransferButton("Transfer All", this::onTransferAll)); + panel.add(createTransferButton("Transfer Selected", this::onTransferSelected)); return panel; } - protected JPanel createProgressPanel() { - JPanel panel = new JPanel(new GridBagLayout()); - GridBagConstraints gbc = new GridBagConstraints(); - gbc.insets = new Insets(10, 10, 0, 10); - gbc.anchor = GridBagConstraints.WEST; - - // Progress bar - gbc.gridx = 0; - gbc.gridy = 0; - gbc.gridwidth = 2; - gbc.fill = GridBagConstraints.HORIZONTAL; - panel.add(taskMonitorComponent, gbc); - - // Status label - gbc.gridy = 1; - gbc.gridwidth = 1; - gbc.fill = GridBagConstraints.NONE; - statusLabel = new JLabel("Initializing..."); - panel.add(statusLabel, gbc); + /// A button that drops down the parts of a match that can be transferred, as the portal's + /// Transfer Symbol button does, and hands the chosen one to {@code onChosen} + protected static JButton createTransferButton(String text, Consumer onChosen) { + JPopupMenu menu = new JPopupMenu(); + for (ApplyMatchCmd.Transfer transfer : ApplyMatchCmd.Transfer.values()) { + JMenuItem item = new JMenuItem(transfer.label()); + item.addActionListener(e -> onChosen.accept(transfer)); + menu.add(item); + } - return panel; + JButton button = new JButton(text + " \u25BE"); + button.addActionListener(e -> menu.show(button, 0, button.getHeight())); + return button; } protected JPanel createCollectionSelectorPanel() { @@ -715,7 +855,6 @@ protected JPanel createBinarySelectorPanel() { protected JPanel createThresholdPanel() { JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Minimum similarity")); thresholdSlider = new JSlider(0, 100, 70); thresholdSlider.setMajorTickSpacing(25); @@ -723,8 +862,11 @@ protected JPanel createThresholdPanel() { thresholdSlider.setPaintTicks(true); thresholdSlider.setPaintLabels(true); - thresholdValueLabel = new JLabel("70%", SwingConstants.CENTER); + thresholdValueLabel = new JLabel("70%", SwingConstants.RIGHT); thresholdValueLabel.setFont(thresholdValueLabel.getFont().deriveFont(Font.BOLD, 14f)); + // Room for "100%" so the slider doesn't shift as the value changes + thresholdValueLabel.setPreferredSize(new Dimension(48, thresholdValueLabel.getPreferredSize().height)); + thresholdSlider.addChangeListener(e -> thresholdValueLabel.setText(thresholdSlider.getValue() + "%")); @@ -739,41 +881,83 @@ protected JPanel createThresholdPanel() { protected JPanel createDebugSymbolsPanel() { JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Debug symbols")); JPanel checkboxPanel = new JPanel(); checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.Y_AXIS)); - checkboxPanel.setPreferredSize(new Dimension(0, 52)); - checkboxPanel.setMinimumSize(new Dimension(0, 52)); debugSymbolsCheckBox = new JCheckBox("Only include functions with debug symbols", false); debugSymbolsCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); debugSymbolsCheckBox.addActionListener( - e -> userSubmittedDebugSymbolsCheckBox.setVisible(debugSymbolsCheckBox.isSelected())); + e -> userSubmittedDebugSymbolsCheckBox.setEnabled(debugSymbolsCheckBox.isSelected())); userSubmittedDebugSymbolsCheckBox = new JCheckBox("Include user submitted debug symbols", false); userSubmittedDebugSymbolsCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); - userSubmittedDebugSymbolsCheckBox.setVisible(false); + userSubmittedDebugSymbolsCheckBox.setEnabled(false); + // Indented under the box it depends on JPanel indentedPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); indentedPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + indentedPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); indentedPanel.add(userSubmittedDebugSymbolsCheckBox); checkboxPanel.add(debugSymbolsCheckBox); checkboxPanel.add(indentedPanel); - checkboxPanel.add(Box.createVerticalGlue()); panel.add(checkboxPanel, BorderLayout.CENTER); return panel; } + protected JPanel createPlatformArchitecturePanel() { + JPanel panel = new JPanel(new GridBagLayout()); + panel.setToolTipText("Leave unticked to match any platform or architecture"); + + platformCheckBoxes.put(MatchFilters.PlatformsEnum.LINUX, new JCheckBox("Linux")); + platformCheckBoxes.put(MatchFilters.PlatformsEnum.WINDOWS, new JCheckBox("Windows")); + platformCheckBoxes.put(MatchFilters.PlatformsEnum.ANDROID, new JCheckBox("Android")); + + architectureCheckBoxes.put(MatchFilters.ArchitecturesEnum.X86_64, new JCheckBox("x86 (64-bit)")); + architectureCheckBoxes.put(MatchFilters.ArchitecturesEnum.X86_32, new JCheckBox("x86 (32-bit)")); + architectureCheckBoxes.put(MatchFilters.ArchitecturesEnum.ARM_64, new JCheckBox("ARM (64-bit)")); + + GridBagConstraints gbc = new GridBagConstraints(); + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(0, 0, 0, 10); + + gbc.gridy = 0; + panel.add(new JLabel("Platforms:"), gbc); + for (JCheckBox checkBox : platformCheckBoxes.values()) { + panel.add(checkBox, gbc); + } + + gbc.gridy = 1; + panel.add(new JLabel("Architectures:"), gbc); + for (JCheckBox checkBox : architectureCheckBoxes.values()) { + panel.add(checkBox, gbc); + } + + // Keep the toggles left-aligned when the panel is wider than they are + gbc.gridy = 0; + gbc.weightx = 1; + panel.add(Box.createHorizontalGlue(), gbc); + + return panel; + } + + protected JPanel createUserSelectorPanel() { + userSelector = new UserSelectionPanel( + query -> revengService.searchUsersWithIds(query), + 3 + ); + + return userSelector; + } + protected JPanel createFunctionFilterPanel() { - JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Filter matches by function virtual address, name, hash or binary")); + JPanel panel = new JPanel(new BorderLayout(8, 0)); + panel.add(new JLabel("Filter:"), BorderLayout.WEST); - functionFilterField = new JTextField(); - functionFilterField.setPreferredSize(new Dimension(0, 30)); + functionFilterField = new HintTextField(getFunctionFilterHint()); functionFilterField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() { @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { @@ -793,9 +977,17 @@ public void changedUpdate(javax.swing.event.DocumentEvent e) { panel.add(functionFilterField, BorderLayout.CENTER); + resultsCountLabel = new JLabel("No matches yet"); + panel.add(resultsCountLabel, BorderLayout.EAST); + return panel; } + /// Placeholder for the results filter, naming the columns {@link #matchesFilter} searches + protected String getFunctionFilterHint() { + return "Matched function name, hash or binary"; + } + // Event handler methods protected void onCollectionSelectionChanged(Set selectedCollections) { Set collectionIds = selectedCollections.stream() @@ -849,6 +1041,52 @@ public boolean isUserSubmittedDebugSymbolsEnabled() { return userSubmittedDebugSymbolsCheckBox != null && userSubmittedDebugSymbolsCheckBox.isSelected(); } + public List getSelectedPlatforms() { + return platformCheckBoxes.entrySet().stream() + .filter(entry -> entry.getValue().isSelected()) + .map(Map.Entry::getKey) + .toList(); + } + + public List getSelectedArchitectures() { + return architectureCheckBoxes.entrySet().stream() + .filter(entry -> entry.getValue().isSelected()) + .map(Map.Entry::getKey) + .toList(); + } + + /// The filters sent with the matching request, from the current state of the filter panel + protected MatchFilters buildMatchFilters() { + var filters = new MatchFilters(); + filters.setCollectionIds(collectionSelector.getSelectedCollectionIds().stream() + .map(Integer::longValue).toList()); + filters.setBinaryIds(binarySelector.getSelectedBinaryIds().stream() + .map(Integer::longValue).toList()); + + if (isDebugSymbolsEnabled()) { + var debugTypes = new ArrayList(); + debugTypes.add("SYSTEM"); + if (isUserSubmittedDebugSymbolsEnabled()) { + debugTypes.add("USER"); + } + filters.setDebugTypes(debugTypes); + } + + var platforms = getSelectedPlatforms(); + if (!platforms.isEmpty()) { + filters.setPlatforms(platforms); + } + var architectures = getSelectedArchitectures(); + if (!architectures.isEmpty()) { + filters.setArchitectures(architectures); + } + var userIds = userSelector.getSelectedUserIds(); + if (!userIds.isEmpty()) { + filters.setUserIds(userIds.stream().map(Integer::longValue).toList()); + } + return filters; + } + protected void filterResults() { Set selectedCollectionIds = collectionSelector.getSelectedCollectionIds(); Set selectedBinaryIds = binarySelector.getSelectedBinaryIds(); @@ -869,19 +1107,29 @@ protected void filterResults() { " (IDs: " + selectedBinaryIds + "), threshold: " + threshold + ", debug symbols: " + includeDebugSymbols + - ", user submitted debug symbols: " + includeUserSubmittedDebugSymbols); + ", user submitted debug symbols: " + includeUserSubmittedDebugSymbols + + ", platforms: " + getSelectedPlatforms() + + ", architectures: " + getSelectedArchitectures() + + ", users: " + userSelector.getSelectedUserNames() + + " (IDs: " + userSelector.getSelectedUserIds() + ")"); - taskMonitorComponent.setVisible(true); startFunctionMatching(); } + /// Starts a match, or cancels the one in progress (the button reads Cancel while it runs) protected void onMatchButtonClicked() { + if (matchingThread != null) { + stopPolling(); + statusLabel.setText("Cancelled: press Match Functions to search again"); + return; + } filterResults(); } - protected void onRenameAllButtonClicked() { - renameInBackground(functionMatchResults); + protected void onTransferAll(ApplyMatchCmd.Transfer transfer) { + hideError(); + transferInBackground(functionMatchResults, transfer); } /// The results behind the currently selected table rows. @@ -901,49 +1149,49 @@ protected List getSelectedMatches() { return selectedMatches; } - protected void onRenameSelectedButtonClicked() { + protected void onTransferSelected(ApplyMatchCmd.Transfer transfer) { if (resultsTable.getSelectedRowCount() == 0) { - showError("Please select one or more rows to rename."); + showError("Please select one or more rows to transfer."); return; } hideError(); - renameInBackground(getSelectedMatches()); + transferInBackground(getSelectedMatches(), transfer); } - private void renameInBackground(List matches) { - var task = new Task("Applying Renames", true, false, false) { + private void transferInBackground(List matches, ApplyMatchCmd.Transfer transfer) { + var task = new Task("Transferring " + transfer.label(), true, false, false) { @Override public void run(TaskMonitor monitor) { - batchRenameFunctions(matches); - importFunctionNames(matches); + int applied = applyMatches(matches, transfer); + SwingUtilities.invokeLater(() -> statusLabel.setText("Transferred %s to %d of %d function(s)" + .formatted(transfer.label().toLowerCase(), applied, matches.size()))); } }; - TaskBuilder.withTask(task).launchInBackground(taskMonitorComponent); - } - - protected void batchRenameFunctions(List functionMatches) { - try { - revengService.batchRenamingGhidraMatchesWithSignatures(functionMatches); - } catch (Exception e) { - Msg.error(this, "Failed to rename functions: " + e.getMessage(), e); - SwingUtilities.invokeLater(() -> showError("Failed to rename functions: " + e.getMessage())); - } + // Shown in a task dialog: the dialog's progress bar belongs to matching, and is hidden by now + TaskBuilder.withTask(task).setParent(getComponent()).launchModal(); } - protected void importFunctionNames(List functionMatches) { + /// Applies the matches to the program and returns how many functions were changed. Matches can be + /// skipped, e.g. a signature transfer for a match the portal has no signature for, or a name + /// transfer to a function the analyst named. + protected int applyMatches(List functionMatches, ApplyMatchCmd.Transfer transfer) { var program = analyzedProgram.program(); + int[] applied = {0}; - program.withTransaction("Apply Function Matching Renames", () -> { + program.withTransaction("Apply Function Matching " + transfer.label(), () -> { for (GhidraFunctionMatchWithSignature match : functionMatches) { - // We don't pass a service, because we don't need to update individual functions on the portal - // batchRenameFunctions already does that for us - var cmd = new ApplyMatchCmd(null, analyzedProgram, match, false); - cmd.applyTo(program); + // We don't pass a service, because we don't need to update individual functions on the portal: + // LocalEditSyncService pushes the renames applied here, and only those, in one batch + var cmd = new ApplyMatchCmd(null, analyzedProgram, match, false, transfer); + if (cmd.applyTo(program)) { + applied[0]++; + } } } ); SwingUtilities.invokeLater(this::updateResultsTable); + return applied[0]; } @Override diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java index e0551ba3..396f5cfb 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/AssemblyDiffPanel.java @@ -8,13 +8,17 @@ import com.github.difflib.patch.AbstractDelta; import com.github.difflib.patch.DeltaType; import com.github.difflib.patch.Patch; +import generic.theme.GColor; +import generic.theme.Gui; import ghidra.util.Msg; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; +import org.fife.ui.rsyntaxtextarea.Theme; import org.fife.ui.rtextarea.RTextScrollPane; import javax.swing.*; import java.awt.*; +import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -25,10 +29,10 @@ public class AssemblyDiffPanel extends JPanel { private static final String PLACEHOLDER_TEXT = "Select a row to view assembly comparison"; // Diff highlighting colors - private static final Color DIFF_COLOR_CHANGED = new Color(255, 255, 180); // Light yellow - private static final Color DIFF_COLOR_DELETED = new Color(255, 200, 200); // Light red - private static final Color DIFF_COLOR_INSERTED = new Color(200, 255, 200); // Light green - private static final Color DIFF_COLOR_PLACEHOLDER = new Color(240, 240, 240); // Light gray + private static final Color DIFF_COLOR_CHANGED = new GColor("color.bg.reveng.diff.changed"); + private static final Color DIFF_COLOR_DELETED = new GColor("color.bg.reveng.diff.deleted"); + private static final Color DIFF_COLOR_INSERTED = new GColor("color.bg.reveng.diff.inserted"); + private static final Color DIFF_COLOR_PLACEHOLDER = new GColor("color.bg.reveng.diff.placeholder"); private final RSyntaxTextArea localAssemblyTextArea; private final RSyntaxTextArea matchedAssemblyTextArea; @@ -76,6 +80,14 @@ private RSyntaxTextArea createAssemblyTextArea() { textArea.setEditable(false); textArea.setLineWrap(false); textArea.setHighlightCurrentLine(false); + if (Gui.isDarkTheme()) { + try (var in = RSyntaxTextArea.class.getResourceAsStream("themes/dark.xml")) { + Theme.load(in).apply(textArea); + } catch (IOException e) { + Msg.warn(this, "Failed to load dark editor theme", e); + } + } + textArea.setFont(Gui.getFont("font.monospaced")); textArea.setText(PLACEHOLDER_TEXT); return textArea; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java index 9c7a2f94..40c24e31 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/BinaryLevelFunctionMatchingDialog.java @@ -6,16 +6,17 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; import ghidra.framework.plugintool.PluginTool; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; +import generic.theme.Gui; import javax.swing.*; import java.awt.*; -import java.util.ArrayList; public class BinaryLevelFunctionMatchingDialog extends AbstractFunctionMatchingDialog { - public BinaryLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID) { + public BinaryLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID, + AnalysisBasicInfoOutputBody analysisBasicInfo) { super(ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", true, - tool.getService(GhidraRevengService.class), programWithBinaryID); + tool, programWithBinaryID, analysisBasicInfo); } @Override @@ -46,24 +47,6 @@ protected java.util.List fetchMatches() throws ApiExcepti return flattenMatches(revengService.getAnalysisFunctionMatches(analyzedProgram.analysisID()).getMatches()); } - private MatchFilters buildMatchFilters() { - var filters = new MatchFilters(); - filters.setCollectionIds(collectionSelector.getSelectedCollectionIds().stream() - .map(Integer::longValue).toList()); - filters.setBinaryIds(binarySelector.getSelectedBinaryIds().stream() - .map(Integer::longValue).toList()); - - if (isDebugSymbolsEnabled()) { - var debugTypes = new ArrayList(); - debugTypes.add("SYSTEM"); - if (isUserSubmittedDebugSymbolsEnabled()) { - debugTypes.add("USER"); - } - filters.setDebugTypes(debugTypes); - } - return filters; - } - @Override protected String[] getTableColumnNames() { return new String[]{"Virtual Address", "Function Name", "Matched Function", "Similarity", "Confidence", "Matched Hash", "Matched Binary"}; @@ -82,11 +65,6 @@ protected Object[] getTableRowData(GhidraFunctionMatchWithSignature result) { }; } - @Override - protected String getTableTitle() { - return "Function matching results"; - } - @Override protected int getTableSelectionMode() { return ListSelectionModel.MULTIPLE_INTERVAL_SELECTION; @@ -101,7 +79,7 @@ protected void configureTableColumns() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - c.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + c.setFont(Gui.getFont("font.monospaced")); return c; } }); @@ -141,6 +119,11 @@ protected String getDialogDescription() { return "Match functions in this binary against previously seen samples"; } + @Override + protected String getFunctionFilterHint() { + return "Virtual address, function name, matched function name, hash or binary"; + } + @Override protected boolean matchesFilter(GhidraFunctionMatchWithSignature result) { String filterText = functionFilterField.getText().trim().toLowerCase(); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java index 9cb72692..aa51f656 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/FunctionLevelFunctionMatchingDialog.java @@ -10,20 +10,25 @@ import javax.swing.*; import java.awt.*; -import java.util.ArrayList; import java.util.List; public class FunctionLevelFunctionMatchingDialog extends AbstractFunctionMatchingDialog { private final Function function; - public FunctionLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID, Function function) { + public FunctionLevelFunctionMatchingDialog(PluginTool tool, GhidraRevengService.AnalysedProgram programWithBinaryID, + AnalysisBasicInfoOutputBody analysisBasicInfo, Function function) { super(ReaiPluginPackage.WINDOW_PREFIX + "Function Matching", true, - tool.getService(GhidraRevengService.class), programWithBinaryID); + tool, programWithBinaryID, analysisBasicInfo); this.function = function; } private List matchingFunctionIds; + @Override + protected void dialogShown() { + filterResults(); + } + @Override protected MatchingProgress startMatching() throws ApiException { var functionIDOpt = analyzedProgram.getIDForFunction(function); @@ -35,7 +40,7 @@ protected MatchingProgress startMatching() throws ApiException { var request = new StartMatchingForFunctionsInputBody(); request.setFunctionIds(matchingFunctionIds); request.setMinSimilarity((double) getThreshold()); - request.setResultsPerFunction(25L); + request.setResultsPerFunction(5L); request.setFilters(buildMatchFilters()); var response = revengService.startFunctionsMatching(request); @@ -59,24 +64,6 @@ protected List fetchMatches() throws ApiException { return flattenMatches(revengService.getFunctionsMatches(matchingFunctionIds).getMatches()); } - private MatchFilters buildMatchFilters() { - var filters = new MatchFilters(); - filters.setCollectionIds(collectionSelector.getSelectedCollectionIds().stream() - .map(Integer::longValue).toList()); - filters.setBinaryIds(binarySelector.getSelectedBinaryIds().stream() - .map(Integer::longValue).toList()); - - if (isDebugSymbolsEnabled()) { - var debugTypes = new ArrayList(); - debugTypes.add("SYSTEM"); - if (isUserSubmittedDebugSymbolsEnabled()) { - debugTypes.add("USER"); - } - filters.setDebugTypes(debugTypes); - } - return filters; - } - @Override protected String[] getTableColumnNames() { return new String[]{"Matched Function", "Similarity", "Confidence", "Matched Hash", "Matched Binary"}; @@ -93,11 +80,6 @@ protected Object[] getTableRowData(GhidraFunctionMatchWithSignature result) { }; } - @Override - protected String getTableTitle() { - return "Function Matching Results"; - } - @Override protected int getTableSelectionMode() { return ListSelectionModel.SINGLE_SELECTION; @@ -145,14 +127,13 @@ protected boolean matchesFilter(GhidraFunctionMatchWithSignature result) { } @Override - protected JPanel createRenameButtonsPanel() { - JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); + protected JPanel createTransferButtonsPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0)); - // Only show "Rename Selected" button for function-level matching + // Only offer the selected match for function-level matching, // since we're only matching a single function - JButton renameSelectedButton = new JButton("Rename Selected"); - renameSelectedButton.addActionListener(e -> onRenameSelectedButtonClicked()); - panel.add(renameSelectedButton); + panel.add(createTransferButton("Transfer Symbol", this::onTransferSelected)); return panel; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java index ec9a6f18..6e5a0bdd 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/functionmatching/SimilarFunctionsWindow.java @@ -4,6 +4,7 @@ import ai.reveng.model.GetMatchesStatusOutputBody; import ai.reveng.model.StartMatchingForFunctionsInputBody; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatch; @@ -37,6 +38,7 @@ import javax.swing.event.ListSelectionEvent; import java.awt.*; import java.math.BigDecimal; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -437,6 +439,11 @@ public boolean isCellEditable(int row, int column) { * Task to fetch similar functions from the API */ private class FetchSimilarFunctionsTask extends Task { + // Matching one function is quick: poll every half second, slowing to every 5 while nothing changes, for at most 5 minutes + private static final Duration POLL_INTERVAL = Duration.ofMillis(500); + private static final Duration MAX_POLL_INTERVAL = Duration.ofSeconds(5); + private static final Duration MAX_MATCHING_WAIT = Duration.ofMinutes(5); + private final GhidraRevengService.AnalysedProgram program; private final GhidraRevengService.FunctionWithID functionWithID; @@ -461,21 +468,27 @@ public void run(TaskMonitor monitor) { monitor.setMessage("Fetching matches from RevEng.AI..."); service.startFunctionsMatching(request); - while (true) { - if (monitor.isCancelled()) { + var polled = new StatusPoller(POLL_INTERVAL, MAX_POLL_INTERVAL, MAX_MATCHING_WAIT).poll( + () -> service.getFunctionsMatchingStatus(functionIds), + statusResponse -> AbstractFunctionMatchingDialog.classifyMatchingStatus( + statusResponse.getStatus() == null ? null : statusResponse.getStatus().getValue()), + monitor::isCancelled); + switch (polled.ending()) { + case CANCELLED -> { return; } - GetMatchesStatusOutputBody statusResponse = service.getFunctionsMatchingStatus(functionIds); - String status = statusResponse.getStatus() == null ? null : statusResponse.getStatus().getValue(); - if ("COMPLETED".equals(status)) { - break; - } - if ("FAILED".equals(status)) { - String errorMsg = AbstractFunctionMatchingDialog.errorTextFrom(statusResponse.getMessages()); - throw new RuntimeException(errorMsg == null || errorMsg.isEmpty() - ? "Function matching failed" : errorMsg); + case UNRECOGNISED -> throw new RuntimeException( + "function matching reported a status this plugin does not recognise (it may have been cancelled)"); + case TIMED_OUT -> throw new RuntimeException("function matching has not finished after %s" + .formatted(StatusPoller.describe(polled.waited()))); + case DONE -> { + var statusResponse = polled.status(); + if (statusResponse.getStatus() == GetMatchesStatusOutputBody.StatusEnum.FAILED) { + String errorMsg = AbstractFunctionMatchingDialog.errorTextFrom(statusResponse.getMessages()); + throw new RuntimeException(errorMsg == null || errorMsg.isEmpty() + ? "Function matching failed" : errorMsg); + } } - Thread.sleep(100); } GetMatchesOutputBody response = service.getFunctionsMatches(functionIds); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java index 6770829d..f12f5083 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/help/HelpDialog.java @@ -4,6 +4,7 @@ import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import docking.widgets.label.GLabel; import ghidra.framework.plugintool.PluginTool; +import generic.theme.GThemeDefaults.Colors.Messages; import javax.swing.*; @@ -248,7 +249,7 @@ private JPanel createMenuItem(String name, String description, Integer leftPaddi JLabel descLabel = new JLabel(htmlDescription); descLabel.setFont(descLabel.getFont().deriveFont(Font.ITALIC)); - descLabel.setForeground(Color.GRAY); + descLabel.setForeground(Messages.HINT); descLabel.setAlignmentX(Component.LEFT_ALIGNMENT); descLabel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); @@ -266,7 +267,7 @@ private JLabel createDescription(String text, Integer leftPadding) { JLabel label = new JLabel(htmlText); label.setFont(label.getFont().deriveFont(Font.ITALIC)); - label.setForeground(Color.GRAY); + label.setForeground(Messages.HINT); label.setAlignmentX(Component.LEFT_ALIGNMENT); label.setBorder(BorderFactory.createEmptyBorder(0, paddingLeft, 5, 0)); return label; diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java index 6ed88e1b..c1df2822 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/misc/AnalysisLogComponent.java @@ -4,14 +4,19 @@ import ai.reveng.toolkit.ghidra.core.AnalysisLogConsumer; import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; import ghidra.framework.plugintool.ComponentProviderAdapter; import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Program; +import ghidra.util.Swing; import ghidra.util.exception.CancelledException; import ghidra.util.task.Task; import ghidra.util.task.TaskBuilder; import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitorComponent; +import ghidra.util.task.WrappingTaskMonitor; import javax.swing.*; @@ -24,8 +29,12 @@ public class AnalysisLogComponent extends ComponentProviderAdapter implements An private final JScrollPane scroll; private TaskMonitorComponent taskMonitorComponent; private final JPanel mainPanel; - private final Map trackedPrograms = new ConcurrentHashMap<>(); + /// The task waiting for each program's analysis. At most one per program: a new analysis replaces the + /// wait for an earlier one, which the program is no longer attached to. + private final Map trackedPrograms = new ConcurrentHashMap<>(); private final Map storedLogs = new ConcurrentHashMap<>(); + /// How the program's analysis ended, shown below its logs; absent while it runs or when unknown + private final Map terminalStatusLines = new ConcurrentHashMap<>(); public static String NAME = ReaiPluginPackage.WINDOW_PREFIX + "Analysis Log"; private Program activeProgram; @@ -41,6 +50,10 @@ public AnalysisLogComponent(PluginTool tool) { taskMonitorComponent = new TaskMonitorComponent(false, true); taskMonitorComponent.setIndeterminate(true); taskMonitorComponent.setVisible(false); + // Each wait keeps the cancel to itself, so the shared component can be reset for the next wait without + // resuming one the user cancelled + taskMonitorComponent.addCancelledListener( + () -> trackedPrograms.values().forEach(AnalysisMonitoringTask::stop)); scroll = new JScrollPane(textArea); @@ -71,13 +84,22 @@ public TaskMonitor getTaskMonitor() { public void programActivated(Program program) { // Switch the active log to the given program this.activeProgram = program; - if (trackedPrograms.containsKey(program)) { + if (program != null && trackedPrograms.containsKey(program)) { // If we are tracking this program, show the task monitor taskMonitorComponent.setVisible(true); } else { taskMonitorComponent.setVisible(false); } - setLogs(storedLogs.getOrDefault(program, "No analysis logs available for the active program.")); + setLogs(displayText(program)); + } + + /// The logs last received for the program, or null when none were + public String getStoredLogs(Program program) { + return storedLogs.get(program); + } + + private String displayText(Program program) { + return withTerminalStatus(storedLogs.get(program), terminalStatusLines.get(program)); } public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { @@ -90,35 +112,181 @@ public void processEvent(RevEngAIAnalysisStatusChangedEvent event) { this.setVisible(true); switch (event.getStatus()) { - case Complete, Error -> {} + case Complete, Error -> { + // The wait has ended; say how, so the panel does not look like it is still waiting + terminalStatusLines.put(event.getProgram(), + terminalStatusLine(event.getStatus(), event.getProgramWithBinaryID().analysisID().id())); + refreshIfActive(event.getProgram()); + } + // Unknown: the wait for it has already ended, so starting another would end at once and loop + case Unknown -> {} default -> { - if (!trackedPrograms.containsKey(event.getProgram())){ - // We aren't tracking this program yet, so we start a new task for it - var task = new AnalysisMonitoringTask(event.getProgramWithBinaryID(), this); - var builder = TaskBuilder.withTask(task); - trackedPrograms.put(event.getProgram(), task); - builder.launchInBackground(getTaskMonitor()); + if (event.isFromWait()) { + // Progress from a wait, which is tracked already, or has ended since it reported this: starting + // another here would resume a wait the user cancelled + return; + } + // A new or resumed analysis: an earlier ending no longer applies + if (terminalStatusLines.remove(event.getProgram()) != null) { + refreshIfActive(event.getProgram()); + } + var tracked = trackedPrograms.get(event.getProgram()); + if (tracked != null && tracked.program.equals(event.getProgramWithBinaryID())) { + // Already waiting for this analysis + return; + } + if (tracked != null) { + // Waiting for an analysis the program has since been detached from + tracked.stop(); } + if (taskMonitorComponent.isCancelled()) { + // Left over from a Cancel press; the waits it cancelled have already been stopped + taskMonitorComponent.clearCancelled(); + } + var task = new AnalysisMonitoringTask(event.getProgramWithBinaryID(), this); + trackedPrograms.put(event.getProgram(), task); + TaskBuilder.withTask(task).launchInBackground(task.waitMonitor); } } } + /// Stop waiting for the program's analysis, e.g. because the program was detached from it. The wait ends + /// without firing any further status events for it. + public void stopMonitoring(Program program) { + var task = trackedPrograms.remove(program); + if (task != null) { + task.stop(); + } + updateMonitorVisibility(); + } + + /// Forget everything about a program that was closed, and stop waiting for its analysis + public void programClosed(Program program) { + stopMonitoring(program); + storedLogs.remove(program); + terminalStatusLines.remove(program); + if (activeProgram == program) { + activeProgram = null; + } + } + + private void updateMonitorVisibility() { + // Also called from the background thread of a wait that has ended + Swing.runIfSwingOrRunLater(() -> { + var active = activeProgram; + var show = active != null && trackedPrograms.containsKey(active); + if (!show && trackedPrograms.isEmpty()) { + // Nothing uses the shared monitor any more, so a Cancel pressed on it must not cancel the next wait + taskMonitorComponent.clearCancelled(); + } + taskMonitorComponent.setVisible(show); + }); + } + @Override public void consumeLogs(String logs, GhidraRevengService.ProgramWithID programWithID) { + if (programWithID.program().isClosed()) { + // Arrived after programClosed, and would keep the closed program in the map + return; + } storedLogs.put(programWithID.program(), logs); // If this is the currently active program, update the log display - if (activeProgram == programWithID.program()) { - setLogs(logs); + refreshIfActive(programWithID.program()); + } + + private void refreshIfActive(Program program) { + if (activeProgram == program) { + setLogs(displayText(program)); } } + /// The line that ends the log of an analysis that has finished, or null for a status that is not final + public static String terminalStatusLine(AnalysisStatus status, int analysisId) { + return switch (status) { + case Complete -> "RevEng.AI: analysis %d completed.".formatted(analysisId); + case Error -> ("RevEng.AI: analysis %d failed on the server. Use %s > Analysis > Detach, then create a " + + "new analysis or attach to an existing one.").formatted(analysisId, ReaiPluginPackage.MENU_GROUP_NAME); + default -> null; + }; + } + + /// The text the panel shows: the logs, followed by how the analysis ended when it has + public static String withTerminalStatus(String logs, String statusLine) { + boolean noLogs = logs == null || logs.isBlank(); + if (statusLine == null) { + return noLogs ? NO_LOGS : logs; + } + return noLogs ? statusLine : logs.stripTrailing() + "\n\n" + statusLine; + } + + public static final String NO_LOGS = "No analysis logs available for the active program."; + + + /// What to tell the user when the wait for an analysis ended without it finishing, or null when + /// there is nothing to tell (it finished, or the user cancelled the wait). + public static String unfinishedWaitMessage(StatusPoller.Result result, + GhidraRevengService.ProgramWithID program) { + return switch (result.ending()) { + case UNRECOGNISED -> ("RevEng.AI: analysis %d of %s reports a status this plugin does not recognise; " + + "stopped waiting for it. Reopen the program to check it again, or use View in portal.") + .formatted(program.analysisID().id(), program.program().getName()); + case TIMED_OUT -> ("RevEng.AI: analysis %d of %s has not finished after %s (status: %s); stopped waiting. " + + "It keeps running on the server: reopen the program to resume waiting, or use View in portal.") + .formatted(program.analysisID().id(), program.program().getName(), + StatusPoller.describe(result.waited()), result.status()); + case DONE, CANCELLED -> null; + }; + } + + /// Shows its progress on the shared monitor component, and is cancelled either by the Cancel button there + /// (which cancels every wait shown on it) or on its own, without cancelling the shared component. + private static class StoppableMonitor extends WrappingTaskMonitor { + private volatile boolean stopped; + + StoppableMonitor(TaskMonitor display) { + super(display); + } + + @Override + public boolean isCancelled() { + return stopped || super.isCancelled(); + } + + @Override + public void checkCancelled() throws CancelledException { + if (isCancelled()) { + throw new CancelledException(); + } + } + + @Override + public void setMessage(String message) { + // A stopped wait may still report its analysis' last log line, which would replace the message of the + // wait that is now shown + if (!stopped) { + super.setMessage(message); + } + } + + @Override + public void cancel() { + stopped = true; + } + + // Only the non-deprecated spellings: Ghidra 12.2 removed checkCanceled and clearCanceled + @Override + public void clearCancelled() { + stopped = false; + } + } class AnalysisMonitoringTask extends Task { private final GhidraRevengService.ProgramWithID program; private final AnalysisLogConsumer logConsumer; + private final StoppableMonitor waitMonitor = new StoppableMonitor(getTaskMonitor()); public AnalysisMonitoringTask(GhidraRevengService.ProgramWithID programWithID, AnalysisLogConsumer logConsumer) { super(programWithID.toString(), true, false, false); @@ -126,16 +294,34 @@ public AnalysisMonitoringTask(GhidraRevengService.ProgramWithID programWithID, A this.logConsumer = logConsumer; } + void stop() { + waitMonitor.cancel(); + } + @Override public void run(TaskMonitor monitor) throws CancelledException { // Wait for the analysis var service = tool.getService(GhidraRevengService.class); - service.waitForFinishedAnalysis(monitor, program, this.logConsumer, tool); - /// waitForFinishedAnalysis has already sent the completion event to all plugins - /// so this task just needs to clean up the tracked programs map - // Remove ourselves from the tracked programs when done - trackedPrograms.remove(program.program()); - taskMonitorComponent.setVisible(false); + // Logs fetched just before the wait was stopped belong to an analysis the program has left + AnalysisLogConsumer logs = (text, programWithID) -> { + if (!waitMonitor.isCancelled()) { + logConsumer.consumeLogs(text, programWithID); + } + }; + try { + var result = service.waitForAnalysis(monitor, program, logs, tool); + var message = unfinishedWaitMessage(result, program); + if (message != null) { + tool.getService(ReaiLoggingService.class).warn(message); + SwingUtilities.invokeLater(() -> tool.setStatusInfo(message, true)); + } + } finally { + /// waitForFinishedAnalysis has already sent the completion event to all plugins + /// so this task just needs to clean up the tracked programs map + // Remove ourselves from the tracked programs when done, and only our own entry: a newer analysis of the same program may have replaced it + trackedPrograms.remove(program.program(), this); + updateMonitorVisibility(); + } } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java index 0696a885..5e4bc850 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/binarysimilarity/ui/recentanalyses/RecentAnalysisDialog.java @@ -31,6 +31,7 @@ public class RecentAnalysisDialog extends RevEngDialogComponentProvider { private final PluginTool tool; private final Program program; private final GhidraRevengService ghidraRevengService; + private final JPopupMenu portalPopup = new JPopupMenu(); public RecentAnalysisDialog(PluginTool tool, Program program) { super(ReaiPluginPackage.WINDOW_PREFIX + "Recent Analyses", true); @@ -53,34 +54,33 @@ private void buildInterface() { JPanel titlePanel = createTitlePanel("Find existing analyses for this binary"); mainPanel.add(titlePanel, BorderLayout.NORTH); - // Create the table content - // Add mouse listener to handle clicks on the Analysis ID column + // Consuming the right-click keeps the dialog's docking popup, with its tool-wide actions, from appearing + JMenuItem openInPortalItem = new JMenuItem("Open in Portal"); + openInPortalItem.addActionListener(e -> { + var selected = recentAnalysesTable.getSelectedRowObject(); + if (selected != null) { + ghidraRevengService.openPortalFor(tool, + new TypedApiInterface.AnalysisID(Math.toIntExact(selected.getAnalysisId()))); + } + }); + portalPopup.add(openInPortalItem); recentAnalysesTable.getTable().addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + showPortalPopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + showPortalPopup(e); + } + @Override public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 1) { - int row = recentAnalysesTable.getTable().rowAtPoint(e.getPoint()); - int col = recentAnalysesTable.getTable().columnAtPoint(e.getPoint()); - - if (row >= 0 && col >= 0) { - // Check if clicked column is "Analysis ID" (column 0) - String columnName = recentAnalysesTable.getTable().getColumnName(col); - if ("Analysis ID".equals(columnName)) { - AnalysisRecordBody result = recentAnalysesTable.getModel().getRowObject(row); - if (result != null) { - var analysisID = new TypedApiInterface.AnalysisID(Math.toIntExact(result.getAnalysisId())); - tool.execute(new Task("Open analysis in portal", false, false, false) { - @Override - public void run(TaskMonitor monitor) { - try { - ghidraRevengService.openPortalFor(tool, analysisID); - } catch (Exception ex) { - Msg.error(RecentAnalysisDialog.this, "Failed to open analysis in portal: " + ex.getMessage(), ex); - } - } - }, 0); - } - } + if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) { + var selected = recentAnalysesTable.getSelectedRowObject(); + if (selected != null) { + pickAnalysis(selected); } } } @@ -90,10 +90,9 @@ public void run(TaskMonitor monitor) { JButton pickMostRecentButton = new JButton("Pick most recent"); pickMostRecentButton.setName("Pick most recent"); pickMostRecentButton.addActionListener(e -> { - var mostRecent = recentAnalysesTable.getModel().getModelData().stream().max( + recentAnalysesTable.getModel().getModelData().stream().max( Comparator.comparing(AnalysisRecordBody::getCreation) - ).orElseThrow(); - pickAnalysis(mostRecent); + ).ifPresent(this::pickAnalysis); }); addButton(pickMostRecentButton); @@ -101,6 +100,9 @@ public void run(TaskMonitor monitor) { pickSelectedButton.setName("Pick selected"); pickSelectedButton.addActionListener(e -> { var selectedRowObject = recentAnalysesTable.getSelectedRowObject(); + if (selectedRowObject == null) { + return; + } pickAnalysis(selectedRowObject); }); addButton(pickSelectedButton); @@ -108,6 +110,19 @@ public void run(TaskMonitor monitor) { addWorkPanel(mainPanel); } + private void showPortalPopup(MouseEvent e) { + if (!e.isPopupTrigger()) { + return; + } + e.consume(); + JTable table = recentAnalysesTable.getTable(); + int row = table.rowAtPoint(e.getPoint()); + if (row >= 0) { + table.setRowSelectionInterval(row, row); + portalPopup.show(table, e.getX(), e.getY()); + } + } + private void pickAnalysis(AnalysisRecordBody result) { var service = tool.getService(GhidraRevengService.class); tool.execute(new Task("Attach to analysis", true, false, false) { diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java index 854441ea..1167ec02 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/service/ConversationsApiChatService.java @@ -3,7 +3,6 @@ import ai.reveng.api.ConversationsApi; import ai.reveng.invoker.ApiClient; import ai.reveng.invoker.ApiException; -import ai.reveng.invoker.Configuration; import ai.reveng.invoker.auth.ApiKeyAuth; import ai.reveng.model.ConfirmToolInputBody; import ai.reveng.model.Conversation; @@ -16,6 +15,7 @@ import ai.reveng.toolkit.ghidra.chat.model.Conversations.ConversationSummary; import ai.reveng.toolkit.ghidra.chat.model.Conversations.StoredEvent; import ai.reveng.toolkit.ghidra.chat.model.Conversations.UserMessageReplay; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiImplementation; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; @@ -28,12 +28,14 @@ import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; import java.util.function.Consumer; +import java.util.function.Supplier; /** - * {@link ChatService} backed by the SDK's {@link ConversationsApi}. Short requests reuse the shared, - * already-authenticated {@link Configuration#getDefaultApiClient() default client}; the SSE stream - * uses a dedicated client cloned from it with a long read timeout, since the default 15s read timeout - * would cut a live agent run short. + * {@link ChatService} backed by the SDK's {@link ConversationsApi}. Short requests reuse the + * already-authenticated client of the running {@code GhidraRevengService}; the SSE stream uses a + * dedicated client cloned from it with a long read timeout, since the default 15s read timeout would + * cut a live agent run short. The client is looked up per call, so re-running the setup wizard + * re-targets chat along with everything else. */ public class ConversationsApiChatService implements ChatService { @@ -43,13 +45,19 @@ public class ConversationsApiChatService implements ChatService { private volatile okhttp3.Call activeStreamCall; + private final Supplier client; + + public ConversationsApiChatService(Supplier client) { + this.client = client; + } + private ConversationsApi shortCallApi() { - return new ConversationsApi(Configuration.getDefaultApiClient()); + return new ConversationsApi(client.get()); } /// A conversations client whose HTTP read timeout is long enough to hold a live SSE stream open. private ConversationsApi streamingApi() { - ApiClient shared = Configuration.getDefaultApiClient(); + ApiClient shared = client.get(); ApiClient streamClient = new ApiClient(); streamClient.setBasePath(shared.getBasePath()); streamClient.setHttpClient(shared.getHttpClient().newBuilder() @@ -261,7 +269,8 @@ private static Map executeForJsonMap(okhttp3.Call call, String w okhttp3.ResponseBody responseBody = response.body(); String text = responseBody == null ? "" : responseBody.string(); if (!response.isSuccessful()) { - throw new ApiException(response.code(), "Failed to %s: HTTP %d".formatted(what, response.code())); + throw new ApiException("Failed to %s: HTTP %d".formatted(what, response.code()), + response.code(), response.headers().toMultimap(), text); } Object parsed = GSON.fromJson(text, Map.class); if (!(parsed instanceof Map)) { @@ -283,10 +292,7 @@ private static String eventId(Map ev) { } private static ChatServiceException apiError(String action, ApiException e) { - String detail = e.getResponseBody(); - if (detail == null || detail.isBlank()) { - detail = e.getMessage(); - } - return new ChatServiceException("Failed to %s: %s".formatted(action, detail), e); + return new ChatServiceException( + "Failed to %s: %s".formatted(action, TypedApiImplementation.describeApiException(e)), e); } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java index 74761531..fdd18366 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/AgentChatWindow.java @@ -10,6 +10,7 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.plugins.ReaiPluginPackage; import ghidra.app.services.GoToService; import ghidra.app.services.ProgramManager; @@ -20,11 +21,11 @@ import ghidra.program.model.listing.Program; import ghidra.program.model.symbol.SourceType; import ghidra.program.util.ProgramLocation; -import ghidra.util.BrowserLoader; import ghidra.util.exception.DuplicateNameException; import ghidra.util.exception.InvalidInputException; import ghidra.util.task.Task; import ghidra.util.task.TaskMonitor; +import generic.theme.GThemeDefaults.Colors.Messages; import javax.swing.*; import javax.swing.text.AttributeSet; @@ -105,7 +106,7 @@ private JComponent buildComponent() { top.add(header, BorderLayout.NORTH); contextLabel = new JLabel("No analysis attached"); - contextLabel.setForeground(Color.GRAY); + contextLabel.setForeground(Messages.HINT); top.add(contextLabel, BorderLayout.CENTER); historyModel = new DefaultListModel<>(); @@ -311,7 +312,7 @@ private void onLinkActivated(String href) { // A link from the agent's markdown (e.g. a portal or docs URL) — open it in the browser. if (href.startsWith("http://") || href.startsWith("https://")) { try { - BrowserLoader.display(URI.create(href).toURL(), null, tool); + WebBrowser.open(URI.create(href)); } catch (Exception e) { loggingService().warn("Failed to open link " + href + ": " + e.getMessage()); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java index 58a64533..165601ed 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/chat/ui/ChatController.java @@ -113,7 +113,7 @@ public void loadConversation(String conversationUuid) { lastEventId = null; setState(withTitle); }); - } catch (ChatServiceException e) { + } catch (ChatServiceException | RuntimeException e) { log.warn("Failed to load conversation: " + e.getMessage()); } }); @@ -245,7 +245,7 @@ public void run() { } service.stream(id, resumeFromEventId, stopped::get, event -> runOnUi(() -> onStreamEvent(event))); - } catch (ChatServiceException e) { + } catch (ChatServiceException | RuntimeException e) { if (!stopped.get()) { runOnUi(() -> setState(ChatReducer.reduce(state, new ApiError(e.getMessage())))); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java index 795244f0..581d93ea 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/RevEngAIAnalysisStatusChangedEvent.java @@ -3,7 +3,9 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ghidra.framework.plugintool.PluginEvent; +import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.listing.Program; +import ghidra.util.Swing; /** * Event that is fired when a RevEng.AI analysis result with some program changes. @@ -19,6 +21,9 @@ * (e.g. function info). Use {@link ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisResultsLoaded} for that. */ public class RevEngAIAnalysisStatusChangedEvent extends PluginEvent { + /// The source of the statuses a running wait reports, see {@link #isFromWait()} + public static final String WAIT_SOURCE = "RevEng.AI analysis wait"; + private final AnalysisStatus status; private final GhidraRevengService.ProgramWithID programWithID; @@ -31,6 +36,20 @@ public RevEngAIAnalysisStatusChangedEvent(String sourceName, GhidraRevengService this.programWithID = programWithID; } + /// Fires the event on the Swing thread, after the event being delivered there (if any) has finished. Ghidra + /// drops an event fired while another of the same type is being delivered, taking it for an event loop, so a + /// status reported from a background thread at that moment was lost: e.g. a wait's Error or Complete arriving + /// while the Queued event that started the wait was still being delivered. + public void fireLater(PluginTool tool) { + Swing.runLater(() -> tool.firePluginEvent(this)); + } + + /// Whether a running wait reported this status. Such a status is delivered later than it was seen (see + /// {@link #fireLater}), so the wait may already have ended, e.g. because it was cancelled. + public boolean isFromWait() { + return WAIT_SOURCE.equals(getSourceName()); + } + public AnalysisStatus getStatus() { return status; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java index a9e265cb..8d7b368a 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisDataTypesService.java @@ -162,7 +162,25 @@ public Optional get(AnalysisID analysisID, long dataTypeId) { /// Where a type was filed under a different namespace than its category path implies — see /// {@link #storageKey} — that key is present too, pointing at the same id. public Map ensure(AnalysisID analysisID, Collection roots) throws ApiException { - List closure = GhidraDataTypeEncoder.closure(roots); + return ensureTypes(analysisID, GhidraDataTypeEncoder.closure(roots)); + } + + /// As {@link #ensure}, for types the caller has already closed over their dependencies — the + /// union of several functions' {@link GhidraDataTypeEncoder#reachableTypes}, say. They are + /// de-duplicated by key but neither walked again nor capped: each function's closure is bounded + /// on its own, and the writes are chunked to the endpoints' limits however many there are. + /// + /// A type whose definition names a type with no id here — one that lies past the edge of a + /// capped closure — gets an id but no definition write; see + /// {@link GhidraDataTypeEncoder#updateEntry}. + public Map ensureTypes(AnalysisID analysisID, Collection types) throws ApiException { + Map distinct = new LinkedHashMap<>(); + for (DataType type : types) { + if (type != null) { + distinct.putIfAbsent(GhidraDataTypeEncoder.keyOf(type), type); + } + } + List closure = List.copyOf(distinct.values()); if (closure.isEmpty()) { return Map.of(); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java index 2fcde831..767b522f 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilder.java @@ -7,8 +7,7 @@ import ghidra.util.Msg; import org.json.JSONArray; import org.json.JSONObject; -import ai.reveng.model.AnalysisCreateRequest; -import ai.reveng.model.Tag; +import ai.reveng.model.CreateRequest; import java.util.ArrayList; import java.util.List; @@ -40,11 +39,6 @@ public AnalysisOptionsBuilder hash(TypedApiInterface.BinaryHash hash) { return this; } - public AnalysisOptionsBuilder advancedAnalysis(boolean advanced) { - options.put("advanced_analysis", advanced); - return this; - } - public AnalysisOptionsBuilder fileName(String name) { options.put("file_name", name); return this; @@ -107,35 +101,25 @@ public AnalysisOptionsBuilder architecture(String arch) { } /** - * Converts the current AnalysisOptionsBuilder to an AnalysisCreateRequest object - * that can be used with the new API endpoints + * Converts the current AnalysisOptionsBuilder to the v3 create-analysis request. * - * @return AnalysisCreateRequest object populated with the current options + * @return CreateRequest populated with the current options */ - public AnalysisCreateRequest toAnalysisCreateRequest() { - // Create the request with only the core required fields that we know work - var request = new AnalysisCreateRequest() + public CreateRequest toAnalysisCreateRequest() { + var request = new CreateRequest() .filename(options.getString("file_name")) .sha256Hash(options.getString("sha_256_hash")); - // Include tags if any were provided - List tagStrings = getTags(); - if (!tagStrings.isEmpty()) { - // Convert string tags to Tag objects, filtering out any empty/null strings - List tags = tagStrings.stream() - .filter(tagString -> tagString != null && !tagString.trim().isEmpty()) - .map(tagString -> new Tag().name(tagString)) - .toList(); - - // Only set tags if we have valid ones after filtering - if (!tags.isEmpty()) { - request.setTags(tags); - } + List tags = getTags().stream() + .filter(tag -> tag != null && !tag.trim().isEmpty()) + .toList(); + if (!tags.isEmpty()) { + request.setTags(tags); } if (options.has("binary_scope")) { var scope = options.getString("binary_scope"); - request.analysisScope(ai.reveng.model.AnalysisScope.fromValue(scope)); + request.analysisScope(CreateRequest.AnalysisScopeEnum.fromValue(scope)); } if (options.has("symbols")) { @@ -165,16 +149,12 @@ public AnalysisCreateRequest toAnalysisCreateRequest() { request.setSymbols(symbolsModel); } - var analysisConfig = new ai.reveng.model.AnalysisConfig(); + var analysisConfig = new ai.reveng.model.Config(); if (options.has("skip_capabilities")) { analysisConfig.setGenerateCapabilities(!options.getBoolean("skip_capabilities")); } - if (options.has("advanced_analysis")) { - analysisConfig.setAdvancedAnalysis(options.getBoolean("advanced_analysis")); - } - request.setAnalysisConfig(analysisConfig); var binaryConfig = new ai.reveng.model.BinaryConfig(); @@ -189,7 +169,7 @@ public AnalysisCreateRequest toAnalysisCreateRequest() { request.setBinaryConfig(binaryConfig); - Msg.info(this, "Created AnalysisCreateRequest: " + request); + Msg.info(this, "Created CreateRequest: " + request); return request; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java index 1f013f92..60c77e6b 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureService.java @@ -40,11 +40,30 @@ public FunctionSignatureService(TypedApiInterface api) { /// One function's signature together with the types it references. public record Resolved(BatchFunctionSignatureEntry entry, List dataTypes) {} + /// Whether the entry carries a signature worth applying: the server holds one, and it is more than + /// the placeholder described at {@link #isPlaceholder}. + public static boolean hasUsableSignature(BatchFunctionSignatureEntry entry) { + return Boolean.TRUE.equals(entry.getHasSignature()) && !isPlaceholder(entry); + } + + /// Type extraction stores a signature for every function it reaches, including the ones Ghidra had + /// nothing for, and those come back as `undefined f(void)` with `has_signature` true: source SYSTEM, + /// no parameters, and a return type of data type id 0 — always Ghidra's `undefined` in an analysis' + /// type table — or none at all. Applying one erases whatever the function had locally, and counting + /// it as present stops the better local signature from being pushed. A real `void f(void)` returns + /// `void`, not `undefined`, so it is not mistaken for one. + public static boolean isPlaceholder(BatchFunctionSignatureEntry entry) { + Long returnType = entry.getReturnDataTypeId(); + return entry.getSourceType() == BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM + && (entry.getParameters() == null || entry.getParameters().isEmpty()) + && (returnType == null || returnType == 0L); + } + /// The signature of a single function, or empty when the server holds none for it. public Optional get(FunctionID functionID) { FunctionSignatureBatch batch = getMany(List.of(functionID)); return batch.items().stream() - .filter(entry -> Boolean.TRUE.equals(entry.getHasSignature())) + .filter(FunctionSignatureService::hasUsableSignature) .findFirst() .map(entry -> new Resolved(entry, batch.dataTypesFor(analysisOf(entry)))); } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java index 974bb46f..84b8159c 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraDataTypeEncoder.java @@ -53,9 +53,19 @@ /// overloads without one keep the derived value. public final class GhidraDataTypeEncoder { - /// Upper bound on transitive dependency resolution, so a pathological type graph cannot make a - /// reactive push walk forever. Also keeps a single push well inside the endpoints' batch limits. - private static final int MAX_TYPES = 500; + /// Upper bound on one {@link #closure} walk, so a pathological type graph cannot make a reactive + /// push walk forever. + /// + /// It bounds one function's closure, not a whole push: a push of many functions closes each one + /// separately and hands the union to {@link AnalysisDataTypesService#ensureTypes}, which chunks its + /// writes to the endpoints' limits. Capping the union instead made whether a function's types got + /// ids depend on which other functions happened to share its batch. + /// + /// A function whose own closure is larger than this cannot be pushed: the types at the edge of + /// the walk refer to types it never reached, which have no id, so the function is held back + /// rather than written with null references. {@link #exceedsClosureLimit} tells that case apart + /// from a type the server gave no id. + public static final int MAX_TYPES = 500; /// Ghidra's placeholders for "no calling convention recorded", which the API would rather not /// have at all than have as a literal. @@ -64,8 +74,11 @@ public final class GhidraDataTypeEncoder { private GhidraDataTypeEncoder() {} - /// Resolves a referenced type to the analysis' id for it. Absent ids encode as an omitted - /// reference, which the API reads as "unresolved" rather than as an error. + /// Resolves a referenced type to the analysis' id for it. + /// + /// An absent id is never written as a null reference: the write endpoints replace a stored + /// definition in full, so a null `data_type_id` would erase the type the portal had there. A body + /// that would need one is withheld instead — see {@link #updateEntry} and {@link #unresolvedTypes}. @FunctionalInterface public interface Ids { @Nullable @@ -119,6 +132,54 @@ public static List closure(Collection roots) { return List.copyOf(seen.values()); } + /// The names of the types a push of `function` cannot write in full with `ids`, given its + /// `reachable` types ({@link #reachableTypes}). Empty when the signature and every definition + /// it depends on can be sent. + /// + /// A type counts when it has no id itself, or when it refers to a type that has none: the latter + /// is how a closure cut short by {@link #MAX_TYPES} shows up, and {@link #updateEntry} withholds + /// such a definition rather than write a null reference into it. Either way the function's + /// edit has not fully reached the portal. + public static Set unresolvedTypes(Function function, Collection reachable, Ids ids) { + Set unresolved = new LinkedHashSet<>(); + List named = new ArrayList<>(); + named.add(function.getReturnType()); + for (Parameter parameter : function.getParameters()) { + named.add(parameter.getDataType()); + } + for (DataType type : named) { + if (type == null || ids.idOf(keyOf(type)) == null) { + unresolved.add(nameOf(type)); + } + } + for (DataType type : reachable) { + if (ids.idOf(keyOf(type)) == null || !referencesResolve(type, ids)) { + unresolved.add(nameOf(type)); + } + } + return unresolved; + } + + /// Whether `reachable` ({@link #reachableTypes}) was cut short by {@link #MAX_TYPES}: some type + /// in it refers to a type the walk never reached. + public static boolean exceedsClosureLimit(Collection reachable) { + if (reachable.size() < MAX_TYPES) { + return false; + } + Set reached = new java.util.HashSet<>(); + for (DataType type : reachable) { + reached.add(keyOf(type)); + } + for (DataType type : reachable) { + for (DataType dependency : dependenciesOf(type)) { + if (!reached.contains(keyOf(dependency))) { + return true; + } + } + } + return false; + } + /// The server's identity for a Ghidra type. public static TypeKey keyOf(DataType type) { return new TypeKey(namespaceOf(type), nameOf(type), kindOf(type)); @@ -221,6 +282,9 @@ public static ai.reveng.model.CreateDataTypeEntry createEntry(DataType type, Str /// that never carry a definition, and a composite or reference type that is locally a bare /// placeholder. `PUT` replaces a stored type in full, so writing an empty definition would /// erase whatever the server extracted; a push that has nothing to say says nothing. + /// + /// Empty too when any type it refers to has no id in `ids`, for the same reason: a member or + /// parameter written with a null type would replace the portal's type with nothing. public static Optional updateEntry(DataType type, long id, Ids ids) { return updateEntry(type, namespaceOf(type), id, ids); } @@ -232,6 +296,9 @@ public static Optional updateEntry(DataType String namespace, long id, Ids ids) { + if (!referencesResolve(type, ids)) { + return Optional.empty(); + } Long size = sizeOf(type); String name = nameOf(type); return switch (kindOf(type)) { @@ -310,7 +377,11 @@ public static Optional updateEntry(DataType /// The function's local signature as a signature update, with every type named by id. /// /// `PUT .../signature` replaces the stored signature in full, so parameter storage is carried - /// over as well: leaving it out would clear the storage the server extracted. + /// over as well: leaving it out would clear the storage the server extracted. For the same + /// reason a parameter or return type without an id is refused rather than sent as null; callers + /// check {@link #unresolvedTypes} first. + /// + /// @throws IllegalStateException if `ids` has no id for a parameter or the return type public static ai.reveng.model.UpdateFunctionSignatureInputBody signatureOf(Function function, Ids ids) { var body = new ai.reveng.model.UpdateFunctionSignatureInputBody(); @@ -327,16 +398,24 @@ public static ai.reveng.model.UpdateFunctionSignatureInputBody signatureOf(Funct var input = new ai.reveng.model.SignatureParameterInput() .ordinal((long) ordinal) .name(parameter.getName()) - .dataTypeId(ids.idOf(keyOf(parameter.getDataType()))) + .dataTypeId(requireId(parameter.getDataType(), ids)) .bitLength(Math.max(0, parameter.getLength()) * 8L); storageOf(parameter).ifPresent(input::storage); parameters.add(input); } body.setParameters(parameters); - body.setReturnDataTypeId(ids.idOf(keyOf(function.getReturnType()))); + body.setReturnDataTypeId(requireId(function.getReturnType(), ids)); return body; } + private static long requireId(@Nullable DataType type, Ids ids) { + Long id = type == null ? null : ids.idOf(keyOf(type)); + if (id == null) { + throw new IllegalStateException("No data type id for \"%s\"".formatted(nameOf(type))); + } + return id; + } + /// Convenience overload for callers holding the id map {@link AnalysisDataTypesService#ensure} /// returned. public static ai.reveng.model.UpdateFunctionSignatureInputBody signatureOf(Function function, @@ -361,6 +440,26 @@ private static List roots(Function function) { /// The types one type refers to. A pointer's pointee and an array's element count as /// dependencies because they are types in their own right on the server, each with its own id. private static List dependenciesOf(DataType type) { + List dependencies = referencesOf(type); + dependencies.removeIf(java.util.Objects::isNull); + return dependencies; + } + + /// Whether every type `type`'s definition names has an id, so its update body can be written + /// without a null reference. + private static boolean referencesResolve(DataType type, Ids ids) { + for (DataType reference : referencesOf(type)) { + if (reference == null || ids.idOf(keyOf(reference)) == null) { + return false; + } + } + return true; + } + + /// The types `type`'s definition names, one entry per reference. A member or parameter with no + /// type is kept as a null, since its body would carry a null reference; a pointer with no + /// pointee is `void *` and names nothing. + private static List referencesOf(DataType type) { List dependencies = new ArrayList<>(); switch (kindOf(type)) { case STRUCT, UNION -> { @@ -369,7 +468,12 @@ private static List dependenciesOf(DataType type) { } } case TYPEDEF -> dependencies.add(((TypeDef) type).getDataType()); - case POINTER -> dependencies.add(((Pointer) type).getDataType()); + case POINTER -> { + DataType pointee = ((Pointer) type).getDataType(); + if (pointee != null) { + dependencies.add(pointee); + } + } case ARRAY -> dependencies.add(((Array) type).getDataType()); case FUNCTION_DEFINITION -> { FunctionDefinition definition = (FunctionDefinition) type; @@ -381,7 +485,6 @@ private static List dependenciesOf(DataType type) { default -> { } } - dependencies.removeIf(java.util.Objects::isNull); return dependencies; } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java index e573227e..b4793517 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/GhidraRevengService.java @@ -1,21 +1,25 @@ package ai.reveng.toolkit.ghidra.core.services.api; +import ai.reveng.invoker.ApiClient; import ai.reveng.invoker.ApiException; import ai.reveng.model.*; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.components.SelectableItem; import ai.reveng.toolkit.ghidra.core.AnalysisLogConsumer; import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; +import ai.reveng.toolkit.ghidra.core.ui.WebBrowser; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionBoundary; 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.plugins.ReaiPluginPackage; import ai.reveng.toolkit.ghidra.core.services.api.mocks.MockApi; import ai.reveng.toolkit.ghidra.core.services.api.types.*; import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; import ghidra.app.cmd.function.ApplyFunctionSignatureCmd; import ghidra.app.cmd.function.FunctionRenameOption; import ghidra.app.cmd.function.SetFunctionNameCmd; +import ghidra.framework.OperatingSystem; +import ghidra.framework.Platform; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.ServiceProvider; import ghidra.program.model.address.Address; @@ -30,9 +34,9 @@ import ghidra.program.model.symbol.*; import ghidra.program.model.util.LongPropertyMap; import ghidra.program.model.util.StringPropertyMap; -import ghidra.util.BrowserLoader; import ghidra.util.InvalidNameException; import ghidra.util.Msg; +import ghidra.util.Swing; import ghidra.util.exception.CancelledException; import ghidra.util.exception.DuplicateNameException; import ghidra.util.exception.InvalidInputException; @@ -43,15 +47,18 @@ import java.awt.*; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.MalformedURLException; import java.net.URI; +import java.nio.file.FileSystemException; +import java.nio.file.Files; import java.nio.file.InvalidPathException; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; +import java.time.Duration; import java.util.*; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -81,13 +88,13 @@ public class GhidraRevengService { private static final String REVENG_BOOKMARK_CATEGORY = "Analysed Function"; private final Map statusCache = new HashMap<>(); - private TypedApiInterface api; - private ApiInfo apiInfo; + private volatile TypedApiInterface api; + private volatile ApiInfo apiInfo; - /// Set while the plugin is applying server-sourced changes locally (pull / analysis-sync), so the - /// reactive listener does not echo those changes straight back to the portal. Mirrors the IDA - /// plugin's {@code analysis_sync_service.is_worker_running()} guard. - private final AtomicBoolean pushbackSuppressed = new AtomicBoolean(false); + /// The programs the plugin is writing server-sourced changes into right now, each with how many + /// such writes overlap, so the reactive listener does not echo those changes straight back to the + /// portal. See {@link #startServerTransaction}. + private final Map applyingServerChanges = new ConcurrentHashMap<>(); /// dedicated functions on the GhidraRevengService should be used instead to enforce assumptions via /// type level guarantees @@ -142,6 +149,30 @@ public URI getServer() { return this.apiInfo.hostURI(); } + /// Points the running service at new credentials, as the setup wizard does when it finishes. + /// Swapped in place rather than replaced, because every plugin holds the instance it was handed + /// as a service. Returns false when nothing changed. + public synchronized boolean reconfigure(ApiInfo newApiInfo) { + if (newApiInfo.equals(apiInfo)) { + return false; + } + this.api = new TypedApiImplementation(newApiInfo); + this.apiInfo = newApiInfo; + // Both wrap the old API, and analysis ids from the old host mean nothing on the new one. + this.signatureService = null; + this.analysisDataTypesService = null; + statusCache.clear(); + return true; + } + + /// The HTTP client behind the API, for SDK APIs that {@link TypedApiInterface} does not wrap. + public ApiClient apiClient() { + if (api instanceof TypedApiImplementation impl) { + return impl.apiClient(); + } + throw new IllegalStateException("The configured API is not backed by an HTTP client"); + } + public ProgramWithID registerAnalysisForProgram(Program program, TypedApiInterface.AnalysisID analysisID) { return addAnalysisIDtoProgramOptions(program, analysisID); } @@ -154,10 +185,63 @@ public AnalysedProgram registerFinishedAnalysisForProgram(ProgramWithID programW } statusCache.put(programWithID.analysisID, AnalysisStatus.Complete); - var analysedProgram = associateFunctionInfo(programWithID); - pullFunctionInfoFromAnalysis(analysedProgram, monitor); - monitor.checkCancelled(); - return analysedProgram; + // The function ids alone make the program count as analysed, though none of the portal's names or types + // may have arrived. One transaction around the whole load is rolled back when any part of it fails, so the + // program is left as it was, the load can be retried, and the undo history holds nothing to bring it back. + var program = programWithID.program(); + // Fetched before the transaction opens, so a Detach during the request does not join it + var functionInfo = api.getFunctionInfo(programWithID.analysisID()); + requireStillAttached(programWithID); + var transactionId = program.startTransaction("RevEng.AI: Load analysis results"); + boolean loaded = false; + FunctionAssociation association; + try { + association = associateFunctionInfo(programWithID, functionInfo); + pullFunctionInfoFromAnalysis(association.analysedProgram(), monitor); + monitor.checkCancelled(); + if (!isStillAttached(programWithID)) { + // Detached during the pull. Its change to the options joined this transaction, so rolling back + // would undo the Detach too. Remove the function ids instead, so the program is not taken to + // be analysed by the analysis it has left. + if (!program.isClosed()) { + clearFunctionAssociation(program); + } + loaded = true; + throw new DetachedDuringLoadException(programWithID); + } + loaded = true; + } finally { + // A program closed during the load takes no more transactions, and must not hide why the load failed + if (!program.isClosed()) { + program.endTransaction(transactionId, loaded); + } + } + Msg.showInfo(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function loading summary", association.summary()); + return association.analysedProgram(); + } + + /// What {@link #associateFunctionInfo(ProgramWithID, List)} produced, with the summary to show once the + /// rest of the load has succeeded too. + private record FunctionAssociation(AnalysedProgram analysedProgram, String summary) {} + + /// The program was detached from the analysis, or attached to another one, while its results were loading. + /// The program is left without that analysis' function ids. + public static class DetachedDuringLoadException extends RuntimeException { + public DetachedDuringLoadException(ProgramWithID programWithID) { + super("%s was detached from analysis %d while its results were loading" + .formatted(programWithID.program().getName(), programWithID.analysisID().id())); + } + } + + private boolean isStillAttached(ProgramWithID programWithID) { + return !programWithID.program().isClosed() + && getKnownProgram(programWithID.program()).filter(programWithID::equals).isPresent(); + } + + private void requireStillAttached(ProgramWithID programWithID) { + if (!isStillAttached(programWithID)) { + throw new DetachedDuringLoadException(programWithID); + } } private ProgramWithID addAnalysisIDtoProgramOptions(Program program, TypedApiInterface.AnalysisID analysisID){ @@ -197,12 +281,14 @@ private Optional getAnalysisIDFor(Program program) /// analysis is associated with the program /// Other function information like the name and signature should be loaded in [#pullFunctionInfoFromAnalysis(AnalysedProgram ,TaskMonitor)] /// because this information can change on the server, and thus needs a dedicated method to refresh it - private AnalysedProgram associateFunctionInfo(ProgramWithID knownProgram) { + /// + /// Any association already on the program is replaced, so an earlier load that stopped part way does + /// not block this one. + private FunctionAssociation associateFunctionInfo(ProgramWithID knownProgram, List functionInfo) { var analysisID = knownProgram.analysisID(); var program = knownProgram.program(); - List functionInfo = null; - functionInfo = api.getFunctionInfo(analysisID); var transactionID = program.startTransaction("Associate Function Info"); + clearFunctionAssociation(program); // Create the FunctionID map LongPropertyMap functionIDMap; @@ -267,17 +353,31 @@ private AnalysedProgram associateFunctionInfo(ProgramWithID knownProgram) { } } ); - // Print summary - Msg.showInfo(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function loading summary", - ("Found %d functions from RevEng.AI. Your local Ghidra instance has %d/%d matching function " + - "boundaries. For better results, please start a new analysis from this plugin.").formatted( - functionInfo.size(), - ghidraBoundariesMatchedFunction, - ghidraFunctionCount.get() - )); + var summary = ("Found %d functions from RevEng.AI. Your local Ghidra instance has %d/%d matching function " + + "boundaries. For better results, please start a new analysis from this plugin.").formatted( + functionInfo.size(), + ghidraBoundariesMatchedFunction, + ghidraFunctionCount.get() + ); - return analysedProgram; + return new FunctionAssociation(analysedProgram, summary); + + } + /// Put the synced tag back on a function at an address the analysis still maps to a server + /// function, as after the function was deleted and created again. Does nothing otherwise. + public void restoreSyncedTag(Function function) { + var program = function.getProgram(); + var analysedProgram = getAnalysedProgram(program); + if (analysedProgram.isEmpty() || analysedProgram.get().getIDForFunction(function).isEmpty()) { + return; + } + boolean tagged = function.getTags().stream() + .anyMatch(tag -> REVENGAI_FUNCTION_TAG.equals(tag.getName())); + if (!tagged) { + program.withTransaction("RevEng.AI: Tag re-created function", + () -> function.addTag(REVENGAI_FUNCTION_TAG)); + } } private void markFunctionAsRevEng(BookmarkManager bookmarkManager, Function function, FunctionInfo info) { @@ -290,33 +390,56 @@ private void markFunctionAsRevEng(BookmarkManager bookmarkManager, Function func public record RenameResult(Function func, String originalName, String newName) { } - /// Push a local function rename back to the portal. Returns the namespace-qualified name that was - /// pushed, or empty if the function is not known on the server. - public Optional pushFunctionRename(AnalysedProgram analysedProgram, Function function) throws ApiException { - var withId = analysedProgram.getIDForFunction(function); - if (withId.isEmpty()) { - return Optional.empty(); + /// Push local function renames back to the portal in one request. Answers with the + /// namespace-qualified name pushed for each function; functions not known on the server are left + /// out, and when none is known nothing is sent. + /// + /// @throws IllegalStateException when the portal accepted the request but renamed fewer functions + /// than were sent; it does not say which, so none counts as pushed + public Map pushFunctionRenames(AnalysedProgram analysedProgram, Collection functions) + throws ApiException { + Map pushed = new LinkedHashMap<>(); + List items = new ArrayList<>(); + for (Function function : functions) { + var withId = analysedProgram.getIDForFunction(function); + if (withId.isEmpty()) { + continue; + } + String qualifiedName = qualifiedServerName(function); + var item = new BatchRenameItem(); + item.setFunctionId(withId.get().functionID().value()); + item.setNewName(qualifiedName); + item.setNewMangledName(qualifiedName); + items.add(item); + pushed.put(function, qualifiedName); + } + if (items.isEmpty()) { + return pushed; } - String qualifiedName = qualifiedServerName(function); - var item = new BatchRenameItem(); - item.setFunctionId(withId.get().functionID().value()); - item.setNewName(qualifiedName); - item.setNewMangledName(qualifiedName); var request = new BatchRenameInputBody(); - request.setFunctions(List.of(item)); - api.batchRenameFunctions(request); - return Optional.of(qualifiedName); + request.setFunctions(items); + long renamed = api.batchRenameFunctions(request); + if (renamed < items.size()) { + throw new IllegalStateException("The portal renamed %d of the %d function(s) sent" + .formatted(renamed, items.size())); + } + return pushed; } /// The function name as the portal expects it: qualified with its namespace path (joined by - /// {@code ::}), excluding the artificial RevEng.AI organisational namespace and the global - /// namespace. Ghidra stores only the leaf label on the symbol, so the namespace must be - /// re-attached when pushing a rename back — the portal's function names include the namespace. + /// {@code ::}), excluding the artificial RevEng.AI organisational namespace, the namespaces + /// under it, and the global namespace. Ghidra stores only the leaf label on the symbol, so the + /// namespace must be re-attached when pushing a rename back — the portal's function names + /// include the namespace. Applying a match files the function under + /// {@code RevEng.AI::}, and that binary name is not part of the function's name. static String qualifiedServerName(Function function) { List parts = new ArrayList<>(); parts.add(function.getName()); for (Namespace ns = function.getParentNamespace(); ns != null && !ns.isGlobal(); ns = ns.getParentNamespace()) { - if (!REVENG_AI_NAMESPACE.equals(ns.getName())) { + if (REVENG_AI_NAMESPACE.equals(ns.getName())) { + // Drop the namespaces collected so far: they are all inside RevEng.AI + parts.subList(0, parts.size() - 1).clear(); + } else { parts.add(0, ns.getName()); } } @@ -339,46 +462,98 @@ public enum TypePushOutcome { } /// Push the local signature and variables of a function back to the portal. - public TypePushOutcome pushFunctionTypes(AnalysedProgram analysedProgram, Function function) throws ApiException { + /// + /// @throws UnresolvedDataTypesException if a type the function reaches could not be given an id, + /// so its signature was held back + public TypePushOutcome pushFunctionTypes(AnalysedProgram analysedProgram, Function function) + throws ApiException, UnresolvedDataTypesException { if (analysedProgram.getIDForFunction(function).isEmpty()) { return TypePushOutcome.NOT_MATCHED; } // The function is known to the analysis, so the type pass below ran for it; only the // signature write can still decline. - return pushFunctionTypes(analysedProgram, List.of(function)) > 0 + var push = pushFunctionTypes(analysedProgram, List.of(function)); + var withheld = push.withheld().get(function); + if (withheld != null) { + throw withheld; + } + return push.signaturesWritten() > 0 ? TypePushOutcome.SIGNATURE_WRITTEN : TypePushOutcome.TYPES_ONLY; } - /// Push the local signatures of several functions, and answer with how many the server took. + /// What a push of several functions' types achieved. + /// + /// @param signaturesWritten how many signatures the portal took + /// @param withheld the functions whose signature was not sent because a type they reach + /// has no id, each with the reason; their edits have not gone up + public record TypePush(int signaturesWritten, Map withheld) {} + + /// Push the local signatures of several functions, and answer with how many the server took and + /// which were held back. /// /// The two halves of the write path compose here, and only here. Data-type management is a /// batch affair — the union of everything the functions reach is resolved against the analysis' /// catalogue and created where it is missing, in one pass — while a signature is written one /// function at a time. Running the type pass once for the whole set is the point of keeping the /// two apart: the alternative re-resolves the same closure per function. - public int pushFunctionTypes(AnalysedProgram analysedProgram, Collection functions) throws ApiException { + /// + /// Each function's closure is capped on its own and only the union is handed to the type pass, + /// so how many functions share a batch does not decide which of them get ids. A function that + /// still reaches a type without one is not sent at all: its signature, or a struct it depends + /// on, would otherwise go up with a null type and erase what the portal holds. + public TypePush pushFunctionTypes(AnalysedProgram analysedProgram, Collection functions) + throws ApiException { Map known = new LinkedHashMap<>(); for (Function function : functions) { analysedProgram.getIDForFunction(function) .ifPresent(withId -> known.put(function, withId.functionID())); } if (known.isEmpty()) { - return 0; + return new TypePush(0, Map.of()); } - List roots = new ArrayList<>(); - known.keySet().forEach(function -> roots.addAll(GhidraDataTypeEncoder.reachableTypes(function))); - var ids = analysisDataTypes().ensure(analysedProgram.analysisID(), roots); + Map> reachable = new LinkedHashMap<>(); + List union = new ArrayList<>(); + for (Function function : known.keySet()) { + var types = GhidraDataTypeEncoder.reachableTypes(function); + reachable.put(function, types); + union.addAll(types); + } + var ids = GhidraDataTypeEncoder.Ids.of(analysisDataTypes().ensureTypes(analysedProgram.analysisID(), union)); int pushed = 0; + Map withheld = new LinkedHashMap<>(); for (var entry : known.entrySet()) { - var signature = GhidraDataTypeEncoder.signatureOf(entry.getKey(), ids); + var function = entry.getKey(); + var unresolved = GhidraDataTypeEncoder.unresolvedTypes(function, reachable.get(function), ids); + if (!unresolved.isEmpty()) { + withheld.put(function, new UnresolvedDataTypesException(unresolved, + GhidraDataTypeEncoder.exceedsClosureLimit(reachable.get(function)))); + continue; + } + var signature = GhidraDataTypeEncoder.signatureOf(function, ids); if (signatures().put(analysedProgram.analysisID(), entry.getValue(), signature)) { pushed++; } } - return pushed; + return new TypePush(pushed, withheld); + } + + /// Log the functions a backfill held back as one line: on a large binary there can be many. + private static void logWithheld(ReaiLoggingService log, Map withheld) { + if (withheld.isEmpty()) { + return; + } + final int shown = 5; + String examples = withheld.entrySet().stream().limit(shown) + .map(entry -> "\"%s\" at %s (%s)".formatted(entry.getKey().getName(), + entry.getKey().getEntryPoint(), entry.getValue().getMessage())) + .collect(java.util.stream.Collectors.joining("; ")); + if (withheld.size() > shown) { + examples += "; and %d more".formatted(withheld.size() - shown); + } + log.warn("Did not push the types of %d function(s): %s".formatted(withheld.size(), examples)); } /// Breakdown of a bidirectional analysis sync, shown to the user afterwards. @@ -389,9 +564,34 @@ public record SyncSummary( int canonicalizedNames, int dedupedNames, int pushedNames, - int pushedTypeSets + int pushedTypeSets, + int pushedLocalEdits, + int failedLocalEdits, + int nameConflicts, + int signatureConflicts ) {} + /// What sending the unpushed local edits achieved. Every edit that failed is still marked. + /// + /// @param pushed the edits that reached the portal this time + /// @param unsent the edits that failed for a reason that may pass — see {@link PushFailure} + /// @param unsentError why the last of those failed, or null when none did + /// @param rejected the edits the portal turned down, or that failed for good, one entry each + public record LocalEditFlush(int pushed, int unsent, @Nullable Exception unsentError, + List rejected) { + public int failed() { + return unsent + rejected.size(); + } + } + + /// @param edit which edit, for the log: "rename of \"foo\" at 00401000" + /// @param error why it failed + public record RejectedEdit(String edit, Exception error) { + public PushFailure failure() { + return PushFailure.of(error); + } + } + private record PendingNamePush(TypedApiInterface.FunctionID functionID, String newName, String newMangledName) {} private record InvalidRemoteName(Function function, TypedApiInterface.FunctionID functionID, String remoteName) {} @@ -405,17 +605,21 @@ private record InvalidRemoteName(Function function, TypedApiInterface.FunctionID /// for matched functions whose remote types are absent or could not be applied. Mirrors the IDA /// plugin's {@code analysis_sync.py}. public SyncSummary syncAnalysisUpdates(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) throws ApiException { - pushbackSuppressed.set(true); - try { - return syncAnalysisUpdatesInternal(analysedProgram, monitor, log); - } finally { - pushbackSuppressed.set(false); - } - } - - private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) throws ApiException { var program = analysedProgram.program(); log.info("Starting bidirectional sync with the RevEng.AI portal"); + // Before the remote names are read, so an edit that goes up now is not then reported as a + // conflict with the portal's stale copy of it. + var flush = pushUnpushedEdits(analysedProgram); + if (flush.pushed() > 0) { + log.info("Pushed %d local edit(s) that had not reached the RevEng.AI portal".formatted(flush.pushed())); + } + if (flush.unsent() > 0) { + log.warn("Could not push %d local edit(s) to the RevEng.AI portal: %s" + .formatted(flush.unsent(), flush.unsentError())); + } + for (RejectedEdit rejected : flush.rejected()) { + log.warn("The RevEng.AI portal did not take the %s: %s".formatted(rejected.edit(), rejected.error())); + } Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() .collect(Collectors.toMap(FunctionInfo::functionID, fi -> fi, (a, b) -> a)); @@ -426,8 +630,9 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, int namesModifiedRemotely = 0; int deduped = 0; int canonicalizedNames = 0; + int nameConflicts = 0; - var transactionId = program.startTransaction("RevEng.AI: Sync Analysis Updates"); + var transactionId = startServerTransaction(program, "RevEng.AI: Sync Analysis Updates"); boolean commit = false; try { // Creating the RevEng.AI namespace is a DB write, so it must happen inside the transaction. @@ -453,8 +658,16 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, if (remoteName == null || remoteName.isBlank() || remoteName.equals(function.getName())) { continue; } - // Do not overwrite names the user has explicitly set locally. + // Do not overwrite names the user has explicitly set locally. The portal holding a + // different name for one means both sides renamed it, unless the local rename is + // still waiting to go up. if (function.getSymbol().getSource() == SourceType.USER_DEFINED) { + if (!remoteName.equals(qualifiedServerName(function)) + && !UnpushedEdits.isMarked(program, UnpushedEdits.Kind.NAME, function.getEntryPoint())) { + nameConflicts++; + log.warn("Name conflict at %s: \"%s\" locally, \"%s\" in the portal; kept the local name" + .formatted(function.getEntryPoint(), function.getName(), remoteName)); + } continue; } if (isInvalidGhidraName(remoteName)) { @@ -502,7 +715,7 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, commit = !namePushbacks.isEmpty() || namesModifiedRemotely > 0; canonicalizedNames = canonicalized; } finally { - program.endTransaction(transactionId, commit && !monitor.isCancelled()); + endServerTransaction(program, transactionId, commit && !monitor.isCancelled()); } // Push back over the network only after the local transaction has closed, so we don't hold a @@ -513,53 +726,196 @@ private SyncSummary syncAnalysisUpdatesInternal(AnalysedProgram analysedProgram, } // Pull before pushing, so the back-fill below sees the signatures this sync just applied and // does not send the local placeholder back up for a function the portal already described. - int appliedSignatures = applyRemoteSignatures(analysedProgram, monitor, log); + var signatures = applyRemoteSignatures(analysedProgram, monitor, log); + int appliedSignatures = signatures.applied(); int pushedTypeSets = pushLocalTypesWhereRemoteMissing(analysedProgram, functionInfoMap.keySet(), monitor, log); log.info(("Sync complete: %d matched, %d name(s) applied, %d signature(s) applied, %d canonicalized, " - + "%d de-duplicated, %d name(s) and %d type set(s) pushed back") + + "%d de-duplicated, %d name(s) and %d type set(s) pushed back, %d unpushed local edit(s) " + + "pushed and %d still failing, %d name and %d signature conflict(s)") .formatted(matched, namesModifiedRemotely, appliedSignatures, canonicalizedNames, deduped, - pushedNames, pushedTypeSets)); + pushedNames, pushedTypeSets, flush.pushed(), flush.failed(), nameConflicts, + signatures.conflicts())); return new SyncSummary(matched, namesModifiedRemotely, appliedSignatures, canonicalizedNames, deduped, - pushedNames, pushedTypeSets); + pushedNames, pushedTypeSets, flush.pushed(), flush.failed(), nameConflicts, signatures.conflicts()); + } + + /// Push the local edits whose reactive push failed or never ran — see {@link UnpushedEdits}. A + /// function that is gone, or not part of the analysis, has nothing left to push and is unmarked. + /// Failures are returned rather than logged, so a caller retrying in the background can report an + /// outage once instead of once per attempt. + /// + /// The renames go up as one batch and the type edits through one type pass. When the portal + /// turns a batch down, the edits are sent again one at a time, so a single edit it will never + /// take does not keep the others from going up. + public LocalEditFlush pushUnpushedEdits(AnalysedProgram analysedProgram) { + var program = analysedProgram.program(); + var flush = new FlushTally(); + Map renamed = markedFunctions(program, UnpushedEdits.Kind.NAME); + sendIsolatingRejections(program, UnpushedEdits.Kind.NAME, renamed, flush, + functions -> new Sent(pushFunctionRenames(analysedProgram, functions).size(), Map.of()), + function -> "rename of \"%s\" at %s".formatted(function.getName(), function.getEntryPoint())); + + Map retyped = markedFunctions(program, UnpushedEdits.Kind.TYPES); + // A function the analysis does not know has no types on the portal to update. + retyped.keySet().removeIf(function -> { + boolean unknown = analysedProgram.getIDForFunction(function).isEmpty(); + if (unknown) { + UnpushedEdits.clear(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint()); + } + return unknown; + }); + // A signature the portal has no extraction for is declined, but its types went up, which is + // all this push can do. One held back for want of a type id has not gone up, and stays marked. + sendIsolatingRejections(program, UnpushedEdits.Kind.TYPES, retyped, flush, + functions -> { + var push = pushFunctionTypes(analysedProgram, functions); + return new Sent(functions.size() - push.withheld().size(), Map.copyOf(push.withheld())); + }, + function -> "types of \"%s\" at %s".formatted(function.getName(), function.getEntryPoint())); + return new LocalEditFlush(flush.pushed, flush.unsent, flush.unsentError, List.copyOf(flush.rejected)); + } + + private static final class FlushTally { + int pushed; + int unsent; + Exception unsentError; + final List rejected = new ArrayList<>(); + } + + @FunctionalInterface + private interface EditSender { + /// Send the edits of these functions and answer with how many went up. + Sent send(List functions) throws Exception; + } + + /// @param pushed how many edits went up + /// @param failed the functions whose edit was held back without failing the rest, with why + private record Sent(int pushed, Map failed) {} + + /// The functions with a `kind` edit marked, each with the address it is marked at. A mark whose + /// function is gone is cleared, since nothing is left to send. + private static Map markedFunctions(Program program, UnpushedEdits.Kind kind) { + Map marked = new LinkedHashMap<>(); + for (Address entryPoint : UnpushedEdits.marked(program, kind)) { + var function = program.getFunctionManager().getFunctionAt(entryPoint); + if (function == null) { + UnpushedEdits.clear(program, kind, entryPoint); + } else { + marked.put(function, entryPoint); + } + } + return marked; + } + + /// Send `marked` as one batch and clear the marks of what went up. When the portal turns the + /// batch down, send each edit on its own to find the ones it will not take. A failure that may + /// pass leaves the rest for a later attempt instead, since sending them one by one would only + /// fail the same way more often. + private static void sendIsolatingRejections(Program program, UnpushedEdits.Kind kind, + Map marked, FlushTally flush, + EditSender sender, + java.util.function.Function describe) { + if (marked.isEmpty()) { + return; + } + List functions = List.copyOf(marked.keySet()); + try { + settle(program, kind, marked, functions, sender.send(functions), flush, describe); + return; + } catch (Exception e) { + if (PushFailure.of(e) != PushFailure.REJECTED || functions.size() == 1) { + record(flush, functions, e, describe); + return; + } + } + for (Function function : functions) { + try { + settle(program, kind, marked, List.of(function), sender.send(List.of(function)), flush, describe); + } catch (Exception e) { + record(flush, List.of(function), e, describe); + } + } + } + + /// Clear the marks of the `sent` edits that went up, and record the ones held back. + private static void settle(Program program, UnpushedEdits.Kind kind, Map marked, + List functions, Sent sent, FlushTally flush, + java.util.function.Function describe) { + flush.pushed += sent.pushed(); + for (Function function : functions) { + Exception failure = sent.failed().get(function); + if (failure == null) { + UnpushedEdits.clear(program, kind, marked.get(function)); + } else { + record(flush, List.of(function), failure, describe); + } + } + } + + private static void record(FlushTally flush, List functions, Exception e, + java.util.function.Function describe) { + if (PushFailure.of(e) == PushFailure.TRANSIENT) { + flush.unsent += functions.size(); + flush.unsentError = e; + } else { + functions.forEach(function -> flush.rejected.add(new RejectedEdit(describe.apply(function), e))); + } } /// Apply the signatures — and with them the data types they name — that the portal holds for this /// analysis' functions, and answer with how many landed. /// - /// Names are deliberately left alone. {@link #syncAnalysisUpdatesInternal} owns that decision, + /// Names are deliberately left alone. {@link #syncAnalysisUpdates} owns that decision, /// including canonicalising names Ghidra rejects and de-duplicating the ones it has already /// applied this run, so the command is given {@link FunctionRenameOption#NO_CHANGE} and nothing /// here competes with it. /// - /// A signature is applied unless the analyst wrote the local one by hand; anything Ghidra's own - /// analysis inferred is fair game. That is also what makes a second sync useful: an earlier pull - /// stamps {@link SourceType#ANALYSIS}, so a "default only" guard would turn every pull after the - /// first into a no-op. - private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor monitor, ReaiLoggingService log) { + /// A signature is applied unless the analyst wrote the local one by hand, or the server only has + /// what it extracted itself and the local one is better-founded — see + /// {@link #localSignatureOutranks}. A signature edited in the portal still replaces one Ghidra + /// inferred. That is also what makes a second sync useful: an earlier pull stamps + /// {@link SourceType#ANALYSIS}, so a "default only" guard would turn every pull after the first + /// into a no-op. + /// + /// A hand-written local signature that differs from the portal's is counted as a conflict rather + /// than applied, unless the local edit is still waiting to go up. + private SignaturePull applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor monitor, + ReaiLoggingService log) { var functionMap = analysedProgram.getFunctionMap(); if (functionMap.isEmpty()) { - return 0; + return new SignaturePull(0, 0); } var batch = signatures().getMany(List.copyOf(functionMap.keySet())); Map decoders = new HashMap<>(); var program = analysedProgram.program(); int applied = 0; - var transactionId = program.startTransaction("RevEng.AI: Apply Portal Signatures"); + int conflicts = 0; + var transactionId = startServerTransaction(program, "RevEng.AI: Apply Portal Signatures"); try { for (BatchFunctionSignatureEntry entry : batch.items()) { if (monitor.isCancelled()) { break; } - if (!Boolean.TRUE.equals(entry.getHasSignature())) { + if (!FunctionSignatureService.hasUsableSignature(entry)) { continue; } var function = functionMap.get(new TypedApiInterface.FunctionID(entry.getFunctionId())); if (function == null || function.isExternal() || function.isThunk() - || function.getSignatureSource() == SourceType.USER_DEFINED) { + || localSignatureOutranks(function, entry)) { continue; } var signature = getFunctionSignature(entry, decoderFor(decoders, batch, entry)); + if (function.getSignatureSource() == SourceType.USER_DEFINED) { + if (!matchesLocalSignature(function, signature) + && !UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint())) { + conflicts++; + log.warn("Signature conflict for \"%s\" at %s: the portal holds %s; kept the local signature" + .formatted(function.getName(), function.getEntryPoint(), + signature.getPrototypeString())); + } + continue; + } // The portal derives a signature for every function when the analysis completes, so // most of them match what is already on the function. Applying those regardless would // churn the type manager and fill the undo history on every sync. @@ -581,9 +937,22 @@ private int applyRemoteSignatures(AnalysedProgram analysedProgram, TaskMonitor m } } } finally { - program.endTransaction(transactionId, applied > 0 && !monitor.isCancelled()); + endServerTransaction(program, transactionId, applied > 0 && !monitor.isCancelled()); } - return applied; + return new SignaturePull(applied, conflicts); + } + + /// @param applied portal signatures that landed locally + /// @param conflicts hand-written local signatures the portal disagrees with + private record SignaturePull(int applied, int conflicts) {} + + /// Whether the function's own signature beats one the server extracted itself. A SYSTEM signature + /// is what server-side Ghidra worked out, so it adds nothing over a signature imported from debug + /// info locally, or one local analysis inferred, and replacing either can only lose information. + private static boolean localSignatureOutranks(Function function, BatchFunctionSignatureEntry entry) { + var local = function.getSignatureSource(); + return entry.getSourceType() == BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM + && (local == SourceType.IMPORTED || local == SourceType.ANALYSIS); } /// Apply one server-sourced signature to a function. @@ -670,8 +1039,8 @@ private int pushNameBacks(List namePushbacks) throws ApiExcepti }).toList(); var request = new BatchRenameInputBody(); request.setFunctions(items); - api.batchRenameFunctions(request); - return namePushbacks.size(); + // The count the portal reports, not the number asked for: a rename it skipped did not happen. + return Math.toIntExact(api.batchRenameFunctions(request)); } /// Push local types for matched functions whose remote types are absent or could not be applied, @@ -680,12 +1049,14 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, Set matchedIds, TaskMonitor monitor, ReaiLoggingService log) { - // Only the matched functions are candidates, and only whether the server holds a signature - // at all matters here, so ask for exactly those ids and skip the type closure. + // Only the matched functions are candidates, and only whether the server holds a usable + // signature matters here, so ask for exactly those ids and skip the type closure. A placeholder + // counts as missing: unlike a function with no signature at all, it is a stored row the + // signature PUT accepts, so these are the functions a push can actually fill in. Set remotePresent = signatures() .getMany(List.copyOf(matchedIds), false) .items().stream() - .filter(BatchFunctionSignatureEntry::getHasSignature) + .filter(FunctionSignatureService::hasUsableSignature) .map(item -> new TypedApiInterface.FunctionID(item.getFunctionId())) .collect(Collectors.toSet()); @@ -711,9 +1082,11 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, } try { // One type pass over the union of every candidate's types, then a signature write each. - int pushed = pushFunctionTypes(analysedProgram, candidates); + var push = pushFunctionTypes(analysedProgram, candidates); + int pushed = push.signaturesWritten(); log.info("Pushed local types for %d of %d functions the portal had none for" .formatted(pushed, candidates.size())); + logWithheld(log, push.withheld()); return pushed; } catch (ApiException e) { Msg.warn(this, "Failed to push local types during sync", e); @@ -721,6 +1094,58 @@ private int pushLocalTypesWhereRemoteMissing(AnalysedProgram analysedProgram, } } + /// Start a transaction that writes server-sourced changes into `program`, during which the reactive + /// listener ignores that program's type and variable events. Close it with + /// {@link #endServerTransaction}. + /// + /// The window is this one write, not the whole sync: a sync spends most of its time on network + /// calls, and suppressing for all of it dropped every edit the analyst made meanwhile, in every + /// open program. Ghidra delivers change events later, from a timer, so the window is bounded by + /// flushing them: once before, so edits made up to now are delivered as the analyst's, and once + /// after, so this write's own events are delivered while they are still recognisably ours. + /// Function and variable renames are never suppressed — see + /// {@link ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService}. + private int startServerTransaction(Program program, String description) { + deliverPendingEvents(program); + applyingServerChanges.merge(program, 1, Integer::sum); + try { + return program.startTransaction(description); + } catch (RuntimeException e) { + releaseServerChanges(program); + throw e; + } + } + + private void endServerTransaction(Program program, int transactionId, boolean commit) { + try { + program.endTransaction(transactionId, commit); + deliverPendingEvents(program); + } finally { + releaseServerChanges(program); + } + } + + /// Deliver every change event `program` has queued, and wait until the listeners have seen them. + /// + /// {@link Program#flushEvents} alone does not wait. Ghidra's event timer runs on the Swing thread + /// and takes the queued events and delivers them in one Swing task; when it has just taken them, + /// a flush from another thread finds the queue empty and returns while they are still being + /// delivered. Queuing an empty task behind it waits that delivery out. + private static void deliverPendingEvents(Program program) { + program.flushEvents(); + Swing.runNow(() -> {}); + } + + private void releaseServerChanges(Program program) { + applyingServerChanges.computeIfPresent(program, (p, writes) -> writes > 1 ? writes - 1 : null); + } + + /// True while the plugin is writing server-sourced changes into `program`; the reactive listener + /// uses this to avoid pushing those changes back to the portal. + public boolean isApplyingServerChanges(Program program) { + return applyingServerChanges.containsKey(program); + } + private boolean applyRemoteName(Program program, Function function, Namespace revEngNamespace, String name) { try { function.setParentNamespace(revEngNamespace); @@ -759,155 +1184,151 @@ static boolean isInvalidGhidraName(String name) { /// * the type signature of the function /// /// It assumes that the initial load already happened, i.e. the functions have an associated FunctionID already. - /// The initial association happens in {@link #associateFunctionInfo(ProgramWithID)} + /// The initial association happens in {@link #associateFunctionInfo(ProgramWithID, List)} /// public List pullFunctionInfoFromAnalysis(AnalysedProgram analysedProgram, TaskMonitor monitor) { - pushbackSuppressed.set(true); - try { - return pullFunctionInfoFromAnalysisInternal(analysedProgram, monitor); - } finally { - pushbackSuppressed.set(false); - } - } - - /// True while the plugin is applying server-sourced changes locally; the reactive listener uses - /// this to avoid pushing those changes back to the portal. - public boolean isPushbackSuppressed() { - return pushbackSuppressed.get(); - } - - private List pullFunctionInfoFromAnalysisInternal(AnalysedProgram analysedProgram, TaskMonitor monitor) { - var transactionId = analysedProgram.program().startTransaction("RevEng.AI: Pull Function Info from Analysis"); + var transactionId = startServerTransaction(analysedProgram.program(), "RevEng.AI: Pull Function Info from Analysis"); List renameResults = new ArrayList<>(); int failedRenames = 0; + try { - var revEngNamespace = getRevEngAINameSpace(analysedProgram.program()); + var revEngNamespace = getRevEngAINameSpace(analysedProgram.program()); - Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() - .collect( - Collectors.toMap( - FunctionInfo::functionID, - fi -> fi - ) - ); - - - // /v3/functions/signatures is addressed by function id rather than by analysis, so ask for - // the functions this analysis reported. The response carries the types those signatures - // reference alongside them, which is what the decoders below are built from. - var signatureBatch = signatures().getMany(List.copyOf(functionInfoMap.keySet())); - Map decoders = new HashMap<>(); - Map signatureMap = signatureBatch.items() - .stream() - .filter(BatchFunctionSignatureEntry::getHasSignature) - .collect( - Collectors.toMap( - item -> new TypedApiInterface.FunctionID(item.getFunctionId()), - item -> item, - (existing, replacement) -> existing - ) - ); + Map functionInfoMap = api.getFunctionInfo(analysedProgram.analysisID()).stream() + .collect( + Collectors.toMap( + FunctionInfo::functionID, + fi -> fi + ) + ); - for (Function function : analysedProgram.program().getFunctionManager().getFunctions(true)) { - if (monitor.isCancelled()) { - continue; - } - var ghidraMangledName = function.getSymbol().getName(false); - // Skip external and thunk functions because we don't support them - if (function.isExternal() || function.isThunk()) { - Msg.debug(this, "Skipping external/thunk function %s".formatted(ghidraMangledName)); - continue; - } - var fID = analysedProgram.getIDForFunction(function); - if (fID.isEmpty()) { - Msg.info(this, "Function %s has no associated FunctionID, skipping".formatted(function.getName())); - continue; - } + // /v3/functions/signatures is addressed by function id rather than by analysis, so ask for + // the functions this analysis reported. The response carries the types those signatures + // reference alongside them, which is what the decoders below are built from. + var signatureBatch = signatures().getMany(List.copyOf(functionInfoMap.keySet())); + Map decoders = new HashMap<>(); + Map signatureMap = signatureBatch.items() + .stream() + .filter(FunctionSignatureService::hasUsableSignature) + .collect( + Collectors.toMap( + item -> new TypedApiInterface.FunctionID(item.getFunctionId()), + item -> item, + (existing, replacement) -> existing + ) + ); + + for (Function function : analysedProgram.program().getFunctionManager().getFunctions(true)) { + if (monitor.isCancelled()) { + continue; + } + var ghidraMangledName = function.getSymbol().getName(false); + // Skip external and thunk functions because we don't support them + if (function.isExternal() || function.isThunk()) { + Msg.debug(this, "Skipping external/thunk function %s".formatted(ghidraMangledName)); + continue; + } + + var fID = analysedProgram.getIDForFunction(function); + if (fID.isEmpty()) { + Msg.info(this, "Function %s has no associated FunctionID, skipping".formatted(function.getName())); + continue; + } - // Get the current name on the server side - FunctionInfo details = functionInfoMap.get(fID.get().functionID); + // Get the current name on the server side + FunctionInfo details = functionInfoMap.get(fID.get().functionID); + if (details == null) { + Msg.warn(this, "No server info for function %s, skipping".formatted(function.getName())); + continue; + } - // Extract the mangled name from Ghidra - var revEngMangledName = details.functionMangledName(); - var revEngDemangledName = details.functionName(); + // Extract the mangled name from Ghidra + var revEngMangledName = details.functionMangledName(); + var revEngDemangledName = details.functionName(); - // Skip invalid function mangled names - if (revEngMangledName.contains(" ") || revEngDemangledName.contains(" ")) { - Msg.warn(this, "Skipping renaming of function %s to invalid name %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); - continue; - } + // Skip invalid function mangled names + if (revEngMangledName.contains(" ") || revEngDemangledName.contains(" ")) { + Msg.warn(this, "Skipping renaming of function %s to invalid name %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); + continue; + } - // Get the type information on the server side. Every type the signature refers to is - // resolved by id against its analysis' decoder, so there is nothing left to fail on. - Optional functionSignatureMessageOpt = - Optional.ofNullable(signatureMap.get(fID.get().functionID)) - .map(entry -> getFunctionSignature(entry, decoderFor(decoders, signatureBatch, entry))); - - - analysedProgram.setMangledNameForFunction(function, revEngMangledName); - - /// Source types: - /// DEFAULT: placeholder name automatically assigned by Ghidra when it doesn’t know the real name. - /// ANALYSIS: A name/signature inferred by one of Ghidra’s analysis engines (or demangler) rather than simply “default.” - /// IMPORTED: Information taken from an external source — symbols or signatures imported from a file or database. - /// USER_DEFINED: A name or signature explicitly set by the analyst. - /// See {@link ghidra.program.model.symbol.SourceType} for more details - // The name and the signature are separate decisions. Gating the signature on the name - // source hid every type the portal held for a function that was already named — by the - // analyst, or by an earlier run of this same pull — and the signature apply is what - // carries the data types down. - if (functionSignatureMessageOpt.isEmpty()) { - // No signature to apply, so a rename is all that is left. Skip server-side default - // names — Ghidra's own "FUN_" and IDA's "sub_" — so we never overwrite Ghidra's - // default placeholder with an IDA-style one. - if (function.getSymbol().getSource() == SourceType.DEFAULT - && !revEngMangledName.startsWith("FUN_") && !revEngMangledName.startsWith("sub_") - && !function.getSymbol().getName(false).equals(revEngDemangledName)) { - Msg.info(this, "Renaming function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); - try { - function.setParentNamespace(revEngNamespace); - } catch (DuplicateNameException | InvalidInputException | CircularDependencyException e) { - throw new RuntimeException(e); + // Get the type information on the server side. Every type the signature refers to is + // resolved by id against its analysis' decoder, so there is nothing left to fail on. + // A signature the local one outranks is treated as absent, so the function can still + // take the portal's name below. + Optional functionSignatureMessageOpt = + Optional.ofNullable(signatureMap.get(fID.get().functionID)) + .filter(entry -> !localSignatureOutranks(function, entry)) + .map(entry -> getFunctionSignature(entry, decoderFor(decoders, signatureBatch, entry))); + + + analysedProgram.setMangledNameForFunction(function, revEngMangledName); + + /// Source types: + /// DEFAULT: placeholder name automatically assigned by Ghidra when it doesn’t know the real name. + /// ANALYSIS: A name/signature inferred by one of Ghidra’s analysis engines (or demangler) rather than simply “default.” + /// IMPORTED: Information taken from an external source — symbols or signatures imported from a file or database. + /// USER_DEFINED: A name or signature explicitly set by the analyst. + /// See {@link ghidra.program.model.symbol.SourceType} for more details + // The name and the signature are separate decisions. Gating the signature on the name + // source hid every type the portal held for a function that was already named — by the + // analyst, or by an earlier run of this same pull — and the signature apply is what + // carries the data types down. + if (functionSignatureMessageOpt.isEmpty()) { + // No signature to apply, so a rename is all that is left. Skip server-side default + // names — Ghidra's own "FUN_" and IDA's "sub_" — so we never overwrite Ghidra's + // default placeholder with an IDA-style one. + if (function.getSymbol().getSource() == SourceType.DEFAULT + && !revEngMangledName.startsWith("FUN_") && !revEngMangledName.startsWith("sub_") + && !function.getSymbol().getName(false).equals(revEngDemangledName)) { + Msg.info(this, "Renaming function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); + try { + function.setParentNamespace(revEngNamespace); + } catch (DuplicateNameException | InvalidInputException | CircularDependencyException e) { + throw new RuntimeException(e); + } + var success = new SetFunctionNameCmd(function.getEntryPoint(), revEngDemangledName, SourceType.ANALYSIS) + .applyTo(analysedProgram.program()); + if (success) { + renameResults.add(new RenameResult( + function, + ghidraMangledName, + revEngDemangledName + )); + } else { + failedRenames++; + Msg.error(this, "Failed to rename function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); + } } - var success = new SetFunctionNameCmd(function.getEntryPoint(), revEngDemangledName, SourceType.ANALYSIS) - .applyTo(analysedProgram.program()); - if (success) { + } else if (function.getSignatureSource() != SourceType.USER_DEFINED) { + // RENAME_IF_DEFAULT preserves the long-standing behaviour that applying a signature + // also names a function still carrying Ghidra's placeholder, and leaves every other + // name alone. + var application = applyRemoteSignature(analysedProgram.program(), function, + functionSignatureMessageOpt.get(), monitor, FunctionRenameOption.RENAME_IF_DEFAULT); + // For unclear reasons the signature source is not set by the command in Ghidra 11.2.x and lower + if (application.success()) { renameResults.add(new RenameResult( function, ghidraMangledName, revEngDemangledName )); } else { + Msg.error(this, "Failed to apply signature to function %s".formatted(function.getName())); failedRenames++; - Msg.error(this, "Failed to rename function %s to %s [%s]".formatted(ghidraMangledName, revEngMangledName, revEngDemangledName)); } } - } else if (function.getSignatureSource() != SourceType.USER_DEFINED) { - // RENAME_IF_DEFAULT preserves the long-standing behaviour that applying a signature - // also names a function still carrying Ghidra's placeholder, and leaves every other - // name alone. - var application = applyRemoteSignature(analysedProgram.program(), function, - functionSignatureMessageOpt.get(), monitor, FunctionRenameOption.RENAME_IF_DEFAULT); - // For unclear reasons the signature source is not set by the command in Ghidra 11.2.x and lower - if (application.success()) { - renameResults.add(new RenameResult( - function, - ghidraMangledName, - revEngDemangledName - )); - } else { - Msg.error(this, "Failed to apply signature to function %s".formatted(function.getName())); - failedRenames++; - } - } + } + } finally { + // Done iterating over all functions. A transaction that changed nothing leaves no undo entry, and + // aborting it would abort the load it runs inside too, so it is discarded only when cancelled + endServerTransaction(analysedProgram.program(), transactionId, !monitor.isCancelled()); } - // Done iterating over all functions. If nothing changed, discard the transaction, to keep undo history clean - analysedProgram.program().endTransaction(transactionId, !renameResults.isEmpty() && !monitor.isCancelled()); if (failedRenames > 0){ Msg.showError(this, null, ReaiPluginPackage.WINDOW_PREFIX + "Function Update Summary", ("Failed to update %d functions from RevEng.AI. Please check the error log for details.").formatted( @@ -935,7 +1356,18 @@ public List searchForHash(TypedApiInterface.BinaryHash hash) } public void removeProgramAssociation(Program program){ - // Clear all function ID data + clearFunctionAssociation(program); + var reaiOptions = program.getOptions(ReaiPluginPackage.REAI_OPTIONS_CATEGORY); + reaiOptions.setLong(OPTION_KEY_ANALYSIS_ID, ReaiPluginPackage.INVALID_ANALYSIS_ID); + // Clear the entire cache. Getting the correct ID is not worth the effort in terms of edge cases to handle + // because this method should still work even if the analysis ID or binary ID that was associated is invalid + statusCache.clear(); + + } + + /// Remove the function ids and the marks on the functions, but keep the analysis id, so the program is + /// known but no longer analysed. Must run inside a transaction. + private void clearFunctionAssociation(Program program) { program.getUsrPropertyManager().removePropertyMap(REAI_FUNCTION_PROP_MAP); program.getUsrPropertyManager().removePropertyMap(REAI_FUNCTION_MANGLED_MAP); @@ -947,12 +1379,6 @@ public void removeProgramAssociation(Program program){ if (revengTag != null) { revengTag.delete(); } - var reaiOptions = program.getOptions(ReaiPluginPackage.REAI_OPTIONS_CATEGORY); - reaiOptions.setLong(OPTION_KEY_ANALYSIS_ID, ReaiPluginPackage.INVALID_ANALYSIS_ID); - // Clear the entire cache. Getting the correct ID is not worth the effort in terms of edge cases to handle - // because this method should still work even if the analysis ID or binary ID that was associated is invalid - statusCache.clear(); - } /// This method is private to the service, because it only concerns itself with how the service determines @@ -1002,6 +1428,11 @@ public TypedApiInterface.BinaryHash upload(Program program) { // we have to drop the first "/" for the path to be valid filePath = Path.of(program.getExecutablePath().substring(1)); } + // The SDK only reports an unreadable file as an opaque HTTP 0, so check up front. + try (var ignored = Files.newInputStream(filePath)) { + } catch (IOException e) { + throw new RuntimeException(unreadableBinaryMessage(filePath, e), e); + } try { var hash = api.upload(filePath); if (hash.equals(hashOfProgram(program))){ @@ -1013,16 +1444,33 @@ public TypedApiInterface.BinaryHash upload(Program program) { "Hash of uploaded file %s from path %s doesn't match the hash of the program loaded in Ghidra %s" .formatted(hash, program.getExecutablePath(), hashOfProgram(program))); } - } catch (FileNotFoundException | ApiException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); + } catch (ApiException e) { + throw new RuntimeException(TypedApiImplementation.describeApiException(e), e); + } + } + + private static String unreadableBinaryMessage(Path path, IOException e) { + String reason = e instanceof NoSuchFileException ? "file not found" + : e instanceof FileSystemException fse && fse.getReason() != null ? fse.getReason() + : e.getMessage(); + String message = "Cannot read %s (%s).".formatted(path, reason); + if (Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.MAC_OS_X + && !(e instanceof NoSuchFileException)) { + message += "\n\nmacOS may be blocking Ghidra from this folder. Grant access in System Settings → " + + "Privacy & Security → Files and Folders, or move the file elsewhere and re-import it."; } + return message; } public TypedApiInterface.BinaryHash upload(Path path) { try { return api.upload(path); - } catch (FileNotFoundException | ApiException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); + } catch (ApiException e) { + throw new RuntimeException(TypedApiImplementation.describeApiException(e), e); } } @@ -1036,7 +1484,7 @@ public AnalysisStatus status(ProgramWithID program) { return api.status(program.analysisID()); } catch (ApiException e) { // This should never happen given that `ProgramWithID` guarantees a valid analysis ID - throw new RuntimeException(e); + throw new RuntimeException(TypedApiImplementation.describeApiException(e), e); } } @@ -1048,7 +1496,11 @@ public AnalysisStatus status(ProgramWithID program) { public AnalysedProgram analyse(Program program, AnalysisOptionsBuilder analysisOptionsBuilder, TaskMonitor monitor) throws CancelledException, ApiException { // Check if we are on the swing thread var programWithBinaryID = startAnalysis(program, analysisOptionsBuilder); - var finalStatus = waitForFinishedAnalysis(monitor, programWithBinaryID, null, null); + var waited = waitForAnalysis(monitor, programWithBinaryID, null, null); + if (waited.ending() != StatusPoller.Ending.DONE) { + throw new IllegalStateException("Analysis %s did not finish (%s, last status: %s)" + .formatted(programWithBinaryID.analysisID().id(), waited.ending(), waited.status())); + } // TODO: Check final status for errors, and do something appropriate on failure var analysedProgram = registerFinishedAnalysisForProgram(programWithBinaryID, monitor); if (getKnownProgram(program).isEmpty()){ @@ -1131,30 +1583,15 @@ public void openPortal(ServiceProvider serviceProvider, String... subPath) { } sb.append(s); } - openURI(serviceProvider, URI.create(sb.toString())); - } - - /// Ghidra's BrowserLoader is more reliable than java.awt.Desktop, which frequently no-ops or is - /// reported unsupported inside Ghidra's JVM. It reads the manual-viewer options off the service - /// provider, which Ghidra 12.2 made mandatory, so the tool has to be threaded this far down. - private void openURI(ServiceProvider serviceProvider, URI uri){ - try { - BrowserLoader.display(uri.toURL(), null, serviceProvider); - } catch (MalformedURLException e) { - Msg.showError( - this, - null, - "URI Opening Failed", - "Browsing to URI %s failed".formatted(uri), - e - ); - } + WebBrowser.open(URI.create(sb.toString())); } /** * @param tool The UI tool for firing an event on status changes. Can be null - * @return The final AnalysisStatus, should be either Complete or Error + * @return The final AnalysisStatus: Complete or Error when the analysis finished, Unknown when the + * server reported a status the plugin does not recognise, or the last status seen when the wait + * reached its time limit or was interrupted */ public AnalysisStatus waitForFinishedAnalysis( TaskMonitor monitor, @@ -1163,38 +1600,91 @@ public AnalysisStatus waitForFinishedAnalysis( @Nullable PluginTool tool ) throws CancelledException { - monitor.setMessage("Checking analysis status"); - // Check the status of the analysis every 500ms - // TODO: In the future this can be made smarter and e.g. wait longer if the analysis log hasn't changed - AnalysisStatus lastStatus = null; - while (true) { - AnalysisStatus currentStatus = this.status(programWithID); - if (currentStatus != AnalysisStatus.Uploaded && currentStatus != AnalysisStatus.Queued) { - // Analysis log endpoint only starts to return data after the analysis is processing - String logs = this.getAnalysisLog(programWithID.analysisID()); - if (logger != null) { - logger.consumeLogs(logs, programWithID); - } - logs.lines().reduce((first, second) -> second).ifPresent(monitor::setMessage); - } - if (currentStatus != lastStatus) { - lastStatus = currentStatus; - if (tool != null){ - tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent(null, programWithID, currentStatus)); - } - } + return waitForAnalysis(monitor, programWithID, logger, tool).status(); + } - if (lastStatus == AnalysisStatus.Complete || lastStatus == AnalysisStatus.Error) { - // Show the UI message for the completion - return lastStatus; - } + /// Like {@link #waitForFinishedAnalysis}, but also says why the wait ended, so the caller can tell + /// the user when it stopped without the analysis finishing. + /// + /// @throws CancelledException the monitor was cancelled + public StatusPoller.Result waitForAnalysis( + TaskMonitor monitor, + ProgramWithID programWithID, + @Nullable AnalysisLogConsumer logger, + @Nullable PluginTool tool + ) throws CancelledException { + monitor.setMessage("Checking analysis status"); + var poller = new StatusPoller( + Duration.ofMillis(pollIntervalMs), Duration.ofMillis(maxPollIntervalMs), Duration.ofMillis(maxAnalysisWaitMs)) + .retrying(e -> { + if (e instanceof ApiException api && isTransient(api)) { + Msg.warn(this, "Transient error polling analysis status, retrying", e); + return true; + } + return false; + }, MAX_POLL_ATTEMPTS, Duration.ofMillis(maxPollBackoffMs)); + AnalysisStatus[] lastStatus = {null}; + StatusPoller.Result result; + try { + result = poller.poll( + () -> api.status(programWithID.analysisID()), + currentStatus -> { + if (currentStatus != AnalysisStatus.Uploaded && currentStatus != AnalysisStatus.Queued) { + // Analysis log endpoint only starts to return data after the analysis is processing + try { + String logs = this.getAnalysisLog(programWithID.analysisID()); + if (logger != null) { + logger.consumeLogs(logs, programWithID); + } + logs.lines().reduce((first, second) -> second).ifPresent(monitor::setMessage); + } catch (RuntimeException e) { + // Logs are cosmetic; a failed fetch must not end the wait + Msg.warn(this, "Failed to fetch analysis logs", e); + } + } + if (currentStatus != lastStatus[0]) { + lastStatus[0] = currentStatus; + if (tool != null) { + new RevEngAIAnalysisStatusChangedEvent(RevEngAIAnalysisStatusChangedEvent.WAIT_SOURCE, programWithID, currentStatus) + .fireLater(tool); + } + } + return switch (currentStatus) { + case Complete, Error -> StatusPoller.Verdict.DONE; + case Uploaded, Queued, Processing -> StatusPoller.Verdict.WAIT; + case Unknown -> StatusPoller.Verdict.UNRECOGNISED; + }; + }, + monitor::isCancelled); + } catch (ApiException e) { + throw new RuntimeException(e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return new StatusPoller.Result<>(StatusPoller.Ending.CANCELLED, lastStatus[0], Duration.ZERO); + } + if (result.ending() == StatusPoller.Ending.CANCELLED) { monitor.checkCancelled(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - return lastStatus; - } } + if (result.ending() == StatusPoller.Ending.TIMED_OUT) { + Msg.warn(this, "Stopped waiting for analysis %s after %s; last status: %s" + .formatted(programWithID.analysisID().id(), StatusPoller.describe(result.waited()), result.status())); + } + return result; + } + + /// First wait between status polls; it grows while the status stays the same + private long pollIntervalMs = 500; + /// Longest wait between status polls while the analysis is running normally + private long maxPollIntervalMs = 5_000; + /// Longest wait between status polls while the status endpoint keeps failing transiently + private long maxPollBackoffMs = 30_000; + /// How long to wait for an analysis before giving up; it keeps running on the server + private long maxAnalysisWaitMs = Duration.ofHours(3).toMillis(); + private static final int MAX_POLL_ATTEMPTS = 10; + + /// 5xx, or no response at all (code 0: connection or timeout failure) + private static boolean isTransient(ApiException e) { + return e.getCode() == 0 || e.getCode() >= 500; } public ProgramWithID startAnalysis(Program program, AnalysisOptionsBuilder analysisOptionsBuilder) throws ApiException { @@ -1221,7 +1711,7 @@ public Map getSignatures(java.u // Create a map from FunctionID to signature for easy lookup, only where the server has one. // The same neighbour can still appear more than once in the response, so keep the first. Map signatureMap = batch.items().stream() - .filter(BatchFunctionSignatureEntry::getHasSignature) + .filter(FunctionSignatureService::hasUsableSignature) .collect(Collectors.toMap( item -> new TypedApiInterface.FunctionID(item.getFunctionId()), item -> item, @@ -1291,6 +1781,27 @@ public CompletableFuture> searchBinariesWithIds(String quer }); } + public CompletableFuture> searchUsersWithIds(String query) { + return CompletableFuture.supplyAsync(() -> { + try { + List selectableItems = api.searchUsers(query).stream() + .filter(result -> result.getUsername() != null && !result.getUsername().trim().isEmpty()) + .map(result -> new SelectableItem( + Math.toIntExact(result.getUserId()), + result.getUsername() + )) + .collect(Collectors.toList()); + + Msg.info(this, "Found " + selectableItems.size() + " users matching '" + query + "'"); + return selectableItems; + + } catch (Exception e) { + Msg.error(this, "Error searching users: " + e.getMessage(), e); + return List.of(); + } + }); + } + public AnalysisBasicInfoOutputBody getBasicDetailsForAnalysis(TypedApiInterface.AnalysisID analysisID) throws ApiException { return api.getAnalysisBasicInfo(analysisID); } @@ -1323,31 +1834,6 @@ public GetMatchesOutputBody getFunctionsMatches(List functionIds) throws A return api.getFunctionsMatches(functionIds); } - public void batchRenamingGhidraMatchesWithSignatures(List functionsList) throws ApiException { - // Pushing types to the portal is not supported yet, so we just extract the function matches and call the other method - batchRenameMatches(functionsList.stream() - .map(GhidraFunctionMatchWithSignature::functionMatch) - .toList()); - - } - - public void batchRenameMatches(List functionsList) throws ApiException { - var items = functionsList.stream() - .map(result -> { - var item = new BatchRenameItem(); - item.setFunctionId(result.origin_function_id().value()); - item.setNewName(result.nearest_neighbor_function_name()); - item.setNewMangledName(result.nearest_neighbor_mangled_function_name()); - return item; - }) - .toList(); - - var request = new BatchRenameInputBody(); - request.setFunctions(items); - api.batchRenameFunctions(request); - } - - /// Old Helper Datatype that encapsulates a Ghidra program with a binary ID and analysis ID /// This only guarantees that the program has an associated analysis, but not that the analysis is finished /// The id of this should also be stored in the program options, but this is currently not enforced yet to allow easier testing diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailure.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailure.java new file mode 100644 index 00000000..391e3997 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailure.java @@ -0,0 +1,44 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; + +import java.io.IOException; + +/// Why pushing a local edit failed, as far as it decides whether trying again can help. +public enum PushFailure { + /// The portal could not be reached or could not answer right now: no connection, a timeout, a + /// 5xx, a 408 or a 429. The same push can succeed later. + TRANSIENT, + /// The portal refused the credentials (401 or 403). Nothing succeeds until the API key is fixed. + AUTH, + /// The portal turned this particular edit down — another 4xx, or a rename it accepted but did not + /// apply — or the plugin failed to build the request. Sending it again gets the same answer. + REJECTED; + + /// Classify a failure by the first HTTP status or I/O error in its cause chain. The typed API + /// wraps some {@link ApiException}s in a plain RuntimeException, so the chain is searched rather + /// than the exception itself. + public static PushFailure of(Throwable failure) { + boolean unanswered = false; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof IOException) { + return TRANSIENT; + } + if (cause instanceof ApiException api) { + int code = api.getCode(); + if (code == 0) { + // The client reports a request that never got an answer as code 0, usually + // with the I/O error as its cause. + unanswered = true; + } else if (code == 401 || code == 403) { + return AUTH; + } else if (code == 408 || code == 429 || code >= 500) { + return TRANSIENT; + } else { + return REJECTED; + } + } + } + return unanswered ? TRANSIENT : REJECTED; + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptor.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptor.java new file mode 100644 index 00000000..a08295e7 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptor.java @@ -0,0 +1,108 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import okhttp3.Interceptor; +import okhttp3.Response; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.time.Duration; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Optional; +import java.util.Set; + +/// Retries idempotent requests that the server answered with a 5xx or a 429. +/// +/// The wait doubles from {@link #baseDelay} on each attempt, unless the response carries a +/// `Retry-After`, which wins. A `Retry-After` longer than {@link #maxDelay} is not waited out: the +/// response goes back to the caller as it is, since blocking a Ghidra task for minutes is worse than +/// failing. POST and PATCH are never retried, because the first attempt may already have taken effect. +/// +/// Installed ahead of the logging interceptor, so every attempt is logged. +public class RetryInterceptor implements Interceptor { + + private static final Set IDEMPOTENT_METHODS = Set.of("GET", "HEAD", "PUT", "DELETE", "OPTIONS"); + + /// Pauses between attempts; tests replace it so they need not sleep. + @FunctionalInterface + public interface Sleeper { + void sleep(Duration duration) throws InterruptedException; + } + + private final int maxAttempts; + private final Duration baseDelay; + private final Duration maxDelay; + private final Sleeper sleeper; + + public RetryInterceptor(int maxAttempts, Duration baseDelay, Duration maxDelay, Sleeper sleeper) { + this.maxAttempts = maxAttempts; + this.baseDelay = baseDelay; + this.maxDelay = maxDelay; + this.sleeper = sleeper; + } + + /// Four attempts, waiting 1 s, 2 s and 4 s in between, and at most 30 s for a `Retry-After`. + public static RetryInterceptor standard() { + return new RetryInterceptor(4, Duration.ofSeconds(1), Duration.ofSeconds(30), + duration -> Thread.sleep(duration.toMillis())); + } + + @Override + public Response intercept(Chain chain) throws IOException { + var request = chain.request(); + var response = chain.proceed(request); + if (!IDEMPOTENT_METHODS.contains(request.method())) { + return response; + } + for (int attempt = 1; attempt < maxAttempts && isRetryable(response.code()); attempt++) { + var delay = delayBefore(attempt, response); + if (delay.isEmpty()) { + return response; + } + response.close(); + try { + sleeper.sleep(delay.get()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Interrupted while waiting to retry " + request.url()); + } + response = chain.proceed(request); + } + return response; + } + + private static boolean isRetryable(int code) { + return code == 429 || (code >= 500 && code < 600); + } + + /// How long to wait before attempt `attempt + 1`, or empty when the server asked for longer than + /// this interceptor is willing to wait. + private Optional delayBefore(int attempt, Response response) { + var retryAfter = retryAfter(response.header("Retry-After")); + if (retryAfter.isPresent()) { + return retryAfter.get().compareTo(maxDelay) <= 0 ? retryAfter : Optional.empty(); + } + var backoff = baseDelay.multipliedBy(1L << (attempt - 1)); + return Optional.of(backoff.compareTo(maxDelay) <= 0 ? backoff : maxDelay); + } + + /// `Retry-After` is either a number of seconds or an HTTP date. + static Optional retryAfter(String header) { + if (header == null || header.isBlank()) { + return Optional.empty(); + } + var value = header.trim(); + try { + return Optional.of(Duration.ofSeconds(Math.max(0, Long.parseLong(value)))); + } catch (NumberFormatException notSeconds) { + try { + var at = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME); + var wait = Duration.between(ZonedDateTime.now(at.getZone()), at); + return Optional.of(wait.isNegative() ? Duration.ZERO : wait); + } catch (DateTimeParseException notADate) { + return Optional.empty(); + } + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java index e915caca..8cab262e 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/ServerDataTypeDecoder.java @@ -290,7 +290,7 @@ private static CategoryPath categoryPath(ServerDataType type) { if (namespace == null || namespace.isBlank()) { return CategoryPath.ROOT; } - return TypePathAndName.fromString(namespace + "::" + leafName(type)).toCategoryPath(); + return TypePathAndName.fromString(sanitise(namespace) + "::" + leafName(type)).toCategoryPath(); } private static String leafName(ServerDataType type) { @@ -298,7 +298,13 @@ private static String leafName(ServerDataType type) { if (name == null || name.isBlank()) { return "anon_%d".formatted(type.id()); } - return TypePathAndName.fromString(name).name(); + String leaf = sanitise(TypePathAndName.fromString(name).name()); + return leaf.isBlank() ? "anon_%d".formatted(type.id()) : leaf; + } + + /// Ghidra rejects names containing control characters. + private static String sanitise(String name) { + return name.replaceAll("\\p{Cntrl}", "_"); } /// Ghidra sizes are `int`; the API's are `long`. Anything that does not fit is not a real type. @@ -333,12 +339,15 @@ private static int pointerLength(@Nullable Long size) { /// Enum values stay strings on the wire because they may be negative or exceed 64 unsigned bits. /// Ghidra can only hold a `long`, so widen through {@link BigInteger} and take the low 64 bits. private static long toLong(String value) { + if (value == null) { + throw new NumberFormatException("missing value"); + } return new BigInteger(value.trim()).longValue(); } /// An exact-width filler for a type we could not build. Ghidra only has undefined1/2/4/8, so /// anything else becomes an array of undefined1 to keep the surrounding layout intact. - private static DataType undefined(long size) { + private static DataType undefined(@Nullable Long size) { long clamped = clampSize(size); if (clamped == 1 || clamped == 2 || clamped == 4 || clamped == 8) { return Undefined.getUndefinedDataType((int) clamped); diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java new file mode 100644 index 00000000..c9d15223 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPoller.java @@ -0,0 +1,180 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import javax.annotation.Nullable; +import java.time.Duration; +import java.util.Objects; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.LongSupplier; +import java.util.function.Predicate; + +/// Polls a server-side job until it reaches a final status, for every job the plugin waits on +/// (analysis, function matching, Similar Functions, AI decompilation). +/// +/// Polls start {@link #interval} apart. While the status stays the same the wait doubles, up to +/// {@link #maxInterval}; any change resets it, so an active job is followed closely and a long, +/// quiet one is not hammered. Polling always ends: when the status is final, when it is one the +/// caller does not recognise, when {@link #timeLimit} is reached, or when the caller cancels. +/// +/// A failed fetch ends polling by rethrowing its exception, unless {@link #retrying} marks it as +/// worth retrying; those back off separately, up to a number of consecutive failures. +public final class StatusPoller { + + /// What a fetched status means for the wait. + public enum Verdict { + /// Still running; poll again. + WAIT, + /// Final, whether it succeeded or failed; the caller reads which from the status. + DONE, + /// A status the caller does not model. Waiting on it could last for ever, so polling ends. + UNRECOGNISED + } + + /// Why polling ended. + public enum Ending { DONE, UNRECOGNISED, TIMED_OUT, CANCELLED } + + /// @param status the last status fetched, or null when none was + public record Result(Ending ending, @Nullable S status, Duration waited) {} + + @FunctionalInterface + public interface Fetch { + S get() throws E; + } + + @FunctionalInterface + interface Sleeper { + void sleep(long millis) throws InterruptedException; + } + + /// Longest single sleep, so a cancellation is noticed promptly even during a long backoff. + private static final long CANCEL_CHECK_MS = 200; + + private final Duration interval; + private final Duration maxInterval; + private final Duration timeLimit; + private Predicate retryable = e -> false; + private int maxConsecutiveFailures = 1; + private Duration maxRetryBackoff; + private LongSupplier nanoClock = System::nanoTime; + private Sleeper sleeper = Thread::sleep; + + public StatusPoller(Duration interval, Duration maxInterval, Duration timeLimit) { + this.interval = interval; + this.maxInterval = maxInterval.compareTo(interval) < 0 ? interval : maxInterval; + this.timeLimit = timeLimit; + this.maxRetryBackoff = this.maxInterval; + } + + /// Retry a fetch that fails with an exception {@code retryable} accepts, backing off up to + /// {@code maxBackoff}, and give up on the {@code maxConsecutiveFailures}th failure in a row. + public StatusPoller retrying(Predicate retryable, int maxConsecutiveFailures, Duration maxBackoff) { + this.retryable = retryable; + this.maxConsecutiveFailures = maxConsecutiveFailures; + this.maxRetryBackoff = maxBackoff; + return this; + } + + /// Poll until {@code classify} reports a final or unrecognised status, the time limit is reached + /// or {@code cancelled} turns true. {@code classify} sees every fetched status exactly once, in + /// order, so it may also act on them (update the UI, trigger a follow-up step). + /// + /// @throws E the fetch failed, and was not retryable or failed too often in a row + /// @throws InterruptedException the polling thread was interrupted while waiting + /// Use {@code nanoClock} and {@code sleeper} instead of the system clock, so tests can check the + /// waits without depending on how fast the machine runs. + StatusPoller withClock(LongSupplier nanoClock, Sleeper sleeper) { + this.nanoClock = nanoClock; + this.sleeper = sleeper; + return this; + } + + public Result poll(Fetch fetch, Function classify, + BooleanSupplier cancelled) throws E, InterruptedException { + long start = nanoClock.getAsLong(); + S last = null; + boolean fetched = false; + long delay = interval.toMillis(); + long retryDelay = interval.toMillis(); + int failures = 0; + while (true) { + if (cancelled.getAsBoolean()) { + return result(Ending.CANCELLED, last, start); + } + S current; + try { + current = fetch.get(); + failures = 0; + retryDelay = interval.toMillis(); + } catch (Exception e) { + if (!retryable.test(e) || ++failures >= maxConsecutiveFailures) { + throw e; + } + if (!sleepWithinLimit(retryDelay, start, cancelled)) { + return result(cancelled.getAsBoolean() ? Ending.CANCELLED : Ending.TIMED_OUT, last, start); + } + retryDelay = Math.min(retryDelay * 2, maxRetryBackoff.toMillis()); + continue; + } + + if (fetched && Objects.equals(current, last)) { + delay = Math.min(delay * 2, maxInterval.toMillis()); + } else { + delay = interval.toMillis(); + } + last = current; + fetched = true; + + switch (classify.apply(current)) { + case DONE -> { + return result(Ending.DONE, current, start); + } + case UNRECOGNISED -> { + return result(Ending.UNRECOGNISED, current, start); + } + case WAIT -> { + if (!sleepWithinLimit(delay, start, cancelled)) { + return result(cancelled.getAsBoolean() ? Ending.CANCELLED : Ending.TIMED_OUT, last, start); + } + } + } + } + } + + public Duration timeLimit() { + return timeLimit; + } + + /// Sleep for {@code millis}, in short steps so a cancellation cuts it short. + /// + /// @return false, without sleeping, if the sleep would run past the time limit; false if + /// cancelled while sleeping; true otherwise + private boolean sleepWithinLimit(long millis, long start, BooleanSupplier cancelled) throws InterruptedException { + long elapsed = (nanoClock.getAsLong() - start) / 1_000_000; + if (elapsed + millis > timeLimit.toMillis()) { + return false; + } + long deadline = nanoClock.getAsLong() + millis * 1_000_000; + long remaining; + while ((remaining = (deadline - nanoClock.getAsLong()) / 1_000_000) > 0) { + if (cancelled.getAsBoolean()) { + return false; + } + sleeper.sleep(Math.min(remaining, CANCEL_CHECK_MS)); + } + return !cancelled.getAsBoolean(); + } + + private Result result(Ending ending, @Nullable S status, long start) { + return new Result<>(ending, status, Duration.ofNanos(nanoClock.getAsLong() - start)); + } + + /// "3 hours" / "30 minute(s)" / "45 second(s)", rounded, for messages that say how long the plugin + /// waited. A wait that hit its time limit stops just short of it, so it is rounded to the nearest unit. + public static String describe(Duration duration) { + long seconds = duration.toSeconds(); + if (seconds >= 2 * 3600) { + return Math.round(seconds / 3600.0) + " hours"; + } + return seconds >= 60 ? Math.round(seconds / 60.0) + " minute(s)" : seconds + " second(s)"; + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDns.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDns.java new file mode 100644 index 00000000..e384e01e --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDns.java @@ -0,0 +1,49 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import okhttp3.Dns; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/// A {@link Dns} that gives up on a lookup after {@code timeout}. +/// +/// OkHttp's connect timeout only starts once an address is resolved. Without a working network +/// the system resolver can block for far longer than that, so every request, and any thread +/// waiting on one, hangs until the OS gives up on DNS. +public record TimeoutDns(Dns delegate, Duration timeout) implements Dns { + + private static final ExecutorService RESOLVER = Executors.newCachedThreadPool(runnable -> { + var thread = new Thread(runnable, "RevEng.AI-DNS"); + thread.setDaemon(true); + return thread; + }); + + @Override + public List lookup(String hostname) throws UnknownHostException { + var lookup = RESOLVER.submit(() -> delegate.lookup(hostname)); + try { + return lookup.get(timeout.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + lookup.cancel(true); + throw new UnknownHostException("DNS lookup for %s timed out after %ds".formatted(hostname, timeout.toSeconds())); + } catch (ExecutionException e) { + if (e.getCause() instanceof UnknownHostException unknownHost) { + throw unknownHost; + } + var unknownHost = new UnknownHostException("DNS lookup for %s failed".formatted(hostname)); + unknownHost.initCause(e.getCause()); + throw unknownHost; + } catch (InterruptedException e) { + lookup.cancel(true); + Thread.currentThread().interrupt(); + throw new UnknownHostException("DNS lookup for %s was interrupted".formatted(hostname)); + } + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java index 76c7cffb..ea5256f4 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiImplementation.java @@ -20,10 +20,11 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.time.Duration; import java.util.*; import java.util.stream.Collectors; -import ai.reveng.invoker.Configuration; +import ai.reveng.invoker.ApiClient; import ai.reveng.invoker.JSON; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -31,6 +32,7 @@ import com.google.gson.JsonParser; import ai.reveng.invoker.auth.ApiKeyAuth; import ai.reveng.invoker.ApiException; +import okhttp3.Dns; import static ai.reveng.toolkit.ghidra.core.services.api.LoggingInterceptor.*; @@ -58,13 +60,59 @@ public class TypedApiImplementation implements TypedApiInterface { private final FunctionsAiDecompilationApi functionsAiDecompilationApi; private final DataTypesApi dataTypesApi; private final IamUsersApi iamUsersApi; + private final AuthenticationUsersApi authenticationUsersApi; private final Map analysisBasicInfoCache = new HashMap<>(); + private final ApiClient apiClient; + private final ApiClient uploadClient; + private final BinariesApi uploadApi; + + /// Ordinary requests: a page of functions or a batch of signatures, which the server answers quickly. + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(15); + + /// Uploading a large binary, and the server hashing and storing it before it answers, takes far + /// longer than any other request. + private static final Duration UPLOAD_TIMEOUT = Duration.ofMinutes(5); + + /// Every instance owns its client. The SDK's default client is process-global, so configuring it + /// here let the setup wizard's throwaway validation instance re-target the running session, and + /// stacked one more logging interceptor onto it per instance. public TypedApiImplementation(String baseUrl, String apiKey) { - var apiClient = Configuration.getDefaultApiClient(); - apiClient.setBasePath(baseUrl); + var userAgent = userAgent(); + var apiClient = newClient(baseUrl, apiKey, userAgent, REQUEST_TIMEOUT); + this.apiClient = apiClient; + this.uploadClient = newClient(baseUrl, apiKey, userAgent, UPLOAD_TIMEOUT); + this.uploadApi = new BinariesApi(uploadClient); + + this.analysisCoreApi = new AnalysesCoreApi(apiClient); + this.searchApi = new SearchApi(apiClient); + this.collectionsApi = new CollectionsApi(apiClient); + this.functionsCoreApi = new FunctionsCoreApi(apiClient); + this.functionsRenamingHistoryApi = new FunctionsRenamingHistoryApi(apiClient); + this.functionsAiDecompilationApi = new FunctionsAiDecompilationApi(apiClient); + this.dataTypesApi = new DataTypesApi(apiClient); + this.configApi = new ConfigApi(apiClient); + this.iamUsersApi = new IamUsersApi(apiClient); + this.authenticationUsersApi = new AuthenticationUsersApi(apiClient); + } + + public TypedApiImplementation(ApiInfo info){ + this(info.hostURI().toString(), info.apiKey()); + } + + /// The configured client this instance talks through, for SDK APIs it does not wrap. + public ApiClient apiClient() { + return apiClient; + } + + /// The client uploads go through, with a longer timeout than {@link #apiClient()}. + ApiClient uploadClient() { + return uploadClient; + } + + private static String userAgent() { String pluginVersion = "unknown"; try { // This file comes from the release.yml running in the CI @@ -78,36 +126,32 @@ public TypedApiImplementation(String baseUrl, String apiKey) { } // Looks like: // Ghidra/11.3.2-PUBLIC (LINUX(Linux) X86_64(amd64)) RevEng.AI_Plugin/v0.15 - var userAgent = "%s/%s-%s (%s) RevEng.AI_Plugin/%s".formatted(Application.getName(), Application.getApplicationVersion(), Platform.CURRENT_PLATFORM, Application.getApplicationReleaseName(), pluginVersion); + return "%s/%s-%s (%s) RevEng.AI_Plugin/%s".formatted(Application.getName(), Application.getApplicationVersion(), Platform.CURRENT_PLATFORM, Application.getApplicationReleaseName(), pluginVersion); + } + private static ApiClient newClient(String baseUrl, String apiKey, String userAgent, Duration timeout) { + var apiClient = new ApiClient(); + apiClient.setBasePath(baseUrl); apiClient.setUserAgent(userAgent); apiClient.addDefaultHeader("X-RevEng-Application", userAgent); // Use a custom HTTP client to add Ghidra specific logging // Set withResponseBody to true if debugging issues with the API to see the full response body - apiClient.setHttpClient(apiClient.getHttpClient().newBuilder().addInterceptor(ghidraLogger(false)).build()); + // Bound DNS too: the connect timeout below doesn't cover it, and offline it can hang for minutes + // Retry sits ahead of the logger so that every attempt is logged + apiClient.setHttpClient(apiClient.getHttpClient().newBuilder() + .addInterceptor(RetryInterceptor.standard()) + .addInterceptor(ghidraLogger(false)) + .dns(new TimeoutDns(Dns.SYSTEM, Duration.ofSeconds(5))) + .build()); apiClient.setConnectTimeout(5000); - apiClient.setReadTimeout(15000); - apiClient.setWriteTimeout(15000); + apiClient.setReadTimeout(Math.toIntExact(timeout.toMillis())); + apiClient.setWriteTimeout(Math.toIntExact(timeout.toMillis())); ApiKeyAuth APIKey = (ApiKeyAuth) apiClient.getAuthentication("APIKey"); APIKey.setApiKey(apiKey); - - this.analysisCoreApi = new AnalysesCoreApi(apiClient); - this.searchApi = new SearchApi(apiClient); - this.collectionsApi = new CollectionsApi(apiClient); - this.functionsCoreApi = new FunctionsCoreApi(apiClient); - this.functionsRenamingHistoryApi = new FunctionsRenamingHistoryApi(apiClient); - this.functionsAiDecompilationApi = new FunctionsAiDecompilationApi(apiClient); - this.dataTypesApi = new DataTypesApi(apiClient); - this.configApi = new ConfigApi(apiClient); - this.iamUsersApi = new IamUsersApi(apiClient); - } - - - public TypedApiImplementation(ApiInfo info){ - this(info.hostURI().toString(), info.apiKey()); + return apiClient; } public BinaryHash upload(Path binPath) throws FileNotFoundException, ApiException { @@ -116,9 +160,12 @@ public BinaryHash upload(Path binPath) throws FileNotFoundException, ApiExceptio if (!bin.exists()) throw new FileNotFoundException("Binary to upload does not exist"); - var result = this.analysisCoreApi.uploadFile(UploadFileType.fromValue("BINARY"), bin, null, true); + var result = this.uploadApi.v3UploadFile(bin, "BINARY", true); - return new BinaryHash(result.getData().getSha256Hash()); + if (result.getSha256Hash() == null) { + throw new ApiException("Upload response carried no hash"); + } + return new BinaryHash(result.getSha256Hash()); } /// GET /v3/analyses, filtered to one binary hash and paged to exhaustion. @@ -150,16 +197,30 @@ public List search(BinaryHash hash) { return results; } + /// POST /v3/analyses + /// + /// Answers with a long-running operation: the analysis id rides on its metadata while pending + /// and on its response once done. @Override public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { var analysisRequest = options.toAnalysisCreateRequest(); - var result = this.analysisCoreApi.createAnalysis(analysisRequest, null); - return new AnalysisID(result.getData().getAnalysisId()); + var operation = this.analysisCoreApi.v3CreateAnalysis(analysisRequest, null); + Long analysisId = operation.getMetadata() != null ? operation.getMetadata().getAnalysisId() : null; + if (analysisId == null && operation.getResponse() != null) { + analysisId = operation.getResponse().getAnalysisId(); + } + if (analysisId == null) { + throw new ApiException("Create-analysis operation " + operation.getName() + " carried no analysis id"); + } + return new AnalysisID(Math.toIntExact(analysisId)); } @Override public AnalysisStatus status(AnalysisID analysisID) throws ApiException { var status = analysisCoreApi.getAnalysisStatus(analysisID.id()); + if (status.getData() == null) { + throw new ApiException("Analysis status response carried no data"); + } return AnalysisStatus.fromApiValue(status.getData().getAnalysisStatus()); } @@ -193,8 +254,11 @@ public List getFunctionInfo(AnalysisID analysisID) { new FunctionID(f.getFunctionId()), f.getFunctionName(), // The mangled name is optional here; an unmangled symbol carries none, - // and callers rely on this field being populated. - f.getMangledName() != null ? f.getMangledName() : f.getFunctionName(), + // and callers rely on this field being populated. The server also sends + // it as "" rather than leaving it out, which would otherwise slip past + // the FUN_/sub_ guard on renames. + f.getMangledName() == null || f.getMangledName().isBlank() + ? f.getFunctionName() : f.getMangledName(), f.getFunctionVaddr(), Math.toIntExact(f.getFunctionSize()) ) @@ -286,7 +350,7 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID } return new FunctionSignatureBatch(items, dataTypes); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -302,7 +366,7 @@ public List listAnalysisDataTypes(AnalysisID analysisID, long of return ServerDataTypeReader.readEntries( executeForJsonObject(call, "list analysis data types"), "items"); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -350,7 +414,7 @@ public List getFunctionSignatureHistory(AnalysisID ana .getVersions(); return versions == null ? List.of() : versions; } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -359,7 +423,8 @@ private static JsonObject executeForJsonObject(okhttp3.Call call, String what) t okhttp3.ResponseBody responseBody = response.body(); String text = responseBody == null ? "" : responseBody.string(); if (!response.isSuccessful()) { - throw new ApiException(response.code(), "Failed to %s: HTTP %d".formatted(what, response.code())); + throw new ApiException("Failed to %s: HTTP %d".formatted(what, response.code()), + response.code(), response.headers().toMultimap(), text); } JsonElement parsed = JsonParser.parseString(text); if (!parsed.isJsonObject()) { @@ -456,12 +521,12 @@ public AIDecompilationStatus pollAIDecompileStatus(FunctionID functionID) { inlineComments, decompilationProgress); } catch (ApiException e) { + // A function that was never decompiled is a 200 with status UNINITIALISED; a 404 means the + // function itself was not found, and treating it as "not started yet" polled for ever. if (e.getCode() == 404) { - return new AIDecompilationStatus( - DecompilationData.StatusEnum.UNINITIALISED, - null, null, null, null, null, List.of(), null); + throw new RuntimeException("RevEng.AI could not find function %d (HTTP 404)".formatted(functionID.value()), e); } - throw new RuntimeException("Failed to poll AI decompilation status", e); + throw new RuntimeException("Failed to poll AI decompilation status: " + describeApiException(e), e); } } @@ -513,10 +578,20 @@ public void deleteAIDecompilationInlineComment(FunctionID functionID, long line) functionsAiDecompilationApi.deleteAiDecompilationInlineComment(functionID.value(), line); } - private static String describeApiException(ApiException e) { - // The SDK's ApiException carries the HTTP status and response body separately from the message; - // surface both so callers logging only getMessage() can still diagnose server-side failures. - return "HTTP " + e.getCode() + " — " + (e.getResponseBody() != null ? e.getResponseBody() : e.getMessage()); + /// The status and the server's `error.message`, falling back to the raw body, then the exception's + /// own message. {@link ApiException#getMessage()} itself dumps the body and every header. + public static String describeApiException(ApiException e) { + String body = e.getResponseBody(); + String detail = body != null && !body.isBlank() ? body : e.getMessage(); + try { + JsonElement message = JsonParser.parseString(body).getAsJsonObject() + .getAsJsonObject("error").get("message"); + if (message != null && message.isJsonPrimitive() && !message.getAsString().isBlank()) { + detail = message.getAsString(); + } + } catch (RuntimeException ignored) { + } + return "HTTP " + e.getCode() + " — " + detail; } /// POST /v3/functions/rename, with a one-item body: v3 has no per-function rename route. @@ -534,7 +609,7 @@ public void renameFunction(FunctionID id, String newName, String newNameMangled) try { response = functionsRenamingHistoryApi.batchRenameFunctions(request); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } Long renamedCount = response == null ? null : response.getRenamedCount(); if (renamedCount == null || renamedCount < 1) { @@ -548,7 +623,7 @@ public FunctionDetails getFunctionDetails(FunctionID id) { try { return FunctionDetails.fromServerResponse(functionsCoreApi.getFunctionDetails_0(id.value())); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -593,6 +668,12 @@ public List searchBinaries(String partialBinaryName, String return this.searchApi.searchBinaries(1, 10, partialBinaryName, null, null, modelName, null, null, null).getData().getResults(); } + @Override + public List searchUsers(String searchTerm) throws ApiException { + var results = this.authenticationUsersApi.v3ListUsers(searchTerm).getResults(); + return results != null ? results : List.of(); + } + @Override public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(AnalysisID analysisID) throws ApiException { AnalysisBasicInfoOutputBody cachedResult = analysisBasicInfoCache.get(analysisID); @@ -640,8 +721,10 @@ public GetMatchesOutputBody getFunctionsMatches(List functionIds) throws A } @Override - public void batchRenameFunctions(BatchRenameInputBody request) throws ApiException { - this.functionsRenamingHistoryApi.batchRenameFunctions(request); + public long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + var response = this.functionsRenamingHistoryApi.batchRenameFunctions(request); + Long renamedCount = response == null ? null : response.getRenamedCount(); + return renamedCount == null ? 0 : renamedCount; } /// GET /v3/functions/{function_id}/blocks @@ -657,7 +740,7 @@ public List getAssembly(FunctionID id) { DisassemblyOutputBody disassembly = this.functionsCoreApi.getFunctionBlocks_0(id.value()); return DisassemblyBlocksReader.readAssembly(disassembly.getBasicBlocks()); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @@ -688,16 +771,16 @@ public ConfigResponse getConfig() { try { return this.configApi.getConfig().getData(); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } @Override - public User getMe() { + public CurrentUser getMe() { try { return this.iamUsersApi.getMe(); } catch (ApiException e) { - throw new RuntimeException(e); + throw new RuntimeException(describeApiException(e), e); } } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java index 789ab84e..4a87aba1 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/TypedApiInterface.java @@ -209,6 +209,10 @@ default List searchBinaries(String partialCollectionName, St throw new UnsupportedOperationException("searchBinaries not implemented yet"); } + default List searchUsers(String searchTerm) throws ApiException { + throw new UnsupportedOperationException("searchUsers not implemented yet"); + } + default AnalysisBasicInfoOutputBody getAnalysisBasicInfo(AnalysisID analysisID) throws ApiException { throw new UnsupportedOperationException("getAnalysisBasicInfo not implemented yet"); } @@ -237,7 +241,9 @@ default GetMatchesOutputBody getFunctionsMatches(List functionIds) throws throw new UnsupportedOperationException("getFunctionsMatches not implemented yet"); } - default void batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + /// Answers with the number of functions the server actually renamed, which can be fewer than were + /// asked for even though the request succeeded. + default long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { throw new UnsupportedOperationException("batchRenameFunctions not implemented yet"); } @@ -249,7 +255,7 @@ default ConfigResponse getConfig() throws ApiException { throw new UnsupportedOperationException("getConfig not implemented yet"); } - default User getMe() throws ApiException { + default CurrentUser getMe() throws ApiException { throw new UnsupportedOperationException("getMe not implemented yet"); } } diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java new file mode 100644 index 00000000..86f59f13 --- /dev/null +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/UnresolvedDataTypesException.java @@ -0,0 +1,48 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import java.util.Set; + +/// A function's types could not all be given a portal id, so its signature was not written. +/// +/// Sending the signature anyway would name the missing types as null, and the portal replaces a +/// stored signature in full, so it would lose the types it had. The edit is held back instead and +/// stays unpushed. {@link PushFailure} classifies this as {@link PushFailure#REJECTED}: sending the +/// same edit again gets the same answer. +public final class UnresolvedDataTypesException extends Exception { + + private final Set typeNames; + private final boolean pastClosureLimit; + + /// @param typeNames the types the function reaches that could not be written in full + /// @param pastClosureLimit whether the function reaches more types than + /// {@link GhidraDataTypeEncoder#MAX_TYPES}, which is then the cause + /// rather than the portal + public UnresolvedDataTypesException(Set typeNames, boolean pastClosureLimit) { + super(pastClosureLimit ? describeLimit() : describe(typeNames)); + this.typeNames = Set.copyOf(typeNames); + this.pastClosureLimit = pastClosureLimit; + } + + public Set typeNames() { + return typeNames; + } + + public boolean pastClosureLimit() { + return pastClosureLimit; + } + + private static String describeLimit() { + return ("it reaches more than %d data types, the most the plugin pushes for one function, so " + + "the signature was not sent").formatted(GhidraDataTypeEncoder.MAX_TYPES); + } + + private static String describe(Set typeNames) { + final int shown = 5; + String names = typeNames.stream().limit(shown).map("\"%s\""::formatted) + .collect(java.util.stream.Collectors.joining(", ")); + if (typeNames.size() > shown) { + names += " and %d more".formatted(typeNames.size() - shown); + } + return "no portal id for the data type(s) %s, so the signature was not sent".formatted(names); + } +} diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java index 372628ca..72219ee3 100644 --- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java +++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/api/datatypes/ServerDataTypeReader.java @@ -7,6 +7,7 @@ import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** * Reads the spec's {@code DataTypeEntry} JSON straight into the flattened {@link ServerDataType}, @@ -60,7 +61,9 @@ public static List readEntries(JsonElement body, String field) { } List entries = new ArrayList<>(); for (JsonElement entry : array.getAsJsonArray()) { - entries.add(readEntry(entry)); + if (!entry.isJsonNull()) { + entries.add(readEntry(entry)); + } } return entries; } @@ -108,7 +111,7 @@ private static List list(JsonObject owner, String field, Type type, JsonD return List.of(); } List 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 echo(CreateAnalysisDataTypesInputBody request, LongSupplier nextId) { + return echo(request, nextId, name -> true); + } + + /// As {@link #echo(CreateAnalysisDataTypesInputBody, LongSupplier)}, but leaving out the types + /// whose name `created` rejects, the way a server that will not create a type answers. + static List echo(CreateAnalysisDataTypesInputBody request, LongSupplier nextId, + Predicate created) { + return request.getDataTypes().stream() + .map(entry -> (Object) entry.getActualInstance()) + .filter(instance -> created.test(string(instance, "getName"))) + .map(instance -> new ServerDataType(nextId.getAsLong(), string(instance, "getNamespace"), + string(instance, "getName"), + ServerDataType.Kind.fromJson(string(instance, "getKind")), + null, "USER", false, null, null, null)) + .toList(); + } + + private static String string(Object target, String method) { + try { + Object value = target.getClass().getMethod(method).invoke(target); + return value == null ? null : value.toString(); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/ai/reveng/DetachDuringAnalysisTest.java b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java new file mode 100644 index 00000000..091fcad0 --- /dev/null +++ b/src/test/java/ai/reveng/DetachDuringAnalysisTest.java @@ -0,0 +1,219 @@ +package ai.reveng; + +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.misc.AnalysisLogComponent; +import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisResultsLoaded; +import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +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.AnalysisManagementPlugin; +import docking.widgets.OptionDialog; +import ghidra.app.services.ProgramManager; +import ghidra.framework.plugintool.PluginTool; +import ghidra.program.model.listing.Program; +import ghidra.util.task.Task; +import ghidra.util.task.TaskMonitorComponent; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; + +/// Detaching or closing a program while its analysis is still being waited on (ENG-4590) +public class DetachDuringAnalysisTest extends RevEngMockableHeadedIntegrationTest { + + private static final TypedApiInterface.AnalysisID OLD = new TypedApiInterface.AnalysisID(1); + private static final TypedApiInterface.AnalysisID NEW = new TypedApiInterface.AnalysisID(2); + + /// Analyses stay Processing until marked finished; function info requests are recorded + private static class RunningAnalysesAPI extends UnimplementedAPI { + final Set finished = ConcurrentHashMap.newKeySet(); + final Map statusCalls = new ConcurrentHashMap<>(); + final AtomicInteger functionInfoCalls = new AtomicInteger(); + /// Holds function info requests until released, when set + volatile CountDownLatch functionInfoGate; + + int statusCalls(AnalysisID id) { + return statusCalls.computeIfAbsent(id, k -> new AtomicInteger()).get(); + } + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.computeIfAbsent(analysisID, k -> new AtomicInteger()).incrementAndGet(); + return finished.contains(analysisID) ? AnalysisStatus.Complete : AnalysisStatus.Processing; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + return "logs of analysis " + analysisID.id(); + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + functionInfoCalls.incrementAndGet(); + var gate = functionInfoGate; + if (gate != null) { + try { + gate.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + return List.of(); + } + } + + private record Fixture(PluginTool tool, GhidraRevengService service, RunningAnalysesAPI api, Program program, + AnalysisLogComponent logComponent) { + + @SuppressWarnings("unchecked") + Map trackedPrograms() { + return (Map) getInstanceField("trackedPrograms", logComponent); + } + + /// The analysis the program's wait is for, or empty when nothing waits for it + Optional monitoredAnalysis() { + return Optional.ofNullable(trackedPrograms().get(program)) + .map(task -> (GhidraRevengService.ProgramWithID) getInstanceField("program", task)); + } + + /// As StartAnalysisTask does: attach the program, then report the analysis as queued + GhidraRevengService.ProgramWithID startAnalysis(TypedApiInterface.AnalysisID id) { + var programWithID = service.registerAnalysisForProgram(program, id); + runSwing(() -> tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued))); + return programWithID; + } + + void stopAllWaits() { + ((TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent)).cancel(); + waitForTasks(); + } + } + + private Fixture fixture() throws Exception { + var tool = env.getTool(); + var api = new RunningAnalysesAPI(); + var service = addMockedService(tool, api); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + var logComponent = (AnalysisLogComponent) tool.getComponentProvider(AnalysisLogComponent.NAME); + return new Fixture(tool, service, api, program, logComponent); + } + + /// Detach through the menu action and its confirmation, as the analyst does + private void detach(Fixture fixture) { + performAction(getAction(fixture.tool(), "Detach"), false); + pressButtonByText(awaitDialog(OptionDialog.class), "Detach"); + waitForSwing(); + assertTrue(fixture.service().getKnownProgram(fixture.program()).isEmpty()); + } + + private static boolean hasFunctionIds(Program program) { + return program.getUsrPropertyManager().getLongPropertyMap("RevEngAI_FunctionID_Map") != null; + } + + /// Detach stops the wait for the old analysis, and its Complete arriving late loads nothing into the + /// program, which is now attached to another analysis + @Test + public void testLateCompleteAfterDetachIsIgnored() throws Exception { + var fixture = fixture(); + var old = fixture.startAnalysis(OLD); + waitForCondition(() -> fixture.api().statusCalls(OLD) > 0, "the old analysis should be waited on"); + var resultsLoaded = new AtomicBoolean(); + fixture.tool().addEventListener(RevEngAIAnalysisResultsLoaded.class, e -> resultsLoaded.set(true)); + + detach(fixture); + waitForCondition(() -> fixture.monitoredAnalysis().isEmpty(), "detaching should stop the wait"); + // Attached to another analysis, e.g. through Attach to existing + var current = fixture.service().registerAnalysisForProgram(fixture.program(), NEW); + + // The old analysis now finishes, and its Complete arrives from a wait that had not noticed the detach yet + fixture.api().finished.add(OLD); + runSwing(() -> fixture.tool().firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent(null, old, AnalysisStatus.Complete))); + waitForTasks(); + waitForSwing(); + + assertEquals("the old analysis' results should not be fetched", 0, fixture.api().functionInfoCalls.get()); + assertFalse("no function ids should be written", hasFunctionIds(fixture.program())); + assertFalse(resultsLoaded.get()); + assertEquals(Optional.of(current), fixture.service().getKnownProgram(fixture.program())); + } + + /// Detach while the finished analysis' results are being fetched: the load writes nothing and reports no failure + @Test + public void testDetachDuringResultsLoadWritesNothing() throws Exception { + var fixture = fixture(); + var gate = new CountDownLatch(1); + fixture.api().functionInfoGate = gate; + fixture.startAnalysis(OLD); + var resultsLoaded = new AtomicBoolean(); + fixture.tool().addEventListener(RevEngAIAnalysisResultsLoaded.class, e -> resultsLoaded.set(true)); + + // The analysis finishes, and its wait starts loading the results + fixture.api().finished.add(OLD); + waitForCondition(() -> fixture.api().functionInfoCalls.get() > 0, "the results should start loading"); + + detach(fixture); + var current = fixture.service().registerAnalysisForProgram(fixture.program(), NEW); + gate.countDown(); + waitForTasks(); + waitForSwing(); + + assertFalse("no function ids should be written", hasFunctionIds(fixture.program())); + assertFalse(resultsLoaded.get()); + assertEquals(Optional.of(current), fixture.service().getKnownProgram(fixture.program())); + assertTrue("an abandoned load is not a failed one", + ((Set) getInstanceField("failedLoads", getPlugin(fixture.tool(), AnalysisManagementPlugin.class))).isEmpty()); + } + + /// After Detach, a new analysis of the same program is waited on + @Test + public void testNewAnalysisAfterDetachIsMonitored() throws Exception { + var fixture = fixture(); + fixture.startAnalysis(OLD); + waitForCondition(() -> fixture.monitoredAnalysis().isPresent(), "the old analysis should be waited on"); + + detach(fixture); + var oldCalls = fixture.api().statusCalls(OLD); + var next = fixture.startAnalysis(NEW); + + assertEquals(Optional.of(next), fixture.monitoredAnalysis()); + waitForCondition(() -> fixture.api().statusCalls(NEW) > 0, "the new analysis should be polled"); + // Polling continues for the new analysis only + waitForCondition(() -> fixture.api().statusCalls(NEW) > 1, "the new analysis should keep being polled"); + assertTrue(fixture.api().statusCalls(OLD) <= oldCalls + 1); + + fixture.stopAllWaits(); + assertTrue(fixture.monitoredAnalysis().isEmpty()); + } + + /// Closing the program stops the wait, and forgets the program's logs + @Test + public void testClosingProgramStopsMonitoring() throws Exception { + var fixture = fixture(); + fixture.startAnalysis(OLD); + waitForCondition(() -> fixture.logComponent().getStoredLogs(fixture.program()) != null, + "the analysis logs should arrive"); + + runSwing(() -> fixture.tool().getService(ProgramManager.class).closeProgram(fixture.program(), true)); + waitForTasks(); + + assertTrue(fixture.trackedPrograms().isEmpty()); + assertNull(fixture.logComponent().getStoredLogs(fixture.program())); + var calls = fixture.api().statusCalls(OLD); + sleep(500); + assertEquals("the closed program's analysis should no longer be polled", calls, fixture.api().statusCalls(OLD)); + } +} diff --git a/src/test/java/ai/reveng/ForkTempDir.java b/src/test/java/ai/reveng/ForkTempDir.java new file mode 100644 index 00000000..b583641d --- /dev/null +++ b/src/test/java/ai/reveng/ForkTempDir.java @@ -0,0 +1,32 @@ +package ai.reveng; + +import org.junit.platform.launcher.LauncherSession; +import org.junit.platform.launcher.LauncherSessionListener; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; + +/// Gives each test JVM its own Ghidra temp dir. Ghidra clears and restores write permission on that +/// dir whenever a JVM initialises, so forks sharing one fail file creation with "Permission denied". +public class ForkTempDir implements LauncherSessionListener { + + static final String PROPERTY = "application.tempdir"; + + @Override + public void launcherSessionOpened(LauncherSession session) { + if (System.getProperty(PROPERTY) != null) { + return; + } + try { + String root = System.getProperty("reveng.test.fork.tmproot"); + var dir = root == null + ? Files.createTempDirectory("ghidra-test-fork") + : Files.createTempDirectory(Path.of(root), "fork"); + System.setProperty(PROPERTY, dir.toString()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/src/test/java/ai/reveng/ForkTempDirTest.java b/src/test/java/ai/reveng/ForkTempDirTest.java new file mode 100644 index 00000000..d5bc7623 --- /dev/null +++ b/src/test/java/ai/reveng/ForkTempDirTest.java @@ -0,0 +1,24 @@ +package ai.reveng; + +import ghidra.framework.Application; +import ghidra.test.AbstractGhidraHeadlessIntegrationTest; +import org.junit.Test; + +import java.io.File; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/// Ghidra briefly drops write permission on its user temp dir whenever a JVM starts, so parallel +/// test forks sharing one dir fail to create files at random. Each fork must get its own. +public class ForkTempDirTest extends AbstractGhidraHeadlessIntegrationTest { + + @Test + public void ghidraTempDirIsPrivateToThisFork() { + String forkTempDir = System.getProperty("application.tempdir"); + assertNotNull("per-fork temp dir must be set", forkTempDir); + File userTempDir = Application.getUserTempDirectory(); + assertTrue(userTempDir + " should be under " + forkTempDir, + userTempDir.toPath().startsWith(new File(forkTempDir).toPath())); + } +} diff --git a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java index 50a7f74b..97e69164 100644 --- a/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java +++ b/src/test/java/ai/reveng/FunctionLevelFunctionMatchingDialogTest.java @@ -1,22 +1,34 @@ package ai.reveng; import ai.reveng.model.*; +import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; +import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.AbstractFunctionMatchingDialog; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.functionmatching.FunctionLevelFunctionMatchingDialog; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.AnalysisOptionsBuilder; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; 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.core.services.api.types.FunctionMatch; import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; import ai.reveng.toolkit.ghidra.plugins.BinarySimilarityPlugin; +import docking.AbstractErrDialog; import docking.DockingWindowManager; import ghidra.program.model.data.Undefined; +import ghidra.program.model.symbol.SourceType; import ghidra.util.task.TaskMonitor; -import ghidra.util.task.TaskMonitorComponent; import org.junit.Test; import javax.swing.*; +import generic.theme.GColor; +import java.math.BigDecimal; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; @@ -51,7 +63,7 @@ public void testDialogOpensWithMockedService() throws Exception { // Create and show the dialog FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -98,7 +110,7 @@ public void testDialogHasResultsTableConfigured() throws Exception { // Create the dialog FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -133,7 +145,7 @@ public void testAssemblyComparisonPanelExists() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -150,6 +162,47 @@ public void testAssemblyComparisonPanelExists() throws Exception { waitForSwing(); } + @Test + public void testUserSubmittedDebugSymbolsAlwaysVisibleAndEnabledByParent() throws Exception { + var tool = env.getTool(); + + var mockApi = new FunctionMatchingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JCheckBox debugSymbols = (JCheckBox) getInstanceField("debugSymbolsCheckBox", foundDialog); + JCheckBox userSubmitted = (JCheckBox) getInstanceField("userSubmittedDebugSymbolsCheckBox", foundDialog); + + assertTrue(userSubmitted.isVisible()); + assertFalse(userSubmitted.isEnabled()); + + setToggleButtonSelected(debugSymbols, true); + assertTrue(userSubmitted.isVisible()); + assertTrue(userSubmitted.isEnabled()); + + setToggleButtonSelected(debugSymbols, false); + assertTrue(userSubmitted.isVisible()); + assertFalse(userSubmitted.isEnabled()); + + close(foundDialog); + waitForSwing(); + } + @Test public void testFunctionMatchingTriggersAPICall() throws Exception { var tool = env.getTool(); @@ -167,7 +220,7 @@ public void testFunctionMatchingTriggersAPICall() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -175,17 +228,70 @@ public void testFunctionMatchingTriggersAPICall() throws Exception { var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); assertNotNull("Dialog should be shown", foundDialog); - // Verify the initial status message - JLabel statusLabel = (JLabel) getInstanceField("statusLabel", foundDialog); - assertNotNull("Status label should exist", statusLabel); - assertTrue("Status should show ready message", - statusLabel.getText().contains("Ready")); + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + waitForCondition(() -> resultsTable.getRowCount() > 0, + "Results table should populate without pressing Match Functions"); + assertTrue("Function matching API should have been called", mockApi.functionMatchingCalled); + assertEquals("Should request 5 results per function", + Long.valueOf(5L), mockApi.lastMatchingRequest.getResultsPerFunction()); // Close the dialog close(foundDialog); waitForSwing(); } + @Test + @SuppressWarnings("unchecked") + public void testPlatformAndArchitectureTogglesAreSentAsMatchFilters() throws Exception { + var tool = env.getTool(); + + var mockApi = new FunctionMatchingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + // The automatic run on open leaves platform, architecture and user unfiltered, i.e. any + waitForCondition(() -> mockApi.lastMatchingRequest != null, "Matching should start when the dialog opens"); + MatchFilters initialFilters = mockApi.lastMatchingRequest.getFilters(); + assertNull(initialFilters.getPlatforms()); + assertNull(initialFilters.getArchitectures()); + assertNull(initialFilters.getUserIds()); + waitForTasks(); + + var platforms = (java.util.Map) getInstanceField("platformCheckBoxes", foundDialog); + var architectures = (java.util.Map) getInstanceField("architectureCheckBoxes", foundDialog); + setToggleButtonSelected(platforms.get(MatchFilters.PlatformsEnum.LINUX), true); + setToggleButtonSelected(architectures.get(MatchFilters.ArchitecturesEnum.ARM_64), true); + + waitForMatchingIdle(foundDialog); + var firstRequest = mockApi.lastMatchingRequest; + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForCondition(() -> mockApi.lastMatchingRequest != firstRequest, "Pressing Match Functions should start a new match"); + waitForTasks(); + + MatchFilters filters = mockApi.lastMatchingRequest.getFilters(); + assertEquals(List.of(MatchFilters.PlatformsEnum.LINUX), filters.getPlatforms()); + assertEquals(List.of(MatchFilters.ArchitecturesEnum.ARM_64), filters.getArchitectures()); + assertNull(filters.getUserIds()); + + close(foundDialog); + waitForSwing(); + } + @Test public void testClickMatchButtonPopulatesResultsTable() throws Exception { var tool = env.getTool(); @@ -203,7 +309,7 @@ public void testClickMatchButtonPopulatesResultsTable() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); // Show dialog without blocking, then wait for it to appear @@ -211,16 +317,17 @@ public void testClickMatchButtonPopulatesResultsTable() throws Exception { var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); assertNotNull("Dialog should be shown", foundDialog); - // Get the results table before clicking JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); assertNotNull("Results table should exist", resultsTable); - assertEquals("Results table should be empty initially", 0, resultsTable.getRowCount()); - // Find and click the "Match Functions" button + // Find and click the "Match Functions" button once the automatic match on open is done + waitForMatchingIdle(foundDialog); + var firstRequest = mockApi.lastMatchingRequest; JButton matchButton = findButtonByText(foundDialog.getComponent(), "Match Functions"); assertNotNull("Match Functions button should exist", matchButton); pressButton(matchButton); + waitForCondition(() -> mockApi.lastMatchingRequest != firstRequest, "Pressing Match Functions should start a new match"); // Wait for the API call to complete and results to be processed // The mock API returns COMPLETED status immediately, so we just need to wait for Swing @@ -244,9 +351,8 @@ public void testClickMatchButtonPopulatesResultsTable() throws Exception { "Status label should stop saying it is loading once matching has finished"); assertTrue("The finished status should report the matches, was: " + statusLabel.getText(), statusLabel.getText().contains("Matching complete")); - TaskMonitorComponent monitor = - (TaskMonitorComponent) getInstanceField("taskMonitorComponent", foundDialog); - assertFalse("The progress bar should not be left spinning", monitor.isVisible()); + JProgressBar progressBar = (JProgressBar) getInstanceField("matchingProgressBar", foundDialog); + assertFalse("The progress bar should not be left spinning", progressBar.isVisible()); // Close the dialog close(foundDialog); @@ -275,7 +381,7 @@ public void testSelectedMatchFollowsSortOrderNotModelOrder() throws Exception { waitForSwing(); FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> - new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, testFunction) + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) ); runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); @@ -284,6 +390,7 @@ public void testSelectedMatchFollowsSortOrderNotModelOrder() throws Exception { JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + waitForMatchingIdle(foundDialog); pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); waitForTasks(); waitForSwing(); @@ -322,6 +429,260 @@ public void testSelectedMatchFollowsSortOrderNotModelOrder() throws Exception { waitForSwing(); } + @Test + public void testSortBySimilarityAndConfidence() throws Exception { + var tool = env.getTool(); + + var mockApi = new MultiMatchMockApi() { + @Override + public GetMatchesOutputBody getFunctionsMatches(List functionIds) { + var response = super.getFunctionsMatches(functionIds); + var matches = response.getMatches().get(0).getMatchedFunctions(); + matches.get(0).setConfidence(0.0); + matches.get(2).setConfidence(null); + return response; + } + }; + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + + waitForMatchingIdle(foundDialog); + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForTasks(); + waitForSwing(); + waitForCondition(() -> resultsTable.getRowCount() == 3, + "Results table should hold all three mocked matches"); + + // Similarity: zeta 0.50, alpha 0.95, mid 0.72 + runSwing(() -> resultsTable.getRowSorter().toggleSortOrder(1)); + waitForSwing(); + assertEquals("zeta_match", resultsTable.getValueAt(0, 0)); + assertEquals("mid_match", resultsTable.getValueAt(1, 0)); + assertEquals("alpha_match", resultsTable.getValueAt(2, 0)); + + // Confidence: zeta 0, alpha 0.95, mid null + runSwing(() -> resultsTable.getRowSorter().toggleSortOrder(2)); + waitForSwing(); + assertEquals("mid_match", resultsTable.getValueAt(0, 0)); + assertEquals("zeta_match", resultsTable.getValueAt(1, 0)); + assertEquals("alpha_match", resultsTable.getValueAt(2, 0)); + + close(foundDialog); + waitForSwing(); + } + + @Test + public void testSimilarityAndConfidenceCellsAreColorCoded() throws Exception { + var tool = env.getTool(); + + var mockApi = new FunctionMatchingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + + waitForMatchingIdle(foundDialog); + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForTasks(); + waitForSwing(); + waitForCondition(() -> resultsTable.getRowCount() > 0, "Results table should have rows"); + + // Similarity (1) and Confidence (2) hold BigDecimal values on a 0-100 scale + for (int column : new int[]{1, 2}) { + var renderer = runSwing(() -> resultsTable.getCellRenderer(0, column)); + var high = runSwing(() -> renderer.getTableCellRendererComponent( + resultsTable, new BigDecimal("99.93"), false, false, 0, column).getForeground()); + assertEquals(new GColor("color.fg.reveng.similarity.low"), high); + var low = runSwing(() -> renderer.getTableCellRendererComponent( + resultsTable, BigDecimal.ZERO, false, false, 0, column).getForeground()); + assertEquals(new GColor("color.fg.reveng.similarity.critical"), low); + } + + close(foundDialog); + waitForSwing(); + } + + @Test + public void testRightClickOffersMatchedBinaryInPortal() throws Exception { + var tool = env.getTool(); + + var mockApi = new MultiMatchMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JTable resultsTable = (JTable) getInstanceField("resultsTable", foundDialog); + assertNull(invokeInstanceMethod("getSelectedMatchedAnalysisID", foundDialog)); + + waitForMatchingIdle(foundDialog); + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForTasks(); + waitForSwing(); + waitForCondition(() -> resultsTable.getRowCount() == 3, + "Results table should hold all three mocked matches"); + + var cell = runSwing(() -> resultsTable.getCellRect(1, 0, true)); + var rightClick = new java.awt.event.MouseEvent(resultsTable, java.awt.event.MouseEvent.MOUSE_PRESSED, + System.currentTimeMillis(), java.awt.event.InputEvent.BUTTON3_DOWN_MASK, + cell.x + 1, cell.y + 1, 1, true, java.awt.event.MouseEvent.BUTTON3); + runSwing(() -> resultsTable.dispatchEvent(rightClick)); + var popup = (JPopupMenu) getInstanceField("portalPopup", foundDialog); + assertTrue("Right click should show the portal popup", runSwing(popup::isVisible)); + assertTrue("Right click should not reach the docking popup", rightClick.isConsumed()); + assertEquals("Right click should select the row under the cursor", 1, resultsTable.getSelectedRow()); + var item = (JMenuItem) popup.getComponent(0); + assertEquals("Open in Portal", item.getText()); + assertTrue(item.isEnabled()); + assertEquals(new TypedApiInterface.AnalysisID(12345), + invokeInstanceMethod("getSelectedMatchedAnalysisID", foundDialog)); + runSwing(() -> popup.setVisible(false)); + + close(foundDialog); + waitForSwing(); + } + + /** + * Transferring names must rename on the portal exactly the functions it renamed locally, once each. + * A function whose name the analyst set is skipped locally, so pushing the matched name for it would + * leave the portal holding a different name from the one kept in Ghidra. + */ + @Test + public void testTransferOnlyRenamesOnThePortalWhatItAppliedLocally() throws Exception { + var tool = env.getTool(); + + var mockApi = new RenameRecordingMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var otherFunction = builder.createEmptyFunction("other_function", "0x2000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + var program = analysedProgram.program(); + env.showTool(program); + waitForSwing(); + + // A name the analyst set is kept, so nothing about its match may reach the portal + program.withTransaction("analyst rename", () -> testFunction.setName("analyst_name", SourceType.USER_DEFINED)); + program.withTransaction("analysis name", () -> otherFunction.setName("analysis_name", SourceType.ANALYSIS)); + + var sync = new LocalEditSyncService(service, tool.getService(ReaiLoggingService.class), (message, warning) -> {}); + sync.attach(program); + try { + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + waitForMatchingIdle(foundDialog); + + var matches = List.of( + matchFor(testFunction, 100, "similar_function"), + matchFor(otherFunction, 101, "other_similar_function")); + var applied = invokeInstanceMethod("applyMatches", foundDialog, + new Class[] {List.class, ApplyMatchCmd.Transfer.class}, + new Object[] {matches, ApplyMatchCmd.Transfer.NAME}); + assertEquals(1, applied); + assertEquals("analyst_name", testFunction.getName()); + assertEquals("other_similar_function", otherFunction.getName()); + + waitForCondition(() -> !mockApi.renameRequests.isEmpty(), "the applied rename should be pushed"); + Thread.sleep(1000); + assertEquals("Each applied rename should be pushed once: " + mockApi.renameRequests, + 1, mockApi.renameRequests.size()); + var pushed = mockApi.renameRequests.get(0).getFunctions(); + assertEquals(1, pushed.size()); + assertEquals(Long.valueOf(101), pushed.get(0).getFunctionId()); + assertEquals("other_similar_function", pushed.get(0).getNewName()); + + close(foundDialog); + waitForSwing(); + } finally { + sync.dispose(); + } + } + + private static GhidraFunctionMatchWithSignature matchFor(ghidra.program.model.listing.Function function, + long functionId, String matchedName) { + return new GhidraFunctionMatchWithSignature(function, new FunctionMatch( + new TypedApiInterface.FunctionID(functionId), + new TypedApiInterface.FunctionID(functionId + 100), + matchedName, + matchedName, + "libc.so", + new TypedApiInterface.BinaryHash("1".repeat(64)), + false, + BigDecimal.valueOf(0.95), + BigDecimal.valueOf(0.87), + null), null); + } + + /// Knows a second function, and records the renames sent to the portal. + static class RenameRecordingMockApi extends FunctionMatchingMockApi { + final List renameRequests = new CopyOnWriteArrayList<>(); + + @Override + public List getFunctionInfo(TypedApiInterface.AnalysisID analysisID) { + return List.of( + new FunctionInfo(new TypedApiInterface.FunctionID(100), "test_function", "test_function", 0x1000L, 50), + new FunctionInfo(new TypedApiInterface.FunctionID(101), "other_function", "other_function", 0x2000L, 50)); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) { + renameRequests.add(request); + return request.getFunctions().size(); + } + } + /** * Returns several matches whose server order differs from their alphabetical order, so that * sorting the results table genuinely separates view indices from model indices. @@ -366,6 +727,244 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { } } + /// The function-level dialog matches by itself when it opens, and its Match button reads Cancel while + /// a run is going. Waits for that first run to finish, so that pressing Match starts a new run rather + /// than, on a slow machine, cancelling the one that started after the button was looked up. + /// A status the SDK does not model (the server's CANCELLED) ends the wait instead of polling for ever + @Test + public void testUnrecognisedMatchingStatusStopsPolling() throws Exception { + var tool = env.getTool(); + var statusPolls = new java.util.concurrent.atomic.AtomicInteger(); + var mockApi = new FunctionMatchingMockApi() { + @Override + public StartMatchingOutputBody startFunctionsMatching(StartMatchingForFunctionsInputBody request) { + super.startFunctionsMatching(request); + var response = new StartMatchingOutputBody(); + response.setStatus(StartMatchingOutputBody.StatusEnum.RUNNING); + return response; + } + + @Override + public GetMatchesStatusOutputBody getFunctionsMatchingStatus(List functionIds) { + statusPolls.incrementAndGet(); + var response = new GetMatchesStatusOutputBody(); + response.setStatus(GetMatchesStatusOutputBody.StatusEnum.fromValue("CANCELLED")); + return response; + } + }; + var service = addMockedService(tool, mockApi); + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JLabel statusLabel = (JLabel) getInstanceField("statusLabel", foundDialog); + JButton matchButton = (JButton) getInstanceField("matchButton", foundDialog); + // The dialog sleeps a 2s poll interval before it sees CANCELLED, as long as waitForCondition's own limit + awaitCondition(() -> runSwing(() -> statusLabel.getText().equals("Stopped waiting for function matching") + && getInstanceField("matchingThread", foundDialog) == null + && matchButton.getText().equals("Match Functions")), + "An unrecognised status should end the matching run"); + JTextArea errorArea = (JTextArea) getInstanceField("errorArea", foundDialog); + assertTrue(errorArea.getText(), errorArea.getText().contains("does not recognise")); + assertEquals(1, statusPolls.get()); + + close(foundDialog); + waitForSwing(); + } + + private void waitForMatchingIdle(FunctionLevelFunctionMatchingDialog dialog) { + JLabel statusLabel = (JLabel) getInstanceField("statusLabel", dialog); + JButton matchButton = (JButton) getInstanceField("matchButton", dialog); + // Checked on the EDT: the run is marked finished and the button relabelled in one Swing update, + // which a check from the test thread can otherwise see half done + waitForCondition(() -> runSwing(() -> statusLabel.getText().startsWith("Matching complete") + && getInstanceField("matchingThread", dialog) == null + && matchButton.getText().equals("Match Functions")), + "The automatic match on open should finish"); + } + + /// A run that is cancelled and replaced must not reach the UI. Its thread, once its request came back, + /// used to hide the progress bar of the run that replaced it on the way out. + @Test + public void testCancelledRunDoesNotHideTheNextRunsProgress() throws Exception { + var tool = env.getTool(); + + var mockApi = new StillRunningMockApi(); + var service = addMockedService(tool, mockApi); + + env.addPlugin(BinarySimilarityPlugin.class); + + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + FunctionLevelFunctionMatchingDialog dialog = runSwing(() -> + new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo(service, analysedProgram), testFunction) + ); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(FunctionLevelFunctionMatchingDialog.class); + + JProgressBar progressBar = (JProgressBar) getInstanceField("matchingProgressBar", foundDialog); + JLabel statusLabel = (JLabel) getInstanceField("statusLabel", foundDialog); + // The first run's request is held by the mock, as a slow server would; while running, the Match button cancels + waitForCondition(() -> mockApi.lastMatchingRequest != null, "Matching should start when the dialog opens"); + pressButton(findButtonByText(foundDialog.getComponent(), "Cancel")); + waitForSwing(); + assertFalse("Cancelling should hide the progress bar", progressBar.isVisible()); + + var firstRequest = mockApi.lastMatchingRequest; + pressButton(findButtonByText(foundDialog.getComponent(), "Match Functions")); + waitForCondition(() -> mockApi.lastMatchingRequest != firstRequest, "Pressing Match Functions should start a new run"); + waitForCondition(() -> statusLabel.getText().contains("step 2 of 4"), + "The step reported by the server should be shown"); + + // Only now does the cancelled run's request come back + mockApi.firstStartGate.countDown(); + waitForCondition(() -> mockApi.firstStartReturned, "The cancelled run's request should return"); + Thread.sleep(200); + waitForSwing(); + assertTrue("The cancelled run must not hide the new run's progress bar", progressBar.isVisible()); + + close(foundDialog); + waitForSwing(); + } + + /// Reports matching as still running, on the second of four steps, so a run never finishes on its own. + /// The first request to start matching is held until {@link #firstStartGate} opens. + static class StillRunningMockApi extends FunctionMatchingMockApi { + final CountDownLatch firstStartGate = new CountDownLatch(1); + volatile boolean firstStartReturned = false; + private final AtomicInteger starts = new AtomicInteger(); + + @Override + public StartMatchingOutputBody startFunctionsMatching(StartMatchingForFunctionsInputBody request) { + boolean first = starts.getAndIncrement() == 0; + super.startFunctionsMatching(request); + if (first) { + // Like a blocking HTTP call, cancelling (an interrupt) doesn't cut this short + boolean interrupted = false; + while (true) { + try { + firstStartGate.await(); + break; + } catch (InterruptedException e) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + firstStartReturned = true; + } + var response = new StartMatchingOutputBody(); + response.setStatus(StartMatchingOutputBody.StatusEnum.RUNNING); + response.setStep("Searching for similar functions"); + response.setStepIndex(1L); + response.setStepsTotal(4L); + return response; + } + + @Override + public GetMatchesStatusOutputBody getFunctionsMatchingStatus(List functionIds) { + var response = new GetMatchesStatusOutputBody(); + response.setStatus(GetMatchesStatusOutputBody.StatusEnum.RUNNING); + response.setStep("Searching for similar functions"); + response.setStepIndex(1L); + response.setStepsTotal(4L); + return response; + } + } + + /// The plugin actions open the dialog through showWhenLoaded, which fetches the analysis details off the + /// Swing thread and builds the dialog with them + @Test + public void testAnalysisDetailsLoadOffTheSwingThreadBeforeTheDialogOpens() throws Exception { + var tool = env.getTool(); + var fetchedOnSwingThread = new java.util.concurrent.atomic.AtomicReference(); + var service = addMockedService(tool, new FunctionMatchingMockApi() { + @Override + public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) + throws ai.reveng.invoker.ApiException { + fetchedOnSwingThread.set(SwingUtilities.isEventDispatchThread()); + return super.getAnalysisBasicInfo(analysisID); + } + }); + env.addPlugin(BinarySimilarityPlugin.class); + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + runSwing(() -> AbstractFunctionMatchingDialog.showWhenLoaded(tool, analysedProgram, + basicInfo -> new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo, testFunction)), false); + + var dialog = awaitDialog(FunctionLevelFunctionMatchingDialog.class); + assertEquals("the details should be fetched, and not on the Swing thread", Boolean.FALSE, fetchedOnSwingThread.get()); + var loaded = (AnalysisBasicInfoOutputBody) getInstanceField("analysisBasicInfo", dialog); + assertEquals("test-model", loaded.getModelName()); + + close(dialog); + waitForSwing(); + } + + /// When the details cannot be fetched the user is told why, and no half-built dialog is shown + @Test + public void testFailedAnalysisDetailsShowAnErrorInsteadOfTheDialog() throws Exception { + setErrorGUIEnabled(true); + var tool = env.getTool(); + var service = addMockedService(tool, new FunctionMatchingMockApi() { + @Override + public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) + throws ai.reveng.invoker.ApiException { + throw new ai.reveng.invoker.ApiException(503, "Service Unavailable"); + } + }); + env.addPlugin(BinarySimilarityPlugin.class); + var builder = newX64Program("test_binary"); + var testFunction = builder.createEmptyFunction("test_function", "0x1000", 50, Undefined.getUndefinedDataType(4)); + var analysedProgram = service.analyse(builder.getProgram(), null, TaskMonitor.DUMMY); + env.showTool(analysedProgram.program()); + waitForSwing(); + + var factoryCalls = new AtomicInteger(); + runSwing(() -> AbstractFunctionMatchingDialog.showWhenLoaded(tool, analysedProgram, basicInfo -> { + factoryCalls.incrementAndGet(); + return new FunctionLevelFunctionMatchingDialog(tool, analysedProgram, basicInfo, testFunction); + }), false); + + var error = awaitDialog(AbstractErrDialog.class); + assertTrue(error.getMessage(), error.getMessage().contains("Failed to fetch the details of analysis 12345")); + assertTrue(error.getMessage(), error.getMessage().contains("HTTP 503")); + close(error); + waitForSwing(); + + assertEquals("no dialog should be built without the details", 0, factoryCalls.get()); + assertNull(getDialogComponent(FunctionLevelFunctionMatchingDialog.class)); + } + + private static AnalysisBasicInfoOutputBody basicInfo(GhidraRevengService service, + GhidraRevengService.AnalysedProgram program) { + try { + return service.getBasicDetailsForAnalysis(program.analysisID()); + } catch (ai.reveng.invoker.ApiException e) { + throw new RuntimeException(e); + } + } + /** * Mock API implementation for function matching dialog tests. * Provides necessary responses for the dialog to function without a real server. @@ -373,6 +972,7 @@ public List getAssembly(TypedApiInterface.FunctionID functionID) { static class FunctionMatchingMockApi extends UnimplementedAPI { private final AnalysisStatus currentStatus = AnalysisStatus.Complete; boolean functionMatchingCalled = false; + volatile StartMatchingForFunctionsInputBody lastMatchingRequest; @Override public TypedApiInterface.AnalysisID analyse(AnalysisOptionsBuilder options) { @@ -399,7 +999,8 @@ public List getFunctionInfo(TypedApiInterface.AnalysisID analysisI } @Override - public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) { + public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.AnalysisID analysisID) + throws ai.reveng.invoker.ApiException { var basic = new AnalysisBasicInfoOutputBody(); basic.setModelId(1L); basic.setModelName("test-model"); @@ -411,6 +1012,7 @@ public AnalysisBasicInfoOutputBody getAnalysisBasicInfo(TypedApiInterface.Analys @Override public StartMatchingOutputBody startFunctionsMatching(StartMatchingForFunctionsInputBody request) { functionMatchingCalled = true; + lastMatchingRequest = request; var response = new StartMatchingOutputBody(); response.setStatus(StartMatchingOutputBody.StatusEnum.COMPLETED); return response; diff --git a/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java b/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java index d036c6bf..9c6b38eb 100644 --- a/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java +++ b/src/test/java/ai/reveng/GhidraDataTypeEncoderTest.java @@ -307,6 +307,21 @@ public void typesWithNothingToSayProduceNoUpdate() { new PointerDataType(new StructureDataType("Unknown", 4)), 1L, key -> null).isEmpty()); } + /// A struct whose members' types are only partly resolved is withheld whole: writing it would + /// send the rest as null types and erase them on the portal. + @Test + public void aCompositeWithAnUnresolvedMemberProducesNoUpdate() { + var resolved = new StructureDataType("Resolved", 4); + var unresolved = new StructureDataType("Unresolved", 4); + var struct = new StructureDataType("Mixed", 0); + struct.add(resolved, "a", null); + struct.add(unresolved, "b", null); + TypeKey resolvedKey = GhidraDataTypeEncoder.keyOf(resolved); + + assertTrue(GhidraDataTypeEncoder.updateEntry(struct, 1L, + key -> key.equals(resolvedKey) ? 2L : null).isEmpty()); + } + /// The namespace round-trips through the category path, which is how a type the plugin pulled /// from the server resolves back to the same entry instead of being created again. @Test diff --git a/src/test/java/ai/reveng/GhidraRevengServiceTest.java b/src/test/java/ai/reveng/GhidraRevengServiceTest.java index 113f3f5f..9218b684 100644 --- a/src/test/java/ai/reveng/GhidraRevengServiceTest.java +++ b/src/test/java/ai/reveng/GhidraRevengServiceTest.java @@ -3,7 +3,9 @@ import ai.reveng.invoker.ApiException; 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.StatusPoller; 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; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; @@ -12,9 +14,13 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; +import java.util.Set; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; public class GhidraRevengServiceTest extends RevEngMockableHeadedIntegrationTest { @@ -42,6 +48,112 @@ public void testKnownProgramLookupIsNetworkFree() throws Exception { statusCallsBefore, mock.statusCalls); } + /// An unreadable binary must fail with the path and reason, not the SDK's raw HTTP 0 dump. + @Test + public void testUploadOfUnreadableFileExplainsWhy() throws Exception { + Path bin = Files.createTempFile("unreadable", ".bin"); + bin.toFile().deleteOnExit(); + Files.setPosixFilePermissions(bin, Set.of()); + var program = newX64Program().getProgram(); + int tx = program.startTransaction("set path"); + program.setExecutablePath(bin.toString()); + program.endTransaction(tx, true); + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public BinaryHash upload(Path binPath) { + throw new RuntimeException(new ApiException("Message: java.io.FileNotFoundException: " + binPath)); + } + }); + + var e = assertThrows(RuntimeException.class, () -> service.upload(program)); + + assertTrue(e.getMessage(), e.getMessage().startsWith("Cannot read " + bin)); + } + + @Test + public void testStatusPollingGivesUpAfterTenFailures() throws Exception { + var statusCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) throws ApiException { + if (++statusCalls[0] > 20) { + return AnalysisStatus.Complete; + } + throw new ApiException(503, "Service Unavailable"); + } + }); + setInstanceField("pollIntervalMs", service, 1L); + setInstanceField("maxPollBackoffMs", service, 1L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + assertThrows(RuntimeException.class, + () -> service.waitForFinishedAnalysis(TaskMonitor.DUMMY, programWithID, null, null)); + assertEquals(10, statusCalls[0]); + } + + @Test + public void testStatusPollingEndsOnUnrecognisedStatus() throws Exception { + var statusCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls[0]++; + return AnalysisStatus.Unknown; + } + }); + setInstanceField("pollIntervalMs", service, 1L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + var result = service.waitForAnalysis(TaskMonitor.DUMMY, programWithID, null, null); + assertEquals(StatusPoller.Ending.UNRECOGNISED, result.ending()); + assertEquals(AnalysisStatus.Unknown, result.status()); + assertEquals(1, statusCalls[0]); + } + + @Test + public void testStatusPollingStopsAtTheTimeLimit() throws Exception { + var logCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Processing; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + logCalls[0]++; + return "still going"; + } + }); + setInstanceField("pollIntervalMs", service, 5L); + setInstanceField("maxPollIntervalMs", service, 20L); + setInstanceField("maxAnalysisWaitMs", service, 200L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + var result = service.waitForAnalysis(TaskMonitor.DUMMY, programWithID, null, null); + assertEquals(StatusPoller.Ending.TIMED_OUT, result.ending()); + assertEquals(AnalysisStatus.Processing, result.status()); + // Backing off to 20ms, 200ms holds well under the 40 polls a fixed 5ms interval would make + assertTrue("polled " + logCalls[0] + " times", logCalls[0] < 25); + } + + @Test + public void testStatusPollingWaitsThroughUploaded() throws Exception { + var statusCalls = new int[1]; + var service = new GhidraRevengService(new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return ++statusCalls[0] < 3 ? AnalysisStatus.Uploaded : AnalysisStatus.Complete; + } + }); + setInstanceField("pollIntervalMs", service, 1L); + var programWithID = new GhidraRevengService.ProgramWithID(newX64Program().getProgram(), new AnalysisID(1)); + + assertEquals(AnalysisStatus.Complete, + service.waitForFinishedAnalysis(TaskMonitor.DUMMY, programWithID, null, null)); + assertEquals(3, statusCalls[0]); + } + static class OfflineAfterSetupAPI extends UnimplementedAPI { volatile boolean offline = false; int statusCalls = 0; diff --git a/src/test/java/ai/reveng/IncompleteLoadTest.java b/src/test/java/ai/reveng/IncompleteLoadTest.java new file mode 100644 index 00000000..b45349c3 --- /dev/null +++ b/src/test/java/ai/reveng/IncompleteLoadTest.java @@ -0,0 +1,155 @@ +package ai.reveng; + +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionInfo; +import ghidra.program.model.data.Undefined; +import ghidra.program.model.listing.Function; +import ghidra.util.exception.CancelledException; +import ghidra.util.task.TaskMonitor; +import ghidra.util.task.TaskMonitorAdapter; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/// A load whose pull fails part way must leave the program as it was, and loading it again must work. +public class IncompleteLoadTest extends RevEngMockableHeadedIntegrationTest { + + private static final String REVENG_TAG = "REVENGAI_SYNCED"; + private static final String REVENG_BOOKMARK_TYPE = "RevEng.AI"; + + /// Serves one function, and fails the signature request while `portalDown` is set, as a 503 would. + private static class FlakyPortal extends UnimplementedAPI { + boolean portalDown = true; + + @Override + public AnalysisStatus status(TypedApiInterface.AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(TypedApiInterface.AnalysisID analysisID) { + return List.of( + new FunctionInfo(new TypedApiInterface.FunctionID(1), "portal_name", "portal_name", 0x4000L, 0x100) + ); + } + + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, + boolean includeDataTypes) { + if (portalDown) { + throw new RuntimeException("HTTP 503 — Service Unavailable"); + } + return FunctionSignatureBatch.empty(); + } + } + + @Test + public void failedPullLeavesProgramUnattachedAndRetrySucceeds() throws Exception { + var portal = new FlakyPortal(); + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + var originalName = function.getName(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + var error = assertThrows(RuntimeException.class, + () -> service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY)); + assertEquals("HTTP 503 — Service Unavailable", error.getMessage()); + + assertTrue("the analysis should stay associated so the load can be retried", + service.getKnownProgram(program).isPresent()); + assertTrue("a program whose pull failed must not count as analysed", + service.getAnalysedProgram(program).isEmpty()); + assertFalse("the function should not be marked as synced", hasRevEngTag(function)); + assertEquals("the function should not keep a RevEng bookmark", + 0, program.getBookmarkManager().getBookmarks(function.getEntryPoint(), REVENG_BOOKMARK_TYPE).length); + assertEquals("nothing was pulled, so the name is unchanged", originalName, function.getName()); + + portal.portalDown = false; + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + assertTrue("the retried load should attach the program", service.getAnalysedProgram(program).isPresent()); + assertEquals(1, analysedProgram.getIDForFunction(function).orElseThrow().functionID().value()); + assertTrue("the function should be marked as synced", hasRevEngTag(function)); + assertEquals("the retried load should pull the portal name", "portal_name", function.getName()); + } + + @Test + public void loadingAnAlreadyAttachedProgramAgainReplacesTheAssociation() throws Exception { + var portal = new FlakyPortal(); + portal.portalDown = false; + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + // Programs saved half attached before this was fixed still carry the property maps + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + assertEquals(1, analysedProgram.getIDForFunction(function).orElseThrow().functionID().value()); + assertEquals("the function should carry exactly one RevEng bookmark", + 1, program.getBookmarkManager().getBookmarks(function.getEntryPoint(), REVENG_BOOKMARK_TYPE).length); + assertTrue(hasRevEngTag(function)); + } + + @Test + public void failedPullLeavesNothingToUndo() throws Exception { + var portal = new FlakyPortal(); + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + var undoNames = program.getAllUndoNames(); + assertThrows(RuntimeException.class, + () -> service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY)); + + assertEquals("a failed load should leave no undo entry that brings the association back", + undoNames, program.getAllUndoNames()); + assertTrue(service.getAnalysedProgram(program).isEmpty()); + assertFalse(hasRevEngTag(function)); + } + + @Test + public void cancelledLoadLeavesProgramUnattached() throws Exception { + var portal = new FlakyPortal(); + portal.portalDown = false; + var service = new GhidraRevengService(portal); + var builder = newX64Program(); + builder.createMemory("matched", "0x4000", 0x100); + Function function = builder.createEmptyFunction(null, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + var originalName = function.getName(); + var monitor = new TaskMonitorAdapter(true); + monitor.cancel(); + + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + assertThrows(CancelledException.class, + () -> service.registerFinishedAnalysisForProgram(programWithID, monitor)); + + assertTrue(service.getKnownProgram(program).isPresent()); + assertTrue("a cancelled load must not count as analysed", service.getAnalysedProgram(program).isEmpty()); + assertFalse(hasRevEngTag(function)); + assertEquals(originalName, function.getName()); + } + + private static boolean hasRevEngTag(Function function) { + return function.getTags().stream().anyMatch(tag -> tag.getName().equals(REVENG_TAG)); + } +} diff --git a/src/test/java/ai/reveng/LocalEditSyncAcrossProgramsTest.java b/src/test/java/ai/reveng/LocalEditSyncAcrossProgramsTest.java new file mode 100644 index 00000000..373a052a --- /dev/null +++ b/src/test/java/ai/reveng/LocalEditSyncAcrossProgramsTest.java @@ -0,0 +1,112 @@ +package ai.reveng; + +import ai.reveng.model.BatchRenameInputBody; +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.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +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.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.Assert.assertEquals; + +/// One {@link LocalEditSyncService} serves every open program, so its debounce must not let an edit in +/// one program cancel a pending push for another program that happens to have a function at the same +/// address. +public class LocalEditSyncAcrossProgramsTest extends RevEngMockableHeadedIntegrationTest { + + private static final long ENTRY = 0x4000L; + + /// Each analysis holds one function at {@link #ENTRY}, with the analysis id as its function id. + private static class RecordingApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + var id = new FunctionID(analysisID.id()); + return List.of(new FunctionInfo(id, "FUN_00004000", "FUN_00004000", ENTRY, 0x100)); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) { + for (var item : request.getFunctions()) { + renamed.put(item.getFunctionId(), item.getNewName()); + } + return request.getFunctions().size(); + } + } + + private LocalEditSyncService sync; + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + private Function analysedFunction(GhidraRevengService service, String name, long analysisId) throws Exception { + var builder = newX64Program(name); + builder.createMemory("code", "0x4000", 0x200); + Function function = builder.createEmptyFunction("FUN_00004000", "0x4000", 0x100, new IntegerDataType()); + var program = builder.getProgram(); + var withId = service.registerAnalysisForProgram(program, new AnalysisID((int) analysisId)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + return function; + } + + private static void rename(Function function, String newName) throws Exception { + Program program = function.getProgram(); + int tx = program.startTransaction("rename"); + try { + function.setName(newName, SourceType.USER_DEFINED); + } finally { + program.endTransaction(tx, true); + } + program.flushEvents(); + } + + @Test + public void editsAtTheSameAddressInTwoProgramsAreBothPushed() throws Exception { + var api = new RecordingApi(); + var service = new GhidraRevengService(api); + Function inA = analysedFunction(service, "a", 1); + Function inB = analysedFunction(service, "b", 2); + + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class), + (message, warning) -> {}); + sync.attach(inA.getProgram()); + sync.attach(inB.getProgram()); + + // Both inside one debounce window, which is where the second used to cancel the first. + rename(inA, "renamed_in_a"); + rename(inB, "renamed_in_b"); + + waitForCondition(() -> api.renamed.size() == 2, "both renames should be pushed"); + assertEquals(Map.of(1L, "renamed_in_a", 2L, "renamed_in_b"), api.renamed); + } +} diff --git a/src/test/java/ai/reveng/LocalEditSyncScopeTest.java b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java new file mode 100644 index 00000000..a27bc91d --- /dev/null +++ b/src/test/java/ai/reveng/LocalEditSyncScopeTest.java @@ -0,0 +1,315 @@ +package ai.reveng; + +import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.model.CreateAnalysisDataTypesInputBody; +import ai.reveng.model.UpdateFunctionSignatureInputBody; +import ai.reveng.toolkit.ghidra.binarysimilarity.cmds.ApplyMatchCmd; +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; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +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.core.services.api.types.FunctionMatch; +import ai.reveng.toolkit.ghidra.core.services.api.types.GhidraFunctionMatchWithSignature; +import ai.reveng.toolkit.ghidra.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ghidra.program.model.address.AddressSet; +import ghidra.program.model.data.FunctionDefinitionDataType; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.data.LongDataType; +import ghidra.program.model.data.ParameterDefinitionImpl; +import ghidra.program.model.data.PointerDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.LocalVariableImpl; +import ghidra.program.model.listing.ParameterImpl; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/// What the reactive push sends, and how many requests it takes. +public class LocalEditSyncScopeTest extends RevEngMockableHeadedIntegrationTest { + + private static final String SYNCED_TAG = "REVENGAI_SYNCED"; + private static final long[] ENTRIES = {0x4000L, 0x4100L, 0x4200L}; + + /// One function per entry in {@link #ENTRIES}, with ids 1, 2 and 3. + private static class RecordingApi extends UnimplementedAPI { + final List renameRequests = new CopyOnWriteArrayList<>(); + final List pushedSignatures = new CopyOnWriteArrayList<>(); + private final AtomicInteger nextDataTypeId = new AtomicInteger(100); + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return java.util.stream.IntStream.range(0, ENTRIES.length) + .mapToObj(i -> new FunctionInfo(new FunctionID(i + 1), "FUN_" + i, "FUN_" + i, ENTRIES[i], 0x100)) + .toList(); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) { + renameRequests.add(request); + return request.getFunctions().size(); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public List createAnalysisDataTypes(AnalysisID analysisID, + CreateAnalysisDataTypesInputBody request) { + return CreatedDataTypes.echo(request, nextDataTypeId::getAndIncrement); + } + + @Override + public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID, + UpdateFunctionSignatureInputBody signature) { + pushedSignatures.add(functionID); + } + } + + private final RecordingApi api = new RecordingApi(); + private Program program; + private Function first; + private LocalEditSyncService sync; + private GhidraRevengService.AnalysedProgram analysedProgram; + + @Before + public void analyse() throws Exception { + var service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("code", "0x4000", 0x400); + for (long entry : ENTRIES) { + builder.createEmptyFunction(null, "0x" + Long.toHexString(entry), 0x100, new IntegerDataType()); + } + program = builder.getProgram(); + first = program.getFunctionManager().getFunctionAt(address(ENTRIES[0])); + program.withTransaction("give it a parameter", () -> rethrow(() -> first.replaceParameters( + Function.FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS, + new ParameterImpl("count", new IntegerDataType(), program)))); + + var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + analysedProgram = service.getAnalysedProgram(program).orElseThrow(); + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class), + (message, warning) -> {}); + sync.attach(program); + } + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + private ghidra.program.model.address.Address address(long offset) { + return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset); + } + + private void edit(String description, Edit change) { + program.withTransaction(description, () -> rethrow(change)); + program.flushEvents(); + } + + private static boolean tagged(Function function) { + return function.getTags().stream().anyMatch(tag -> SYNCED_TAG.equals(tag.getName())); + } + + @Test + public void renamesInOneProgramGoUpInOneRequest() throws Exception { + for (int i = 0; i < ENTRIES.length; i++) { + var function = program.getFunctionManager().getFunctionAt(address(ENTRIES[i])); + var name = "renamed_" + i; + edit("rename", () -> function.setName(name, SourceType.USER_DEFINED)); + } + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the renames should be pushed"); + Thread.sleep(1_000); + assertEquals("one request for all three renames", 1, api.renameRequests.size()); + var pushed = api.renameRequests.get(0).getFunctions().stream() + .collect(java.util.stream.Collectors.toMap(item -> item.getFunctionId(), item -> item.getNewName())); + assertEquals(Map.of(1L, "renamed_0", 2L, "renamed_1", 3L, "renamed_2"), pushed); + } + + /// "Apply Match" files the function under `RevEng.AI::`. That namespace only + /// organises the matches, so the rename it triggers must push the bare name, not + /// `::`. + @Test + public void anAppliedMatchPushesItsNameWithoutTheMatchedBinary() throws Exception { + var match = new GhidraFunctionMatchWithSignature(first, new FunctionMatch( + new FunctionID(1), + new FunctionID(200), + "matched_name", + "matched_name", + "libfoo.so", + new BinaryHash("abc123"), + false, + BigDecimal.valueOf(0.9), + BigDecimal.valueOf(0.9), + null), null); + edit("apply match", () -> new ApplyMatchCmd(null, analysedProgram, match, true).applyTo(program)); + assertEquals("RevEng.AI::libfoo.so", first.getParentNamespace().getName(true)); + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the rename should be pushed"); + assertEquals("matched_name", api.renameRequests.get(0).getFunctions().get(0).getNewName()); + } + + /// The matching dialog applies a transfer with no service, so the sync service is what pushes it. A + /// signature-only transfer changes the prototype and nothing else: the signature goes up once, and no + /// rename does. + @Test + public void aSignatureTransferPushesTheSignatureOnceAndNoRename() throws Exception { + var originalName = first.getName(); + edit("transfer the signature", () -> assertTrue(new ApplyMatchCmd(null, analysedProgram, + matchWithSignature(), false, ApplyMatchCmd.Transfer.SIGNATURE).applyTo(program))); + assertEquals(originalName, first.getName()); + assertEquals("buf", first.getParameter(1).getName()); + + waitForCondition(() -> !api.pushedSignatures.isEmpty(), "the transferred signature should be pushed"); + // Past the debounce, so a second push or a rename would have gone up by now + Thread.sleep(1_000); + assertEquals(List.of(new FunctionID(1)), api.pushedSignatures); + assertTrue("renames pushed: " + api.renameRequests, api.renameRequests.isEmpty()); + } + + /// Transferring both pushes each once: one rename, one signature. + @Test + public void aNameAndSignatureTransferPushesEachOnce() throws Exception { + edit("transfer name and signature", () -> assertTrue(new ApplyMatchCmd(null, analysedProgram, + matchWithSignature(), false, ApplyMatchCmd.Transfer.NAME_AND_SIGNATURE).applyTo(program))); + + waitForCondition(() -> !api.pushedSignatures.isEmpty() && !api.renameRequests.isEmpty(), + "the transferred name and signature should be pushed"); + Thread.sleep(1_000); + assertEquals(List.of(new FunctionID(1)), api.pushedSignatures); + assertEquals("renames pushed: " + api.renameRequests, 1, api.renameRequests.size()); + var pushed = api.renameRequests.get(0).getFunctions(); + assertEquals(1, pushed.size()); + assertEquals(Long.valueOf(1), pushed.get(0).getFunctionId()); + assertEquals("matched_name", pushed.get(0).getNewName()); + } + + private GhidraFunctionMatchWithSignature matchWithSignature() { + var signature = new FunctionDefinitionDataType("matched_name"); + signature.setReturnType(IntegerDataType.dataType); + signature.setArguments( + new ParameterDefinitionImpl("len", IntegerDataType.dataType, null), + new ParameterDefinitionImpl("buf", PointerDataType.dataType, null)); + return new GhidraFunctionMatchWithSignature(first, new FunctionMatch( + new FunctionID(1), + new FunctionID(200), + "matched_name", + "matched_name", + "libfoo.so", + new BinaryHash("abc123"), + false, + BigDecimal.valueOf(0.9), + BigDecimal.valueOf(0.9), + null), signature); + } + + /// A namespace the analyst made is part of the function's name on the portal. + @Test + public void aRenameInsideAnAnalystNamespaceKeepsTheNamespace() throws Exception { + edit("move and rename", () -> { + var namespace = program.getSymbolTable().createNameSpace(null, "MyClass", SourceType.USER_DEFINED); + first.setParentNamespace(namespace); + first.setName("method", SourceType.USER_DEFINED); + }); + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the rename should be pushed"); + assertEquals("MyClass::method", api.renameRequests.get(0).getFunctions().get(0).getNewName()); + } + + /// Every namespace inside RevEng.AI is dropped, while one the analyst made above it is kept. + @Test + public void aRenameDropsOnlyTheNamespacesInsideRevEngAi() throws Exception { + edit("move and rename", () -> { + var symbols = program.getSymbolTable(); + var outer = symbols.createNameSpace(null, "Outer", SourceType.USER_DEFINED); + var reveng = symbols.createNameSpace(outer, "RevEng.AI", SourceType.USER_DEFINED); + var binary = symbols.createNameSpace(reveng, "libfoo.so", SourceType.USER_DEFINED); + var inner = symbols.createNameSpace(binary, "Inner", SourceType.USER_DEFINED); + first.setParentNamespace(inner); + first.setName("name", SourceType.USER_DEFINED); + }); + + waitForCondition(() -> !api.renameRequests.isEmpty(), "the rename should be pushed"); + assertEquals("Outer::name", api.renameRequests.get(0).getFunctions().get(0).getNewName()); + } + + @Test + public void localVariableEditsPushNothingButAParameterRenameDoes() throws Exception { + edit("add a local", () -> first.addLocalVariable( + new LocalVariableImpl("local", new IntegerDataType(), -0x10, program), SourceType.USER_DEFINED)); + var local = first.getLocalVariables()[0]; + edit("rename the local", () -> local.setName("renamed_local", SourceType.USER_DEFINED)); + edit("retype the local", () -> local.setDataType(new LongDataType(), SourceType.USER_DEFINED)); + + // Past the debounce, so any push these had scheduled would have gone up. + Thread.sleep(1_000); + assertTrue("signatures pushed: " + api.pushedSignatures, api.pushedSignatures.isEmpty()); + + edit("rename the parameter", () -> first.getParameter(0).setName("renamed_count", SourceType.USER_DEFINED)); + waitForCondition(() -> !api.pushedSignatures.isEmpty(), "a parameter rename should push the signature"); + assertEquals(List.of(new FunctionID(1)), api.pushedSignatures); + } + + @Test + public void aFunctionCreatedAgainKeepsItsTag() throws Exception { + assertTrue(tagged(first)); + var entry = first.getEntryPoint(); + var body = new AddressSet(first.getBody()); + edit("delete", () -> program.getFunctionManager().removeFunction(entry)); + edit("create again", () -> program.getFunctionManager() + .createFunction(null, entry, body, SourceType.USER_DEFINED)); + + var recreated = program.getFunctionManager().getFunctionAt(entry); + waitForCondition(() -> tagged(recreated), "the re-created function should be tagged again"); + } + + @Test + public void aNewFunctionAtAnUnmappedAddressIsNotTagged() throws Exception { + var entry = address(0x4300L); + edit("create", () -> program.getFunctionManager() + .createFunction(null, entry, new AddressSet(entry, address(0x43ffL)), SourceType.USER_DEFINED)); + + Thread.sleep(500); + assertFalse(tagged(program.getFunctionManager().getFunctionAt(entry))); + } + + private interface Edit { + void run() throws Exception; + } + + private static void rethrow(Edit edit) { + try { + edit.run(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java new file mode 100644 index 00000000..faf98c35 --- /dev/null +++ b/src/test/java/ai/reveng/LocalEditsDuringSyncTest.java @@ -0,0 +1,236 @@ +package ai.reveng; + +import ai.reveng.model.BatchFunctionSignatureEntry; +import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.model.CreateAnalysisDataTypesInputBody; +import ai.reveng.model.UpdateFunctionSignatureInputBody; +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.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +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.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ghidra.program.model.data.LongDataType; +import ghidra.program.model.data.Undefined; +import ghidra.program.model.listing.Function; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/// Edits the analyst makes while a sync is running are pushed; only the changes the sync itself +/// writes are kept from going back up. +public class LocalEditsDuringSyncTest extends RevEngMockableHeadedIntegrationTest { + + private static final ReaiLoggingService NOOP_LOG = new ReaiLoggingService() { + @Override public void info(String message) {} + @Override public void warn(String message) {} + @Override public void error(String message) {} + }; + + /// Each analysis holds one function at 0x4000, with the analysis id as its function id. + private static class RecordingApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + final List pushedSignatures = new CopyOnWriteArrayList<>(); + final Map remoteNames = new ConcurrentHashMap<>(); + /// The portal's return type for every function, or null when it holds no signatures. + volatile String remoteReturnType; + /// When set, the next sync of analysis 1 waits for it while reading the portal's names. + volatile CountDownLatch holdSyncOfAnalysis1; + final CountDownLatch syncWaiting = new CountDownLatch(1); + private long nextDataTypeId = 100; + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + var hold = holdSyncOfAnalysis1; + if (hold != null && analysisID.id() == 1) { + syncWaiting.countDown(); + try { + hold.await(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + var name = remoteNames.getOrDefault(analysisID.id(), "FUN_00004000"); + return List.of(new FunctionInfo(new FunctionID(analysisID.id()), name, name, 0x4000L, 0x100)); + } + + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, boolean includeDataTypes) { + if (remoteReturnType == null) { + return FunctionSignatureBatch.empty(); + } + var entries = functionIDs.stream().map(id -> { + var entry = new BatchFunctionSignatureEntry(); + entry.setAnalysisId(id.value()); + entry.setFunctionId(id.value()); + entry.setFunctionName("FUN_00004000"); + entry.setHasSignature(true); + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.USER); + entry.setReturnDataTypeId(1L); + entry.setParameters(List.of()); + return entry; + }).toList(); + var returnType = new ServerDataType(1L, "", remoteReturnType, ServerDataType.Kind.BASE, + 4L, "AUTO", false, null, null, null); + Map> types = new ConcurrentHashMap<>(); + functionIDs.forEach(id -> types.put(new AnalysisID((int) id.value()), List.of(returnType))); + return new FunctionSignatureBatch(entries, types); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) { + for (var item : request.getFunctions()) { + renamed.put(item.getFunctionId(), item.getNewName()); + } + return request.getFunctions().size(); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public synchronized List createAnalysisDataTypes(AnalysisID analysisID, + CreateAnalysisDataTypesInputBody request) { + return CreatedDataTypes.echo(request, () -> nextDataTypeId++); + } + + @Override + public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID, + UpdateFunctionSignatureInputBody signature) { + pushedSignatures.add(functionID); + } + } + + private final RecordingApi api = new RecordingApi(); + private final GhidraRevengService service = new GhidraRevengService(api); + private LocalEditSyncService sync; + + @After + public void tearDown() { + var hold = api.holdSyncOfAnalysis1; + if (hold != null) { + hold.countDown(); + } + if (sync != null) { + sync.dispose(); + } + } + + /// A function whose signature came from Ghidra's analysis, as on a real binary; ProgramBuilder + /// would otherwise stamp it user-defined, which a pull leaves alone. + private Function analysedFunction(String name, int analysisId) throws Exception { + var builder = newX64Program(name); + builder.createMemory("code", "0x4000", 0x200); + Function function = builder.createEmptyFunction( + "FUN_00004000", "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + program.withTransaction("analysis signature", () -> function.setSignatureSource(SourceType.ANALYSIS)); + var withId = service.registerAnalysisForProgram(program, new AnalysisID(analysisId)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + return function; + } + + private void listenTo(Function... functions) { + sync = new LocalEditSyncService(service, env.getTool().getService(ReaiLoggingService.class), + (message, warning) -> {}); + for (Function function : functions) { + sync.attach(function.getProgram()); + } + } + + private static void edit(Function function, String description, Runnable change) { + var program = function.getProgram(); + program.withTransaction(description, change::run); + program.flushEvents(); + } + + private GhidraRevengService.SyncSummary syncWithPortal(Function function) throws Exception { + return service.syncAnalysisUpdates( + service.getAnalysedProgram(function.getProgram()).orElseThrow(), TaskMonitor.DUMMY, NOOP_LOG); + } + + @Test + public void editsMadeWhileASyncWaitsOnThePortalArePushed() throws Exception { + Function inA = analysedFunction("a", 1); + Function inB = analysedFunction("b", 2); + listenTo(inA, inB); + + var hold = new CountDownLatch(1); + api.holdSyncOfAnalysis1 = hold; + Thread syncing = new Thread(() -> { + try { + syncWithPortal(inA); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + syncing.start(); + assertTrue("the sync should be waiting on the portal", api.syncWaiting.await(30, TimeUnit.SECONDS)); + + // In the program being synced, and in another one. + edit(inA, "rename", () -> rethrow(() -> inA.setName("mine_a", SourceType.USER_DEFINED))); + edit(inB, "rename", () -> rethrow(() -> inB.setName("mine_b", SourceType.USER_DEFINED))); + edit(inB, "retype", () -> rethrow(() -> inB.setReturnType(new LongDataType(), SourceType.USER_DEFINED))); + + waitForCondition(() -> api.renamed.size() == 2 && !api.pushedSignatures.isEmpty(), + "edits made during the sync should be pushed while it is still running"); + assertEquals(Map.of(1L, "mine_a", 2L, "mine_b"), api.renamed); + assertEquals(List.of(new FunctionID(2)), api.pushedSignatures); + + hold.countDown(); + syncing.join(30_000); + assertEquals("the sync keeps the analyst's name", "mine_a", inA.getName()); + } + + @Test + public void whatTheSyncAppliesIsNotPushedBack() throws Exception { + Function function = analysedFunction("a", 1); + listenTo(function); + api.remoteNames.put(1, "theirs"); + api.remoteReturnType = "int"; + + var summary = syncWithPortal(function); + assertEquals("theirs", function.getName()); + assertEquals(1, summary.appliedSignatures()); + assertEquals("int", function.getReturnType().getName()); + + // Past the debounce, so anything the sync's own events had scheduled would have gone up. + Thread.sleep(1_000); + assertTrue("renames pushed: " + api.renamed, api.renamed.isEmpty()); + assertTrue("signatures pushed: " + api.pushedSignatures, api.pushedSignatures.isEmpty()); + } + + private interface Edit { + void run() throws Exception; + } + + private static void rethrow(Edit edit) { + try { + edit.run(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java b/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java index 016b1fd8..a8fc6cc8 100644 --- a/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java +++ b/src/test/java/ai/reveng/PortalAnalysisIntegrationTest.java @@ -190,6 +190,8 @@ public AnalysisID analyse(AnalysisOptionsBuilder options) throws ApiException { ), false ); + // The results are loaded in a background task + waitForTasks(); waitForSwing(); // Check that we received the results loaded event, i.e. other plugins would have been notified assertTrue(receivedResultsLoadedEvent.get()); diff --git a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java index 09131892..21ec569c 100644 --- a/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java +++ b/src/test/java/ai/reveng/PullSignaturesOnSyncTest.java @@ -2,7 +2,9 @@ import ai.reveng.model.BatchFunctionSignatureEntry; import ai.reveng.model.BatchRenameInputBody; +import ai.reveng.model.CreateAnalysisDataTypesInputBody; import ai.reveng.model.SignatureParameterEntry; +import ai.reveng.model.UpdateFunctionSignatureInputBody; 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.FunctionID; @@ -19,10 +21,13 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /// The portal -> Ghidra half of "Sync With Portal": the signature the portal holds, and the data /// types it names, land on the matched function. @@ -52,6 +57,18 @@ private static class SignatureApi extends UnimplementedAPI { String remoteSignatureName = FUNCTION_NAME; /// The name the portal gives the single parameter, or null for a parameter it does not name. String remoteParameterName = "count"; + /// What the portal reports as `has_signature`; the generated model lets a JSON null through. + Boolean remoteHasSignature = true; + /// Calls of {@link #getFunctionInfo} after which the portal stops listing the function. + int functionInfoCallsBeforeRemoval = Integer.MAX_VALUE; + /// The `source_type` the portal reports for its signature. + BatchFunctionSignatureEntry.SourceTypeEnum remoteSourceType; + /// When true the portal holds only the `undefined f(void)` placeholder extraction stores for a + /// function Ghidra had no signature for. + boolean remotePlaceholder = false; + /// Every function a signature was pushed for. + final List pushedSignatures = new ArrayList<>(); + private long nextDataTypeId = 100; @Override public AnalysisStatus status(AnalysisID analysisID) { @@ -60,6 +77,9 @@ public AnalysisStatus status(AnalysisID analysisID) { @Override public List getFunctionInfo(AnalysisID analysisID) { + if (functionInfoCallsBeforeRemoval-- <= 0) { + return List.of(); + } return List.of(new FunctionInfo( new FunctionID(FUNCTION_ID), FUNCTION_NAME, FUNCTION_NAME, ADDRESS, 0x100)); } @@ -67,14 +87,24 @@ public List getFunctionInfo(AnalysisID analysisID) { @Override public FunctionSignatureBatch listFunctionSignatures(List functionIDs, boolean includeDataTypes) { - if (remoteReturnType == null) { - return FunctionSignatureBatch.empty(); - } var entry = new BatchFunctionSignatureEntry(); entry.setAnalysisId(1L); entry.setFunctionId(FUNCTION_ID); entry.setFunctionName(remoteSignatureName); - entry.setHasSignature(true); + entry.setHasSignature(remoteHasSignature); + if (remotePlaceholder) { + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM); + entry.setReturnDataTypeId(0L); + entry.setParameters(List.of()); + var undefined = new ServerDataType(0L, "", "undefined", ServerDataType.Kind.BASE, + 1L, "AUTO", false, null, null, null); + return new FunctionSignatureBatch(List.of(entry), + Map.of(new AnalysisID(1), List.of(undefined))); + } + if (remoteReturnType == null) { + return FunctionSignatureBatch.empty(); + } + entry.setSourceType(remoteSourceType); entry.setReturnDataTypeId(1L); var parameter = new SignatureParameterEntry(); parameter.setOrdinal(0L); @@ -89,8 +119,26 @@ public FunctionSignatureBatch listFunctionSignatures(List functionID } @Override - public void batchRenameFunctions(BatchRenameInputBody request) { + public long batchRenameFunctions(BatchRenameInputBody request) { // A name pushback is not what these tests are about; accept and ignore it. + return request.getFunctions().size(); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + return List.of(); + } + + @Override + public List createAnalysisDataTypes(AnalysisID analysisID, + CreateAnalysisDataTypesInputBody request) { + return CreatedDataTypes.echo(request, () -> nextDataTypeId++); + } + + @Override + public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID, + UpdateFunctionSignatureInputBody signature) { + pushedSignatures.add(functionID); } } @@ -100,6 +148,11 @@ private record Fixture(GhidraRevengService service, GhidraRevengService.Analysed /// Attach an analysis that holds no signature yet, so the attach-time pull leaves the local /// signature alone and each test can decide what the portal gains afterwards. private Fixture attachWithoutRemoteSignature(SignatureApi api) throws Exception { + return attachWithoutRemoteSignature(api, SourceType.ANALYSIS); + } + + private Fixture attachWithoutRemoteSignature(SignatureApi api, SourceType localSignatureSource) + throws Exception { var service = new GhidraRevengService(api); var builder = newX64Program(); builder.createMemory("mem", "0x4000", 0x100); @@ -110,8 +163,8 @@ private Fixture attachWithoutRemoteSignature(SignatureApi api) throws Exception // to leave alone. A real stripped binary's signature comes from Ghidra's own analysis, and // that is the case under test: it is neither hand-written nor default, so the old // "default signatures only" guard skipped exactly these. - program.withTransaction("mark the signature analysis-derived", () -> - function.setSignatureSource(SourceType.ANALYSIS)); + program.withTransaction("set the local signature's source", () -> + function.setSignatureSource(localSignatureSource)); var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); @@ -215,4 +268,140 @@ public void leavesASignatureTheAnalystWroteAlone() throws Exception { 0, summary.appliedSignatures()); assertEquals("char", function.getReturnType().getName()); } + + /// Extraction stores `undefined f(void)` for every function Ghidra had nothing for. Applying it + /// erased real DWARF and analysis signatures on every QA binary. + @Test + public void doesNotApplyThePortalsPlaceholderSignature() throws Exception { + var api = new SignatureApi(); + api.remotePlaceholder = true; + var fixture = attachWithoutRemoteSignature(api, SourceType.IMPORTED); + + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(0, summary.appliedSignatures()); + assertEquals("the local signature survives attach and sync", + "undefined8", fixture.function().getReturnType().getName()); + } + + /// A placeholder is a stored row the signature PUT accepts, so it is exactly where the better + /// local signature can be pushed. + @Test + public void pushesTheLocalSignatureWhenThePortalOnlyHasAPlaceholder() throws Exception { + var api = new SignatureApi(); + api.remotePlaceholder = true; + var fixture = attachWithoutRemoteSignature(api, SourceType.IMPORTED); + + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(1, summary.pushedTypeSets()); + assertEquals(List.of(new FunctionID(FUNCTION_ID)), api.pushedSignatures); + } + + /// A function Ghidra knows nothing about has nothing worth pushing over the placeholder. + @Test + public void doesNotPushADefaultLocalSignatureOverAPlaceholder() throws Exception { + var api = new SignatureApi(); + api.remotePlaceholder = true; + var fixture = attachWithoutRemoteSignature(api, SourceType.DEFAULT); + + fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertTrue(api.pushedSignatures.isEmpty()); + } + + /// A signature the server extracted itself is what server-side Ghidra worked out, so it never + /// replaces one local analysis inferred or debug info supplied. + @Test + public void aSignatureTheServerExtractedDoesNotReplaceALocalAnalysisOne() throws Exception { + var api = new SignatureApi(); + api.remoteSourceType = BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM; + var fixture = attachWithoutRemoteSignature(api); + + api.remoteReturnType = "int"; + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(0, summary.appliedSignatures()); + assertEquals("undefined8", fixture.function().getReturnType().getName()); + } + + @Test + public void aSignatureTheServerExtractedStillFillsADefaultLocalOne() throws Exception { + var api = new SignatureApi(); + api.remoteSourceType = BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM; + var fixture = attachWithoutRemoteSignature(api, SourceType.DEFAULT); + + api.remoteReturnType = "int"; + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(1, summary.appliedSignatures()); + assertEquals("int", fixture.function().getReturnType().getName()); + } + + /// An edit made in the portal still beats what Ghidra inferred. + @Test + public void aSignatureEditedInThePortalReplacesALocalAnalysisOne() throws Exception { + var api = new SignatureApi(); + api.remoteSourceType = BatchFunctionSignatureEntry.SourceTypeEnum.USER; + var fixture = attachWithoutRemoteSignature(api); + + api.remoteReturnType = "int"; + var summary = fixture.service().syncAnalysisUpdates(fixture.analysed(), TaskMonitor.DUMMY, NOOP_LOG); + + assertEquals(1, summary.appliedSignatures()); + assertEquals("int", fixture.function().getReturnType().getName()); + } + + @Test + public void nullHasSignatureIsTreatedAsNoSignature() throws Exception { + var api = new SignatureApi(); + api.remoteReturnType = "int"; + api.remoteHasSignature = null; + + var fixture = attachWithoutRemoteSignature(api); + + assertEquals("undefined8", fixture.function().getReturnType().getName()); + } + + /// The function list can change between the attach-time association and the pull that follows. + @Test + public void functionNoLongerListedByThePortalIsSkipped() throws Exception { + var api = new SignatureApi(); + api.functionInfoCallsBeforeRemoval = 1; + + var fixture = attachWithoutRemoteSignature(api); + + assertEquals(FUNCTION_NAME, fixture.function().getName()); + } + + /// A failure while pulling must not leave the program's transaction open. + @Test + public void failedPullDoesNotLeakTransaction() throws Exception { + var api = new SignatureApi() { + int calls = 0; + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + // The pull runs after the attach-time association; make it fail there. + if (calls++ == 0) { + return super.getFunctionInfo(analysisID); + } + throw new RuntimeException("simulated failure"); + } + }; + var service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("mem", "0x4000", 0x100); + builder.createEmptyFunction(FUNCTION_NAME, "0x4000", 0x100, Undefined.getUndefinedDataType(8)); + var program = builder.getProgram(); + var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); + + try { + service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + } catch (RuntimeException expected) { + // the transaction is what matters + } + + assertNull("transaction must be closed", program.getCurrentTransactionInfo()); + } } diff --git a/src/test/java/ai/reveng/PushFunctionTypesTest.java b/src/test/java/ai/reveng/PushFunctionTypesTest.java index 9f1cf827..bd3d120e 100644 --- a/src/test/java/ai/reveng/PushFunctionTypesTest.java +++ b/src/test/java/ai/reveng/PushFunctionTypesTest.java @@ -5,12 +5,16 @@ import ai.reveng.model.UpdateAnalysisDataTypesInputBody; import ai.reveng.model.UpdateFunctionSignatureInputBody; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.UnresolvedDataTypesException; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; 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.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; import ghidra.app.cmd.function.CreateFunctionCmd; import ghidra.program.model.data.IntegerDataType; import ghidra.program.model.data.PointerDataType; @@ -21,12 +25,17 @@ import ghidra.util.task.TaskMonitor; import org.junit.Test; +import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /// Tests how {@link GhidraRevengService#pushFunctionTypes} composes the two halves of the write /// path: batch data-type management, then one signature write per function. @@ -37,9 +46,12 @@ public class PushFunctionTypesTest extends RevEngMockableHeadedIntegrationTest { /// Records every write and assigns ids to created types the way the server does. private static class RecordingApi extends UnimplementedAPI { - final List calls = new ArrayList<>(); - final List signatures = new ArrayList<>(); - final List signedFunctions = new ArrayList<>(); + final List calls = new CopyOnWriteArrayList<>(); + final List signatures = new CopyOnWriteArrayList<>(); + final List signedFunctions = new CopyOnWriteArrayList<>(); + final List updates = new CopyOnWriteArrayList<>(); + /// Types the server leaves out of its create response, so they never get an id. + volatile Set uncreatable = Set.of(); private long nextId = 100; @Override @@ -64,21 +76,14 @@ public List listAnalysisDataTypes(AnalysisID analysisID, long of public List createAnalysisDataTypes(AnalysisID analysisID, CreateAnalysisDataTypesInputBody request) { calls.add("create"); - List created = new ArrayList<>(); - for (var entry : request.getDataTypes()) { - Object instance = entry.getActualInstance(); - created.add(new ServerDataType(nextId++, string(instance, "getNamespace"), - string(instance, "getName"), - ServerDataType.Kind.fromJson(string(instance, "getKind")), - null, "USER", false, null, null, null)); - } - return created; + return CreatedDataTypes.echo(request, () -> nextId++, name -> !uncreatable.contains(name)); } @Override public List updateAnalysisDataTypes(AnalysisID analysisID, UpdateAnalysisDataTypesInputBody request) { calls.add("update"); + updates.add(request); return List.of(); } @@ -97,14 +102,6 @@ public void updateFunctionSignature(AnalysisID analysisID, FunctionID functionID signatures.add(signature); } - private static String string(Object target, String method) { - try { - Object value = target.getClass().getMethod(method).invoke(target); - return value == null ? null : value.toString(); - } catch (ReflectiveOperationException e) { - throw new RuntimeException(e); - } - } } private record Fixture(GhidraRevengService service, @@ -144,7 +141,8 @@ private Fixture twoFunctionsSharingAStruct() throws Exception { public void multiFunctionPushResolvesTypesOnceThenWritesEachSignature() throws Exception { var fixture = twoFunctionsSharingAStruct(); - int pushed = fixture.service().pushFunctionTypes(fixture.analysedProgram(), fixture.functions()); + int pushed = fixture.service().pushFunctionTypes(fixture.analysedProgram(), fixture.functions()) + .signaturesWritten(); assertEquals("both signatures written", 2, pushed); assertEquals("one catalogue read for the whole push", 1, count(fixture.api(), "list")); @@ -230,6 +228,213 @@ public void singleFunctionPushReportsAFunctionTheAnalysisDoesNotKnow() throws Ex assertEquals(GhidraRevengService.TypePushOutcome.NOT_MATCHED, outcome); } + /// A function whose parameter points at a struct with `members` members of distinct struct types, + /// so its closure holds a little over `members` types. + private static Function functionReachingStructs(ghidra.program.database.ProgramBuilder builder, String name, + String address, int members) throws Exception { + var state = new StructureDataType(name + "_state", 0); + for (int i = 0; i < members; i++) { + state.add(new StructureDataType(name + "_member_" + i, 4), "m" + i, null); + } + return builder.createEmptyFunction(name, address, 0x100, new IntegerDataType(), + new ParameterImpl("state", new PointerDataType(state), builder.getProgram())); + } + + /// Two functions that each reach about 300 types, under the 500-type closure cap on their own + /// but over it together. Capping the union left some of the second function's types without an + /// id, and its struct then went up with null member types, erasing them on the portal. + @Test + public void aBatchOverTheClosureCapSendsNoNullTypeIds() throws Exception { + var api = new RecordingApi(); + var service = new GhidraRevengService(api); + var builder = newX64Program("push"); + builder.createMemory("code", "0x4000", 0x400); + Function first = functionReachingStructs(builder, "first", "0x4000", 300); + Function second = functionReachingStructs(builder, "second", "0x4200", 300); + var programWithID = service.registerAnalysisForProgram(builder.getProgram(), new AnalysisID(1)); + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + var push = service.pushFunctionTypes(analysedProgram, List.of(first, second)); + + assertEquals("nothing held back: " + push.withheld(), 0, push.withheld().size()); + assertEquals("both signatures written", 2, push.signaturesWritten()); + List referenced = new ArrayList<>(); + java.util.Map stateMembers = new java.util.HashMap<>(); + for (var request : api.updates) { + for (var entry : request.getDataTypes()) { + referenced.addAll(referencedIds(entry.getActualInstance())); + if (entry.getActualInstance() instanceof ai.reveng.model.UpdateStructDataType struct) { + stateMembers.put(struct.getName(), struct.getDefinition().getMembers().size()); + } + } + } + assertEquals("both structs were written in full", + java.util.Map.of("first_state", 300, "second_state", 300), stateMembers); + assertFalse("no type write names a null type", referenced.contains(null)); + for (var signature : api.signatures) { + assertNotNull(signature.getReturnDataTypeId()); + signature.getParameters().forEach(parameter -> assertNotNull(parameter.getDataTypeId())); + } + } + + /// Every `data_type_id` an update body refers to, nulls included. + private static List referencedIds(Object update) { + List ids = new ArrayList<>(); + if (update instanceof ai.reveng.model.UpdateStructDataType struct) { + struct.getDefinition().getMembers().forEach(member -> ids.add(member.getDataTypeId())); + } else if (update instanceof ai.reveng.model.UpdateUnionDataType union) { + union.getDefinition().getMembers().forEach(member -> ids.add(member.getDataTypeId())); + } else if (update instanceof ai.reveng.model.UpdatePointerDataType pointer) { + ids.add(pointer.getDefinition().getPointeeDataTypeId()); + } else if (update instanceof ai.reveng.model.UpdateTypedefDataType typedef) { + ids.add(typedef.getDefinition().getTargetDataTypeId()); + } else if (update instanceof ai.reveng.model.UpdateArrayDataType array) { + ids.add(array.getDefinition().getElementDataTypeId()); + } else if (update instanceof ai.reveng.model.UpdateFunctionDataType function) { + function.getDefinition().getParameters().forEach(parameter -> ids.add(parameter.getDataTypeId())); + ids.add(function.getDefinition().getReturnDataTypeId()); + } + return ids; + } + + /// The first function takes a pointer to a struct the server never gives an id; the second + /// only takes an int. + private Fixture oneFunctionWithAnUnresolvableType() throws Exception { + var api = new RecordingApi(); + api.uncreatable = Set.of("orphan_t"); + var service = new GhidraRevengService(api); + var builder = newX64Program("push"); + builder.createMemory("code", "0x4000", 0x400); + var program = builder.getProgram(); + var orphan = new StructureDataType("orphan_t", 0); + orphan.add(new IntegerDataType(), "count", null); + Function first = builder.createEmptyFunction("first", "0x4000", 0x100, new IntegerDataType(), + new ParameterImpl("state", new PointerDataType(orphan), program)); + Function second = builder.createEmptyFunction("second", "0x4200", 0x100, new IntegerDataType(), + new ParameterImpl("count", new IntegerDataType(), program)); + var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + api.calls.clear(); + return new Fixture(service, api, analysedProgram, List.of(first, second)); + } + + @Test + public void aFunctionReachingATypeWithNoIdIsNotSentAndStaysUnpushed() throws Exception { + var fixture = oneFunctionWithAnUnresolvableType(); + var program = fixture.analysedProgram().program(); + Function first = fixture.functions().get(0); + Function second = fixture.functions().get(1); + fixture.functions().forEach(function -> + UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint())); + + var flush = fixture.service().pushUnpushedEdits(fixture.analysedProgram()); + + assertEquals("only the second signature went up", List.of(new FunctionID(2)), fixture.api().signedFunctions); + assertTrue("the held-back edit is still marked", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, first.getEntryPoint())); + assertFalse("the other one went up", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, second.getEntryPoint())); + assertEquals(1, flush.pushed()); + assertEquals(1, flush.rejected().size()); + var rejected = flush.rejected().get(0); + assertTrue(rejected.edit(), rejected.edit().contains("\"first\"")); + assertTrue(rejected.error().getMessage(), rejected.error().getMessage().contains("orphan_t")); + for (var request : fixture.api().updates) { + for (var entry : request.getDataTypes()) { + assertFalse("no type write names a null type", + referencedIds(entry.getActualInstance()).contains(null)); + } + } + } + + @Test + public void singleFunctionPushThrowsWhenATypeHasNoId() throws Exception { + var fixture = oneFunctionWithAnUnresolvableType(); + try { + fixture.service().pushFunctionTypes(fixture.analysedProgram(), fixture.functions().get(0)); + fail("the push should have been held back"); + } catch (UnresolvedDataTypesException e) { + assertTrue(e.typeNames().toString(), e.typeNames().contains("orphan_t")); + } + assertTrue("no signature was sent", fixture.api().signedFunctions.isEmpty()); + } + + /// The reactive push holds the edit back, keeps it marked, and reports it like any other edit the + /// portal did not take. + @Test + public void aReactiveEditReachingATypeWithNoIdIsReportedAndKept() throws Exception { + var fixture = oneFunctionWithAnUnresolvableType(); + var program = fixture.analysedProgram().program(); + Function second = fixture.functions().get(1); + List warnings = new CopyOnWriteArrayList<>(); + var sync = new LocalEditSyncService(fixture.service(), new ReaiLoggingService() { + @Override public void info(String message) {} + @Override public void warn(String message) {} + @Override public void error(String message) {} + }, (message, warning) -> { + if (warning) { + warnings.add(message); + } + }, List.of(Duration.ofHours(1))); + sync.attach(program); + try { + var orphan = new StructureDataType("orphan_t", 0); + orphan.add(new IntegerDataType(), "count", null); + program.withTransaction("retype", () -> + second.setReturnType(new PointerDataType(orphan), SourceType.USER_DEFINED)); + program.flushEvents(); + + waitForCondition(() -> !warnings.isEmpty(), "the held-back edit should be reported"); + assertTrue(warnings.get(0), warnings.get(0).contains("did not take")); + assertTrue("the edit is kept for the next sync", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, second.getEntryPoint())); + assertFalse("its signature was never sent", fixture.api().signedFunctions.contains(new FunctionID(2))); + } finally { + sync.dispose(); + } + } + + /// One function whose own closure is over the cap: its struct has more distinct member types + /// than the walk takes. The types at the edge of the walk refer to ones it never reached, so the + /// signature and those definitions would carry null ids; the function is held back instead, and + /// the reason names the limit rather than blaming the portal. + @Test + public void aFunctionOverTheClosureCapOnItsOwnSendsNoNullIdsAndStaysUnpushed() throws Exception { + var api = new RecordingApi(); + var service = new GhidraRevengService(api); + var builder = newX64Program("push"); + builder.createMemory("code", "0x4000", 0x400); + Function big = functionReachingStructs(builder, "first", "0x4000", 600); + var program = builder.getProgram(); + var programWithID = service.registerAnalysisForProgram(program, new AnalysisID(1)); + var analysedProgram = service.registerFinishedAnalysisForProgram(programWithID, TaskMonitor.DUMMY); + + try { + service.pushFunctionTypes(analysedProgram, big); + fail("the push should have been held back"); + } catch (UnresolvedDataTypesException e) { + assertTrue("the limit is the cause", e.pastClosureLimit()); + assertTrue(e.getMessage(), e.getMessage().contains("more than 500 data types")); + } + + UnpushedEdits.mark(program, UnpushedEdits.Kind.TYPES, big.getEntryPoint()); + var flush = service.pushUnpushedEdits(analysedProgram); + + assertTrue("no signature was sent", api.signedFunctions.isEmpty()); + assertTrue("the edit is still marked", + UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, big.getEntryPoint())); + assertEquals(1, flush.rejected().size()); + for (var request : api.updates) { + for (var entry : request.getDataTypes()) { + assertFalse("no type write names a null type", + referencedIds(entry.getActualInstance()).contains(null)); + if (entry.getActualInstance() instanceof ai.reveng.model.UpdateStructDataType struct) { + assertFalse("the struct is not written in part", struct.getName().equals("first_state")); + } + } + } + } + private static int count(RecordingApi api, String call) { return (int) api.calls.stream().filter(call::equals).count(); } diff --git a/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java b/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java index 7fc07b6c..c9b04e23 100644 --- a/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java +++ b/src/test/java/ai/reveng/ReaiAPIServicePluginTest.java @@ -108,4 +108,29 @@ public void testPluginFailsToLoadWithMalformedConfigFile() throws Exception { var service = tool.getService(GhidraRevengService.class); assertNull("GhidraRevengService should not be registered with bad config", service); } + + /// Valid JSON lacking `pluginSettings` must be reported like a malformed file, not crash the plugin. + @Test + public void testPluginFailsToLoadWithConfigFileMissingPluginSettings() throws Exception { + setErrorGUIEnabled(true); + var tool = env.getTool(); + + Path configFile = createTempDirectory("reai-test").toPath().resolve("reai.json"); + Files.writeString(configFile, "{}"); + + TestableReaiAPIServicePlugin.setConfigPathOverride(configFile); + + runSwing(() -> { + try { + tool.addPlugin(TestableReaiAPIServicePlugin.class.getName()); + } catch (Exception e) { + // Expected — plugin should fail after showing error dialog + } + }, false); + + var errorDialog = waitForDialogComponent("Load Config"); + assertNotNull("Error dialog should appear for config without pluginSettings", errorDialog); + close(errorDialog); + waitForSwing(); + } } diff --git a/src/test/java/ai/reveng/RecentAnalysisDialogTest.java b/src/test/java/ai/reveng/RecentAnalysisDialogTest.java index aae9693b..856d7c56 100644 --- a/src/test/java/ai/reveng/RecentAnalysisDialogTest.java +++ b/src/test/java/ai/reveng/RecentAnalysisDialogTest.java @@ -8,10 +8,14 @@ import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; import ai.reveng.model.AnalysisRecordBody; import docking.DockingWindowManager; +import ghidra.framework.Log4jErrorLogger; +import ghidra.util.DefaultErrorLogger; +import ghidra.util.Msg; import org.junit.Test; import javax.swing.*; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -107,6 +111,53 @@ public void testSelectRecentAnalysisFiresEventAndUpdatesKnownProgram() throws Ex eventProgramWithID.program(), knownProgram.get().program()); } + @Test + public void testDoubleClickPicksAnalysisAndRightClickOffersPortal() throws Exception { + var tool = env.getTool(); + var service = addMockedService(tool, new RecentAnalysesMockApi()); + + var builder = newX64Program("test_binary"); + builder.createMemory("test", "0x1000", 100); + var program = builder.getProgram(); + env.showTool(program); + waitForSwing(); + + AtomicBoolean eventReceived = new AtomicBoolean(false); + tool.addEventListener(RevEngAIAnalysisStatusChangedEvent.class, e -> eventReceived.set(true)); + + RecentAnalysisDialog dialog = runSwing(() -> new RecentAnalysisDialog(tool, program)); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(RecentAnalysisDialog.class); + + @SuppressWarnings("unchecked") + var tableModel = (docking.widgets.table.threaded.ThreadedTableModel) + getInstanceField("recentAnalysesTableModel", foundDialog); + waitForTableModel(tableModel); + @SuppressWarnings("unchecked") + var table = ((ghidra.util.table.GhidraFilterTable) + getInstanceField("recentAnalysesTable", foundDialog)).getTable(); + + clickTableCell(table, 0, 0, 1); + assertFalse("Single click should only select", eventReceived.get()); + + var cell = runSwing(() -> table.getCellRect(0, 0, true)); + var rightClick = new java.awt.event.MouseEvent(table, java.awt.event.MouseEvent.MOUSE_PRESSED, + System.currentTimeMillis(), java.awt.event.InputEvent.BUTTON3_DOWN_MASK, + cell.x + 1, cell.y + 1, 1, true, java.awt.event.MouseEvent.BUTTON3); + runSwing(() -> table.dispatchEvent(rightClick)); + var popup = (JPopupMenu) getInstanceField("portalPopup", foundDialog); + assertTrue("Right click should show the portal popup", runSwing(popup::isVisible)); + assertTrue("Right click should not reach the docking popup", rightClick.isConsumed()); + assertEquals(1, popup.getComponentCount()); + assertEquals("Open in Portal", ((JMenuItem) popup.getComponent(0)).getText()); + runSwing(() -> popup.setVisible(false)); + + clickTableCell(table, 0, 0, 2); + waitForCondition(eventReceived::get, "Double click should pick the analysis"); + assertEquals(RecentAnalysesMockApi.MOCK_ANALYSIS_ID, + service.getKnownProgram(program).orElseThrow().analysisID().id()); + } + @Test public void testDialogShowsRecentAnalyses() throws Exception { var tool = env.getTool(); @@ -145,6 +196,68 @@ public void testDialogShowsRecentAnalyses() throws Exception { waitForSwing(); } + @Test + public void testPickSelectedWithoutSelectionDoesNothing() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new RecentAnalysesMockApi()); + + var builder = newX64Program("test_binary"); + builder.createMemory("test", "0x1000", 100); + var program = builder.getProgram(); + env.showTool(program); + waitForSwing(); + + List errors = new CopyOnWriteArrayList<>(); + Msg.setErrorLogger(new DefaultErrorLogger() { + @Override + public void error(Object originator, Object message, Throwable throwable) { + errors.add(message); + } + }); + try { + RecentAnalysisDialog dialog = runSwing(() -> new RecentAnalysisDialog(tool, program)); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(RecentAnalysisDialog.class); + + pressButton(findButtonByText(foundDialog.getComponent(), "Pick selected")); + waitForTasks(); + waitForSwing(); + + assertEquals(List.of(), errors); + close(foundDialog); + } finally { + Msg.setErrorLogger(new Log4jErrorLogger()); + } + } + + @Test + public void testPickMostRecentWithoutAnalysesDoesNothing() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new UnimplementedAPI() { + @Override + public List search(TypedApiInterface.BinaryHash hash) { + return List.of(); + } + }); + + var builder = newX64Program("test_binary"); + builder.createMemory("test", "0x1000", 100); + var program = builder.getProgram(); + env.showTool(program); + waitForSwing(); + + RecentAnalysisDialog dialog = runSwing(() -> new RecentAnalysisDialog(tool, program)); + runSwing(() -> DockingWindowManager.showDialog(null, dialog), false); + var foundDialog = waitForDialogComponent(RecentAnalysisDialog.class); + waitForTasks(); + + pressButton(findButtonByText(foundDialog.getComponent(), "Pick most recent")); + waitForSwing(); + + assertTrue("dialog should stay open", foundDialog.isVisible()); + close(foundDialog); + } + /** * Mock API implementation for recent analysis dialog tests. * Provides necessary responses for the dialog to function without a real server. diff --git a/src/test/java/ai/reveng/RejectedLocalEditsTest.java b/src/test/java/ai/reveng/RejectedLocalEditsTest.java new file mode 100644 index 00000000..760643f4 --- /dev/null +++ b/src/test/java/ai/reveng/RejectedLocalEditsTest.java @@ -0,0 +1,177 @@ +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.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +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.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/// Failures that sending again cannot fix: an edit the portal turns down, and a refused API key. +public class RejectedLocalEditsTest extends RevEngMockableHeadedIntegrationTest { + + /// Two functions, at 0x4000 (id 1) and 0x4100 (id 2). + private static class PickyApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + final AtomicInteger renameRequests = new AtomicInteger(); + /// The portal validates the whole request, so one name it refuses fails the batch. + volatile String refusedPrefix = "bad_"; + volatile boolean keyRefused; + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of( + new FunctionInfo(new FunctionID(1), "FUN_00004000", "FUN_00004000", 0x4000L, 0x100), + new FunctionInfo(new FunctionID(2), "FUN_00004100", "FUN_00004100", 0x4100L, 0x100)); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + renameRequests.incrementAndGet(); + if (keyRefused) { + throw new ApiException(401, "Unauthorized"); + } + if (request.getFunctions().stream().anyMatch(item -> item.getNewName().startsWith(refusedPrefix))) { + throw new ApiException(422, "Unprocessable Entity"); + } + request.getFunctions().forEach(item -> renamed.put(item.getFunctionId(), item.getNewName())); + return request.getFunctions().size(); + } + } + + private static class RecordingLog implements ReaiLoggingService { + final List warnings = new CopyOnWriteArrayList<>(); + @Override public void info(String message) {} + @Override public void warn(String message) { warnings.add(message); } + @Override public void error(String message) {} + } + + private final PickyApi api = new PickyApi(); + private final RecordingLog log = new RecordingLog(); + private final List statusWarnings = new CopyOnWriteArrayList<>(); + private final List statusInfos = new CopyOnWriteArrayList<>(); + private Program program; + private Function first; + private Function second; + private LocalEditSyncService sync; + + @Before + public void analyse() throws Exception { + var service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("code", "0x4000", 0x200); + first = builder.createEmptyFunction("FUN_00004000", "0x4000", 0x100, new IntegerDataType()); + second = builder.createEmptyFunction("FUN_00004100", "0x4100", 0x100, new IntegerDataType()); + program = builder.getProgram(); + var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + // A retry after a wait only happens when the portal cannot be reached, which these tests + // never do; one that came anyway would show up as an extra request. + sync = new LocalEditSyncService(service, log, + (message, warning) -> (warning ? statusWarnings : statusInfos).add(message), + List.of(Duration.ofHours(1))); + sync.attach(program); + } + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + private void rename(Function function, String newName) throws Exception { + program.withTransaction("rename", () -> function.setName(newName, SourceType.USER_DEFINED)); + program.flushEvents(); + } + + private boolean marked(Function function) { + return UnpushedEdits.isMarked(program, UnpushedEdits.Kind.NAME, function.getEntryPoint()); + } + + @Test + public void anEditThePortalTurnsDownDoesNotHoldBackTheOthers() throws Exception { + // Both in one debounce window, so they go up as one batch, which the portal refuses. + rename(first, "good_one"); + rename(second, "bad_two"); + + waitForCondition(() -> !statusWarnings.isEmpty(), "the rejected edit should be reported"); + assertEquals(Map.of(1L, "good_one"), api.renamed); + assertFalse("the accepted rename is no longer waiting", marked(first)); + assertTrue("the rejected rename stays for the next sync", marked(second)); + assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("will not be retried")); + assertTrue(log.warnings.stream().anyMatch(warning -> warning.contains("\"bad_two\""))); + + // Nothing is sent after that: a rejected edit is not retried automatically. + int requests = api.renameRequests.get(); + Thread.sleep(1_000); + assertEquals(requests, api.renameRequests.get()); + assertEquals(1, statusWarnings.size()); + } + + @Test + public void anEditTurnedDownAgainIsNotReportedAgain() throws Exception { + rename(second, "bad_two"); + waitForCondition(() -> !statusWarnings.isEmpty(), "the rejected edit should be reported"); + + // Another rejected edit to the same function sends both again; only the new one is news. + rename(first, "bad_one"); + waitForCondition(() -> statusWarnings.size() == 2, "the second rejected edit should be reported"); + assertTrue(statusWarnings.get(1), statusWarnings.get(1).contains("did not take 1 local edit")); + } + + @Test + public void aRefusedKeyIsReportedOnceAndResumesWhenAPushSucceeds() throws Exception { + api.keyRefused = true; + rename(first, "first_name"); + waitForCondition(() -> !statusWarnings.isEmpty(), "the refused key should be reported"); + assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("API key")); + + // Each rename is tried once by itself and once by the retry that follows its failure. + rename(first, "first_name_again"); + waitForCondition(() -> api.renameRequests.get() >= 4, "the second rename should be tried"); + Thread.sleep(500); + assertEquals("one report while the key is refused: " + statusWarnings, 1, statusWarnings.size()); + int requestsWhileRefused = api.renameRequests.get(); + Thread.sleep(1_000); + assertEquals("no retries while the key is refused", requestsWhileRefused, api.renameRequests.get()); + + api.keyRefused = false; + rename(second, "second_name"); + waitForCondition(() -> api.renamed.size() == 2, "the earlier rename should follow the one that got through"); + assertEquals(Map.of(1L, "first_name_again", 2L, "second_name"), api.renamed); + // The mock records the rename inside the send, and the mark is cleared only once the send returns. + waitForCondition(() -> !marked(first), "the earlier rename should no longer be marked"); + waitForCondition(() -> !statusInfos.isEmpty(), "the edits that followed should be reported"); + assertTrue(statusInfos.get(0), statusInfos.get(0).contains("pushed 1 local edit")); + } +} diff --git a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java index 9f25a0fb..ab79aae5 100644 --- a/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java +++ b/src/test/java/ai/reveng/RevEngMockableHeadedIntegrationTest.java @@ -3,6 +3,11 @@ import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.plugins.LoggingPlugin; +import docking.DialogComponentProvider; +import generic.jar.ResourceFile; +import ghidra.GhidraTestApplicationLayout; +import utility.application.ApplicationLayout; +import ghidra.framework.GModule; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.mgr.ServiceManager; import ghidra.framework.plugintool.util.PluginException; @@ -12,12 +17,34 @@ import org.junit.After; import org.junit.Before; +import java.io.File; import java.io.IOException; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BooleanSupplier; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; /// Base class abstract class RevEngMockableHeadedIntegrationTest extends AbstractGhidraHeadedIntegrationTest { protected TestEnv env; + /// Registers this project as a module so its data/*.theme.properties load, as for an installed extension. + @Override + protected ApplicationLayout createApplicationLayout() throws IOException { + return new GhidraTestApplicationLayout(new File(getTestDirectoryPath())) { + @Override + protected Map findGhidraModules() throws IOException { + var modules = new HashMap<>(super.findGhidraModules()); + var root = new ResourceFile(new File("").getAbsoluteFile()); + modules.put(root.getName(), new GModule(applicationRootDirs, root)); + return modules; + } + }; + } + @Before public void setup() throws IOException, PluginException { // For most tests we want to fail if a user visible error would show up. @@ -44,6 +71,48 @@ protected ProgramBuilder newX64Program(String name) throws Exception { return new ProgramBuilder(name, ProgramBuilder._X64, this); } + /// Polls for a dialog against this test's own deadline: the timeout that waitForDialogComponent takes is + /// ignored in favour of Ghidra's 2s default, which a slow CI runner can exceed while a task is still running + protected static T awaitDialog(Class type) { + return awaitDialog(type, "timed out waiting for " + type.getSimpleName()); + } + + /// As {@link #awaitDialog(Class)}, failing with the given message so a CI timeout says what was expected + protected static T awaitDialog(Class type, String message) { + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + T dialog; + while ((dialog = getDialogComponent(type)) == null && System.nanoTime() < deadline) { + sleep(DEFAULT_WAIT_DELAY); + } + if (dialog == null) { + // Only seen on CI so far; the stacks show where the work that leads to the dialog stopped + System.err.println("awaitDialog timed out: " + message + "\n" + threadDump()); + } + assertNotNull(message, dialog); + return dialog; + } + + private static String threadDump() { + var dump = new StringBuilder(); + Thread.getAllStackTraces().forEach((thread, stack) -> { + dump.append('"').append(thread.getName()).append("\" ").append(thread.getState()).append('\n'); + for (var frame : stack) { + dump.append(" at ").append(frame).append('\n'); + } + }); + return dump.toString(); + } + + /// Like waitForCondition, but against this test's own 30s deadline: Ghidra's default limit is about 2s, which + /// a wait that spans a real poll interval (function matching sleeps 2s between polls) can exceed on CI + protected static void awaitCondition(BooleanSupplier condition, String message) { + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + boolean met; + while (!(met = condition.getAsBoolean()) && System.nanoTime() < deadline) { + sleep(DEFAULT_WAIT_DELAY); + } + assertTrue(message, met); + } /// This method adds a provided mocked service to the tool diff --git a/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java b/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java index 6772a52a..25870b62 100644 --- a/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java +++ b/src/test/java/ai/reveng/ServerDataTypeDecoderTest.java @@ -218,4 +218,66 @@ public void resolvesBaseTypesByName() { assertEquals("int", decoder.typeFor(1L, 0).getName()); } + + /// `size` is nullable on the wire. An unsized type that falls back to a filler must not fail the + /// decode. + @Test + public void unsizedTypesFallBackToFiller() { + var decoder = ServerDataTypeDecoder.decode(types(""" + {"items": [ + {"data_type_id": 1, "namespace": "", "name": "not_a_ghidra_type", "kind": "BASE", + "size": null, "source_type": "AUTO", "has_definition": false}, + {"data_type_id": 2, "namespace": "", "name": "orphan_t", "kind": "TYPEDEF", + "source_type": "AUTO", "has_definition": false} + ]} + """)); + + assertEquals(1, decoder.typeFor(1L, 0).getLength()); + assertTrue(decoder.typeFor(2L, 0) instanceof TypeDef); + } + + /// Null entries in any array are skipped rather than failing the whole decode. + @Test + public void skipsNullArrayElements() { + var decoder = ServerDataTypeDecoder.decode(types(""" + {"items": [ + null, + {"data_type_id": 1, "namespace": "", "name": "S", "kind": "STRUCT", + "size": 4, "source_type": "AUTO", "has_definition": true, + "definition": {"members": [ + null, + {"name": "x", "offset": 0, "size": 4, "data_type_id": null, "is_bitfield": false}]}}, + {"data_type_id": 2, "namespace": "", "name": "U", "kind": "UNION", + "size": 4, "source_type": "AUTO", "has_definition": true, + "definition": {"members": [null]}}, + {"data_type_id": 3, "namespace": "", "name": "E", "kind": "ENUM", + "size": 4, "source_type": "AUTO", "has_definition": true, + "definition": {"values": [null, {"name": "NO_VALUE", "value": null}, {"name": "A", "value": "1"}]}}, + {"data_type_id": 4, "namespace": "", "name": "F", "kind": "FUNCTION_DEFINITION", + "size": 0, "source_type": "AUTO", "has_definition": true, + "definition": {"return_data_type_id": null, "parameters": [null]}} + ]} + """)); + + assertEquals("x", ((Structure) decoder.typeFor(1L, 0)).getComponentAt(0).getFieldName()); + assertEquals(1L, ((Enum) decoder.typeFor(3L, 0)).getValue("A")); + } + + /// Names Ghidra rejects (control characters, empty namespace segments) must not fail the decode. + @Test + public void sanitisesNamesGhidraRejects() { + var decoder = ServerDataTypeDecoder.decode(types(""" + {"items": [ + {"data_type_id": 1, "namespace": "ns::::inner", "name": "bad\\nname", "kind": "STRUCT", + "size": 4, "source_type": "AUTO", "has_definition": false}, + {"data_type_id": 2, "namespace": "", "name": "::", "kind": "TYPEDEF", + "size": 4, "source_type": "AUTO", "has_definition": false} + ]} + """)); + + DataType struct = decoder.typeFor(1L, 0); + assertEquals("bad_name", struct.getName()); + assertEquals("/ns/inner", struct.getCategoryPath().getPath()); + assertNotNull(decoder.typeFor(2L, 0)); + } } diff --git a/src/test/java/ai/reveng/SetupWizardTest.java b/src/test/java/ai/reveng/SetupWizardTest.java index f0be50a5..af17214a 100644 --- a/src/test/java/ai/reveng/SetupWizardTest.java +++ b/src/test/java/ai/reveng/SetupWizardTest.java @@ -179,6 +179,47 @@ public void testEditingAfterValidationResetsState() throws Exception { tool.getOptions(REAI_OPTIONS_CATEGORY).getString(ReaiPluginPackage.OPTION_KEY_APIKEY, null)); } + /** + * Hostnames without a scheme, with surrounding whitespace or trailing slashes are normalised before saving. + */ + @Test + public void testHostnamesAreNormalised() throws Exception { + var tool = env.getTool(); + + var wizardState = new WizardState(); + wizardState.put(SetupWizardStateKey.CREDENTIAL_VALIDATOR, + (CredentialValidator) apiInfo -> {}); + var tempConfigFile = createTempDirectory("reai-wizard-test").toPath().resolve("reai.json"); + wizardState.put(SetupWizardStateKey.CONFIGFILE, tempConfigFile.toString()); + + SetupWizardManager setupManager = new SetupWizardManager(wizardState, tool); + WizardManager wizardManager = new WizardManager("RevEng.AI: Configuration", true, setupManager); + runSwing(() -> wizardManager.showWizard(tool.getToolFrame()), false); + var dialog = waitForDialogComponent("RevEng.AI: Configuration"); + + JTextField apiKeyField = (JTextField) findComponentByName(dialog.getComponent(), "apiKey"); + JTextField hostnameField = (JTextField) findComponentByName(dialog.getComponent(), "apiHostname"); + JTextField portalField = (JTextField) findComponentByName(dialog.getComponent(), "portalHostname"); + setText(apiKeyField, "test-api-key"); + setText(hostnameField, "api.test.example.com:8443/ "); + setText(portalField, " https://portal.test.example.com/"); + + JButton validateButton = findButtonByText(dialog.getComponent(), "Validate Credentials"); + pressButton(validateButton); + waitForTasks(); + waitForSwing(); + + JButton finishButton = findButtonByText(dialog.getComponent(), "Finish"); + assertTrue("Finish should be enabled after validation", finishButton.isEnabled()); + pressButton(finishButton); + waitForSwing(); + + assertEquals("https://api.test.example.com:8443", + tool.getOptions(REAI_OPTIONS_CATEGORY).getString(ReaiPluginPackage.OPTION_KEY_HOSTNAME, null)); + assertEquals("https://portal.test.example.com", + tool.getOptions(REAI_OPTIONS_CATEGORY).getString(ReaiPluginPackage.OPTION_KEY_PORTAL_HOSTNAME, null)); + } + @Test public void testUserCredentialsPanel() throws Exception { var tool = env.getTool(); diff --git a/src/test/java/ai/reveng/StatusEventDeliveryTest.java b/src/test/java/ai/reveng/StatusEventDeliveryTest.java new file mode 100644 index 00000000..ab0bd15c --- /dev/null +++ b/src/test/java/ai/reveng/StatusEventDeliveryTest.java @@ -0,0 +1,67 @@ +package ai.reveng; + +import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; +import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import ghidra.framework.plugintool.PluginEvent; +import ghidra.framework.plugintool.PluginTool; +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.BiConsumer; + +import static org.junit.Assert.assertEquals; + +/// Ghidra drops an event fired while another of the same type is being delivered, taking it for an event loop. A wait +/// reports its first status from a background thread, which on a slow machine can be while the Queued event that +/// started it is still being delivered; the Error or Complete it reported was then lost. +public class StatusEventDeliveryTest extends RevEngMockableHeadedIntegrationTest { + + @Test + public void aStatusFiredLaterDuringAnotherStatusDeliveryArrives() throws Exception { + var received = deliverQueuedThenFireFromBackground(RevEngAIAnalysisStatusChangedEvent::fireLater); + + assertEquals(List.of(AnalysisStatus.Queued, AnalysisStatus.Error), received); + } + + /// Documents the Ghidra behaviour fireLater works around, so a Ghidra version that stops dropping these is noticed + @Test + public void aStatusFiredDirectlyDuringAnotherStatusDeliveryIsDropped() throws Exception { + var received = deliverQueuedThenFireFromBackground((event, tool) -> tool.firePluginEvent(event)); + + assertEquals(List.of(AnalysisStatus.Queued), received); + } + + /// Fires Queued; while it is being delivered, a background thread fires Error with {@code fire} and is waited for + private List deliverQueuedThenFireFromBackground( + BiConsumer fire) throws Exception { + var tool = env.getTool(); + var program = newX64Program().getProgram(); + var programWithID = new GhidraRevengService.ProgramWithID(program, new TypedApiInterface.AnalysisID(7)); + List received = new CopyOnWriteArrayList<>(); + + tool.addListenerForAllPluginEvents((PluginEvent event) -> { + if (!(event instanceof RevEngAIAnalysisStatusChangedEvent status)) { + return; + } + received.add(status.getStatus()); + if (status.getStatus() == AnalysisStatus.Queued) { + var waitThread = new Thread(() -> fire.accept( + new RevEngAIAnalysisStatusChangedEvent(null, programWithID, AnalysisStatus.Error), tool)); + waitThread.start(); + try { + waitThread.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); + + runSwing(() -> tool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued))); + waitForSwing(); + return List.copyOf(received); + } +} diff --git a/src/test/java/ai/reveng/TestAnalysisLogComponent.java b/src/test/java/ai/reveng/TestAnalysisLogComponent.java index a8c80870..bfda4458 100644 --- a/src/test/java/ai/reveng/TestAnalysisLogComponent.java +++ b/src/test/java/ai/reveng/TestAnalysisLogComponent.java @@ -1,20 +1,29 @@ package ai.reveng; +import ai.reveng.invoker.ApiException; import ai.reveng.toolkit.ghidra.binarysimilarity.ui.misc.AnalysisLogComponent; import ai.reveng.toolkit.ghidra.core.services.api.GhidraRevengService; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface; import ai.reveng.toolkit.ghidra.plugins.AnalysisManagementPlugin; import ai.reveng.toolkit.ghidra.core.RevEngAIAnalysisStatusChangedEvent; import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; import ai.reveng.toolkit.ghidra.core.services.api.types.*; +import docking.DefaultActionContext; +import docking.widgets.OptionDialog; import ghidra.program.model.listing.Program; import ghidra.util.task.Task; import ghidra.util.task.TaskMonitorComponent; import org.junit.Test; +import javax.swing.JTextArea; + +import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; @@ -30,6 +39,13 @@ private GhidraRevengService.ProgramWithID getPlaceHolderID() throws Exception{ ); } + /// Attach the program to its analysis, as StartAnalysisTask does before reporting it queued. Status events + /// for an analysis the program is not attached to are ignored. + private static GhidraRevengService.ProgramWithID attach(GhidraRevengService service, + GhidraRevengService.ProgramWithID programWithID) { + return service.registerAnalysisForProgram(programWithID.program(), programWithID.analysisID()); + } + /// If a user starts Ghidra for a program with an associated analysis that is still processing on the server, /// then the analysis log component should show that the analysis is still processing, and automatically /// fetch the logs and fire @@ -38,16 +54,15 @@ private GhidraRevengService.ProgramWithID getPlaceHolderID() throws Exception{ public void testResumeWaitingForProcessingAnalysis() throws Exception{ var defaultTool = env.showTool(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { @Override public AnalysisStatus status(AnalysisID analysisID) { return AnalysisStatus.Processing; } }); -// defaultTool.getService(GhidraRevengService.class); env.addPlugin(AnalysisManagementPlugin.class); - var programWithID = getPlaceHolderID(); + var programWithID = attach(service, getPlaceHolderID()); defaultTool.firePluginEvent( new RevEngAIAnalysisStatusChangedEvent( "Test", @@ -70,7 +85,7 @@ public void testFullAnalysisFlow() throws Exception { var defaultTool = env.showTool(); var programWithID = getPlaceHolderID(); - addMockedService(defaultTool, new UnimplementedAPI() { + var service = addMockedService(defaultTool, new UnimplementedAPI() { private final Map statusMap = new HashMap<>(); { @@ -96,6 +111,7 @@ public List getFunctionInfo(AnalysisID analysisID) { } } ); + attach(service, programWithID); env.addPlugin(AnalysisManagementPlugin.class); // Start a new analysis that is queued defaultTool.firePluginEvent( @@ -118,4 +134,401 @@ public List getFunctionInfo(AnalysisID analysisID) { TaskMonitorComponent taskMonitorComponent = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); assertFalse(taskMonitorComponent.isVisible()); } + + @Test + public void testTransientServerErrorsDoNotStopMonitoring() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + var logCalls = new AtomicInteger(); + + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) throws ApiException { + return switch (statusCalls.incrementAndGet()) { + case 1 -> throw new ApiException(503, "Service Unavailable"); + case 2 -> AnalysisStatus.Processing; + default -> AnalysisStatus.Complete; + }; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + if (logCalls.incrementAndGet() == 1) { + throw new RuntimeException(new ApiException(500, "Internal Server Error")); + } + return "PLACEHOLDER_LOGS"; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of(); + } + }); + attach(service, programWithID); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) + ); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + waitForTasks(); + + assertTrue(statusCalls.get() >= 3); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + } + + @Test + public void testCancelledMonitoringUntracksProgram() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Queued; + } + }); + attach(service, programWithID); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) + ); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + TaskMonitorComponent taskMonitor = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + taskMonitor.cancel(); + waitForTasks(); + + assertFalse(trackedPrograms.containsKey(programWithID.program())); + TaskMonitorComponent taskMonitorComponent = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + assertFalse(taskMonitorComponent.isVisible()); + } + + /// A wait's statuses are delivered after it reported them, so one can arrive once the wait has been cancelled. + /// It must not start the wait again. + @Test + public void testStatusFromACancelledWaitDoesNotResumeIt() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.incrementAndGet(); + return AnalysisStatus.Queued; + } + }); + attach(service, programWithID); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued)); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + ((TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent)).cancel(); + waitForTasks(); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + + // The Queued the cancelled wait reported, arriving late + runSwing(() -> defaultTool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent( + RevEngAIAnalysisStatusChangedEvent.WAIT_SOURCE, programWithID, AnalysisStatus.Queued))); + waitForSwing(); + int callsAfterCancel = statusCalls.get(); + waitForTasks(); + + assertFalse("a late status must not start another wait", trackedPrograms.containsKey(programWithID.program())); + assertEquals("no polling after the cancel", callsAfterCancel, statusCalls.get()); + } + + /// An analysis that was still Uploaded when Ghidra closed is waited on again when the program is reopened + @Test + public void testReopenedUploadedAnalysisIsWaitedOn() throws Exception { + var defaultTool = env.getTool(); + var statusCalls = new AtomicInteger(); + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + // Error ends the wait without loading results, which this mock does not provide + return statusCalls.incrementAndGet() <= 2 ? AnalysisStatus.Uploaded : AnalysisStatus.Error; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + + // Waits for the tool to be idle, so also for the monitoring task the reopen starts + env.showTool(program); + waitForTasks(); + + // The check on reopen, then the monitoring task polling until the analysis ends + assertEquals(3, statusCalls.get()); + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(program)); + // The wait ended in Error, which is reported + pressButtonByText(awaitDialog(OptionDialog.class), "Keep attached"); + } + + private static final String FAILED_ANALYSIS_LOGS = "Unpacking binary\nDisassembling\nFATAL: worker ran out of memory\n"; + + /// An analysis that always reports Error, with a log whose last line says why + private static class FailedAnalysisAPI extends UnimplementedAPI { + final AtomicInteger logCalls = new AtomicInteger(); + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Error; + } + + @Override + public String getAnalysisLogs(AnalysisID analysisID) { + logCalls.incrementAndGet(); + return FAILED_ANALYSIS_LOGS; + } + } + + /// The error dialog, once the work that leads to it has run: the Queued event starts the wait (a task), the wait + /// fires the Error event (Swing), which starts the log fetch (a task), which shows the dialog (Swing). How many + /// rounds that takes varies between machines, so poll for the dialog; the limit only bounds a broken run. + private OptionDialog awaitErrorDialog() { + return awaitDialog(OptionDialog.class, "the failed analysis should be reported"); + } + + private String logText(AnalysisLogComponent logComponent) { + return runSwing(() -> ((JTextArea) getInstanceField("textArea", logComponent)).getText()); + } + + /// An analysis started in the session that fails on the server is reported with the end of its log, and + /// Detach in that report frees the program for a new analysis, like the Detach action does + @Test + public void testErrorDuringSessionOffersDetach() throws Exception { + var tool = env.getTool(); + var service = addMockedService(tool, new FailedAnalysisAPI()); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + // As StartAnalysisTask does: associate the program, then report the analysis as queued + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); + tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued)); + + var dialog = awaitErrorDialog(); + assertTrue(dialog.getMessage(), dialog.getMessage().contains("analysis 7 of " + program.getName() + " failed")); + assertTrue(dialog.getMessage(), dialog.getMessage().contains("FATAL: worker ran out of memory")); + var context = new DefaultActionContext(); + assertFalse(getAction(tool, "Create new").isEnabledForContext(context)); + + pressButtonByText(dialog, "Detach"); + waitForSwing(); + + assertTrue(service.getKnownProgram(program).isEmpty()); + assertTrue(getAction(tool, "Create new").isEnabledForContext(context)); + assertTrue(getAction(tool, "Attach to existing").isEnabledForContext(context)); + assertFalse(getAction(tool, "Detach").isEnabledForContext(context)); + + // The log panel says how the analysis ended instead of stopping at the last log line + AnalysisLogComponent logComponent = (AnalysisLogComponent) tool.getComponentProvider(AnalysisLogComponent.NAME); + var text = logText(logComponent); + assertTrue(text, text.contains("FATAL: worker ran out of memory")); + assertTrue(text, text.endsWith(AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Error, 7))); + } + + /// Keeping the failed analysis attached leaves the association alone, and the same failure is not reported again + @Test + public void testKeepAttachedReportsFailureOnce() throws Exception { + var tool = env.getTool(); + var service = addMockedService(tool, new FailedAnalysisAPI()); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + var programWithID = service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); + tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("StartAnalysisTask", programWithID, AnalysisStatus.Queued)); + + pressButtonByText(awaitErrorDialog(), "Keep attached"); + waitForSwing(); + assertEquals(Optional.of(programWithID), service.getKnownProgram(program)); + + // The same failure reported again, e.g. by Check status or a repeated event + tool.firePluginEvent(new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Error)); + waitForSwing(); + waitForTasks(); + waitForSwing(); + assertNull(getDialogComponent(OptionDialog.class)); + } + + /// A program reopened with an analysis that failed while Ghidra was closed gets the same single report + @Test + public void testReopenedFailedAnalysisIsReportedOnce() throws Exception { + var tool = env.getTool(); + var api = new FailedAnalysisAPI(); + var service = addMockedService(tool, api); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(7)); + + env.showTool(program); + var dialog = awaitDialog(OptionDialog.class); + assertTrue(dialog.getMessage(), dialog.getMessage().contains("FATAL: worker ran out of memory")); + pressButtonByText(dialog, "Detach"); + waitForSwing(); + waitForTasks(); + + assertTrue(service.getKnownProgram(program).isEmpty()); + assertNull(getDialogComponent(OptionDialog.class)); + // Only the report fetched the log: nothing waits on an analysis that has already ended + assertEquals(1, api.logCalls.get()); + } + + @Test + public void testTerminalStatusText() { + assertEquals("RevEng.AI: analysis 3 completed.", AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Complete, 3)); + var error = AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Error, 3); + assertTrue(error, error.contains("analysis 3 failed on the server")); + assertTrue(error, error.contains("Detach")); + assertNull(AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Processing, 3)); + + assertEquals(AnalysisLogComponent.NO_LOGS, AnalysisLogComponent.withTerminalStatus(null, null)); + assertEquals("a\nb", AnalysisLogComponent.withTerminalStatus("a\nb", null)); + assertEquals("done", AnalysisLogComponent.withTerminalStatus(" ", "done")); + assertEquals("a\nb\n\ndone", AnalysisLogComponent.withTerminalStatus("a\nb\n", "done")); + } + + /// A new analysis for the program clears how the previous one ended + @Test + public void testNewAnalysisClearsTerminalStatus() throws Exception { + var tool = env.getTool(); + addMockedService(tool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Queued; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + env.showTool(program); + AnalysisLogComponent logComponent = (AnalysisLogComponent) tool.getComponentProvider(AnalysisLogComponent.NAME); + var finished = new GhidraRevengService.ProgramWithID(program, new TypedApiInterface.AnalysisID(3)); + // Delivered to the log component directly: the plugin would load results for a Complete event + runSwing(() -> logComponent.processEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", finished, AnalysisStatus.Complete))); + assertEquals(AnalysisLogComponent.terminalStatusLine(AnalysisStatus.Complete, 3), logText(logComponent)); + + var next = new GhidraRevengService.ProgramWithID(program, new TypedApiInterface.AnalysisID(4)); + runSwing(() -> logComponent.processEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", next, AnalysisStatus.Queued))); + assertEquals(AnalysisLogComponent.NO_LOGS, logText(logComponent)); + TaskMonitorComponent taskMonitor = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + taskMonitor.cancel(); + waitForTasks(); + } + + /// An analysis reporting an unrecognised status on reopen is reported, not waited on + @Test + public void testReopenedUnknownAnalysisIsNotWaitedOn() throws Exception { + var defaultTool = env.getTool(); + var statusCalls = new AtomicInteger(); + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.incrementAndGet(); + return AnalysisStatus.Unknown; + } + }); + env.addPlugin(AnalysisManagementPlugin.class); + var program = newX64Program().getProgram(); + service.registerAnalysisForProgram(program, new TypedApiInterface.AnalysisID(1)); + + env.showTool(program); + waitForCondition(() -> statusCalls.get() > 0, "the status should be checked on reopen"); + waitForTasks(); + waitForSwing(); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(program)); + assertEquals(1, statusCalls.get()); + } + + /// An Unknown status neither starts a wait (it would end at once) nor restarts one when its event arrives late + @Test + public void testUnknownStatusIsNotMonitored() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + statusCalls.incrementAndGet(); + return AnalysisStatus.Unknown; + } + }); + attach(service, programWithID); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Unknown) + ); + waitForSwing(); + waitForTasks(); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + assertEquals(0, statusCalls.get()); + } + + /// A wait that ends on an Unknown status is reported once and is not restarted by its own status event + @Test + public void testWaitEndingOnUnknownStatusStops() throws Exception { + var defaultTool = env.showTool(); + var programWithID = getPlaceHolderID(); + var statusCalls = new AtomicInteger(); + + var service = addMockedService(defaultTool, new UnimplementedAPI() { + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return statusCalls.incrementAndGet() == 1 ? AnalysisStatus.Processing : AnalysisStatus.Unknown; + } + }); + attach(service, programWithID); + env.addPlugin(AnalysisManagementPlugin.class); + defaultTool.firePluginEvent( + new RevEngAIAnalysisStatusChangedEvent("Test", programWithID, AnalysisStatus.Queued) + ); + waitForTasks(); + waitForSwing(); + waitForTasks(); + + AnalysisLogComponent logComponent = (AnalysisLogComponent) defaultTool.getComponentProvider(AnalysisLogComponent.NAME); + var trackedPrograms = (Map) getInstanceField("trackedPrograms", logComponent); + assertFalse(trackedPrograms.containsKey(programWithID.program())); + assertEquals(2, statusCalls.get()); + TaskMonitorComponent taskMonitorComponent = (TaskMonitorComponent) getInstanceField("taskMonitorComponent", logComponent); + assertFalse(taskMonitorComponent.isVisible()); + } + + @Test + public void testUnfinishedWaitMessages() throws Exception { + var programWithID = getPlaceHolderID(); + var name = programWithID.program().getName(); + + var unrecognised = AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.UNRECOGNISED, AnalysisStatus.Unknown, Duration.ofSeconds(3)), + programWithID); + assertTrue(unrecognised, unrecognised.contains("analysis 1 of " + name)); + assertTrue(unrecognised, unrecognised.contains("does not recognise")); + + var timedOut = AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.TIMED_OUT, AnalysisStatus.Processing, Duration.ofHours(3).minusSeconds(2)), + programWithID); + assertTrue(timedOut, timedOut.contains("has not finished after 3 hours (status: Processing)")); + assertTrue(timedOut, timedOut.contains("reopen the program")); + + assertNull(AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.DONE, AnalysisStatus.Complete, Duration.ZERO), programWithID)); + assertNull(AnalysisLogComponent.unfinishedWaitMessage( + new StatusPoller.Result<>(StatusPoller.Ending.CANCELLED, AnalysisStatus.Queued, Duration.ZERO), programWithID)); + } } diff --git a/src/test/java/ai/reveng/UnpushedLocalEditsTest.java b/src/test/java/ai/reveng/UnpushedLocalEditsTest.java new file mode 100644 index 00000000..9513221d --- /dev/null +++ b/src/test/java/ai/reveng/UnpushedLocalEditsTest.java @@ -0,0 +1,239 @@ +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.AnalysisID; +import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.FunctionSignatureBatch; +import ai.reveng.toolkit.ghidra.core.services.api.datatypes.ServerDataType; +import ai.reveng.toolkit.ghidra.core.services.api.mocks.UnimplementedAPI; +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.core.services.logging.ReaiLoggingService; +import ai.reveng.toolkit.ghidra.core.services.sync.LocalEditSyncService; +import ai.reveng.toolkit.ghidra.core.services.sync.UnpushedEdits; +import ghidra.program.model.data.IntegerDataType; +import ghidra.program.model.data.LongDataType; +import ghidra.program.model.listing.Function; +import ghidra.program.model.listing.Program; +import ghidra.program.model.symbol.SourceType; +import ghidra.util.task.TaskMonitor; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/// A local edit whose push fails is reported, stays marked as unpushed, and goes up on the next sync. +public class UnpushedLocalEditsTest extends RevEngMockableHeadedIntegrationTest { + + private static final long FUNCTION_ID = 1; + + /// One function at 0x4000. Its portal name is whatever was last pushed, unless a test sets one. + private static class FlakyApi extends UnimplementedAPI { + final Map renamed = new ConcurrentHashMap<>(); + volatile String remoteName = "FUN_00004000"; + volatile boolean renameThrows; + volatile boolean renameSkipped; + volatile boolean typesThrow; + final AtomicInteger renameAttempts = new AtomicInteger(); + + @Override + public AnalysisStatus status(AnalysisID analysisID) { + return AnalysisStatus.Complete; + } + + @Override + public List getFunctionInfo(AnalysisID analysisID) { + return List.of(new FunctionInfo(new FunctionID(FUNCTION_ID), remoteName, remoteName, 0x4000L, 0x100)); + } + + @Override + public List listAnalysisDataTypes(AnalysisID analysisID, long offset, long limit) { + if (typesThrow) { + // How TypedApiImplementation wraps an ApiException from this call. + throw new RuntimeException(new ApiException(503, "Service Unavailable")); + } + return List.of(); + } + + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, boolean includeDataTypes) { + return FunctionSignatureBatch.empty(); + } + + @Override + public long batchRenameFunctions(BatchRenameInputBody request) throws ApiException { + renameAttempts.incrementAndGet(); + if (renameThrows) { + throw new ApiException(503, "Service Unavailable"); + } + if (renameSkipped) { + return 0; + } + for (var item : request.getFunctions()) { + renamed.put(item.getFunctionId(), item.getNewName()); + remoteName = item.getNewName(); + } + return request.getFunctions().size(); + } + } + + private static class RecordingLog implements ReaiLoggingService { + final List warnings = new CopyOnWriteArrayList<>(); + @Override public void info(String message) {} + @Override public void warn(String message) { warnings.add(message); } + @Override public void error(String message) {} + } + + private final FlakyApi api = new FlakyApi(); + private final RecordingLog log = new RecordingLog(); + private final List statusWarnings = new CopyOnWriteArrayList<>(); + private final List statusInfos = new CopyOnWriteArrayList<>(); + private GhidraRevengService service; + private Function function; + private Program program; + private LocalEditSyncService sync; + + @Before + public void analyse() throws Exception { + service = new GhidraRevengService(api); + var builder = newX64Program(); + builder.createMemory("code", "0x4000", 0x200); + function = builder.createEmptyFunction("FUN_00004000", "0x4000", 0x100, new IntegerDataType()); + program = builder.getProgram(); + var withId = service.registerAnalysisForProgram(program, new AnalysisID(1)); + service.registerFinishedAnalysisForProgram(withId, TaskMonitor.DUMMY); + } + + @After + public void disposeSync() { + if (sync != null) { + sync.dispose(); + } + } + + /// With retries far enough off that they never run during the test. + private void listen() { + listen(List.of(Duration.ofHours(1))); + } + + private void listen(List retryDelays) { + sync = new LocalEditSyncService(service, log, + (message, warning) -> (warning ? statusWarnings : statusInfos).add(message), retryDelays); + sync.attach(program); + } + + private void rename(String newName) throws Exception { + program.withTransaction("rename", () -> function.setName(newName, SourceType.USER_DEFINED)); + program.flushEvents(); + } + + private boolean nameMarked() { + return UnpushedEdits.isMarked(program, UnpushedEdits.Kind.NAME, function.getEntryPoint()); + } + + private GhidraRevengService.SyncSummary syncWithPortal() throws Exception { + return service.syncAnalysisUpdates(service.getAnalysedProgram(program).orElseThrow(), TaskMonitor.DUMMY, log); + } + + @Test + public void aFailedRenameIsReportedAndSentByTheNextSync() throws Exception { + listen(); + api.renameThrows = true; + rename("mine"); + + waitForCondition(() -> !statusWarnings.isEmpty(), "the failed push should reach the status bar"); + assertTrue(statusWarnings.get(0), statusWarnings.get(0).contains("retried automatically")); + assertTrue(log.warnings.contains(statusWarnings.get(0))); + assertTrue(api.renamed.isEmpty()); + assertTrue(nameMarked()); + + api.renameThrows = false; + var summary = syncWithPortal(); + + assertEquals(Map.of(FUNCTION_ID, "mine"), api.renamed); + assertEquals(1, summary.pushedLocalEdits()); + assertEquals(0, summary.failedLocalEdits()); + assertEquals("the edit went up first, so it is no conflict", 0, summary.nameConflicts()); + assertFalse(nameMarked()); + } + + @Test + public void failuresAreReportedOnceAndRetriedUntilTheyGoUp() throws Exception { + listen(List.of(Duration.ofMillis(300))); + api.renameThrows = true; + rename("first"); + waitForCondition(() -> !statusWarnings.isEmpty(), "the outage should be reported"); + rename("second"); + + // The second rename's own push, then at least one automatic retry, all failing. + waitForCondition(() -> api.renameAttempts.get() >= 3, "the failed edit should be retried"); + assertEquals("one report however many pushes fail: " + statusWarnings, 1, statusWarnings.size()); + assertEquals(1, log.warnings.size()); + assertTrue(nameMarked()); + + api.renameThrows = false; + waitForCondition(() -> !statusInfos.isEmpty(), "the recovery should be reported"); + assertEquals(Map.of(FUNCTION_ID, "second"), api.renamed); + assertFalse(nameMarked()); + assertTrue(statusInfos.get(0), statusInfos.get(0).contains("pushed 1 local edit")); + assertEquals(1, statusWarnings.size()); + } + + @Test + public void aRenameThePortalSkippedCountsAsFailed() throws Exception { + listen(); + api.renameSkipped = true; + rename("mine"); + + waitForCondition(() -> !statusWarnings.isEmpty(), "a renamed_count of zero should be reported"); + assertTrue(nameMarked()); + } + + @Test + public void aSuccessfulRenameLeavesNothingMarked() throws Exception { + listen(); + rename("mine"); + + waitForCondition(() -> api.renamed.size() == 1, "the rename should be pushed"); + waitForCondition(() -> !nameMarked(), "the mark should be cleared once the push succeeded"); + assertTrue(statusWarnings.isEmpty()); + } + + /// A RuntimeException used to die unseen inside the discarded future. + @Test + public void anUncheckedFailureInATypePushIsReported() throws Exception { + listen(); + api.typesThrow = true; + program.withTransaction("retype", () -> function.setReturnType(new LongDataType(), SourceType.USER_DEFINED)); + program.flushEvents(); + + waitForCondition(() -> !statusWarnings.isEmpty(), "the failed type push should reach the status bar"); + assertTrue(UnpushedEdits.isMarked(program, UnpushedEdits.Kind.TYPES, function.getEntryPoint())); + } + + @Test + public void reportsANameBothSidesChanged() throws Exception { + // Renamed without the listener, so the local name never went up and is not marked as unpushed: + // it looks like an edit that reached the portal before the portal's copy was renamed again. + rename("mine"); + api.remoteName = "theirs"; + + var summary = syncWithPortal(); + + assertEquals(1, summary.nameConflicts()); + assertEquals("mine", function.getName()); + assertTrue(log.warnings.stream().anyMatch(warning -> warning.contains("theirs"))); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java index 362a61f8..9f228c2e 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/chat/ui/ChatControllerTest.java @@ -231,4 +231,21 @@ public void loadConversationSetsTitleAndState() { assertEquals("Prior chat", view.lastState.title()); } + + /// An unchecked failure in the worker must end the run, or Send stays disabled. + @Test + public void uncheckedWorkerFailureEndsTheRun() { + var service = new FakeChatService() { + @Override + public void sendMessage(String conversationId, String content, ConversationContext context) { + throw new IllegalStateException("boom"); + } + }; + var view = new RecordingView(); + var controller = controller(service, view, new RecordingCallbacks()); + + controller.send("hello"); + + assertEquals("error", view.lastState.runStatus()); + } } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AIDecompilationNotFoundTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AIDecompilationNotFoundTest.java new file mode 100644 index 00000000..c6096189 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AIDecompilationNotFoundTest.java @@ -0,0 +1,36 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.*; + +/// A function that was never decompiled answers 200 with status UNINITIALISED, so a 404 means the +/// function itself was not found. Reading it as UNINITIALISED made the window poll for ever. +public class AIDecompilationNotFoundTest extends AbstractStubServerTest { + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/v3/functions/7/ai-decompilation", exchange -> { + byte[] body = "{\"error\": {\"code\": \"NOT_FOUND\", \"message\": \"function not found\"}}" + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(404, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + } + + @Test + public void notFoundIsAnErrorNotUninitialised() { + var thrown = assertThrows(RuntimeException.class, + () -> api().pollAIDecompileStatus(new TypedApiInterface.FunctionID(7))); + assertTrue(thrown.getMessage(), thrown.getMessage().contains("could not find function 7")); + assertTrue(thrown.getCause() instanceof ApiException api && api.getCode() == 404); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java index efeb5a0e..261538c9 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AbstractStubServerTest.java @@ -1,7 +1,5 @@ package ai.reveng.toolkit.ghidra.core.services.api; -import ai.reveng.invoker.ApiClient; -import ai.reveng.invoker.Configuration; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import ghidra.test.AbstractGhidraHeadlessIntegrationTest; @@ -19,17 +17,9 @@ public abstract class AbstractStubServerTest extends AbstractGhidraHeadlessIntegrationTest { protected HttpServer server; - private ApiClient originalApiClient; @Before public void startStubServer() throws Exception { - // TypedApiImplementation mutates the ApiClient that Configuration holds as a process-global - // singleton (base path, stacked interceptors). The test task forks in parallel and runs - // several classes per fork, so without this save/restore one class leaks its client into - // whichever class runs next in the same fork. - originalApiClient = Configuration.getDefaultApiClient(); - Configuration.setDefaultApiClient(new ApiClient()); - server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); configureStubs(server); server.start(); @@ -40,9 +30,6 @@ public void stopStubServer() { if (server != null) { server.stop(0); } - if (originalApiClient != null) { - Configuration.setDefaultApiClient(originalApiClient); - } } /// Registers the contexts this test serves. Called before the server is started. diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java index a2e5fb0f..d5f40f35 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/AnalysisOptionsBuilderTest.java @@ -1,7 +1,6 @@ package ai.reveng.toolkit.ghidra.core.services.api; -import ai.reveng.model.AnalysisCreateRequest; -import ai.reveng.model.Tag; +import ai.reveng.model.CreateRequest; import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionBoundary; import org.junit.Test; @@ -22,7 +21,7 @@ public void testToAnalysisCreateRequest_IncludeInAnalysisFlag() { new FunctionBoundary("excluded_fn", 0x1020, 0x1030, false), new FunctionBoundary("default_fn", 0x1040, 0x1050))); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); List boundaries = request.getSymbols().getFunctionBoundaries(); assertEquals("All boundaries are sent regardless of the include flag", 3, boundaries.size()); @@ -47,7 +46,7 @@ public void testToAnalysisCreateRequest_WithNoTags() { .hash(new TypedApiInterface.BinaryHash("a".repeat(64))) .fileName("test.bin"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that tags are either null or empty, but not containing empty tags if (request.getTags() != null) { @@ -64,15 +63,13 @@ public void testToAnalysisCreateRequest_WithValidTags() { .addTag("malware") .addTag("suspicious"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that tags are properly set assertNotNull("Tags should not be null", request.getTags()); assertEquals("Should have 2 tags", 2, request.getTags().size()); - List tagNames = request.getTags().stream() - .map(Tag::getName) - .toList(); + List tagNames = request.getTags(); assertTrue("Should contain 'malware' tag", tagNames.contains("malware")); assertTrue("Should contain 'suspicious' tag", tagNames.contains("suspicious")); @@ -88,12 +85,12 @@ public void testToAnalysisCreateRequest_WithEmptyStringTag() { .addTag(" ") // whitespace only .addTag("valid-tag"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that empty/whitespace tags are filtered out assertNotNull("Tags should not be null", request.getTags()); assertEquals("Should only have 1 valid tag after filtering", 1, request.getTags().size()); - assertEquals("Should only contain the valid tag", "valid-tag", request.getTags().getFirst().getName()); + assertEquals("Should only contain the valid tag", "valid-tag", request.getTags().getFirst()); } @Test @@ -104,7 +101,7 @@ public void testToAnalysisCreateRequest_WithMultipleTags() { .fileName("test.bin") .addTags(Arrays.asList("tag1", "tag2", "tag3")); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that all tags are properly set assertNotNull("Tags should not be null", request.getTags()); @@ -121,7 +118,7 @@ public void testToAnalysisCreateRequest_WithOnlyEmptyTags() { .addTag(" ") .addTag("\t"); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); // Verify that no tags are set when all are empty if (request.getTags() != null) { @@ -139,7 +136,7 @@ public void testToAnalysisCreateRequest_BasicFields() { .hash(new TypedApiInterface.BinaryHash(hash)) .fileName(filename); - AnalysisCreateRequest request = builder.toAnalysisCreateRequest(); + CreateRequest request = builder.toAnalysisCreateRequest(); assertEquals("Filename should match", filename, request.getFilename()); assertEquals("SHA256 hash should match", hash, request.getSha256Hash()); diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java new file mode 100644 index 00000000..b4521cf0 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiClientIsolationTest.java @@ -0,0 +1,128 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.Configuration; +import ai.reveng.toolkit.ghidra.core.services.api.types.ApiInfo; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * Every {@link TypedApiImplementation} owns its HTTP client. They used to share the SDK's + * process-global default client, so the setup wizard's throwaway validation instance re-targeted + * the running session: a mistyped key there made every later call fail with 401. + */ +public class ApiClientIsolationTest extends AbstractStubServerTest { + + private final List authorizations = new CopyOnWriteArrayList<>(); + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> { + authorizations.add(exchange.getRequestHeaders().getFirst("Authorization")); + exchange.sendResponseHeaders(401, -1); + exchange.close(); + }); + } + + private String stubUrl() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + /// Any request will do; only the credentials it carries are of interest. + private static void call(TypedApiInterface api) { + try { + api.getAnalysisBasicInfo(new TypedApiInterface.AnalysisID(1)); + } catch (Exception expected) { + // the stub answers 401 + } + } + + @Test + public void validatingOtherCredentialsDoesNotChangeTheRunningInstancesKey() { + var running = new TypedApiImplementation(stubUrl(), "real-key"); + new TypedApiImplementation("http://127.0.0.1:1", "typo-key"); + + call(running); + + assertEquals(List.of("real-key"), authorizations); + assertEquals(stubUrl(), running.apiClient().getBasePath()); + } + + @Test + public void instancesDoNotTouchTheSdksDefaultClient() { + var defaultClient = Configuration.getDefaultApiClient(); + var basePath = defaultClient.getBasePath(); + + var api = api(); + + assertNotSame(defaultClient, api.apiClient()); + assertSame(defaultClient, Configuration.getDefaultApiClient()); + assertEquals(basePath, defaultClient.getBasePath()); + } + + /// Each instance used to add one more interceptor to the shared client, so every request was + /// logged once per instance ever created. + @Test + public void eachClientLogsRequestsOnce() { + api(); + api(); + var third = api(); + + long loggers = third.apiClient().getHttpClient().interceptors().stream() + .filter(LoggingInterceptor.class::isInstance) + .count(); + assertEquals(1, loggers); + } + + /// Uploads used to share the 15 s limit of every other request. + @Test + public void uploadsGetALongerTimeoutThanOtherRequests() { + var api = api(); + + assertEquals(15_000, api.apiClient().getHttpClient().readTimeoutMillis()); + assertEquals(300_000, api.uploadClient().getHttpClient().readTimeoutMillis()); + assertEquals(300_000, api.uploadClient().getHttpClient().writeTimeoutMillis()); + assertEquals(stubUrl(), api.uploadClient().getBasePath()); + } + + @Test + public void bothClientsRetry() { + var api = api(); + + for (var client : List.of(api.apiClient(), api.uploadClient())) { + assertEquals(1, client.getHttpClient().interceptors().stream() + .filter(RetryInterceptor.class::isInstance) + .count()); + } + } + + @Test + public void reconfiguringTheServiceSwitchesItsCredentials() { + var service = new GhidraRevengService(new ApiInfo(stubUrl(), "http://portal.invalid", "old-key")); + var oldClient = service.apiClient(); + + assertTrue(service.reconfigure(new ApiInfo(stubUrl(), "http://portal.invalid", "new-key"))); + call(service.getApi()); + + assertEquals(List.of("new-key"), authorizations); + assertNotSame(oldClient, service.apiClient()); + } + + @Test + public void reconfiguringWithTheSameCredentialsKeepsTheClient() { + var info = new ApiInfo(stubUrl(), "http://portal.invalid", "key"); + var service = new GhidraRevengService(info); + var client = service.apiClient(); + + assertFalse(service.reconfigure(new ApiInfo(stubUrl(), "http://portal.invalid", "key"))); + assertSame(client, service.apiClient()); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiErrorMessageTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiErrorMessageTest.java new file mode 100644 index 00000000..03ae0867 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ApiErrorMessageTest.java @@ -0,0 +1,95 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import ai.reveng.toolkit.ghidra.chat.service.ChatServiceException; +import ai.reveng.toolkit.ghidra.chat.service.ConversationsApiChatService; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/// A failed request must reach the user as the server's `error.message`, not as a dropped body or +/// the SDK's full {@link ApiException} dump of message, body and headers. +public class ApiErrorMessageTest extends AbstractStubServerTest { + + private static final String SERVER_MESSAGE = "page_size must be at most 500"; + private static final String CONVERSATION_ID = "11111111-2222-3333-4444-555555555555"; + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> { + byte[] bytes = "{\"error\":{\"code\":\"BAD_REQUEST\",\"message\":\"%s\"}}" + .formatted(SERVER_MESSAGE).getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(422, bytes.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(bytes); + } + }); + } + + /// Goes through the generated `*Call` and reads the body by hand. + @Test + public void rawCallKeepsTheResponseBody() { + try { + api().createAnalysisDataTypes(new TypedApiInterface.AnalysisID(1), + new ai.reveng.model.CreateAnalysisDataTypesInputBody()); + fail("a 422 should raise"); + } catch (ApiException e) { + assertEquals(422, e.getCode()); + assertTrue(e.getResponseBody(), e.getResponseBody().contains(SERVER_MESSAGE)); + } + } + + @Test + public void rawCallFailureShowsServerMessage() { + assertShowsServerMessage(() -> api().listAnalysisDataTypes(new TypedApiInterface.AnalysisID(1), 0, 1000)); + } + + /// Goes through a generated model method. + @Test + public void modelCallFailureShowsServerMessage() { + assertShowsServerMessage(() -> api().getFunctionDetails(new TypedApiInterface.FunctionID(1))); + } + + /// Chat reads the conversation through the generated `*Call`. + @Test + public void chatRawCallFailureShowsServerMessage() { + assertChatShowsServerMessage("load conversation", chat -> chat.getConversation(CONVERSATION_ID)); + } + + @Test + public void chatModelCallFailureShowsServerMessage() { + assertChatShowsServerMessage("cancel run", chat -> chat.cancelRun(CONVERSATION_ID)); + } + + private interface ChatRequest { + void run(ConversationsApiChatService chat) throws ChatServiceException; + } + + private void assertChatShowsServerMessage(String action, ChatRequest request) { + var client = api().apiClient(); + try { + request.run(new ConversationsApiChatService(() -> client)); + fail("a 422 should raise"); + } catch (ChatServiceException e) { + assertEquals("Failed to " + action + ": HTTP 422 — " + SERVER_MESSAGE, e.getMessage()); + } + } + + private static void assertShowsServerMessage(Runnable request) { + try { + request.run(); + fail("a 422 should raise"); + } catch (RuntimeException e) { + assertEquals("HTTP 422 — " + SERVER_MESSAGE, e.getMessage()); + assertFalse(e.getMessage(), e.getMessage().contains("HTTP response headers")); + } + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java index 6fa62d81..d8fa4787 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/ConversationReplayTest.java @@ -1,7 +1,5 @@ package ai.reveng.toolkit.ghidra.core.services.api; -import ai.reveng.invoker.ApiClient; -import ai.reveng.invoker.Configuration; import ai.reveng.toolkit.ghidra.chat.model.Conversations.ConversationReplay; import ai.reveng.toolkit.ghidra.chat.service.ChatServiceException; import ai.reveng.toolkit.ghidra.chat.service.ConversationsApiChatService; @@ -31,9 +29,8 @@ protected void configureStubs(HttpServer server) { } private ConversationReplay replay() throws ChatServiceException { - ApiClient client = Configuration.getDefaultApiClient(); - client.setBasePath("http://127.0.0.1:" + server.getAddress().getPort()); - return new ConversationsApiChatService().getConversation(UUID); + var client = api().apiClient(); + return new ConversationsApiChatService(() -> client).getConversation(UUID); } @Test diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java new file mode 100644 index 00000000..34f6edab --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/EmptyResponseDataTest.java @@ -0,0 +1,31 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +/// `data` is optional on the base response wrapper, so a body without it must surface as an +/// {@link ApiException} rather than a NullPointerException. +public class EmptyResponseDataTest extends AbstractStubServerTest { + + private static final String EMPTY = "{\"status\": false, \"data\": null, \"message\": \"nope\"}"; + private static final String OPERATION_WITHOUT_ID = "{\"name\": \"operations/1\", \"done\": false}"; + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> respondJson(exchange, EMPTY)); + server.createContext("/v3/analyses", exchange -> respondJson(exchange, OPERATION_WITHOUT_ID)); + } + + @Test(expected = ApiException.class) + public void statusWithoutDataThrowsApiException() throws Exception { + api().status(new TypedApiInterface.AnalysisID(1)); + } + + @Test(expected = ApiException.class) + public void analyseWithoutAnalysisIdThrowsApiException() throws Exception { + api().analyse(new AnalysisOptionsBuilder() + .hash(new TypedApiInterface.BinaryHash("a".repeat(64))) + .fileName("test.bin")); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java index 25d3db02..221ed273 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/FunctionSignatureServiceTest.java @@ -2,6 +2,7 @@ import ai.reveng.invoker.ApiException; import ai.reveng.model.BatchFunctionSignatureEntry; +import ai.reveng.model.SignatureParameterEntry; import ai.reveng.model.UpdateFunctionSignatureInputBody; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.AnalysisID; import ai.reveng.toolkit.ghidra.core.services.api.TypedApiInterface.FunctionID; @@ -120,6 +121,69 @@ public void getReturnsOnlyFunctionsTheServerHasASignatureFor() { assertTrue(service.get(new FunctionID(3)).isEmpty()); } + /// What the server stores for a function Ghidra had no signature for: `undefined f(void)`. + private static BatchFunctionSignatureEntry placeholder() { + var entry = new BatchFunctionSignatureEntry(); + entry.setHasSignature(true); + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.SYSTEM); + entry.setParameters(List.of()); + entry.setReturnDataTypeId(0L); + return entry; + } + + @Test + public void undefinedReturnAndNoParametersFromTheServerIsAPlaceholder() { + assertTrue(FunctionSignatureService.isPlaceholder(placeholder())); + assertFalse(FunctionSignatureService.hasUsableSignature(placeholder())); + } + + @Test + public void unresolvedReturnTypeAndNoParametersIsAPlaceholder() { + var entry = placeholder(); + entry.setReturnDataTypeId(null); + assertTrue(FunctionSignatureService.isPlaceholder(entry)); + } + + /// `void f(void)` is a real signature: its return type is `void`, not `undefined` (id 0). + @Test + public void aRealReturnTypeIsNotAPlaceholder() { + var entry = placeholder(); + entry.setReturnDataTypeId(5L); + assertFalse(FunctionSignatureService.isPlaceholder(entry)); + assertTrue(FunctionSignatureService.hasUsableSignature(entry)); + } + + @Test + public void parametersMakeItARealSignature() { + var entry = placeholder(); + entry.setParameters(List.of(new SignatureParameterEntry())); + assertFalse(FunctionSignatureService.isPlaceholder(entry)); + } + + /// Once someone edits or copies a signature it is theirs, even if it reads `undefined f(void)`. + @Test + public void aSignatureSomeoneWroteIsNotAPlaceholder() { + var entry = placeholder(); + entry.setSourceType(BatchFunctionSignatureEntry.SourceTypeEnum.USER); + assertFalse(FunctionSignatureService.isPlaceholder(entry)); + } + + @Test + public void getSkipsAPlaceholder() { + var service = new FunctionSignatureService(new UnimplementedAPI() { + @Override + public FunctionSignatureBatch listFunctionSignatures(List functionIDs, + boolean includeDataTypes) { + var entry = placeholder(); + entry.setAnalysisId(1L); + entry.setFunctionId(functionIDs.get(0).value()); + return new FunctionSignatureBatch(List.of(entry), Map.of()); + } + }); + + assertTrue(service.get(new FunctionID(1)).isEmpty()); + } + /// Accepts a signature write for one function and answers 404 for every other, which is how the /// endpoint reports a function it never extracted a signature for. private static class WritingApi extends UnimplementedAPI { diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java index 126129da..c4d599c4 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/GetFunctionInfoPaginationTest.java @@ -92,6 +92,20 @@ public void getFunctionInfo_fallsBackToTheFunctionNameWhenUnmangled() { functions.stream().map(FunctionInfo::functionMangledName).collect(Collectors.toList())); } + /** + * Staging sends mangled_name as "" for functions with no mangled symbol. Kept as-is, an empty + * name never starts with FUN_ or sub_, so the rename guard would let a placeholder through. + */ + @Test + public void getFunctionInfo_treatsAnEmptyMangledNameAsAbsent() { + allFunctionIds = List.of(10L, EMPTY_MANGLED_ID, BLANK_MANGLED_ID); + + List functions = fetch(); + + assertEquals(List.of("mangled_10", "func_" + EMPTY_MANGLED_ID, "func_" + BLANK_MANGLED_ID), + functions.stream().map(FunctionInfo::functionMangledName).collect(Collectors.toList())); + } + private List fetch() { return api().getFunctionInfo(new TypedApiInterface.AnalysisID(ANALYSIS_ID)); } @@ -124,9 +138,21 @@ private static String pageResponse(List functionIds, int totalCount) { /** The id whose entry the stub serves without a mangled_name. */ private static final long UNMANGLED_ID = 99L; + /** The ids whose entries carry an empty and a whitespace-only mangled_name. */ + private static final long EMPTY_MANGLED_ID = 98L; + private static final long BLANK_MANGLED_ID = 97L; private static String functionJson(long id) { - String mangledName = id == UNMANGLED_ID ? "" : "\"mangled_name\":\"mangled_%d\",".formatted(id); + String mangledName; + if (id == UNMANGLED_ID) { + mangledName = ""; + } else if (id == EMPTY_MANGLED_ID) { + mangledName = "\"mangled_name\":\"\","; + } else if (id == BLANK_MANGLED_ID) { + mangledName = "\"mangled_name\":\" \","; + } else { + mangledName = "\"mangled_name\":\"mangled_%d\",".formatted(id); + } return """ {"function_id":%d,"function_name":"func_%d",%s\ "function_vaddr":%d,"function_size":32,"binary_id":7,"debug":false,\ diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailureTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailureTest.java new file mode 100644 index 00000000..8b44eb02 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/PushFailureTest.java @@ -0,0 +1,47 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import org.junit.Test; + +import java.net.SocketTimeoutException; + +import static org.junit.Assert.assertEquals; + +public class PushFailureTest { + + private static ApiException status(int code) { + return new ApiException(code, "status " + code); + } + + @Test + public void noAnswerOrAServerSideErrorMayPass() { + assertEquals(PushFailure.TRANSIENT, PushFailure.of(new ApiException(new SocketTimeoutException("timeout")))); + assertEquals(PushFailure.TRANSIENT, PushFailure.of(new ApiException("no answer"))); + for (int code : new int[] {408, 429, 500, 502, 503, 504}) { + assertEquals("status " + code, PushFailure.TRANSIENT, PushFailure.of(status(code))); + } + } + + @Test + public void aRefusedKeyNeedsTheAnalyst() { + assertEquals(PushFailure.AUTH, PushFailure.of(status(401))); + assertEquals(PushFailure.AUTH, PushFailure.of(status(403))); + } + + @Test + public void anyOtherClientErrorOrALocalFailureIsFinal() { + for (int code : new int[] {400, 404, 409, 422}) { + assertEquals("status " + code, PushFailure.REJECTED, PushFailure.of(status(code))); + } + assertEquals(PushFailure.REJECTED, PushFailure.of(new IllegalStateException("renamed 0 of 1"))); + assertEquals(PushFailure.REJECTED, PushFailure.of(new IllegalArgumentException("cannot encode"))); + } + + /// The typed API wraps some failures in a plain RuntimeException. + @Test + public void looksThroughWrappers() { + assertEquals(PushFailure.REJECTED, PushFailure.of(new RuntimeException(status(404)))); + assertEquals(PushFailure.TRANSIENT, PushFailure.of(new RuntimeException(status(503)))); + assertEquals(PushFailure.AUTH, PushFailure.of(new RuntimeException(status(401)))); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptorTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptorTest.java new file mode 100644 index 00000000..00cf045f --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/RetryInterceptorTest.java @@ -0,0 +1,164 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import com.sun.net.httpserver.HttpServer; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.time.Duration; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/// Exercised through a real {@link OkHttpClient} against a loopback server, with the waits recorded +/// instead of slept. +public class RetryInterceptorTest { + + /// One canned answer: a status code and, optionally, a `Retry-After`. + private record Answer(int code, String retryAfter) { + static Answer of(int code) { + return new Answer(code, null); + } + } + + private HttpServer server; + private final ConcurrentLinkedQueue answers = new ConcurrentLinkedQueue<>(); + private final List methods = new ArrayList<>(); + private final List sleeps = new ArrayList<>(); + private OkHttpClient client; + + @Before + public void start() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + synchronized (methods) { + methods.add(exchange.getRequestMethod()); + } + var answer = answers.isEmpty() ? Answer.of(200) : answers.poll(); + if (answer.retryAfter() != null) { + exchange.getResponseHeaders().add("Retry-After", answer.retryAfter()); + } + exchange.getRequestBody().readAllBytes(); + exchange.sendResponseHeaders(answer.code(), -1); + exchange.close(); + }); + server.start(); + client = new OkHttpClient.Builder() + .addInterceptor(new RetryInterceptor(4, Duration.ofSeconds(1), Duration.ofSeconds(30), sleeps::add)) + .build(); + } + + @After + public void stop() { + server.stop(0); + } + + private int send(String method) throws IOException { + var body = method.equals("GET") ? null : RequestBody.create("{}", MediaType.get("application/json")); + var request = new Request.Builder() + .url("http://127.0.0.1:" + server.getAddress().getPort() + "/v2/anything") + .method(method, body) + .build(); + try (var response = client.newCall(request).execute()) { + return response.code(); + } + } + + private void answer(Answer... canned) { + answers.addAll(List.of(canned)); + } + + @Test + public void retriesAServerErrorAndReturnsTheEventualSuccess() throws IOException { + answer(Answer.of(503)); + + assertEquals(200, send("GET")); + assertEquals(2, methods.size()); + assertEquals(List.of(Duration.ofSeconds(1)), sleeps); + } + + @Test + public void backsOffExponentiallyAndGivesUpAfterTheLastAttempt() throws IOException { + answer(Answer.of(500), Answer.of(502), Answer.of(503), Answer.of(504)); + + assertEquals("the last answer reaches the caller", 504, send("GET")); + assertEquals(4, methods.size()); + assertEquals(List.of(Duration.ofSeconds(1), Duration.ofSeconds(2), Duration.ofSeconds(4)), sleeps); + } + + @Test + public void waitsAsLongAsRetryAfterAsks() throws IOException { + answer(new Answer(429, "3")); + + assertEquals(200, send("GET")); + assertEquals(List.of(Duration.ofSeconds(3)), sleeps); + } + + /// Blocking a Ghidra task for minutes is worse than reporting the rate limit. + @Test + public void doesNotWaitOutARetryAfterBeyondTheCap() throws IOException { + answer(new Answer(429, "120")); + + assertEquals(429, send("GET")); + assertEquals(1, methods.size()); + assertTrue(sleeps.isEmpty()); + } + + /// The first attempt may already have taken effect. + @Test + public void neverRetriesPostOrPatch() throws IOException { + answer(Answer.of(503), Answer.of(503)); + + assertEquals(503, send("POST")); + assertEquals(503, send("PATCH")); + assertEquals(List.of("POST", "PATCH"), methods); + assertTrue(sleeps.isEmpty()); + } + + @Test + public void retriesPutAndDelete() throws IOException { + answer(Answer.of(503)); + assertEquals(200, send("PUT")); + answer(Answer.of(503)); + assertEquals(200, send("DELETE")); + assertEquals(List.of("PUT", "PUT", "DELETE", "DELETE"), methods); + } + + @Test + public void leavesClientErrorsAlone() throws IOException { + for (int code : new int[] {400, 401, 404, 422}) { + answer(Answer.of(code)); + assertEquals(code, send("GET")); + } + assertEquals(4, methods.size()); + assertTrue(sleeps.isEmpty()); + } + + @Test + public void readsRetryAfterAsSecondsOrAnHttpDate() { + assertEquals(Duration.ofSeconds(7), RetryInterceptor.retryAfter("7").orElseThrow()); + assertTrue(RetryInterceptor.retryAfter("soon").isEmpty()); + assertTrue(RetryInterceptor.retryAfter(null).isEmpty()); + + var inTenSeconds = ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(10) + .format(DateTimeFormatter.RFC_1123_DATE_TIME); + var wait = RetryInterceptor.retryAfter(inTenSeconds).orElseThrow(); + assertTrue(wait + " should be about ten seconds", + wait.compareTo(Duration.ofSeconds(8)) >= 0 && wait.compareTo(Duration.ofSeconds(10)) <= 0); + + var past = ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(1).format(DateTimeFormatter.RFC_1123_DATE_TIME); + assertEquals(Duration.ZERO, RetryInterceptor.retryAfter(past).orElseThrow()); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java new file mode 100644 index 00000000..9b796976 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkRecordedResponseTest.java @@ -0,0 +1,199 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.model.DecompilationData; +import ai.reveng.model.GetMatchesStatusOutputBody; +import ai.reveng.model.ProgressMessage; +import ai.reveng.model.CurrentUser; +import ai.reveng.model.WorkflowProgress; +import ai.reveng.toolkit.ghidra.core.services.api.types.AIDecompilationStatus; +import ai.reveng.toolkit.ghidra.core.services.api.types.FunctionMatch; +import com.sun.net.httpserver.HttpServer; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/// Runs staging-shaped response bodies (`src/test/resources/sdk-responses`) through the generated +/// SDK models via the plugin's own {@link TypedApiImplementation} calls. {@link SdkSchemaTest} only +/// pins that the accessors exist; this checks that a real body deserialises — every required field +/// present, every enum value known — and that the values land where the plugin reads them. +public class SdkRecordedResponseTest extends AbstractStubServerTest { + + private static final long DECOMPILED_FUNCTION = 101; + private static final long RUNNING_FUNCTION = 102; + private static final int ANALYSIS = 7; + + private static final String DECOMP = "/v3/functions/" + DECOMPILED_FUNCTION + "/ai-decompilation"; + private static final String RUNNING_DECOMP = "/v3/functions/" + RUNNING_FUNCTION + "/ai-decompilation"; + + /// "METHOD path" to the recorded body served for it. + private static final Map ROUTES = Map.ofEntries( + Map.entry("GET " + DECOMP, "ai-decompilation.json"), + Map.entry("GET " + DECOMP + "/summary/status", "ai-decompilation-summary-status.json"), + Map.entry("GET " + DECOMP + "/summary", "ai-decompilation-summary.json"), + Map.entry("GET " + DECOMP + "/inline-comments/status", "ai-decompilation-inline-comments-status.json"), + Map.entry("GET " + DECOMP + "/inline-comments", "ai-decompilation-inline-comments.json"), + Map.entry("PATCH " + DECOMP + "/inline-comments", "ai-decompilation-inline-comments-patch.json"), + Map.entry("DELETE " + DECOMP + "/inline-comments/6", "ai-decompilation-inline-comments-delete.json"), + Map.entry("GET " + RUNNING_DECOMP, "ai-decompilation-running.json"), + Map.entry("GET " + RUNNING_DECOMP + "/status", "ai-decompilation-status.json"), + Map.entry("GET /v3/analyses/" + ANALYSIS + "/auto-unstrip/status", "auto-unstrip-status.json"), + Map.entry("POST /v3/functions/canonical-names", "canonical-names.json"), + Map.entry("GET /v2/iam/me", "iam-me.json"), + Map.entry("GET /v2/config", "config.json"), + Map.entry("GET /v3/analyses/" + ANALYSIS + "/functions/matches/status", "matches-status-completed.json"), + Map.entry("GET /v3/functions/matches/status", "matches-status-running.json"), + Map.entry("GET /v3/analyses/" + ANALYSIS + "/functions/matches", "analysis-matches.json"), + Map.entry("GET /v2/search/binaries", "search-binaries.json"), + Map.entry("GET /v3/collections", "collections.json")); + + private final List requests = new CopyOnWriteArrayList<>(); + + @Override + protected void configureStubs(HttpServer server) { + server.createContext("/", exchange -> { + String route = exchange.getRequestMethod() + " " + exchange.getRequestURI().getPath(); + requests.add(route); + String fixture = ROUTES.get(route); + if (fixture == null) { + exchange.sendResponseHeaders(404, -1); + exchange.close(); + return; + } + respondJson(exchange, recorded(fixture)); + }); + } + + @Test + public void completedDecompilationCarriesTextSummaryAndComments() { + AIDecompilationStatus status = api().pollAIDecompileStatus(new TypedApiInterface.FunctionID(DECOMPILED_FUNCTION)); + + assertEquals(DecompilationData.StatusEnum.COMPLETED, status.status()); + assertTrue(status.decompilation().startsWith("int parse_header(char *buf, int len)")); + assertEquals(WorkflowProgress.StatusEnum.COMPLETED, status.summaryStatus()); + // ai_summary is the plain-text form; summary carries markup. + assertEquals("Parses an HTTP header from buf and returns the length of the remaining payload, " + + "or -1 if the buffer is shorter than 8 bytes.", status.summary()); + assertEquals(WorkflowProgress.StatusEnum.COMPLETED, status.inlineCommentsStatus()); + assertEquals(List.of( + new AIDecompilationStatus.InlineCommentEntry(3, "Reject buffers too short to hold the 8-byte header."), + new AIDecompilationStatus.InlineCommentEntry(6, "Skip the 4-byte magic and parse the length field.")), + status.inlineComments()); + } + + @Test + public void runningDecompilationCarriesPipelineProgress() { + AIDecompilationStatus status = api().pollAIDecompileStatus(new TypedApiInterface.FunctionID(RUNNING_FUNCTION)); + + assertEquals(DecompilationData.StatusEnum.RUNNING, status.status()); + WorkflowProgress progress = status.decompilationProgress(); + assertNotNull("the progress body should deserialise", progress); + assertEquals(WorkflowProgress.StatusEnum.RUNNING, progress.getStatus()); + assertEquals("decompiling", progress.getStep()); + assertEquals(Long.valueOf(2), progress.getStepIndex()); + assertEquals(Long.valueOf(7), progress.getStepsTotal()); + assertEquals(4, progress.getMessages().size()); + ProgressMessage first = progress.getMessages().get(0); + assertEquals(ProgressMessage.LevelEnum.INFO, first.getLevel()); + assertEquals("Preparing decompilation", first.getText()); + assertNotNull(first.getTimestamp()); + } + + @Test + public void inlineCommentEditsDeserialiseTheirResponses() throws Exception { + var api = api(); + api.setAIDecompilationInlineComment(new TypedApiInterface.FunctionID(DECOMPILED_FUNCTION), 6, "Length field is big-endian."); + api.deleteAIDecompilationInlineComment(new TypedApiInterface.FunctionID(DECOMPILED_FUNCTION), 6); + + assertEquals(List.of("PATCH " + DECOMP + "/inline-comments", "DELETE " + DECOMP + "/inline-comments/6"), requests); + } + + @Test + public void autoUnstripStatusMapsToTheKnownState() throws Exception { + assertEquals(TypedApiInterface.AutoUnstripStatus.COMPLETED, + api().getAutoUnstripStatus(new TypedApiInterface.AnalysisID(ANALYSIS))); + } + + @Test + public void canonicalNamesComeBackKeyedByInput() throws Exception { + assertEquals(Map.of("_ZN3fooC1Ev", "foo", "sub_401000", "sub_401000"), + api().canonicalizeFunctionNames(List.of("_ZN3fooC1Ev", "sub_401000"))); + } + + @Test + public void currentUserCarriesTier() { + assertEquals(CurrentUser.TierEnum.REVERSER, api().getMe().getTier()); + } + + @Test + public void configCarriesMaxFileSize() { + assertEquals(31_457_280L, api().getConfig().getMaxFileSizeBytes().longValue()); + } + + @Test + public void matchingStatusBodiesDeserialise() throws Exception { + var api = api(); + GetMatchesStatusOutputBody completed = api.getAnalysisFunctionMatchingStatus(new TypedApiInterface.AnalysisID(ANALYSIS)); + assertEquals(GetMatchesStatusOutputBody.StatusEnum.COMPLETED, completed.getStatus()); + assertTrue(completed.getMessages().isEmpty()); + + GetMatchesStatusOutputBody running = api.getFunctionsMatchingStatus(List.of(1109480836L)); + assertEquals(GetMatchesStatusOutputBody.StatusEnum.RUNNING, running.getStatus()); + assertEquals("matching", running.getStep()); + assertEquals(Long.valueOf(1), running.getStepIndex()); + assertEquals(Long.valueOf(3), running.getStepsTotal()); + assertEquals("Searching for similar functions", running.getMessages().get(1).getText()); + } + + @Test + public void matchedFunctionsCarryNameBinaryAndHash() throws Exception { + var body = api().getAnalysisFunctionMatches(new TypedApiInterface.AnalysisID(ANALYSIS)); + var match = body.getMatches().get(0); + var origin = new TypedApiInterface.FunctionID(match.getFunctionId()); + FunctionMatch best = FunctionMatch.fromMatchedFunctionAPIType(match.getMatchedFunctions().get(0), origin); + + assertEquals(new TypedApiInterface.FunctionID(1109480836L), best.origin_function_id()); + assertEquals(new TypedApiInterface.FunctionID(2209481173L), best.nearest_neighbor_id()); + assertEquals("std::thread::_M_start_thread", best.name()); + assertEquals("_ZNSt6thread15_M_start_threadESt10unique_ptrINS_6_StateESt14default_deleteIS1_EEPFvvE", + best.nearest_neighbor_mangled_function_name()); + assertEquals("libstdc++.so.6", best.nearest_neighbor_binary_name()); + assertEquals(new TypedApiInterface.BinaryHash("7399e7775c542bf9bd036dccad91e9fea586a383ae2b958facfcdc03749f202e"), + best.nearest_neighbor_sha_256_hash()); + assertEquals(new TypedApiInterface.AnalysisID(948099), best.nearest_neighbor_analysis_id()); + assertEquals(2, match.getMatchedFunctions().size()); + } + + @Test + public void binarySearchResultsCarryAnalysisAndName() throws Exception { + var results = api().searchBinaries("libstdc", null); + assertEquals(1, results.size()); + assertEquals(Integer.valueOf(948099), results.get(0).getAnalysisId()); + assertEquals("libstdc++.so.6", results.get(0).getBinaryName()); + } + + @Test + public void collectionResultsCarryIdAndName() throws Exception { + var results = api().searchCollections("OpenSSL"); + assertEquals(1, results.size()); + assertEquals(Long.valueOf(42), results.get(0).getCollectionId()); + assertEquals("OpenSSL builds", results.get(0).getCollectionName()); + } + + private static String recorded(String name) throws IOException { + try (InputStream in = SdkRecordedResponseTest.class.getResourceAsStream("/sdk-responses/" + name)) { + if (in == null) { + throw new IOException("missing recorded response " + name); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java index 7a058ddd..8da17ab7 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/SdkSchemaTest.java @@ -34,13 +34,17 @@ public void apiClientsExposeMethodsThePluginCalls() { apis.put("ai.reveng.api.ConfigApi", new String[]{"getConfig"}); apis.put("ai.reveng.api.SearchApi", new String[]{"searchBinaries"}); apis.put("ai.reveng.api.CollectionsApi", new String[]{"v3ListCollections"}); + apis.put("ai.reveng.api.AuthenticationUsersApi", new String[]{"v3ListUsers"}); + // The tier gates the private-scope option in the analysis dialog. + apis.put("ai.reveng.api.IamUsersApi", new String[]{"getMe"}); apis.put("ai.reveng.api.AnalysesCoreApi", new String[]{ - "uploadFile", "createAnalysis", "getAnalysisStatus", "getAnalysisBasicInfo_0", + "v3CreateAnalysis", "getAnalysisStatus", "getAnalysisBasicInfo_0", "startAnalysisFunctionMatching", "getAnalysisFunctionMatchingStatus", "getAnalysisFunctionMatches", - "v3GetAnalysisLogs", "v3ListAnalyses"}); + "v3GetAnalysisLogs", "v3ListAnalyses", "v3GetAnalysisAutoUnstripStatus"}); + apis.put("ai.reveng.api.BinariesApi", new String[]{"v3UploadFile"}); apis.put("ai.reveng.api.FunctionsCoreApi", new String[]{ "startFunctionsMatching", "getFunctionsMatchingStatus", "getFunctionsMatches", - "listAnalysisFunctions", + "listAnalysisFunctions", "v3CanonicalizeFunctionNames", // v3 endpoints; the generator suffixes _0 where the deprecated v2 name collides. "getFunctionBlocks_0", "getFunctionDetails_0"}); apis.put("ai.reveng.api.FunctionsRenamingHistoryApi", new String[]{"batchRenameFunctions"}); @@ -59,10 +63,11 @@ public void apiClientsExposeMethodsThePluginCalls() { "v3CreateAnalysisDataTypesCall", "v3UpdateAnalysisDataTypesCall", "v3UpdateFunctionSignature"}); apis.put("ai.reveng.api.FunctionsAiDecompilationApi", new String[]{ - "createAiDecompilation", "getAiDecompilation", "v3GetAiDecompilationTokens", - "v3UpsertAiDecompilationOverrides", + "createAiDecompilation", "getAiDecompilation", "getAiDecompilationStatus", + "v3GetAiDecompilationTokens", "v3UpsertAiDecompilationOverrides", "getAiDecompilationSummary", "getAiDecompilationSummaryStatus", "getAiDecompilationInlineComments", "getAiDecompilationInlineCommentsStatus", + "patchAiDecompilationInlineComment", "deleteAiDecompilationInlineComment", "regenerateAiDecompilationSummary", "regenerateAiDecompilationInlineComments", "upsertAiDecompilationRating"}); @@ -119,18 +124,29 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.FunctionSignatureVersion", "getValue", "getUpdatedAt", "getUpdatedBy"); - requireMethods(missing, "ai.reveng.model.AnalysisCreateRequest", + requireMethods(missing, "ai.reveng.model.CreateRequest", "getFilename", "getSha256Hash", "getTags", "getAnalysisScope"); - requireMethods(missing, "ai.reveng.model.Tag", "getName"); + requireMethods(missing, "ai.reveng.model.UploadOutputBody", "getSha256Hash"); + requireMethods(missing, "ai.reveng.model.OperationCreateMetadataCreateResult", + "getMetadata", "getResponse"); requireMethods(missing, "ai.reveng.model.StartMatchingForAnalysisInputBody", "getMinSimilarity", "getResultsPerFunction", "getFilters"); requireMethods(missing, "ai.reveng.model.StartMatchingForFunctionsInputBody", "getFunctionIds", "getResultsPerFunction", "getFilters", "getMinSimilarity"); requireMethods(missing, "ai.reveng.model.MatchFilters", - "getCollectionIds", "getBinaryIds", "getDebugTypes"); + "getCollectionIds", "getBinaryIds", "getDebugTypes", "getPlatforms", "getArchitectures", "getUserIds"); + requireMethods(missing, "ai.reveng.model.ListPublicUsersOutputBody", "getResults"); + requireMethods(missing, "ai.reveng.model.PublicUserBody", "getUserId", "getUsername"); requireMethods(missing, "ai.reveng.model.GetMatchesOutputBody", "getMatches", "getStatus"); + // Matching is polled on the status body; its step fields drive the progress text and its + // error-level messages become the failure reason. + requireMethods(missing, "ai.reveng.model.GetMatchesStatusOutputBody", + "getStatus", "getStep", "getStepIndex", "getStepsTotal", "getMessages"); + requireMethods(missing, "ai.reveng.model.ProgressMessage", "getLevel", "getText", "getTimestamp"); + requireMethods(missing, "ai.reveng.model.FunctionMatch", "getFunctionId", "getMatchedFunctions"); requireMethods(missing, "ai.reveng.model.MatchedFunction", - "getFunctionId", "getFunctionName", "getSimilarity", "getConfidence"); + "getFunctionId", "getFunctionName", "getMangledName", "getBinaryName", "getSha256Hash", + "getDebug", "getSimilarity", "getConfidence", "getAnalysisId"); requireMethods(missing, "ai.reveng.model.BatchRenameInputBody", "setFunctions"); requireMethods(missing, "ai.reveng.model.BatchRenameItem", "setFunctionId", "setNewName", "setNewMangledName"); @@ -180,6 +196,32 @@ public void modelTypesExposeAccessorsThePluginReliesOn() { requireMethods(missing, "ai.reveng.model.Token", "getValue"); requireMethods(missing, "ai.reveng.model.UpsertOverridesInputBody", "getOverrides"); + // The AI decompilation poll: the decompilation itself, its pipeline progress while it runs, + // then the summary and inline comments once it completes. + requireMethods(missing, "ai.reveng.model.DecompilationData", "getStatus", "getDecompilation"); + requireMethods(missing, "ai.reveng.model.WorkflowProgress", + "getStatus", "getStep", "getStepIndex", "getStepsTotal", "getMessages"); + requireMethods(missing, "ai.reveng.model.SummaryData", "getAiSummary", "getSummary"); + requireMethods(missing, "ai.reveng.model.CommentsData", "getInlineComments"); + requireMethods(missing, "ai.reveng.model.InlineComment", "getLine", "getComment"); + requireMethods(missing, "ai.reveng.model.PatchCommentBody", "comment", "line"); + + requireMethods(missing, "ai.reveng.model.AutoUnstripStatusOutputBody", "getStatus"); + requireMethods(missing, "ai.reveng.model.CanonicalizeNamesInputBody", "names"); + requireMethods(missing, "ai.reveng.model.CanonicalizeNamesOutputBody", "getResults"); + requireMethods(missing, "ai.reveng.model.CanonicalName", "getName", "getCanonicalName"); + + requireMethods(missing, "ai.reveng.model.CurrentUser", "getTier"); + requireMethods(missing, "ai.reveng.model.BaseResponseConfigResponse", "getData"); + requireMethods(missing, "ai.reveng.model.ConfigResponse", "getMaxFileSizeBytes"); + + // The collection and binary pickers in the matching filters. + requireMethods(missing, "ai.reveng.model.BaseResponseBinarySearchResponse", "getData"); + requireMethods(missing, "ai.reveng.model.BinarySearchResponse", "getResults"); + requireMethods(missing, "ai.reveng.model.BinarySearchResult", "getAnalysisId", "getBinaryName"); + requireMethods(missing, "ai.reveng.model.ListCollectionsOutputBody", "getResults"); + requireMethods(missing, "ai.reveng.model.CollectionListItemBody", "getCollectionId", "getCollectionName"); + assertTrue("SDK model surface drifted: " + missing, missing.isEmpty()); } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java new file mode 100644 index 00000000..274ae91a --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/StatusPollerTest.java @@ -0,0 +1,157 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import ai.reveng.invoker.ApiException; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller.Ending; +import ai.reveng.toolkit.ghidra.core.services.api.StatusPoller.Verdict; +import org.junit.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; + +public class StatusPollerTest { + + private static Verdict classify(String status) { + return switch (status) { + case "DONE", "FAILED" -> Verdict.DONE; + case "RUNNING", "STEP1", "STEP2" -> Verdict.WAIT; + default -> Verdict.UNRECOGNISED; + }; + } + + private static StatusPoller.Fetch sequence(String... statuses) { + Iterator it = List.of(statuses).iterator(); + return () -> it.hasNext() ? it.next() : statuses[statuses.length - 1]; + } + + @Test + public void endsOnFinalStatus() throws Exception { + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .poll(sequence("RUNNING", "RUNNING", "FAILED"), StatusPollerTest::classify, () -> false); + assertEquals(Ending.DONE, result.ending()); + assertEquals("FAILED", result.status()); + } + + @Test + public void endsOnUnrecognisedStatusInsteadOfPollingForEver() throws Exception { + var polls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .poll(() -> { + polls.incrementAndGet(); + return "CANCELLED"; + }, StatusPollerTest::classify, () -> false); + assertEquals(Ending.UNRECOGNISED, result.ending()); + assertEquals("CANCELLED", result.status()); + assertEquals(1, polls.get()); + } + + /// A clock that only moves when the poller sleeps, so waits are exact on any machine. + private static final class FakeClock { + long nanos; + final List sleeps = new ArrayList<>(); + + StatusPoller drive(StatusPoller poller) { + return poller.withClock(() -> nanos, millis -> { + sleeps.add(millis); + nanos += millis * 1_000_000; + }); + } + } + + @Test + public void endsAtTheTimeLimit() throws Exception { + var clock = new FakeClock(); + var result = clock.drive(new StatusPoller(Duration.ofMillis(5), Duration.ofMillis(5), Duration.ofMillis(100))) + .poll(sequence("RUNNING"), StatusPollerTest::classify, () -> false); + assertEquals(Ending.TIMED_OUT, result.ending()); + assertEquals("RUNNING", result.status()); + assertEquals(Duration.ofMillis(100), result.waited()); + assertEquals(20, clock.sleeps.size()); + } + + @Test + public void endsWhenCancelled() throws Exception { + var polls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .poll(() -> "RUNNING", s -> { + polls.incrementAndGet(); + return classify(s); + }, () -> polls.get() >= 3); + assertEquals(Ending.CANCELLED, result.ending()); + assertEquals(3, polls.get()); + } + + @Test + public void cancellingCutsALongWaitShort() throws Exception { + long start = System.nanoTime(); + var polls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofSeconds(30), Duration.ofSeconds(30), Duration.ofMinutes(5)) + .poll(() -> { + polls.incrementAndGet(); + return "RUNNING"; + }, StatusPollerTest::classify, () -> System.nanoTime() - start > 300_000_000L); + assertEquals(Ending.CANCELLED, result.ending()); + assertEquals(1, polls.get()); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 5); + } + + @Test + public void backsOffWhileTheStatusIsUnchangedAndResetsOnChange() throws Exception { + var clock = new FakeClock(); + var result = clock.drive(new StatusPoller(Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofSeconds(10))) + .poll(sequence("RUNNING", "RUNNING", "RUNNING", "RUNNING", "STEP1", "STEP2", "DONE"), + StatusPollerTest::classify, () -> false); + assertEquals(Ending.DONE, result.ending()); + // RUNNING x4: 20, then 40, then 80, then 80 (capped); after each change it is back to 20 + assertEquals(List.of(20L, 40L, 80L, 80L, 20L, 20L), clock.sleeps); + } + + @Test + public void retriesRetryableFailuresThenGivesUp() { + var calls = new AtomicInteger(); + var poller = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .retrying(e -> e instanceof ApiException api && api.getCode() == 503, 4, Duration.ofMillis(1)); + var thrown = assertThrows(ApiException.class, () -> poller.poll(() -> { + calls.incrementAndGet(); + throw new ApiException(503, "Service Unavailable"); + }, StatusPollerTest::classify, () -> false)); + assertEquals(503, thrown.getCode()); + assertEquals(4, calls.get()); + } + + @Test + public void recoversFromARetryableFailure() throws Exception { + var calls = new AtomicInteger(); + var result = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)) + .retrying(e -> e instanceof ApiException, 4, Duration.ofMillis(1)) + .poll(() -> { + if (calls.incrementAndGet() == 1) { + throw new ApiException(503, "Service Unavailable"); + } + return "DONE"; + }, StatusPollerTest::classify, () -> false); + assertEquals(Ending.DONE, result.ending()); + } + + @Test + public void rethrowsAFailureThatIsNotRetryable() { + var calls = new AtomicInteger(); + var poller = new StatusPoller(Duration.ofMillis(1), Duration.ofMillis(1), Duration.ofSeconds(10)); + assertThrows(ApiException.class, () -> poller.poll(() -> { + calls.incrementAndGet(); + throw new ApiException(404, "Not Found"); + }, StatusPollerTest::classify, () -> false)); + assertEquals(1, calls.get()); + } + + @Test + public void describesWaits() { + assertEquals("3 hours", StatusPoller.describe(Duration.ofHours(3).minusSeconds(4))); + assertEquals("30 minute(s)", StatusPoller.describe(Duration.ofMinutes(30).minusSeconds(3))); + assertEquals("45 second(s)", StatusPoller.describe(Duration.ofSeconds(45))); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDnsTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDnsTest.java new file mode 100644 index 00000000..bf021ac1 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/TimeoutDnsTest.java @@ -0,0 +1,59 @@ +package ai.reveng.toolkit.ghidra.core.services.api; + +import okhttp3.Dns; +import org.junit.Test; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CountDownLatch; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * Covers {@link TimeoutDns}, which stops a hanging DNS lookup (e.g. with no network) from + * blocking a request past OkHttp's connect timeout. + */ +public class TimeoutDnsTest { + + @Test + public void returnsTheDelegatesAddresses() throws Exception { + var addresses = List.of(InetAddress.getByAddress("api.reveng.ai", new byte[]{10, 0, 0, 1})); + var dns = new TimeoutDns(hostname -> addresses, Duration.ofSeconds(1)); + + assertEquals(addresses, dns.lookup("api.reveng.ai")); + } + + @Test + public void failsWhenTheLookupHangs() { + var neverReleased = new CountDownLatch(1); + Dns hanging = hostname -> { + try { + neverReleased.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return List.of(); + }; + var dns = new TimeoutDns(hanging, Duration.ofMillis(200)); + + long start = System.nanoTime(); + var e = assertThrows(UnknownHostException.class, () -> dns.lookup("api.reveng.ai")); + long elapsedMillis = (System.nanoTime() - start) / 1_000_000; + + assertTrue(e.getMessage(), e.getMessage().contains("timed out")); + assertTrue("lookup should give up near the timeout, took " + elapsedMillis + "ms", elapsedMillis < 2000); + } + + @Test + public void passesThroughUnknownHost() { + var unknown = new UnknownHostException("no such host"); + var dns = new TimeoutDns(hostname -> { throw unknown; }, Duration.ofSeconds(1)); + + assertSame(unknown, assertThrows(UnknownHostException.class, () -> dns.lookup("nope.invalid"))); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfoTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfoTest.java new file mode 100644 index 00000000..593a2d37 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/ApiInfoTest.java @@ -0,0 +1,43 @@ +package ai.reveng.toolkit.ghidra.core.services.api.types; + +import org.junit.Test; + +import java.net.URI; + +import static org.junit.Assert.assertEquals; + +public class ApiInfoTest { + + @Test + public void normaliseHost_addsHttpsWhenSchemeIsMissing() { + assertEquals("https://api.reveng.ai:8443", ApiInfo.normaliseHost("api.reveng.ai:8443")); + } + + @Test + public void normaliseHost_trimsWhitespace() { + assertEquals("https://api.reveng.ai", ApiInfo.normaliseHost(" https://api.reveng.ai \t")); + } + + @Test + public void normaliseHost_stripsTrailingSlashes() { + assertEquals("https://api.reveng.ai", ApiInfo.normaliseHost("https://api.reveng.ai//")); + } + + @Test + public void normaliseHost_keepsAnExplicitScheme() { + assertEquals("http://localhost:8080", ApiInfo.normaliseHost("http://localhost:8080")); + } + + @Test + public void normaliseHost_leavesBlankInputEmpty() { + assertEquals("", ApiInfo.normaliseHost(" ")); + } + + @Test + public void stringConstructor_normalisesBothHosts() { + var info = new ApiInfo(" api.reveng.ai/ ", "portal.reveng.ai/", "key"); + + assertEquals(URI.create("https://api.reveng.ai"), info.hostURI()); + assertEquals(URI.create("https://portal.reveng.ai"), info.portalURI()); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java index fd0da949..1165b88b 100644 --- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/api/types/TypePathAndNameTest.java @@ -22,4 +22,20 @@ public void fromString_leavesAnUnqualifiedNameWithAnEmptyPath() { assertEquals("PlainName", path.name()); assertArrayEquals("an unqualified name has no path segments", new String[]{}, path.path()); } + + @Test + public void fromString_ignoresEmptySegments() { + var path = TypePathAndName.fromString("a::::b"); + + assertEquals("b", path.name()); + assertArrayEquals(new String[]{"a"}, path.path()); + } + + @Test + public void fromString_acceptsABareSeparator() { + var path = TypePathAndName.fromString("::"); + + assertEquals("", path.name()); + assertArrayEquals(new String[]{}, path.path()); + } } diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java new file mode 100644 index 00000000..f1d83225 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java @@ -0,0 +1,60 @@ +package ai.reveng.toolkit.ghidra.core.services.update; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** Unit tests for the pure parts of {@link UpdateChecker}. */ +public class UpdateCheckerTest { + + private static final String RELEASE = """ + {"tag_name": "v1.2.0", + "html_url": "https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0", + "assets": [ + {"name": "ghidra_12.1.3_plugin-ghidra.zip", "browser_download_url": "https://example/12.1.3.zip"}, + {"name": "ghidra_12.2_plugin-ghidra.zip", "browser_download_url": "https://example/12.2.zip"} + ]} + """; + + @Test + public void comparesSemanticVersions() { + assertTrue(UpdateChecker.isNewer("v1.2.0", "v1.1.9")); + assertTrue(UpdateChecker.isNewer("v2.0.0", "v1.10.10")); + assertTrue(UpdateChecker.isNewer("v1.10.0", "v1.9.0")); + assertFalse(UpdateChecker.isNewer("v1.1.0", "v1.1.0")); + assertFalse(UpdateChecker.isNewer("v1.0.9", "v1.1.0")); + } + + @Test + public void unparseableVersionsAreNeverNewer() { + assertFalse(UpdateChecker.isNewer("v1.2.0", UpdateChecker.UNKNOWN_VERSION)); + assertFalse(UpdateChecker.isNewer("latest", "v1.0.0")); + assertFalse(UpdateChecker.isNewer("v1.2", "v1.0.0")); + } + + @Test + public void findsAssetForGhidraVersion() { + var update = UpdateChecker.findUpdate("v1.1.0", "12.2", RELEASE).orElseThrow(); + assertEquals("v1.2.0", update.version()); + assertEquals("https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0", update.releaseUrl()); + assertEquals("https://example/12.2.zip", update.downloadUrl()); + } + + @Test + public void noUpdateWhenCurrent() { + assertTrue(UpdateChecker.findUpdate("v1.2.0", "12.2", RELEASE).isEmpty()); + } + + @Test + public void noUpdateWithoutAssetForGhidraVersion() { + assertTrue(UpdateChecker.findUpdate("v1.1.0", "11.4", RELEASE).isEmpty()); + } + + @Test + public void noUpdateOnMalformedJson() { + assertTrue(UpdateChecker.findUpdate("v1.1.0", "12.2", "not json").isEmpty()); + assertTrue(UpdateChecker.findUpdate("v1.1.0", "12.2", "{}").isEmpty()); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTaskDescribeTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTaskDescribeTest.java new file mode 100644 index 00000000..9cddb28e --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/tasks/StartAnalysisTaskDescribeTest.java @@ -0,0 +1,26 @@ +package ai.reveng.toolkit.ghidra.core.tasks; + +import ai.reveng.invoker.ApiException; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +/// A rejected analysis request shows the server's `error.message`, not the raw error body. +public class StartAnalysisTaskDescribeTest { + + private static final ApiException REJECTED = new ApiException(402, Map.of("content-type", List.of("application/json")), + "{\"error\":{\"code\":\"INSUFFICIENT_CREDITS\",\"message\":\"Not enough credits\"}}"); + + @Test + public void showsServerMessage() { + assertEquals("HTTP 402 — Not enough credits", StartAnalysisTask.describe(REJECTED)); + } + + @Test + public void showsServerMessageWhenWrapped() { + assertEquals("HTTP 402 — Not enough credits", StartAnalysisTask.describe(new RuntimeException(REJECTED))); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowserTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowserTest.java new file mode 100644 index 00000000..ff9363c3 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/core/ui/WebBrowserTest.java @@ -0,0 +1,34 @@ +package ai.reveng.toolkit.ghidra.core.ui; + +import ghidra.framework.OperatingSystem; +import org.junit.Test; + +import java.net.URI; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Guards that URLs open with the OS's own launcher, not Ghidra's manual-viewer setting, whose 12.2 + * macOS default ({@code anaconda-navigator}) is usually missing (ENG-4233). + */ +public class WebBrowserTest { + + private static final URI URL = URI.create("https://portal.reveng.ai/analyses/1229816"); + + @Test + public void macUsesOpen() { + assertEquals(List.of("open", URL.toString()), WebBrowser.command(OperatingSystem.MAC_OS_X, URL)); + } + + @Test + public void linuxUsesXdgOpen() { + assertEquals(List.of("xdg-open", URL.toString()), WebBrowser.command(OperatingSystem.LINUX, URL)); + } + + @Test + public void windowsUsesUrlProtocolHandler() { + assertEquals(List.of("rundll32", "url.dll,FileProtocolHandler", URL.toString()), + WebBrowser.command(OperatingSystem.WINDOWS, URL)); + } +} diff --git a/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java b/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java new file mode 100644 index 00000000..0307d714 --- /dev/null +++ b/src/test/java/ai/reveng/toolkit/ghidra/plugins/AnalysisManagementPluginTest.java @@ -0,0 +1,39 @@ +package ai.reveng.toolkit.ghidra.plugins; + +import ai.reveng.toolkit.ghidra.core.services.api.types.AnalysisStatus; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class AnalysisManagementPluginTest { + + @Test + public void checkStatusMessageShowsOnlyStatus() { + assertEquals("Analysis status: Complete", AnalysisManagementPlugin.checkStatusMessage(AnalysisStatus.Complete)); + } + + @Test + public void logTailKeepsLastNonBlankLines() { + assertEquals("", AnalysisManagementPlugin.logTail(null, 3, 50)); + assertEquals("", AnalysisManagementPlugin.logTail(" \n ", 3, 50)); + assertEquals("b\nc\nd", AnalysisManagementPlugin.logTail("a\nb\n\nc \nd\n\n", 3, 50)); + assertEquals("a\nb", AnalysisManagementPlugin.logTail("a\r\nb", 3, 50)); + } + + @Test + public void logTailCutsLongLines() { + assertEquals("abcde...\nxy", AnalysisManagementPlugin.logTail("abcdefgh\nxy", 3, 5)); + } + + @Test + public void analysisErrorMessageShowsLogTailAndChoices() { + var message = AnalysisManagementPlugin.analysisErrorMessage(42, "prog.exe", "step 1\nFATAL"); + assertTrue(message, message.startsWith("The RevEng.AI analysis 42 of prog.exe failed on the server.")); + assertTrue(message, message.contains("End of the analysis log:\nstep 1\nFATAL")); + assertTrue(message, message.contains("Detach")); + + var noLog = AnalysisManagementPlugin.analysisErrorMessage(42, "prog.exe", ""); + assertTrue(noLog, noLog.contains("No analysis log is available.")); + } +} diff --git a/src/test/resources/META-INF/services/org.junit.platform.launcher.LauncherSessionListener b/src/test/resources/META-INF/services/org.junit.platform.launcher.LauncherSessionListener new file mode 100644 index 00000000..0f9fe372 --- /dev/null +++ b/src/test/resources/META-INF/services/org.junit.platform.launcher.LauncherSessionListener @@ -0,0 +1 @@ +ai.reveng.ForkTempDir diff --git a/src/test/resources/sdk-responses/README.md b/src/test/resources/sdk-responses/README.md new file mode 100644 index 00000000..a0b86da3 --- /dev/null +++ b/src/test/resources/sdk-responses/README.md @@ -0,0 +1,6 @@ +Response bodies for `SdkRecordedResponseTest`, one per endpoint, in the shape the staging server +emits them: every field the server writes, including the ones the plugin never reads. They were +taken from the handlers on `platform` origin/staging (the v3 API and the auth service) and, for the +deprecated `/v2/config` and `/v2/search/binaries`, from `reai-api`. + +When an endpoint's response changes, refresh its file from a live staging response. diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments-delete.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-delete.json new file mode 100644 index 00000000..240bb0c2 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-delete.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","inline_comments":[{"line":3,"comment":"Reject buffers too short to hold the 8-byte header."}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments-patch.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-patch.json new file mode 100644 index 00000000..4136314a --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-patch.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","inline_comments":[{"line":3,"comment":"Reject buffers too short to hold the 8-byte header."},{"line":6,"comment":"Length field is big-endian."}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments-status.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-status.json new file mode 100644 index 00000000..6dc95aaa --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments-status.json @@ -0,0 +1 @@ +{"status":"COMPLETED","step":"storing_comments","step_index":2,"steps_total":2,"percent":100,"step_share":0,"messages":[{"timestamp":"2026-11-13T10:05:02.220871Z","step":"generating_comments","level":"INFO","text":"Generating structured comments"},{"timestamp":"2026-11-13T10:05:09.031455Z","step":"storing_comments","level":"INFO","text":"Storing comments"}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-inline-comments.json b/src/test/resources/sdk-responses/ai-decompilation-inline-comments.json new file mode 100644 index 00000000..6e6bd1e9 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-inline-comments.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","inline_comments":[{"line":3,"comment":"Reject buffers too short to hold the 8-byte header."},{"line":6,"comment":"Skip the 4-byte magic and parse the length field."}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-running.json b/src/test/resources/sdk-responses/ai-decompilation-running.json new file mode 100644 index 00000000..6cffe653 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-running.json @@ -0,0 +1 @@ +{"status":"RUNNING"} diff --git a/src/test/resources/sdk-responses/ai-decompilation-status.json b/src/test/resources/sdk-responses/ai-decompilation-status.json new file mode 100644 index 00000000..850b4134 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-status.json @@ -0,0 +1 @@ +{"status":"RUNNING","step":"decompiling","step_index":2,"steps_total":7,"percent":28,"step_share":14,"messages":[{"timestamp":"2026-11-13T10:04:11.482913Z","step":"charging_credits","level":"INFO","text":"Preparing decompilation"},{"timestamp":"2026-11-13T10:04:11.913204Z","step":"fetching_trace","level":"INFO","text":"Reading function trace"},{"timestamp":"2026-11-13T10:04:12.301877Z","step":"decompiling","level":"INFO","text":"Decompiling function"},{"timestamp":"2026-11-13T10:04:12.301877Z","step":"decompiling","level":"INFO","text":"Searching for functionality"}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-summary-status.json b/src/test/resources/sdk-responses/ai-decompilation-summary-status.json new file mode 100644 index 00000000..8c8534e7 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-summary-status.json @@ -0,0 +1 @@ +{"status":"COMPLETED","step":"storing_summary","step_index":2,"steps_total":2,"percent":100,"step_share":0,"messages":[{"timestamp":"2026-11-13T10:05:02.114502Z","step":"summarising","level":"INFO","text":"Generating summary"},{"timestamp":"2026-11-13T10:05:06.870331Z","step":"storing_summary","level":"INFO","text":"Storing summary"}]} diff --git a/src/test/resources/sdk-responses/ai-decompilation-summary.json b/src/test/resources/sdk-responses/ai-decompilation-summary.json new file mode 100644 index 00000000..30c7b3e8 --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation-summary.json @@ -0,0 +1 @@ +{"task_status":"COMPLETED","summary":"Parses an HTTP header from buf and returns the length of the remaining payload, or -1 if the buffer is shorter than 8 bytes.","ai_summary":"Parses an HTTP header from buf and returns the length of the remaining payload, or -1 if the buffer is shorter than 8 bytes.","predicted_function_name":"parse_http_header"} diff --git a/src/test/resources/sdk-responses/ai-decompilation.json b/src/test/resources/sdk-responses/ai-decompilation.json new file mode 100644 index 00000000..b05a3dbc --- /dev/null +++ b/src/test/resources/sdk-responses/ai-decompilation.json @@ -0,0 +1 @@ +{"status":"COMPLETED","decompilation":"int parse_header(char *buf, int len)\n{\n if (len < 8) {\n return -1;\n }\n return read_field(buf + 4, len - 4);\n}\n"} diff --git a/src/test/resources/sdk-responses/analysis-matches.json b/src/test/resources/sdk-responses/analysis-matches.json new file mode 100644 index 00000000..49d342ac --- /dev/null +++ b/src/test/resources/sdk-responses/analysis-matches.json @@ -0,0 +1 @@ +{"status":"COMPLETED","matches":[{"function_id":1109480836,"matched_functions":[{"function_id":2209481173,"function_name":"std::thread::_M_start_thread","binary_id":758289,"analysis_id":948099,"function_vaddr":4198400,"debug":true,"similarity":99.42,"confidence":87.1,"mangled_name":"_ZNSt6thread15_M_start_threadESt10unique_ptrINS_6_StateESt14default_deleteIS1_EEPFvvE","binary_name":"libstdc++.so.6","sha_256_hash":"7399e7775c542bf9bd036dccad91e9fea586a383ae2b958facfcdc03749f202e"},{"function_id":2210377402,"function_name":"std::thread::_M_start_thread","binary_id":760743,"analysis_id":951312,"function_vaddr":4210688,"debug":true,"similarity":97.85,"confidence":12.9,"mangled_name":"_ZNSt6thread15_M_start_threadESt10unique_ptrINS_6_StateESt14default_deleteIS1_EEPFvvE","binary_name":"libstdc++.so.6.0.33","sha_256_hash":"c1a5e0b2f4d1e9a3b7c6d8e0f2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e6f8a0"}],"confidences":[{"name":"std::thread::_M_start_thread","confidence":100.0}]}]} diff --git a/src/test/resources/sdk-responses/auto-unstrip-status.json b/src/test/resources/sdk-responses/auto-unstrip-status.json new file mode 100644 index 00000000..f68b1e26 --- /dev/null +++ b/src/test/resources/sdk-responses/auto-unstrip-status.json @@ -0,0 +1 @@ +{"status":"COMPLETED"} diff --git a/src/test/resources/sdk-responses/canonical-names.json b/src/test/resources/sdk-responses/canonical-names.json new file mode 100644 index 00000000..ae88b94a --- /dev/null +++ b/src/test/resources/sdk-responses/canonical-names.json @@ -0,0 +1 @@ +{"results":[{"name":"_ZN3fooC1Ev","canonical_name":"foo"},{"name":"sub_401000","canonical_name":"sub_401000"}]} diff --git a/src/test/resources/sdk-responses/collections.json b/src/test/resources/sdk-responses/collections.json new file mode 100644 index 00000000..e6b0306b --- /dev/null +++ b/src/test/resources/sdk-responses/collections.json @@ -0,0 +1 @@ +{"results":[{"collection_id":42,"collection_name":"OpenSSL builds","description":"Reference builds of OpenSSL across versions","collection_scope":"PRIVATE","collection_owner":"jdoe","official_collection":false,"collection_tags":["openssl","crypto"],"collection_size":18,"team_id":12,"creation":"2026-01-14T09:30:00.104882Z","updated_at":"2026-01-15T11:02:00.733019Z"}],"page_size":20,"page_number":0,"has_next_page":false} diff --git a/src/test/resources/sdk-responses/config.json b/src/test/resources/sdk-responses/config.json new file mode 100644 index 00000000..7b1e0b29 --- /dev/null +++ b/src/test/resources/sdk-responses/config.json @@ -0,0 +1 @@ +{"status":true,"data":{"dashboard_url":"https://portal.reveng.ai","max_file_size_bytes":31457280,"ai_decompiler_unsupported_languages":["go","rust"],"ai_decompiler_supported_models":["binnet-1.0","binnet-0.7-x86-64-linux","binnet-0.7-x86-32-linux","binnet-0.7-x86-64-windows","binnet-0.7-x86-32-windows","binnet-0.7-arm-64-windows","binnet-0.7-arm-64-linux"]},"message":null,"errors":null,"meta":{"pagination":null}} diff --git a/src/test/resources/sdk-responses/iam-me.json b/src/test/resources/sdk-responses/iam-me.json new file mode 100644 index 00000000..ba5cda12 --- /dev/null +++ b/src/test/resources/sdk-responses/iam-me.json @@ -0,0 +1 @@ +{"user_id":42,"role":"USER","tier":"REVERSER","email":"jane.doe@example.com","created_at":"2026-03-02T09:14:27.512843Z","is_active":true,"profile":{"username":"jdoe","first_name":"Jane","last_name":"Doe","time_zone":"Europe/London","default_team_id":12,"hide_example_binaries":false,"hide_ai_decompilation_comments":false,"agent_chat_layout":"floating"},"signs_in_with":"password"} diff --git a/src/test/resources/sdk-responses/matches-status-completed.json b/src/test/resources/sdk-responses/matches-status-completed.json new file mode 100644 index 00000000..f12195fb --- /dev/null +++ b/src/test/resources/sdk-responses/matches-status-completed.json @@ -0,0 +1 @@ +{"status":"COMPLETED","step":"","step_index":0,"steps_total":0,"percent":100,"step_share":0,"messages":[],"completed_at":"2026-11-13T09:30:00.418273Z"} diff --git a/src/test/resources/sdk-responses/matches-status-running.json b/src/test/resources/sdk-responses/matches-status-running.json new file mode 100644 index 00000000..4d8e8246 --- /dev/null +++ b/src/test/resources/sdk-responses/matches-status-running.json @@ -0,0 +1 @@ +{"status":"RUNNING","step":"matching","step_index":1,"steps_total":3,"percent":3,"step_share":85,"messages":[{"timestamp":"2026-11-13T09:29:41.007112Z","step":"resolving_analysis","level":"INFO","text":"Resolving function IDs for the analysis"},{"timestamp":"2026-11-13T09:29:41.552390Z","step":"matching","level":"INFO","text":"Searching for similar functions"}]} diff --git a/src/test/resources/sdk-responses/search-binaries.json b/src/test/resources/sdk-responses/search-binaries.json new file mode 100644 index 00000000..cf1341bb --- /dev/null +++ b/src/test/resources/sdk-responses/search-binaries.json @@ -0,0 +1 @@ +{"status":true,"data":{"results":[{"binary_id":758289,"binary_name":"libstdc++.so.6","analysis_id":948099,"sha_256_hash":"7399e7775c542bf9bd036dccad91e9fea586a383ae2b958facfcdc03749f202e","tags":["linux","stdlib"],"created_at":"2026-10-02T14:21:07.483912Z","model_id":12,"model_name":"binnet-0.7-x86-64-linux","owned_by":"jdoe"}]},"message":null,"errors":null,"meta":{"pagination":{"page_size":10,"page_number":1,"has_next_page":false}}}