diff --git a/scripts/verify-real-ghidra-dol.mjs b/scripts/verify-real-ghidra-dol.mjs index b69a02037c..17829072d5 100644 --- a/scripts/verify-real-ghidra-dol.mjs +++ b/scripts/verify-real-ghidra-dol.mjs @@ -7,7 +7,11 @@ import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js"; import { withVerifierArtifactScope } from "./lib/verifier-artifact-scope.mjs"; -import { readGhidraLanguageCatalog } from "../dist/ghidra/GhidraLanguageCatalog.js"; +import { AnalysisResourceConstraintError } from "../dist/domain/analysisErrorCore.js"; +import { + admitGhidraLanguageOverride, + readGhidraLanguageCatalog, +} from "../dist/ghidra/GhidraLanguageCatalog.js"; import { parseEvidence } from "../dist/domain/evidence.js"; import { functionDossierSchema } from "../dist/domain/native/functionDossier.js"; import { inspectVerifierGhidraInstallation } from "./lib/ghidra-installation-inspection.mjs"; @@ -100,7 +104,13 @@ async function languageInstalled(languageId) { installation.installDir, scope, ); - return catalog.some((definition) => definition.id === languageId); + const refusal = admitGhidraLanguageOverride( + { languageId }, + catalog, + installation.providerVersion, + ); + if (refusal instanceof AnalysisResourceConstraintError) throw refusal; + return refusal === null; }); } diff --git a/src/ghidra/GhidraLanguageCatalog.ts b/src/ghidra/GhidraLanguageCatalog.ts index a40b187413..ef59d21f9c 100644 --- a/src/ghidra/GhidraLanguageCatalog.ts +++ b/src/ghidra/GhidraLanguageCatalog.ts @@ -1,6 +1,10 @@ import { readdir } from "node:fs/promises"; import { join } from "node:path"; -import { malformedInput, ParseFailureError } from "../domain/parseFailure.js"; +import { + decodeLimit, + malformedInput, + ParseFailureError, +} from "../domain/parseFailure.js"; import { GhidraAdmissionError } from "./GhidraAdmissionError.js"; import { parseXmlDocument } from "../domain/xmlDocument.js"; import { decodeXmlPlistText } from "../domain/propertyListXmlText.js"; @@ -14,6 +18,8 @@ import { withArtifactRegularFile, } from "../resources/index.js"; import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js"; +import type { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; +import { parseLimitConstraint } from "../domain/parseFailureAnalysisError.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { RegularFileOperationCancelled } from "../filesystem/RegularFile.js"; import { readBoundedFileBytes } from "../process/BoundedFileBytes.js"; @@ -24,6 +30,11 @@ export interface GhidraLanguageDefinition { readonly compilerSpecIds: readonly string[]; } +interface GhidraLanguageCatalog { + readonly definitions: readonly GhidraLanguageDefinition[]; + readonly oversizedFiles: readonly string[]; +} + // Language definitions are small XML files; refuse anything implausibly large. const MAX_LDEFS_BYTES = 4 * 1024 * 1024; // Processor modules ship under Processors; installed extensions may add more. @@ -86,14 +97,14 @@ const languageDirectories = async ( }; /** - * Parse one definition before its final close; an oversized file declares - * nothing. The caller's scope owns a descriptor whose close is unconfirmed. + * Parse one definition before its final close. An oversized file remains + * unexamined. The caller's scope owns a descriptor whose close is unconfirmed. */ const readLanguageDefinitionFile = ( path: string, resources: ArtifactResourceScope, signal: AbortSignal | undefined, -): Promise => +): Promise => withArtifactRegularFile( path, resources, @@ -106,7 +117,7 @@ const readLanguageDefinitionFile = ( }); // The XML byte owner validates encoding and declaration before syntax // parsing; a literal U+FFFD cannot diagnose invalid source bytes. - if (bytes === undefined) return []; + if (bytes === undefined) return undefined; try { return parseGhidraLanguageDefinitions(decodeXmlPlistText(bytes)); } catch (cause: unknown) { @@ -232,13 +243,13 @@ export const readGhidraLanguageCatalog = ( installDir: string, resources: ArtifactResourceScope, signal?: AbortSignal, -): Promise => +): Promise => resources.run(async () => { const directories = await languageDirectories(installDir, signal); const files = await discoverLanguageDefinitionFiles(directories, signal); // An empty scan starts no definition reads that could observe cancellation. assertArtifactReadActive(signal); - const results: Array = new Array( + const results = new Array( files.length, ); await runBoundedWorkers( @@ -252,20 +263,46 @@ export const readGhidraLanguageCatalog = ( ); }, ); - return results.flat(); + return { + definitions: results.flatMap((result) => result ?? []), + oversizedFiles: files.filter((_, index) => results[index] === undefined), + }; }); /** * Check a configured import language against the installation before launch, - * so an unknown ID fails as configuration instead of as a failed import. + * returning a configuration error for a missing ID only after a complete scan. */ export const admitGhidraLanguageOverride = ( override: GhidraLanguageOverride, - catalog: readonly GhidraLanguageDefinition[], + catalog: GhidraLanguageCatalog, providerVersion: string, -): ConfigurationError | null => { - const language = catalog.find((value) => value.id === override.languageId); - if (language === undefined) +): ConfigurationError | AnalysisResourceConstraintError | null => { + const language = catalog.definitions.find( + (value) => value.id === override.languageId, + ); + if (language === undefined) { + const path = catalog.oversizedFiles[0]; + if (path !== undefined) + return parseLimitConstraint( + "resolve_analysis_profile", + "file-size", + decodeLimit( + "ghidra-language-definition", + "The configured Ghidra language could not be confirmed because installed language definitions exceeded the size limit.", + { name: "language_definition_bytes", maximum: MAX_LDEFS_BYTES }, + ), + { + diagnostics: { + path, + oversized_definition_count: catalog.oversizedFiles.length, + setting: "REA_GHIDRA_LANGUAGE_ID", + }, + retryable: false, + remediationAction: + "Use a Ghidra installation whose language definitions fit the reported size limit.", + }, + ); return new ConfigurationError("Invalid REA environment configuration", { settings: [ { @@ -274,6 +311,7 @@ export const admitGhidraLanguageOverride = ( }, ], }); + } if ( override.compilerSpecId !== undefined && !language.compilerSpecIds.includes(override.compilerSpecId) diff --git a/src/ghidra/GhidraLanguageOverride.test.ts b/src/ghidra/GhidraLanguageOverride.test.ts index 94dec60fcf..fca93c9464 100644 --- a/src/ghidra/GhidraLanguageOverride.test.ts +++ b/src/ghidra/GhidraLanguageOverride.test.ts @@ -212,9 +212,11 @@ describe("Ghidra language override configuration", () => { describe("Ghidra language catalog", () => { it("parses language IDs and their compiler specs", async () => { - expect( - await readGhidraLanguageCatalog(installDir, new ArtifactResourceScope()), - ).toEqual([ + const catalog = await readGhidraLanguageCatalog( + installDir, + new ArtifactResourceScope(), + ); + expect(catalog.definitions).toEqual([ { id: "x86:LE:32:default", compilerSpecIds: ["windows", "gcc", "borlandcpp"], @@ -226,7 +228,7 @@ describe("Ghidra language catalog", () => { join(installDir, "absent"), new ArtifactResourceScope(), ), - ).toEqual([]); + ).toEqual({ definitions: [], oversizedFiles: [] }); }); it("identifies the malformed installed definition beside a valid selected language", async () => { @@ -267,6 +269,63 @@ describe("Ghidra language catalog", () => { await rm(path); } }); + + it("distinguishes an undefined language from one hidden by the definition size limit", async () => { + const languageId = "x86:LE:31:default"; + const configured = provider({ REA_GHIDRA_LANGUAGE_ID: languageId }); + const path = join( + installDir, + "Ghidra/Processors/x86/data/languages/large.ldefs", + ); + const maximum = 4 * 1024 * 1024; + const definition = ``; + const absent = await configured.resolveAnalysisProfile(pe); + if (absent.ok) throw new Error("Expected a configuration error"); + expect(projectAnalysisError(absent.error)).toMatchObject({ + code: "configuration_invalid", + details: { + settings: [ + { + setting: "REA_GHIDRA_LANGUAGE_ID", + constraint: `is not a language defined by Ghidra ${SUPPORTED_GHIDRA_VERSION}`, + }, + ], + }, + }); + await writeFile(path, definition.padEnd(maximum + 1)); + try { + const known = await provider({ + REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default", + }).resolveAnalysisProfile(pe); + if (!known.ok) throw known.error; + expect(known.value.profile?.parameters.language_id).toBe( + "x86:LE:32:default", + ); + + const uncertain = await configured.resolveAnalysisProfile(pe); + if (uncertain.ok) throw new Error("Expected a file size refusal"); + expect(projectAnalysisError(uncertain.error)).toMatchObject({ + code: "resource_constraint", + details: { + operation: "resolve_analysis_profile", + resource: "file-size", + reported_limits: { boundary: "language_definition_bytes", maximum }, + diagnostics: { + path, + setting: "REA_GHIDRA_LANGUAGE_ID", + oversized_definition_count: 1, + }, + }, + }); + + await writeFile(path, definition); + const repaired = await configured.resolveAnalysisProfile(pe); + if (!repaired.ok) throw repaired.error; + expect(repaired.value.profile?.parameters.language_id).toBe(languageId); + } finally { + await rm(path); + } + }); }); describe("Ghidra language override profile", () => { @@ -339,32 +398,25 @@ describe("Ghidra language override profile", () => { ); }); - it.each([ - { - overrides: { REA_GHIDRA_LANGUAGE_ID: "x86:LE:31:default" }, - setting: "REA_GHIDRA_LANGUAGE_ID", - constraint: `is not a language defined by Ghidra ${SUPPORTED_GHIDRA_VERSION}`, - }, - { - overrides: { - REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default", - REA_GHIDRA_COMPILER_SPEC_ID: "golang", + it("refuses an undefined compiler before launching Ghidra", async () => { + const resolved = await provider({ + REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default", + REA_GHIDRA_COMPILER_SPEC_ID: "golang", + }).resolveAnalysisProfile(pe); + if (resolved.ok) throw new Error("Expected a configuration error"); + expect(projectAnalysisError(resolved.error)).toMatchObject({ + code: "configuration_invalid", + details: { + settings: [ + { + setting: "REA_GHIDRA_COMPILER_SPEC_ID", + constraint: + "must be one of the selected language's compiler specs: windows, gcc, borlandcpp", + }, + ], }, - setting: "REA_GHIDRA_COMPILER_SPEC_ID", - constraint: - "must be one of the selected language's compiler specs: windows, gcc, borlandcpp", - }, - ])( - "refuses an undefined $setting before launching Ghidra", - async ({ overrides, setting, constraint }) => { - const resolved = await provider(overrides).resolveAnalysisProfile(pe); - if (resolved.ok) throw new Error("Expected a configuration error"); - expect(projectAnalysisError(resolved.error)).toMatchObject({ - code: "configuration_invalid", - details: { settings: [{ setting, constraint }] }, - }); - }, - ); + }); + }); it.each(["raw-binary", "dos-mz", "dos-com"] as const)( "attributes a fixed %s import override conflict to the named settings", @@ -417,7 +469,7 @@ it const blocked = join(root, relativePath); try { const original = await readGhidraLanguageCatalog(root, resources); - expect(original.length).toBeGreaterThan(0); + expect(original.definitions.length).toBeGreaterThan(0); await chmod(blocked, 0); await expect(readdir(blocked)).rejects.toMatchObject({ code: "EACCES" }); await expect( @@ -466,7 +518,7 @@ describe("Ghidra concurrent language catalog", () => { const resources = new ArtifactResourceScope(); try { const catalog = await readGhidraLanguageCatalog(root, resources); - expect(catalog.map(({ id }) => id)).toEqual(expectedIds); + expect(catalog.definitions.map(({ id }) => id)).toEqual(expectedIds); } finally { await resources.close(); } diff --git a/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts b/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts index ea8c17dc2d..8096852891 100644 --- a/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts +++ b/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts @@ -54,15 +54,16 @@ it("reads an exact-limit definition while skipping its oversized sibling with bo ); return bytes; }; - await writeFile( - join(directory, OVERSIZED), - definition("huge", LIMIT + 64 * 1024), - ); + const oversizedPath = join(directory, OVERSIZED); + await writeFile(oversizedPath, definition("huge", LIMIT + 64 * 1024)); await writeFile(join(directory, "edge.ldefs"), definition("edge", LIMIT)); expect( await readGhidraLanguageCatalog(root, new ArtifactResourceScope()), - ).toEqual([{ id: "edge:LE:32:default", compilerSpecIds: [] }]); + ).toEqual({ + definitions: [{ id: "edge:LE:32:default", compilerSpecIds: [] }], + oversizedFiles: [oversizedPath], + }); expect(readBytes.value).toBeLessThanOrEqual(LIMIT + 1); }); @@ -76,9 +77,13 @@ it("follows a symlinked definition file", async () => { '', ); await symlink(source, join(languages, "link.ldefs")); - expect( - await readGhidraLanguageCatalog(root, new ArtifactResourceScope()), - ).toEqual([{ id: "link:LE:32:default", compilerSpecIds: [] }]); + const catalog = await readGhidraLanguageCatalog( + root, + new ArtifactResourceScope(), + ); + expect(catalog.definitions).toEqual([ + { id: "link:LE:32:default", compilerSpecIds: [] }, + ]); }); it.skipIf(process.platform === "win32")( diff --git a/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts b/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts index 3081e26c72..5500e38724 100644 --- a/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts +++ b/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts @@ -193,7 +193,10 @@ it.for(["installation roots", "module directories"] as const)( gate.release(); await reading.catch(() => undefined); } - expect(await readGhidraLanguageCatalog(root, resources)).toEqual([]); + expect(await readGhidraLanguageCatalog(root, resources)).toEqual({ + definitions: [], + oversizedFiles: [], + }); }, ); @@ -271,7 +274,8 @@ it("blocks nonempty and empty reads until the caller scope releases the same des expect(resources.hasPending).toBe(true); retained.closeFails = false; - expect(await readGhidraLanguageCatalog(nextRoot, resources)).toEqual([ + const catalog = await readGhidraLanguageCatalog(nextRoot, resources); + expect(catalog.definitions).toEqual([ { id: "x86:LE:32:default", compilerSpecIds: [] }, ]); expect(retained.closeCalls).toBe(4); @@ -285,9 +289,13 @@ it("keeps one scope's retained close out of another scope", async () => { await expect( readGhidraLanguageCatalog(await installation("isolated"), failed), ).rejects.toBeInstanceOf(ArtifactReaderFailure); - expect( - await readGhidraLanguageCatalog(await installation("x86"), scope()), - ).toEqual([{ id: "x86:LE:32:default", compilerSpecIds: [] }]); + const catalog = await readGhidraLanguageCatalog( + await installation("x86"), + scope(), + ); + expect(catalog.definitions).toEqual([ + { id: "x86:LE:32:default", compilerSpecIds: [] }, + ]); expect(failed.hasPending).toBe(true); }); @@ -398,13 +406,18 @@ it("merges sibling cleanup observations and leases across concurrent definition first.closeFails = false; second.closeFails = false; - expect( - await readGhidraLanguageCatalog(await installation("x86"), resources), - ).toEqual([{ id: "x86:LE:32:default", compilerSpecIds: [] }]); + const recovered = await readGhidraLanguageCatalog( + await installation("x86"), + resources, + ); + expect(recovered.definitions).toEqual([ + { id: "x86:LE:32:default", compilerSpecIds: [] }, + ]); expect(first.closeCalls).toBe(2); expect(second.closeCalls).toBe(2); expect(resources.hasPending).toBe(false); - expect(await readGhidraLanguageCatalog(root, resources)).toHaveLength(10); + const catalog = await readGhidraLanguageCatalog(root, resources); + expect(catalog.definitions).toHaveLength(10); }); it("reports the denied definition as primary while owning a sibling close retry", async () => { diff --git a/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts b/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts index 79b1cfe4c1..996639c3f0 100644 --- a/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts +++ b/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts @@ -45,9 +45,11 @@ it("reads independent unsigned, UTF-8 BOM and UTF-16 BOM definitions together", ), ]), ); - expect( - await readGhidraLanguageCatalog(root, new ArtifactResourceScope()), - ).toEqual([ + const catalog = await readGhidraLanguageCatalog( + root, + new ArtifactResourceScope(), + ); + expect(catalog.definitions).toEqual([ { id: "unsigned:LE:32:default", compilerSpecIds: ["default"] }, { id: "utf8:LE:32:default", compilerSpecIds: ["default"] }, { id: "utf16:LE:32:default", compilerSpecIds: ["default"] },