fix(ghidra): report incomplete language catalogs at the file size limit (#13407)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 12:08:44 +00:00
1 parent 29efae350e
commit 3d3e7db5b5
6 files changed
+186 -66

No files matched your search

+51 -13
View File
@@ -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<readonly GhidraLanguageDefinition[]> =>
): Promise<readonly GhidraLanguageDefinition[] | undefined> =>
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<readonly GhidraLanguageDefinition[]> =>
): Promise<GhidraLanguageCatalog> =>
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<readonly GhidraLanguageDefinition[]> = new Array(
const results = new Array<readonly GhidraLanguageDefinition[] | undefined>(
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)
+83 -31
View File
@@ -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 = `<language_definitions><language id="${languageId}"/></language_definitions>`;
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();
}