mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
fix(native)!: report NativeAOT failures as reason codes (#8053)
* fix(native)!: report NativeAOT failures as reason codes PeImage admission failures and parser recoveries used to publish Error.message as NativeAotReport.reason. The report is now a union on status, and reason is a typed code with the fields that code needs. Complete reports keep reason null and a located header. Partial and not_applicable reports carry a code. Caller budget mistakes throw AnalysisInputError or AnalysisResourceConstraintError with a diagnostics code instead of a bare Error. * fix(native): keep out-of-domain hydration pointers partial An inline pointer outside the unsigned 64-bit domain made writeBigUInt64LE throw RangeError, and the hydration catch rethrew it instead of recording a partial report. Those targets are now an admission detail. The load-image summary schema still accepts the optional Ghidra extension's string reason. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
1 parent
5f9187cd27
commit
b894be6361
9 files changed
+678
-256
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { NativeAotParserLimits } from "./nativeAotPe.js";
|
||||
import { AnalysisResourceConstraintError } from "../analysisErrorCore.js";
|
||||
import {
|
||||
NATIVE_AOT_MAX_REPORT_BYTES,
|
||||
parseNativeAotPe,
|
||||
@@ -29,8 +30,15 @@ describe("NativeAOT parser resource budgets", () => {
|
||||
).summary;
|
||||
expect(report).toMatchObject({
|
||||
status: "partial",
|
||||
reason: {
|
||||
code: "source_byte_budget",
|
||||
limit_bytes: bytes.length - 1,
|
||||
observed_bytes: bytes.length,
|
||||
runtime_override: false,
|
||||
},
|
||||
analysis_artifact_sha256: sha,
|
||||
header_address: null,
|
||||
diagnostics: ["source_byte_budget"],
|
||||
coverage: {
|
||||
source_bytes_examined: 0,
|
||||
source_byte_budget_bytes: bytes.length - 1,
|
||||
@@ -76,17 +84,32 @@ describe("NativeAOT parser report admission", () => {
|
||||
it("never returns an over-budget report from early exits", () => {
|
||||
const bytes = nativeAotPeFixture();
|
||||
const sha = nativeAotPeDigest(bytes);
|
||||
expect(() =>
|
||||
const expectReportBudget = (run: () => void): void => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
run();
|
||||
} catch (cause: unknown) {
|
||||
caught = cause;
|
||||
}
|
||||
expect(caught).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
resource: "capacity",
|
||||
retryable: false,
|
||||
diagnostics: { code: "report_budget_too_small" },
|
||||
reportedLimits: { maximum_summary_bytes: 0 },
|
||||
});
|
||||
};
|
||||
expectReportBudget(() => {
|
||||
parseNativeAotPe(bytes, sha, 0, undefined, {
|
||||
sourceBytes: bytes.length - 1,
|
||||
workUnits: 1024,
|
||||
workingMemoryBytes: 1024,
|
||||
}),
|
||||
).toThrow(/minimum truthful report/iu);
|
||||
});
|
||||
});
|
||||
const nonPe = Buffer.from("not a PE image");
|
||||
expect(() => parseNativeAotPe(nonPe, nativeAotPeDigest(nonPe), 0)).toThrow(
|
||||
/minimum truthful report/iu,
|
||||
);
|
||||
expectReportBudget(() => {
|
||||
parseNativeAotPe(nonPe, nativeAotPeDigest(nonPe), 0);
|
||||
});
|
||||
});
|
||||
|
||||
it("does not claim a missing RTR header when signature coverage hits the work limit", () => {
|
||||
@@ -113,7 +136,10 @@ describe("NativeAOT parser report admission", () => {
|
||||
truncation_reason: "work-unit-budget",
|
||||
},
|
||||
});
|
||||
expect(report.reason).not.toMatch(/No supported ReadyToRun directory/iu);
|
||||
expect(report.reason).toEqual({
|
||||
code: "rtr_scan_budget",
|
||||
runtime_override: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not claim a missing root when table discovery is incomplete", () => {
|
||||
@@ -130,10 +156,10 @@ describe("NativeAOT parser report admission", () => {
|
||||
},
|
||||
).summary;
|
||||
expect(report.truncated).toBe(true);
|
||||
expect(report.reason).toMatch(/before determining whether.*root exists/iu);
|
||||
expect(report.reason).not.toMatch(
|
||||
/no unique System\.Object.*fully examined/iu,
|
||||
);
|
||||
expect(report.reason).toMatchObject({
|
||||
code: "system_object_root_unproven",
|
||||
runtime_override: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("explains a hydration work budget on the partial report", () => {
|
||||
@@ -155,18 +181,13 @@ describe("NativeAOT parser report admission", () => {
|
||||
workingMemoryBytes: 1024 * 1024,
|
||||
},
|
||||
).summary;
|
||||
const visible = [summary.reason ?? "", ...summary.diagnostics].join("\n");
|
||||
expect(summary.status).toBe("partial");
|
||||
expect(visible).toContain("NativeAOT parser work budget is exhausted");
|
||||
expect(visible).toContain(
|
||||
"This release has no runtime override for that NativeAOT parser budget",
|
||||
);
|
||||
expect(visible).toContain(
|
||||
"Repeating the unchanged request fails the same way",
|
||||
);
|
||||
expect(summary.diagnostics.join("\n")).toContain(
|
||||
"Read-only hydration stopped:",
|
||||
);
|
||||
expect(summary.reason).toEqual({
|
||||
code: "system_object_root_unproven",
|
||||
runtime_override: false,
|
||||
hydration: { detail: "work_budget", runtime_override: false },
|
||||
});
|
||||
expect(summary.diagnostics).toEqual(["work_budget"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -195,9 +216,7 @@ describe("NativeAOT detail and summary byte accounting", () => {
|
||||
low,
|
||||
);
|
||||
expect(belowBoundary?.derived_memory ?? null).toBeNull();
|
||||
expect(belowBoundary?.diagnostics.join(" ")).toContain(
|
||||
"omitted because the final serialized report exceeded its byte budget",
|
||||
);
|
||||
expect(belowBoundary?.diagnostics).toContain("detail_rows_omitted");
|
||||
expect(
|
||||
belowBoundary === undefined
|
||||
? 0
|
||||
@@ -221,8 +240,10 @@ describe("NativeAOT detail and summary byte accounting", () => {
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
// Budgets below the fixed report header cannot carry an honest summary.
|
||||
expect(cause).toBeInstanceOf(AnalysisResourceConstraintError);
|
||||
expect(cause).toMatchObject({
|
||||
message: "NativeAOT metadata summary exceeds its report-byte budget",
|
||||
diagnostics: { code: "summary_exceeds_budget" },
|
||||
retryable: false,
|
||||
});
|
||||
}
|
||||
budget--;
|
||||
|
||||
@@ -27,8 +27,7 @@ it.each([
|
||||
expect(result.summary).toMatchObject({
|
||||
status: "not_applicable",
|
||||
method_tables: 0,
|
||||
reason:
|
||||
"No supported ReadyToRun directory signature was found in initialized non-executable PE sections.",
|
||||
reason: { code: "no_rtr_directory" },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -50,7 +49,7 @@ it.each([
|
||||
expect(result.summary).toMatchObject({
|
||||
status: "not_applicable",
|
||||
method_tables: 0,
|
||||
reason: "PE optional header is too short for image mapping fields",
|
||||
reason: { code: "optional_header_too_short" },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -117,12 +117,12 @@ describe("NativeAOT DEHYDRATED_DATA hydration output", () => {
|
||||
[
|
||||
"COPY past the mapped section",
|
||||
[{ copy: fill(NATIVE_AOT_HYDRATION_CAPACITY + 1) }],
|
||||
"Hydrated metadata exceeds its mapped PE section",
|
||||
"exceeds_mapped_section",
|
||||
],
|
||||
[
|
||||
"pointer fixup past the mapped section after growth",
|
||||
[{ copy: fill(NATIVE_AOT_HYDRATION_CAPACITY - 4) }, { fixupPtr: TARGET }],
|
||||
"Hydrated metadata exceeds its mapped PE section",
|
||||
"exceeds_mapped_section",
|
||||
],
|
||||
[
|
||||
"COPY payload past DEHYDRATED_DATA after growth",
|
||||
@@ -130,7 +130,7 @@ describe("NativeAOT DEHYDRATED_DATA hydration output", () => {
|
||||
{ copy: fill(INITIAL_OUTPUT + 1) },
|
||||
{ raw: Buffer.from([4 << 3, 1, 2]) },
|
||||
],
|
||||
"DEHYDRATED_DATA COPY leaves its section",
|
||||
"copy_leaves_section",
|
||||
],
|
||||
[
|
||||
"fixup index outside captured sections after growth",
|
||||
@@ -138,12 +138,61 @@ describe("NativeAOT DEHYDRATED_DATA hydration output", () => {
|
||||
{ copy: fill(INITIAL_OUTPUT + 1) },
|
||||
{ raw: Buffer.from([(31 << 3) | 3, 0xff, 0xff, 0xff]) },
|
||||
],
|
||||
"DEHYDRATED_DATA fixup leaves captured PE sections",
|
||||
"fixup_leaves_sections",
|
||||
],
|
||||
])("reports %s as partial without an overlay", (_case, commands, reason) => {
|
||||
])("reports %s as partial without an overlay", (_case, commands, detail) => {
|
||||
const { summary } = hydrate(commands);
|
||||
expect(summary.status).toBe("partial");
|
||||
expect(summary.derived_overlay).toBeNull();
|
||||
expect(summary.diagnostics.join("\n")).toContain(reason);
|
||||
expect(summary.reason).toMatchObject({
|
||||
code: "hydration_failed",
|
||||
detail,
|
||||
});
|
||||
expect(summary.diagnostics).toEqual([detail]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("NativeAOT hydration pointer domain", () => {
|
||||
it.each([
|
||||
{
|
||||
label: "negative",
|
||||
imageBase: 0x10000n,
|
||||
delta: -0x80000000,
|
||||
},
|
||||
{
|
||||
label: "above uint64",
|
||||
imageBase: (1n << 64n) - 0x62000n,
|
||||
delta: 0x7fffffff,
|
||||
},
|
||||
])(
|
||||
"keeps a partial report when an inline pointer is $label",
|
||||
({ imageBase, delta }) => {
|
||||
const { bytes } = nativeAotPeHydrationFixture([
|
||||
{ inlinePtr: [NATIVE_AOT_HYDRATION_BASE] },
|
||||
]);
|
||||
const fixtureBase = 0x140000000n;
|
||||
bytes.writeBigUInt64LE(imageBase, 0x98 + 24);
|
||||
// Directory rows store absolute VAs. Move them with the image base so
|
||||
// the directory stays admitted and hydration still runs.
|
||||
for (const offset of [0x618, 0x620, 0x630, 0x638]) {
|
||||
const value = bytes.readBigUInt64LE(offset);
|
||||
if (value >= fixtureBase)
|
||||
bytes.writeBigUInt64LE(value - fixtureBase + imageBase, offset);
|
||||
}
|
||||
// The first inline pointer is at RVA 0x3005. Image base 0x10000 makes
|
||||
// that VA 0x13005, and delta -0x80000000 leaves the unsigned domain.
|
||||
bytes.writeInt32LE(delta, 0x1605);
|
||||
const summary = parseNativeAotPe(
|
||||
bytes,
|
||||
nativeAotPeDigest(bytes),
|
||||
NATIVE_AOT_MAX_REPORT_BYTES,
|
||||
).summary;
|
||||
expect(summary.status).toBe("partial");
|
||||
expect(summary.derived_overlay).toBeNull();
|
||||
expect(summary.reason).toMatchObject({
|
||||
code: "no_system_object_root",
|
||||
hydration: { detail: "pointer_outside_address_domain" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -63,7 +63,7 @@ it.each([
|
||||
);
|
||||
expect(result.summary).toMatchObject({
|
||||
status: "not_applicable",
|
||||
reason: "PE virtual section overlaps headers or another section",
|
||||
reason: { code: "virtual_section_overlap" },
|
||||
coverage: { basis: "unsupported-layout" },
|
||||
});
|
||||
},
|
||||
@@ -138,7 +138,7 @@ it("rejects a PE header that reuses DOS header fields", () => {
|
||||
);
|
||||
expect(result.summary).toMatchObject({
|
||||
status: "not_applicable",
|
||||
reason: "PE header overlaps the DOS header",
|
||||
reason: { code: "pe_header_overlaps_dos" },
|
||||
coverage: { basis: "unsupported-layout" },
|
||||
});
|
||||
});
|
||||
@@ -163,7 +163,7 @@ it.each([
|
||||
} else {
|
||||
expect(result.summary).toMatchObject({
|
||||
status: "not_applicable",
|
||||
reason: "PE image exceeds the 64-bit address domain",
|
||||
reason: { code: "address_domain" },
|
||||
coverage: { basis: "unsupported-layout" },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ describe("NativeAOT indexed MethodTable closure", () => {
|
||||
SUMMARY_BUDGET,
|
||||
);
|
||||
expect(parsed.summary.method_tables).toBe(0);
|
||||
expect(parsed.summary.reason).toContain("unique System.Object");
|
||||
expect(parsed.summary.reason).toEqual({ code: "no_system_object_root" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -162,8 +162,7 @@ describe("read-only NativeAOT PE parser", () => {
|
||||
);
|
||||
expect(parsed.summary).toMatchObject({
|
||||
status: "not_applicable",
|
||||
reason:
|
||||
"No supported ReadyToRun directory signature was found in initialized non-executable PE sections.",
|
||||
reason: { code: "no_rtr_directory" },
|
||||
method_tables: 0,
|
||||
});
|
||||
});
|
||||
@@ -215,7 +214,7 @@ describe("read-only NativeAOT PE parser", () => {
|
||||
SUMMARY_BUDGET,
|
||||
"0x180000000",
|
||||
).summary.reason,
|
||||
).toMatch(/preferred image base/iu);
|
||||
).toEqual({ code: "rebased_image" });
|
||||
});
|
||||
|
||||
it("reports an unsupported hydration opcode as partial without mutating the snapshot", () => {
|
||||
@@ -231,18 +230,21 @@ describe("read-only NativeAOT PE parser", () => {
|
||||
expect(parsed.summary).toMatchObject({
|
||||
status: "partial",
|
||||
derived_overlay: null,
|
||||
diagnostics: [
|
||||
expect.stringContaining("Unsupported DEHYDRATED_DATA command"),
|
||||
],
|
||||
reason: {
|
||||
code: "hydration_failed",
|
||||
detail: "unsupported_command",
|
||||
command: 6,
|
||||
},
|
||||
diagnostics: ["unsupported_command"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("NativeAOT PE signature admission", () => {
|
||||
it.each([
|
||||
["MZ", "Not a PE image"],
|
||||
["PE", "MZ header does not declare a PE image"],
|
||||
])(
|
||||
["MZ", { code: "not_pe_image" }],
|
||||
["PE", { code: "mz_header_not_pe" }],
|
||||
] as const)(
|
||||
"rejects a high-bit lookalike of the %s signature",
|
||||
(signature, reason) => {
|
||||
const bytes = nativeAotPeFixture();
|
||||
|
||||
+373
-206
@@ -3,7 +3,20 @@ import { createHash } from "node:crypto";
|
||||
import { readPeOptionalHeaderFixedFields } from "../peOptionalHeader.js";
|
||||
import { readPeCoffHeader } from "../peCoffHeader.js";
|
||||
import { readPeSectionHeader } from "../peSectionHeader.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../analysisErrorCore.js";
|
||||
import type { NativeMetadataRecovery } from "./nativeMetadataRecovery.js";
|
||||
import {
|
||||
NativeAotAdmissionError,
|
||||
nativeAotHydrationFacts,
|
||||
nativeAotHydrationReason,
|
||||
WINDOWS_IMAGE_LOADER_SECTION_LIMIT,
|
||||
type NativeAotHydrationFacts,
|
||||
type NativeAotReason,
|
||||
type NativeAotTruncationReason,
|
||||
} from "./nativeAotReason.js";
|
||||
|
||||
const RTR_SIGNATURE = 0x00525452;
|
||||
const RTR_ROW_SIZE = 24;
|
||||
@@ -92,12 +105,10 @@ export class NativeAotSnapshotIdentityError extends Error {
|
||||
|
||||
/** Hydration stops by throwing; other scans record truncation and continue. */
|
||||
class NativeAotParserBudgetError extends Error {
|
||||
readonly code = "parser_budget" as const;
|
||||
|
||||
constructor(readonly budget: "work" | "working-memory") {
|
||||
super(
|
||||
budget === "work"
|
||||
? "NativeAOT parser work budget is exhausted"
|
||||
: "NativeAOT working-memory budget is exhausted",
|
||||
);
|
||||
super(budget);
|
||||
this.name = "NativeAotParserBudgetError";
|
||||
}
|
||||
}
|
||||
@@ -108,15 +119,36 @@ const parserBudgetExhausted = (
|
||||
throw new NativeAotParserBudgetError(budget);
|
||||
};
|
||||
|
||||
const NATIVE_AOT_PARSER_BUDGET_RECOVERY =
|
||||
"This release has no runtime override for that NativeAOT parser budget. Repeating the unchanged request fails the same way.";
|
||||
const nativeAotHydrationFailure = (cause: unknown): NativeAotHydrationFacts => {
|
||||
if (cause instanceof NativeAotParserBudgetError)
|
||||
return nativeAotHydrationFacts(
|
||||
cause.budget === "work" ? "work_budget" : "working_memory_budget",
|
||||
);
|
||||
if (
|
||||
cause instanceof NativeAotAdmissionError &&
|
||||
cause.reason.code === "hydration_failed"
|
||||
)
|
||||
return nativeAotHydrationFacts(cause.reason.detail, cause.reason.command);
|
||||
throw cause;
|
||||
};
|
||||
|
||||
const nativeAotHydrationFailure = (cause: unknown): string =>
|
||||
cause instanceof NativeAotParserBudgetError
|
||||
? `${cause.message}. ${NATIVE_AOT_PARSER_BUDGET_RECOVERY}`
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: "DEHYDRATED_DATA could not be hydrated";
|
||||
const reportBudgetRefusal = (
|
||||
code:
|
||||
| "report_budget_too_small"
|
||||
| "summary_exceeds_budget"
|
||||
| "summary_exceeded_after_serialization",
|
||||
maximumSummaryBytes: number,
|
||||
): AnalysisResourceConstraintError =>
|
||||
new AnalysisResourceConstraintError(
|
||||
"parse_native_aot_pe",
|
||||
"capacity",
|
||||
code,
|
||||
{ maximum_summary_bytes: maximumSummaryBytes },
|
||||
{
|
||||
diagnostics: { code },
|
||||
retryable: false,
|
||||
},
|
||||
);
|
||||
|
||||
type Section = {
|
||||
readonly rva: number;
|
||||
@@ -332,63 +364,111 @@ export type NativeAotString = {
|
||||
readonly address: string;
|
||||
readonly value: string;
|
||||
};
|
||||
export type NativeAotReport = {
|
||||
type NativeAotCoverage = {
|
||||
readonly pointer_candidates_examined: number;
|
||||
readonly pointer_slots_examined?: number;
|
||||
readonly scan_bytes_examined?: number;
|
||||
readonly scan_bytes_omitted?: number;
|
||||
readonly rtr_signature_scan_bytes_examined?: number;
|
||||
readonly rtr_signature_scan_bytes_omitted?: number;
|
||||
readonly method_table_validation_items_examined?: number;
|
||||
readonly work_units_examined?: number;
|
||||
readonly method_tables_recovered: number;
|
||||
readonly frozen_string_candidates: number;
|
||||
readonly frozen_scan_bytes_examined?: number;
|
||||
readonly frozen_scan_bytes_omitted?: number;
|
||||
readonly frozen_string_data_bytes_examined?: number;
|
||||
readonly source_bytes_examined?: number;
|
||||
readonly source_bytes_omitted?: number;
|
||||
readonly work_budget_units?: number;
|
||||
readonly source_byte_budget_bytes?: number;
|
||||
readonly working_memory_budget_bytes?: number;
|
||||
readonly working_memory_bytes_peak?: number;
|
||||
readonly truncation_reason?: NativeAotTruncationReason;
|
||||
readonly basis:
|
||||
| "raw-image-pointer-scan"
|
||||
| "raw-image-and-rehydrated-pointer-scan"
|
||||
| "unsupported-layout"
|
||||
| "no-rtr-header";
|
||||
};
|
||||
|
||||
type NativeAotReportBase = {
|
||||
readonly format: "dotnet-nativeaot";
|
||||
readonly status: "complete" | "partial" | "not_applicable";
|
||||
readonly reason: string | null;
|
||||
readonly analysis_artifact_sha256: string;
|
||||
readonly analysis_mode: "read-only-derived-overlay";
|
||||
readonly header_address: string | null;
|
||||
readonly discovery: "signature-heuristic" | null;
|
||||
readonly format_major: number | null;
|
||||
readonly format_minor: number | null;
|
||||
readonly method_tables: number;
|
||||
readonly types: readonly NativeAotType[];
|
||||
readonly frozen_strings: readonly NativeAotString[];
|
||||
readonly truncated?: boolean;
|
||||
readonly types_omitted?: number;
|
||||
readonly frozen_strings_omitted?: number;
|
||||
readonly derived_memory: null;
|
||||
readonly coverage: NativeAotCoverage;
|
||||
readonly diagnostics: readonly string[];
|
||||
readonly limitations: readonly string[];
|
||||
readonly output_budget_bytes?: number;
|
||||
};
|
||||
|
||||
type NativeAotLocatedHeader = {
|
||||
readonly header_address: string;
|
||||
readonly discovery: "signature-heuristic";
|
||||
readonly format_major: number;
|
||||
readonly format_minor: number;
|
||||
readonly derived_overlay: {
|
||||
readonly address: string;
|
||||
readonly size_bytes: number;
|
||||
readonly sha256: string;
|
||||
} | null;
|
||||
readonly derived_memory: null;
|
||||
readonly coverage: {
|
||||
readonly pointer_candidates_examined: number;
|
||||
readonly pointer_slots_examined?: number;
|
||||
readonly scan_bytes_examined?: number;
|
||||
readonly scan_bytes_omitted?: number;
|
||||
readonly rtr_signature_scan_bytes_examined?: number;
|
||||
readonly rtr_signature_scan_bytes_omitted?: number;
|
||||
readonly method_table_validation_items_examined?: number;
|
||||
readonly work_units_examined?: number;
|
||||
readonly method_tables_recovered: number;
|
||||
readonly frozen_string_candidates: number;
|
||||
readonly frozen_scan_bytes_examined?: number;
|
||||
readonly frozen_scan_bytes_omitted?: number;
|
||||
readonly frozen_string_data_bytes_examined?: number;
|
||||
readonly source_bytes_examined?: number;
|
||||
readonly source_bytes_omitted?: number;
|
||||
readonly work_budget_units?: number;
|
||||
readonly source_byte_budget_bytes?: number;
|
||||
readonly working_memory_budget_bytes?: number;
|
||||
readonly working_memory_bytes_peak?: number;
|
||||
readonly truncation_reason?:
|
||||
| "source-byte-budget"
|
||||
| "work-unit-budget"
|
||||
| "working-memory-budget"
|
||||
| "response-budget";
|
||||
readonly basis:
|
||||
| "raw-image-pointer-scan"
|
||||
| "raw-image-and-rehydrated-pointer-scan"
|
||||
| "unsupported-layout"
|
||||
| "no-rtr-header";
|
||||
};
|
||||
readonly diagnostics: readonly string[];
|
||||
readonly limitations: readonly string[];
|
||||
};
|
||||
|
||||
type NativeAotAbsentHeader = {
|
||||
readonly header_address: null;
|
||||
readonly discovery: null;
|
||||
readonly format_major: null;
|
||||
readonly format_minor: null;
|
||||
readonly derived_overlay: null;
|
||||
};
|
||||
|
||||
type NativeAotTruncated = {
|
||||
readonly truncated: true;
|
||||
readonly types_omitted: number;
|
||||
readonly frozen_strings_omitted: number;
|
||||
readonly output_budget_bytes: number;
|
||||
};
|
||||
|
||||
type NativeAotUntruncated = {
|
||||
readonly truncated?: false;
|
||||
readonly types_omitted?: number;
|
||||
readonly frozen_strings_omitted?: number;
|
||||
};
|
||||
|
||||
type NativeAotNotApplicableReport = NativeAotReportBase &
|
||||
NativeAotAbsentHeader &
|
||||
NativeAotUntruncated & {
|
||||
readonly status: "not_applicable";
|
||||
readonly reason: NativeAotReason;
|
||||
};
|
||||
|
||||
/** Complete reports have a header and no reason. Failures carry a reason code. */
|
||||
export type NativeAotReport =
|
||||
| (NativeAotReportBase &
|
||||
NativeAotLocatedHeader &
|
||||
NativeAotUntruncated & {
|
||||
readonly status: "complete";
|
||||
readonly reason: null;
|
||||
readonly types_omitted?: 0;
|
||||
readonly frozen_strings_omitted?: 0;
|
||||
})
|
||||
| (NativeAotReportBase &
|
||||
NativeAotLocatedHeader &
|
||||
(NativeAotTruncated | NativeAotUntruncated) & {
|
||||
readonly status: "partial";
|
||||
readonly reason: NativeAotReason;
|
||||
})
|
||||
| (NativeAotReportBase &
|
||||
NativeAotAbsentHeader &
|
||||
NativeAotTruncated & {
|
||||
readonly status: "partial";
|
||||
readonly reason: NativeAotReason;
|
||||
})
|
||||
| NativeAotNotApplicableReport;
|
||||
export type NativeAotPeResult = {
|
||||
readonly summary: NativeAotReport;
|
||||
readonly readTypeDetail: (
|
||||
@@ -407,7 +487,12 @@ export const nativeAotSnapshotOverCapacity = (
|
||||
{
|
||||
format: "dotnet-nativeaot",
|
||||
status: "partial",
|
||||
reason: `The captured PE exceeds the read-only NativeAOT snapshot byte budget of ${String(limits.sourceBytes)} bytes. This release has no runtime override.`,
|
||||
reason: {
|
||||
code: "source_byte_budget",
|
||||
limit_bytes: limits.sourceBytes,
|
||||
observed_bytes: sourceBytesAtLeast,
|
||||
runtime_override: false,
|
||||
},
|
||||
analysis_artifact_sha256: sha256,
|
||||
analysis_mode: "read-only-derived-overlay",
|
||||
header_address: null,
|
||||
@@ -442,9 +527,7 @@ export const nativeAotSnapshotOverCapacity = (
|
||||
truncation_reason: "source-byte-budget",
|
||||
basis: "unsupported-layout",
|
||||
},
|
||||
diagnostics: [
|
||||
`The private snapshot was observed to contain at least ${sourceBytesAtLeast} bytes, above the ${limits.sourceBytes} byte NativeAOT source limit; no parser snapshot was admitted.`,
|
||||
],
|
||||
diagnostics: ["source_byte_budget"],
|
||||
limitations: [
|
||||
"NativeAOT metadata was not inspected because the captured snapshot exceeded the local source-byte budget.",
|
||||
"The artifact digest identifies the selected target; no metadata facts are inferred from the omitted snapshot.",
|
||||
@@ -463,9 +546,7 @@ const assertNativeAotReportFits = (
|
||||
maximumBytes < 0 ||
|
||||
Buffer.byteLength(JSON.stringify(report)) > maximumBytes
|
||||
)
|
||||
throw new Error(
|
||||
"NativeAOT report-byte budget is too small for the minimum truthful report",
|
||||
);
|
||||
throw reportBudgetRefusal("report_budget_too_small", maximumBytes);
|
||||
return report;
|
||||
};
|
||||
|
||||
@@ -490,42 +571,52 @@ class PeImage {
|
||||
constructor(bytes: Buffer) {
|
||||
this.#bytes = bytes;
|
||||
if (bytes.length < 0x40 || bytes.toString("latin1", 0, 2) !== "MZ")
|
||||
throw new Error("Not a PE image");
|
||||
throw new NativeAotAdmissionError({ code: "not_pe_image" });
|
||||
const observed = observeMzWindowsHeader(bytes);
|
||||
if (observed.state !== "declared" || observed.signature !== "PE")
|
||||
throw new Error("MZ header does not declare a PE image");
|
||||
throw new NativeAotAdmissionError({ code: "mz_header_not_pe" });
|
||||
const peOffset = observed.offset;
|
||||
if (peOffset < 0x40) throw new Error("PE header overlaps the DOS header");
|
||||
if (peOffset < 0x40)
|
||||
throw new NativeAotAdmissionError({ code: "pe_header_overlaps_dos" });
|
||||
this.#range(peOffset, 24);
|
||||
const coff = readPeCoffHeader(bytes.subarray(peOffset + 4, peOffset + 24));
|
||||
if (!coff.ok) throw new Error(coff.error.message);
|
||||
if (!coff.ok)
|
||||
throw new NativeAotAdmissionError({ code: "coff_header_truncated" });
|
||||
this.#machine = coff.value.machine;
|
||||
const { sectionCount: count, optionalHeaderSize: optionalSize } =
|
||||
coff.value;
|
||||
// Microsoft documents a 96-section Windows image-loader limit. This
|
||||
// parser accepts executable PE images, not arbitrary COFF object files.
|
||||
if (count > 96)
|
||||
throw new Error("PE image exceeds the Windows 96-section limit");
|
||||
if (count > WINDOWS_IMAGE_LOADER_SECTION_LIMIT)
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "section_limit",
|
||||
limit: WINDOWS_IMAGE_LOADER_SECTION_LIMIT,
|
||||
observed: count,
|
||||
});
|
||||
const optional = peOffset + 24;
|
||||
this.#range(optional, optionalSize);
|
||||
// Mapping fields through SizeOfHeaders must belong to this header,
|
||||
// independently of whether the following file bytes are available.
|
||||
if (optionalSize < 64)
|
||||
throw new Error(
|
||||
"PE optional header is too short for image mapping fields",
|
||||
);
|
||||
throw new NativeAotAdmissionError({ code: "optional_header_too_short" });
|
||||
const fixed = readPeOptionalHeaderFixedFields(
|
||||
bytes.subarray(optional, optional + optionalSize),
|
||||
);
|
||||
if (!fixed.ok || fixed.value.magic !== 0x20b || this.#machine !== 0x8664)
|
||||
throw new Error("Only x64 PE32+ is supported");
|
||||
if (!fixed.ok)
|
||||
throw new NativeAotAdmissionError(
|
||||
fixed.error.reason === "unsupported-magic"
|
||||
? { code: "unsupported_pe32_plus" }
|
||||
: { code: "optional_header_truncated" },
|
||||
);
|
||||
if (fixed.value.magic !== 0x20b || this.#machine !== 0x8664)
|
||||
throw new NativeAotAdmissionError({ code: "unsupported_pe32_plus" });
|
||||
this.imageBase = fixed.value.imageBase;
|
||||
this.sizeOfImage = fixed.value.sizeOfImage;
|
||||
this.#sizeOfHeaders = fixed.value.sizeOfHeaders;
|
||||
if (count < 1 || this.sizeOfImage === 0)
|
||||
throw new Error("Unsupported PE image extent");
|
||||
throw new NativeAotAdmissionError({ code: "unsupported_image_extent" });
|
||||
if (this.imageBase + BigInt(this.sizeOfImage) > 1n << 64n)
|
||||
throw new Error("PE image exceeds the 64-bit address domain");
|
||||
throw new NativeAotAdmissionError({ code: "address_domain" });
|
||||
const sectionOffset = optional + optionalSize;
|
||||
this.#range(sectionOffset, count * 40);
|
||||
if (
|
||||
@@ -533,13 +624,12 @@ class PeImage {
|
||||
this.#sizeOfHeaders > this.#bytes.length ||
|
||||
this.#sizeOfHeaders > this.sizeOfImage
|
||||
)
|
||||
throw new Error(
|
||||
"PE declared headers do not fit the captured image layout",
|
||||
);
|
||||
throw new NativeAotAdmissionError({ code: "headers_do_not_fit" });
|
||||
this.sections = Array.from({ length: count }, (_, index) => {
|
||||
const p = sectionOffset + index * 40;
|
||||
const parsed = readPeSectionHeader(bytes.subarray(p, p + 40));
|
||||
if (!parsed.ok) throw new Error(parsed.error.message);
|
||||
if (!parsed.ok)
|
||||
throw new NativeAotAdmissionError({ code: "section_header_truncated" });
|
||||
const section = parsed.value;
|
||||
return {
|
||||
virtualSize: section.virtual_size,
|
||||
@@ -552,7 +642,7 @@ class PeImage {
|
||||
for (const section of this.sections) {
|
||||
this.#range(section.rawOffset, section.rawSize);
|
||||
if (section.rva + virtualExtent(section) > this.sizeOfImage)
|
||||
throw new Error("PE section exceeds the declared image extent");
|
||||
throw new NativeAotAdmissionError({ code: "section_exceeds_image" });
|
||||
}
|
||||
// Establish one virtual owner before any scan, read, permission query or
|
||||
// hydration. Empty sections own no bytes; adjacent intervals remain valid.
|
||||
@@ -562,9 +652,7 @@ class PeImage {
|
||||
let mappedEnd = this.#sizeOfHeaders;
|
||||
for (const section of mapped) {
|
||||
if (section.rva < mappedEnd)
|
||||
throw new Error(
|
||||
"PE virtual section overlaps headers or another section",
|
||||
);
|
||||
throw new NativeAotAdmissionError({ code: "virtual_section_overlap" });
|
||||
mappedEnd = section.rva + virtualExtent(section);
|
||||
}
|
||||
}
|
||||
@@ -661,7 +749,7 @@ class PeImage {
|
||||
size < 0 ||
|
||||
offset > this.#bytes.length - size
|
||||
)
|
||||
throw new Error("PE field leaves the captured file");
|
||||
throw new NativeAotAdmissionError({ code: "field_outside_file" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -676,9 +764,9 @@ const readU32 = (bytes: Buffer | null, offset = 0): number | null =>
|
||||
: bytes.readUInt32LE(offset);
|
||||
const notApplicable = (
|
||||
sha: string,
|
||||
reason: string,
|
||||
reason: NativeAotReason,
|
||||
basis: NativeAotReport["coverage"]["basis"],
|
||||
): NativeAotReport => ({
|
||||
): NativeAotNotApplicableReport => ({
|
||||
format: "dotnet-nativeaot",
|
||||
status: "not_applicable",
|
||||
reason,
|
||||
@@ -927,22 +1015,32 @@ const hydrate = (
|
||||
length < 5n ||
|
||||
length > BigInt(image.virtualBytesRemaining(dehydrated.start))
|
||||
)
|
||||
throw new Error("DEHYDRATED_DATA length is outside its mapped section");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "length_outside_section",
|
||||
});
|
||||
const first = image.read(dehydrated.start, Number(length));
|
||||
if (first === null)
|
||||
throw new Error("DEHYDRATED_DATA leaves captured PE sections");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "leaves_captured_sections",
|
||||
});
|
||||
const base = readRelativePointer(image, dehydrated.start);
|
||||
if (base === null)
|
||||
throw new Error("DEHYDRATED_DATA has no hydration base pointer");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "missing_base_pointer",
|
||||
});
|
||||
const outputLimit = Math.min(
|
||||
image.virtualBytesRemaining(base),
|
||||
budget.limits.workUnits - budget.workUnits,
|
||||
budget.limits.workingMemoryBytes - budget.workingMemoryBytes,
|
||||
);
|
||||
if (outputLimit === 0)
|
||||
throw new Error(
|
||||
"DEHYDRATED_DATA hydration base is outside mapped PE sections",
|
||||
);
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "base_outside_mapped_sections",
|
||||
});
|
||||
let output = Buffer.alloc(Math.min(outputLimit, 64 * 1024));
|
||||
if (!budget.reserveWorkingMemory(output.byteLength))
|
||||
parserBudgetExhausted("working-memory");
|
||||
@@ -961,7 +1059,10 @@ const hydrate = (
|
||||
) {
|
||||
if (length > budget.limits.workUnits - budget.workUnits)
|
||||
parserBudgetExhausted("work");
|
||||
throw new Error("Hydrated metadata exceeds its mapped PE section");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "exceeds_mapped_section",
|
||||
});
|
||||
}
|
||||
const start = outputLength;
|
||||
const required = start + length;
|
||||
@@ -995,18 +1096,31 @@ const hydrate = (
|
||||
if (!budget.consumeWork(4)) parserBudgetExhausted("work");
|
||||
const delta = target - (base + BigInt(outputLength));
|
||||
if (delta < -0x80000000n || delta > 0x7fffffffn)
|
||||
throw new Error("Hydrated relative pointer does not fit int32");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "relative_pointer_overflow",
|
||||
});
|
||||
reserveOutput(4).writeInt32LE(Number(delta), 0);
|
||||
};
|
||||
const appendPtr = (target: bigint): void => {
|
||||
if (!budget.consumeWork(8)) parserBudgetExhausted("work");
|
||||
// writeBigUInt64LE throws RangeError outside the unsigned 64-bit domain.
|
||||
// That is a malformed fixup, not an unexpected parser failure.
|
||||
if (target < 0n || target > 0xffffffffffffffffn)
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "pointer_outside_address_domain",
|
||||
});
|
||||
reserveOutput(8).writeBigUInt64LE(target, 0);
|
||||
};
|
||||
const readFixup = (index: number): bigint => {
|
||||
const fixupLocation = dehydrated.end + BigInt(index * 4);
|
||||
const target = readRelativePointer(image, fixupLocation);
|
||||
if (target === null)
|
||||
throw new Error("DEHYDRATED_DATA fixup leaves captured PE sections");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "fixup_leaves_sections",
|
||||
});
|
||||
return target;
|
||||
};
|
||||
try {
|
||||
@@ -1020,7 +1134,10 @@ const hydrate = (
|
||||
const extraBytes = payload - 28;
|
||||
if (extraBytes > 0) {
|
||||
if (extraBytes > 3 || cursor > first.length - extraBytes)
|
||||
throw new Error("Invalid DEHYDRATED_DATA payload encoding");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "invalid_payload_encoding",
|
||||
});
|
||||
payload = 0;
|
||||
for (let i = 0; i < extraBytes; i++)
|
||||
payload += (first[cursor++] ?? 0) * 2 ** (8 * i);
|
||||
@@ -1029,7 +1146,10 @@ const hydrate = (
|
||||
switch (command) {
|
||||
case 0: {
|
||||
if (cursor > first.length - payload)
|
||||
throw new Error("DEHYDRATED_DATA COPY leaves its section");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "copy_leaves_section",
|
||||
});
|
||||
append(first.subarray(cursor, cursor + payload));
|
||||
cursor += payload;
|
||||
break;
|
||||
@@ -1049,14 +1169,20 @@ const hydrate = (
|
||||
payload > Math.floor((first.length - cursor) / 4) ||
|
||||
payload > Math.floor((outputLimit - outputLength) / 4)
|
||||
)
|
||||
throw new Error("Inline relative fixups leave DEHYDRATED_DATA");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "inline_relative_fixups_leave",
|
||||
});
|
||||
for (let i = 0; i < payload; i++) {
|
||||
const target = readRelativePointer(
|
||||
image,
|
||||
dehydrated.start + BigInt(cursor),
|
||||
);
|
||||
if (target === null)
|
||||
throw new Error("Invalid inline relative pointer");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "invalid_inline_relative_pointer",
|
||||
});
|
||||
cursor += 4;
|
||||
appendRel(target);
|
||||
}
|
||||
@@ -1067,19 +1193,30 @@ const hydrate = (
|
||||
payload > Math.floor((first.length - cursor) / 4) ||
|
||||
payload > Math.floor((outputLimit - outputLength) / 8)
|
||||
)
|
||||
throw new Error("Inline pointer fixups leave DEHYDRATED_DATA");
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "inline_pointer_fixups_leave",
|
||||
});
|
||||
for (let i = 0; i < payload; i++) {
|
||||
const target = readRelativePointer(
|
||||
image,
|
||||
dehydrated.start + BigInt(cursor),
|
||||
);
|
||||
if (target === null) throw new Error("Invalid inline pointer");
|
||||
if (target === null)
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "invalid_inline_pointer",
|
||||
});
|
||||
cursor += 4;
|
||||
appendPtr(target);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unsupported DEHYDRATED_DATA command ${command}`);
|
||||
throw new NativeAotAdmissionError({
|
||||
code: "hydration_failed",
|
||||
detail: "unsupported_command",
|
||||
command,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
@@ -1247,14 +1384,30 @@ export const parseNativeAotPe = (
|
||||
limits = DEFAULT_NATIVE_AOT_PARSER_LIMITS,
|
||||
): NativeAotPeResult => {
|
||||
if (!Number.isSafeInteger(maximumSummaryBytes) || maximumSummaryBytes < 0)
|
||||
throw new Error(
|
||||
"NativeAOT summary budget must be a non-negative safe integer",
|
||||
);
|
||||
for (const limit of Object.values(limits))
|
||||
if (!Number.isSafeInteger(limit) || limit < 0)
|
||||
throw new Error(
|
||||
"NativeAOT parser limits must be non-negative safe integers",
|
||||
);
|
||||
throw new AnalysisInputError("parse_native_aot_pe", undefined, [
|
||||
{
|
||||
path: ["maximumSummaryBytes"],
|
||||
reason: "out_of_range",
|
||||
minimum: 0,
|
||||
...(Number.isFinite(maximumSummaryBytes)
|
||||
? { observed: maximumSummaryBytes }
|
||||
: {}),
|
||||
},
|
||||
]);
|
||||
const invalidLimit = (
|
||||
Object.entries(limits) as readonly (readonly [string, number])[]
|
||||
).find(([, limit]) => !Number.isSafeInteger(limit) || limit < 0);
|
||||
if (invalidLimit !== undefined)
|
||||
throw new AnalysisInputError("parse_native_aot_pe", undefined, [
|
||||
{
|
||||
path: ["limits", invalidLimit[0]],
|
||||
reason: "out_of_range",
|
||||
minimum: 0,
|
||||
...(Number.isFinite(invalidLimit[1])
|
||||
? { observed: invalidLimit[1] }
|
||||
: {}),
|
||||
},
|
||||
]);
|
||||
if (bytes.byteLength > limits.sourceBytes)
|
||||
return parsedSummary(
|
||||
nativeAotSnapshotOverCapacity(
|
||||
@@ -1272,12 +1425,9 @@ export const parseNativeAotPe = (
|
||||
try {
|
||||
image = new PeImage(bytes);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof NativeAotAdmissionError)) throw cause;
|
||||
return parsedSummary(
|
||||
notApplicable(
|
||||
sha256,
|
||||
cause instanceof Error ? cause.message : "Unsupported PE image",
|
||||
"unsupported-layout",
|
||||
),
|
||||
notApplicable(sha256, cause.reason, "unsupported-layout"),
|
||||
maximumSummaryBytes,
|
||||
);
|
||||
}
|
||||
@@ -1286,11 +1436,7 @@ export const parseNativeAotPe = (
|
||||
BigInt(loadedImageBase) !== image.imageBase
|
||||
)
|
||||
return parsedSummary(
|
||||
notApplicable(
|
||||
sha256,
|
||||
"Ghidra loaded the PE at a base different from its preferred image base; relocation-aware metadata mapping is not implemented.",
|
||||
"unsupported-layout",
|
||||
),
|
||||
notApplicable(sha256, { code: "rebased_image" }, "unsupported-layout"),
|
||||
maximumSummaryBytes,
|
||||
);
|
||||
const budget = new NativeAotParserBudget(limits);
|
||||
@@ -1301,11 +1447,13 @@ export const parseNativeAotPe = (
|
||||
{
|
||||
...notApplicable(
|
||||
sha256,
|
||||
"RTR signature scanning reached the NativeAOT parser work budget; a unique ReadyToRun directory was not established.",
|
||||
{ code: "rtr_scan_budget", runtime_override: false },
|
||||
"no-rtr-header",
|
||||
),
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
types_omitted: 0,
|
||||
frozen_strings_omitted: 0,
|
||||
output_budget_bytes: maximumSummaryBytes,
|
||||
coverage: {
|
||||
pointer_candidates_examined: 0,
|
||||
@@ -1326,26 +1474,20 @@ export const parseNativeAotPe = (
|
||||
: { truncation_reason: budget.truncationReason }),
|
||||
basis: "no-rtr-header",
|
||||
},
|
||||
diagnostics: [
|
||||
"No metadata hydration was attempted because signature coverage was incomplete.",
|
||||
],
|
||||
diagnostics: ["rtr_scan_incomplete"],
|
||||
},
|
||||
maximumSummaryBytes,
|
||||
);
|
||||
if (directorySearch.directory === null && directorySearch.matches === 0)
|
||||
return parsedSummary(
|
||||
notApplicable(
|
||||
sha256,
|
||||
"No supported ReadyToRun directory signature was found in initialized non-executable PE sections.",
|
||||
"no-rtr-header",
|
||||
),
|
||||
notApplicable(sha256, { code: "no_rtr_directory" }, "no-rtr-header"),
|
||||
maximumSummaryBytes,
|
||||
);
|
||||
if (directorySearch.matches !== 1 || directorySearch.directory === null)
|
||||
return parsedSummary(
|
||||
notApplicable(
|
||||
sha256,
|
||||
"Multiple plausible ReadyToRun directories were found; metadata identity is ambiguous.",
|
||||
{ code: "ambiguous_rtr_directory" },
|
||||
"unsupported-layout",
|
||||
),
|
||||
maximumSummaryBytes,
|
||||
@@ -1356,7 +1498,11 @@ export const parseNativeAotPe = (
|
||||
{
|
||||
...notApplicable(
|
||||
sha256,
|
||||
`RTR ${directory.major}.${directory.minor} is detected but this parser supports only the .NET 8 RTR 9.1 method-table layout.`,
|
||||
{
|
||||
code: "unsupported_rtr_version",
|
||||
format_major: directory.major,
|
||||
format_minor: directory.minor,
|
||||
},
|
||||
"unsupported-layout",
|
||||
),
|
||||
status: "partial",
|
||||
@@ -1375,7 +1521,7 @@ export const parseNativeAotPe = (
|
||||
{
|
||||
...notApplicable(
|
||||
sha256,
|
||||
"RTR 9.1 directory does not contain exactly one DEHYDRATED_DATA section; metadata recovery is incomplete.",
|
||||
{ code: "dehydrated_section_count" },
|
||||
"unsupported-layout",
|
||||
),
|
||||
status: "partial",
|
||||
@@ -1387,13 +1533,11 @@ export const parseNativeAotPe = (
|
||||
maximumSummaryBytes,
|
||||
);
|
||||
let overlay: ReturnType<typeof hydrate> = null;
|
||||
let hydrationError: string | null = null;
|
||||
let hydrationBudgetLimited = false;
|
||||
let hydration: NativeAotHydrationFacts | null = null;
|
||||
try {
|
||||
overlay = hydrate(image, dehydrated[0] as RtrSection, budget);
|
||||
} catch (cause: unknown) {
|
||||
hydrationBudgetLimited = cause instanceof NativeAotParserBudgetError;
|
||||
hydrationError = nativeAotHydrationFailure(cause);
|
||||
hydration = nativeAotHydrationFailure(cause);
|
||||
}
|
||||
const discovered = discoverTables(image, overlay, budget);
|
||||
const frozen = directory.sections.find(
|
||||
@@ -1432,18 +1576,19 @@ export const parseNativeAotPe = (
|
||||
frozen === undefined || frozen.end < frozenFirstCandidate + 14n
|
||||
? 0
|
||||
: Number((frozen.end - 14n - frozenFirstCandidate) / 8n + 1n);
|
||||
const discoveryReason =
|
||||
const hydrationAttachment = hydration === null ? {} : { hydration };
|
||||
const discoveryReason: NativeAotReason | null =
|
||||
discovered.truncated && discovered.tables.includedCount === 0
|
||||
? "RTR 9.1 was found, but method-table discovery reached its resource budget before determining whether a unique System.Object root exists."
|
||||
? {
|
||||
code: "system_object_root_unproven",
|
||||
runtime_override: false,
|
||||
...hydrationAttachment,
|
||||
}
|
||||
: discovered.tables.includedCount === 0
|
||||
? "RTR 9.1 was found, but no unique System.Object method-table root could be recovered from the fully examined image pointers."
|
||||
: hydrationError;
|
||||
const recoveryReason =
|
||||
hydrationBudgetLimited &&
|
||||
hydrationError !== null &&
|
||||
discoveryReason !== hydrationError
|
||||
? `${discoveryReason} ${hydrationError}`
|
||||
: discoveryReason;
|
||||
? { code: "no_system_object_root", ...hydrationAttachment }
|
||||
: hydration === null
|
||||
? null
|
||||
: nativeAotHydrationReason(hydration);
|
||||
const reportLimitations = [
|
||||
"Only x64 PE32+ with RTR 9.1 is supported.",
|
||||
"No Ghidra database types, labels, functions, or bytes are created or changed.",
|
||||
@@ -1455,12 +1600,12 @@ export const parseNativeAotPe = (
|
||||
: []),
|
||||
];
|
||||
const reportFacts = {
|
||||
format: "dotnet-nativeaot",
|
||||
reason: recoveryReason,
|
||||
format: "dotnet-nativeaot" as const,
|
||||
reason: discoveryReason,
|
||||
analysis_artifact_sha256: sha256,
|
||||
analysis_mode: "read-only-derived-overlay",
|
||||
analysis_mode: "read-only-derived-overlay" as const,
|
||||
header_address: hex(directory.address),
|
||||
discovery: "signature-heuristic",
|
||||
discovery: "signature-heuristic" as const,
|
||||
format_major: directory.major,
|
||||
format_minor: directory.minor,
|
||||
method_tables: discovered.tables.includedCount,
|
||||
@@ -1473,16 +1618,10 @@ export const parseNativeAotPe = (
|
||||
size_bytes: overlay.sizeBytes,
|
||||
sha256: overlay.sha256,
|
||||
},
|
||||
derived_memory: null,
|
||||
diagnostics:
|
||||
hydrationError === null
|
||||
? []
|
||||
: [`Read-only hydration stopped: ${hydrationError}`],
|
||||
derived_memory: null as null,
|
||||
diagnostics: hydration === null ? [] : [hydration.detail],
|
||||
limitations: reportLimitations,
|
||||
} satisfies Omit<
|
||||
NativeAotReport,
|
||||
"status" | "types" | "frozen_strings" | "coverage"
|
||||
>;
|
||||
};
|
||||
const coverageFacts = {
|
||||
pointer_candidates_examined: discovered.pointerCount,
|
||||
pointer_slots_examined: discovered.pointerSlotsExamined,
|
||||
@@ -1501,8 +1640,16 @@ export const parseNativeAotPe = (
|
||||
? "raw-image-pointer-scan"
|
||||
: "raw-image-and-rehydrated-pointer-scan",
|
||||
} satisfies Omit<NativeAotReport["coverage"], "frozen_string_candidates">;
|
||||
const budgetSkeleton: NativeAotReport = {
|
||||
const budgetSkeleton = {
|
||||
...reportFacts,
|
||||
// A later truncated report replaces a null discovery reason. Reserve the
|
||||
// longest truncation code so that replacement still fits the same budget.
|
||||
reason:
|
||||
discoveryReason ??
|
||||
({
|
||||
code: "truncated",
|
||||
truncation_reason: "working-memory-budget",
|
||||
} satisfies NativeAotReason),
|
||||
status: "complete",
|
||||
types: [],
|
||||
frozen_strings: [],
|
||||
@@ -1515,7 +1662,7 @@ export const parseNativeAotPe = (
|
||||
// fields so the summary budget remains valid after frozen-region work.
|
||||
work_units_examined: budget.limits.workUnits,
|
||||
working_memory_bytes_peak: budget.limits.workingMemoryBytes,
|
||||
truncation_reason: "response-budget",
|
||||
truncation_reason: "working-memory-budget",
|
||||
frozen_string_candidates: 0,
|
||||
frozen_scan_bytes_examined: frozenCandidateBound * 8,
|
||||
frozen_string_data_bytes_examined:
|
||||
@@ -1526,9 +1673,7 @@ export const parseNativeAotPe = (
|
||||
let remainingSummaryBytes =
|
||||
maximumSummaryBytes - Buffer.byteLength(JSON.stringify(budgetSkeleton));
|
||||
if (remainingSummaryBytes < 0)
|
||||
throw new Error(
|
||||
"NativeAOT metadata summary exceeds its report-byte budget",
|
||||
);
|
||||
throw reportBudgetRefusal("summary_exceeds_budget", maximumSummaryBytes);
|
||||
let typesOmitted = 0;
|
||||
discovered.tables.forEachIncluded((table) => {
|
||||
const row: NativeAotType = { address: hex(table.address), type: null };
|
||||
@@ -1611,38 +1756,66 @@ export const parseNativeAotPe = (
|
||||
(typesOmitted > 0 || frozenStringsOmitted > 0
|
||||
? "response-budget"
|
||||
: undefined);
|
||||
const summary: NativeAotReport = {
|
||||
...reportFacts,
|
||||
status:
|
||||
truncated ||
|
||||
hydrationError !== null ||
|
||||
discovered.tables.includedCount === 0
|
||||
? "partial"
|
||||
: "complete",
|
||||
types,
|
||||
frozen_strings: frozenStrings,
|
||||
truncated,
|
||||
types_omitted: typesOmitted,
|
||||
frozen_strings_omitted: frozenStringsOmitted,
|
||||
coverage: {
|
||||
...coverageFacts,
|
||||
work_units_examined: budget.workUnits,
|
||||
working_memory_bytes_peak: budget.workingMemoryBytesPeak,
|
||||
...(truncationReason === undefined
|
||||
? {}
|
||||
: { truncation_reason: truncationReason }),
|
||||
frozen_string_candidates: frozenCandidates,
|
||||
frozen_scan_bytes_examined: frozenScanBytesExamined,
|
||||
frozen_string_data_bytes_examined: frozenStringDataBytesExamined,
|
||||
frozen_scan_bytes_omitted: Math.max(
|
||||
0,
|
||||
frozenCandidateBound * 8 - frozenScanBytesExamined,
|
||||
),
|
||||
},
|
||||
const partial =
|
||||
truncated || hydration !== null || discovered.tables.includedCount === 0;
|
||||
const publishedReason: NativeAotReason = discoveryReason ?? {
|
||||
code: "truncated",
|
||||
truncation_reason: truncationReason ?? "response-budget",
|
||||
};
|
||||
const examinedCoverage = {
|
||||
...coverageFacts,
|
||||
work_units_examined: budget.workUnits,
|
||||
working_memory_bytes_peak: budget.workingMemoryBytesPeak,
|
||||
frozen_string_candidates: frozenCandidates,
|
||||
frozen_scan_bytes_examined: frozenScanBytesExamined,
|
||||
frozen_string_data_bytes_examined: frozenStringDataBytesExamined,
|
||||
frozen_scan_bytes_omitted: Math.max(
|
||||
0,
|
||||
frozenCandidateBound * 8 - frozenScanBytesExamined,
|
||||
),
|
||||
...(truncationReason === undefined
|
||||
? {}
|
||||
: { truncation_reason: truncationReason }),
|
||||
};
|
||||
const summary: NativeAotReport = partial
|
||||
? truncated
|
||||
? {
|
||||
...reportFacts,
|
||||
status: "partial",
|
||||
reason: publishedReason,
|
||||
types,
|
||||
frozen_strings: frozenStrings,
|
||||
truncated: true,
|
||||
types_omitted: typesOmitted,
|
||||
frozen_strings_omitted: frozenStringsOmitted,
|
||||
coverage: examinedCoverage,
|
||||
}
|
||||
: {
|
||||
...reportFacts,
|
||||
status: "partial",
|
||||
reason: publishedReason,
|
||||
types,
|
||||
frozen_strings: frozenStrings,
|
||||
truncated: false,
|
||||
types_omitted: 0,
|
||||
frozen_strings_omitted: 0,
|
||||
coverage: examinedCoverage,
|
||||
}
|
||||
: {
|
||||
...reportFacts,
|
||||
status: "complete",
|
||||
reason: null,
|
||||
types,
|
||||
frozen_strings: frozenStrings,
|
||||
truncated: false,
|
||||
types_omitted: 0,
|
||||
frozen_strings_omitted: 0,
|
||||
coverage: examinedCoverage,
|
||||
};
|
||||
if (Buffer.byteLength(JSON.stringify(summary)) > maximumSummaryBytes)
|
||||
throw new Error(
|
||||
"NativeAOT metadata summary exceeded its report-byte budget after serialization",
|
||||
throw reportBudgetRefusal(
|
||||
"summary_exceeded_after_serialization",
|
||||
maximumSummaryBytes,
|
||||
);
|
||||
const readTypeDetail = (
|
||||
address: string,
|
||||
@@ -1694,9 +1867,7 @@ export const parseNativeAotPe = (
|
||||
};
|
||||
let remaining = maximumBytes - Buffer.byteLength(JSON.stringify(metadata));
|
||||
if (remaining < 0) {
|
||||
metadata.diagnostics.push(
|
||||
"The NativeAOT detail report budget is too small for the requested MethodTable summary.",
|
||||
);
|
||||
metadata.diagnostics.push("detail_budget_too_small");
|
||||
metadata.truncated = true;
|
||||
metadata.status = "partial";
|
||||
return Buffer.byteLength(JSON.stringify(metadata)) <= maximumBytes
|
||||
@@ -1808,14 +1979,12 @@ export const parseNativeAotPe = (
|
||||
}
|
||||
}
|
||||
if (detailBudget.truncationReason !== undefined)
|
||||
metadata.diagnostics.push(
|
||||
"MethodTable memory hashing stopped at the parser work budget.",
|
||||
);
|
||||
metadata.diagnostics.push("method_table_hash_work_budget");
|
||||
metadata.interfaces_omitted = interfacesOmitted;
|
||||
metadata.virtual_slots_omitted = slotsOmitted;
|
||||
metadata.truncated =
|
||||
discovered.truncated ||
|
||||
hydrationError !== null ||
|
||||
hydration !== null ||
|
||||
detailBudget.truncationReason !== undefined ||
|
||||
interfacesOmitted > 0 ||
|
||||
slotsOmitted > 0 ||
|
||||
@@ -1827,9 +1996,7 @@ export const parseNativeAotPe = (
|
||||
metadata.interfaces.length = 0;
|
||||
metadata.virtual_slots_omitted += metadata.virtual_slots.length;
|
||||
metadata.virtual_slots.length = 0;
|
||||
metadata.diagnostics.push(
|
||||
"MethodTable detail rows were omitted because the final serialized report exceeded its byte budget.",
|
||||
);
|
||||
metadata.diagnostics.push("detail_rows_omitted");
|
||||
metadata.truncated = true;
|
||||
metadata.status = "partial";
|
||||
if (Buffer.byteLength(JSON.stringify(metadata)) > maximumBytes)
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Windows image-loader maximum for a PE executable. This is a format
|
||||
* constraint, not a REA resource budget, so it is not an environment setting.
|
||||
*/
|
||||
export const WINDOWS_IMAGE_LOADER_SECTION_LIMIT = 96;
|
||||
|
||||
const NATIVE_AOT_HYDRATION_DETAILS = [
|
||||
"length_outside_section",
|
||||
"leaves_captured_sections",
|
||||
"missing_base_pointer",
|
||||
"base_outside_mapped_sections",
|
||||
"exceeds_mapped_section",
|
||||
"relative_pointer_overflow",
|
||||
"fixup_leaves_sections",
|
||||
"invalid_payload_encoding",
|
||||
"copy_leaves_section",
|
||||
"inline_relative_fixups_leave",
|
||||
"invalid_inline_relative_pointer",
|
||||
"inline_pointer_fixups_leave",
|
||||
"invalid_inline_pointer",
|
||||
"pointer_outside_address_domain",
|
||||
"unsupported_command",
|
||||
"work_budget",
|
||||
"working_memory_budget",
|
||||
] as const;
|
||||
|
||||
/** Stable hydration failure, independent of the sentence previously thrown. */
|
||||
export type NativeAotHydrationDetail =
|
||||
(typeof NATIVE_AOT_HYDRATION_DETAILS)[number];
|
||||
|
||||
const NATIVE_AOT_TRUNCATION_REASONS = [
|
||||
"source-byte-budget",
|
||||
"work-unit-budget",
|
||||
"working-memory-budget",
|
||||
"response-budget",
|
||||
] as const;
|
||||
|
||||
export type NativeAotTruncationReason =
|
||||
(typeof NATIVE_AOT_TRUNCATION_REASONS)[number];
|
||||
|
||||
const NATIVE_AOT_SIMPLE_REASON_CODES = [
|
||||
"not_pe_image",
|
||||
"mz_header_not_pe",
|
||||
"pe_header_overlaps_dos",
|
||||
"coff_header_truncated",
|
||||
"section_header_truncated",
|
||||
"optional_header_too_short",
|
||||
"optional_header_truncated",
|
||||
"unsupported_pe32_plus",
|
||||
"unsupported_image_extent",
|
||||
"address_domain",
|
||||
"headers_do_not_fit",
|
||||
"section_exceeds_image",
|
||||
"virtual_section_overlap",
|
||||
"field_outside_file",
|
||||
"rebased_image",
|
||||
"no_rtr_directory",
|
||||
"ambiguous_rtr_directory",
|
||||
"dehydrated_section_count",
|
||||
] as const;
|
||||
|
||||
const nativeAotHydrationFactsSchema = z.strictObject({
|
||||
detail: z.enum(NATIVE_AOT_HYDRATION_DETAILS),
|
||||
command: z.int().nonnegative().optional(),
|
||||
runtime_override: z.literal(false).optional(),
|
||||
});
|
||||
|
||||
/** Hydration facts that can ride along with a discovery reason. */
|
||||
export type NativeAotHydrationFacts = z.infer<
|
||||
typeof nativeAotHydrationFactsSchema
|
||||
>;
|
||||
|
||||
const nonnegative = z.int().nonnegative();
|
||||
|
||||
/** Public NativeAOT admission and recovery reason. Display text is not the code. */
|
||||
export const nativeAotReasonSchema = z.discriminatedUnion("code", [
|
||||
z.strictObject({ code: z.enum(NATIVE_AOT_SIMPLE_REASON_CODES) }),
|
||||
z.strictObject({
|
||||
code: z.literal("section_limit"),
|
||||
limit: z.literal(WINDOWS_IMAGE_LOADER_SECTION_LIMIT),
|
||||
observed: z.int().positive(),
|
||||
}),
|
||||
z.strictObject({
|
||||
code: z.literal("source_byte_budget"),
|
||||
limit_bytes: nonnegative,
|
||||
observed_bytes: nonnegative,
|
||||
runtime_override: z.literal(false),
|
||||
}),
|
||||
z.strictObject({
|
||||
code: z.literal("rtr_scan_budget"),
|
||||
runtime_override: z.literal(false),
|
||||
}),
|
||||
z.strictObject({
|
||||
code: z.literal("unsupported_rtr_version"),
|
||||
format_major: nonnegative,
|
||||
format_minor: nonnegative,
|
||||
}),
|
||||
z.strictObject({
|
||||
code: z.literal("hydration_failed"),
|
||||
detail: z.enum(NATIVE_AOT_HYDRATION_DETAILS),
|
||||
command: z.int().nonnegative().optional(),
|
||||
runtime_override: z.literal(false).optional(),
|
||||
}),
|
||||
z.strictObject({
|
||||
code: z.literal("no_system_object_root"),
|
||||
hydration: nativeAotHydrationFactsSchema.optional(),
|
||||
}),
|
||||
z.strictObject({
|
||||
code: z.literal("system_object_root_unproven"),
|
||||
runtime_override: z.literal(false),
|
||||
hydration: nativeAotHydrationFactsSchema.optional(),
|
||||
}),
|
||||
z.strictObject({
|
||||
code: z.literal("truncated"),
|
||||
truncation_reason: z.enum(NATIVE_AOT_TRUNCATION_REASONS),
|
||||
}),
|
||||
]);
|
||||
|
||||
export type NativeAotReason = z.infer<typeof nativeAotReasonSchema>;
|
||||
|
||||
/** Admission failure whose public identity is `reason.code`, not `message`. */
|
||||
export class NativeAotAdmissionError extends Error {
|
||||
readonly code: NativeAotReason["code"];
|
||||
|
||||
constructor(readonly reason: NativeAotReason) {
|
||||
super(reason.code);
|
||||
this.name = "NativeAotAdmissionError";
|
||||
this.code = reason.code;
|
||||
}
|
||||
}
|
||||
|
||||
/** Hydration detail carried on a reason without copying an Error message. */
|
||||
export const nativeAotHydrationFacts = (
|
||||
detail: NativeAotHydrationDetail,
|
||||
command?: number,
|
||||
): NativeAotHydrationFacts => {
|
||||
const budget =
|
||||
detail === "work_budget" || detail === "working_memory_budget"
|
||||
? { runtime_override: false as const }
|
||||
: {};
|
||||
return command === undefined
|
||||
? { detail, ...budget }
|
||||
: { detail, command, ...budget };
|
||||
};
|
||||
|
||||
const BUDGET_HYDRATION_DETAILS = new Set<NativeAotHydrationDetail>([
|
||||
"work_budget",
|
||||
"working_memory_budget",
|
||||
]);
|
||||
|
||||
/** Reason for a hydration failure, including the no-override fact for parser budgets. */
|
||||
export const nativeAotHydrationReason = (
|
||||
facts: NativeAotHydrationFacts,
|
||||
): NativeAotReason =>
|
||||
BUDGET_HYDRATION_DETAILS.has(facts.detail)
|
||||
? { code: "hydration_failed", ...facts, runtime_override: false }
|
||||
: { code: "hydration_failed", ...facts };
|
||||
@@ -59,7 +59,7 @@ describe("NativeAOT recovery evidence", () => {
|
||||
const summary = {
|
||||
format: "dotnet-nativeaot",
|
||||
status: "not_applicable",
|
||||
reason: "No supported row layout found",
|
||||
reason: { code: "no_rtr_directory" },
|
||||
analysis_artifact_sha256: "b".repeat(64),
|
||||
header_address: null,
|
||||
discovery: null,
|
||||
@@ -74,4 +74,25 @@ describe("NativeAOT recovery evidence", () => {
|
||||
};
|
||||
expect(nativeMetadataRecoverySummarySchema.parse(summary)).toEqual(summary);
|
||||
});
|
||||
it("accepts the optional Ghidra extension's string reason", () => {
|
||||
// NativeAotExtension.inspectImage copies this not_applicable summary, and
|
||||
// ReaGhidraExtensions adds the artifact digest before load-image parsing.
|
||||
const summary = {
|
||||
format: "dotnet-nativeaot",
|
||||
status: "not_applicable",
|
||||
reason: "No NativeAOT directory with the supported row layout was found.",
|
||||
analysis_artifact_sha256: "c".repeat(64),
|
||||
header_address: null,
|
||||
discovery: null,
|
||||
format_major: null,
|
||||
format_minor: null,
|
||||
method_tables: 0,
|
||||
types: [],
|
||||
derived_memory: null,
|
||||
coverage: null,
|
||||
diagnostics: [],
|
||||
limitations: ["extension-limitation"],
|
||||
};
|
||||
expect(nativeMetadataRecoverySummarySchema.parse(summary)).toEqual(summary);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { nativeAotReasonSchema } from "./nativeAotReason.js";
|
||||
|
||||
const address = z.string().regex(/^0x[0-9a-f]+$/u);
|
||||
const relatedType = z.strictObject({ address, type: z.string().nullable() });
|
||||
@@ -51,7 +52,10 @@ export const nativeMetadataRecoverySummarySchema = z.strictObject({
|
||||
format: z.literal("dotnet-nativeaot"),
|
||||
analysis_mode: z.literal("read-only-derived-overlay").optional(),
|
||||
status: z.enum(["complete", "partial", "not_applicable"]),
|
||||
reason: z.string().nullable(),
|
||||
// The read-only parser publishes a code. The optional Ghidra extension
|
||||
// still sends the historical string on not_applicable, unsupported, and
|
||||
// failed image summaries. Both shapes remain valid at this boundary.
|
||||
reason: z.union([nativeAotReasonSchema, z.string(), z.null()]),
|
||||
analysis_artifact_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
header_address: address.nullable(),
|
||||
discovery: z.enum(["symbol", "signature-heuristic"]).nullable(),
|
||||
|
||||
Reference in new issue
Block a user