From 6ab595cfd6fc67f6bfe7313e39f736ed67f036a3 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:37:23 -0500 Subject: [PATCH] fix(limits)!: make the IL2CPP pointer index adjustable and require owned refusal limits (#14243) * fix(limits): make the IL2CPP pointer index adjustable and name ELF note budgets in details.limit inspect_il2cpp_metadata accepts max_native_index_bytes (default 1 GiB, needs binary_path) for the estimated ELF virtual pointer index. The index refusal now carries its own limit name (virtual-pointer-index-bytes) and a details.limit naming the parameter, its effective value, default and range, instead of a fixed ceiling with no override. The binary file allowance and the loader's fixed capacities are unchanged. inspect_elf_notes and inspect_elf_debug_link refusals for max_file_bytes, the decoded section-name budget and max_entries now set details.limit. One domain-owned bounds object per operation feeds both the schema and the limit. Two guards keep new in-code refusal limits owned: - scripts/verify/fixed-ceilings.mjs (run by npm run lint) requires every fixedAllowanceOptions, fixedProducerInputAllowance, artifactFixedLimitFailure or inline fixedAllowance declaration to be listed in fixed-ceiling-registry.json with its class (format, protocol, representation, derived, forwarding, or pending with an issue) and reason, and fails on stale entries. - The untyped-budget-refusal architecture guard counts refusals whose only recovery is an authored remediationAction, with a shrink-only baseline. Fixes #14175 Part of #14234 BREAKING CHANGE: an inspect_il2cpp_metadata refusal at the ELF pointer index reports reported_limits.boundary "virtual-pointer-index-bytes" and details.limit for max_native_index_bytes, and no longer carries a details.refusal fixed_ceiling. * fix(limits): track IL2CPP's remaining fixed allowances with the native readers * fix(limits): run the authored-only refusal count from lint, where TypeScript is installed The architecture guards run before npm ci in CI and must stay dependency-free, so the AST-based count moves into fixed-ceilings.mjs with its own shrink-only baseline and --shrink-baselines. * fix(limits): register producer and native wrapper ceilings by the allowance they name fixedProducerInputAllowance names its allowance in its second argument, and fixedNativeAllowance forwards its first, so the guard now reads each helper's allowance argument and checks the callers of both. * fix(limits): delete the authored-only baseline when its last count is removed reconcileBaselineFile returns delete once no count remains, but the verifier ignored it and the next run read the file unconditionally, so --shrink-baselines could not finish. An absent baseline now reads as empty and shrinking removes the file. * fix(limits): record the advertised IL2CPP input schema with max_native_index_bytes --- docs/il2cpp-metadata.md | 2 +- docs/reference/limits-and-recovery.md | 25 + docs/reference/rea-limit-inventory.md | 29 + package.json | 2 +- .../tools/inspect_il2cpp_metadata.json | 2 +- scripts/verify/fixed-ceiling-guard.d.mts | 5 + scripts/verify/fixed-ceiling-guard.mjs | 155 +++++ scripts/verify/fixed-ceiling-registry.json | 607 ++++++++++++++++++ scripts/verify/fixed-ceilings.d.mts | 18 + scripts/verify/fixed-ceilings.mjs | 211 ++++++ .../untyped-budget-refusal-baseline.json | 84 +++ src/cli/il2cppCommands.ts | 4 + src/domain/il2cpp/il2cppMetadata.ts | 42 ++ src/domain/native/elfDebugLink.ts | 31 +- src/domain/native/elfNotes.ts | 31 +- .../native/elfPointerRelocations.test.ts | 4 +- src/domain/native/elfPointerRelocations.ts | 17 +- src/domain/native/elfReadBudgets.ts | 38 ++ src/il2cpp/Il2cppBinaryFile.ts | 11 +- src/il2cpp/Il2cppBinaryFormat.ts | 10 +- src/il2cpp/Il2cppBinaryImage.ts | 15 +- src/il2cpp/Il2cppMetadataProvider.ts | 17 + src/native/elf/ElfDebugLinkProvider.ts | 17 + src/native/elf/ElfNotesProvider.ts | 17 + .../boundary/filesystem/elfDebugLink.test.ts | 21 + tests/boundary/filesystem/elfNotes.test.ts | 31 + .../il2cpp/il2cppMetadataProvider.test.ts | 71 +- tests/evaluation/fixedCeilingGuard.test.ts | 134 ++++ 28 files changed, 1623 insertions(+), 28 deletions(-) create mode 100644 scripts/verify/fixed-ceiling-guard.d.mts create mode 100644 scripts/verify/fixed-ceiling-guard.mjs create mode 100644 scripts/verify/fixed-ceiling-registry.json create mode 100644 scripts/verify/fixed-ceilings.d.mts create mode 100644 scripts/verify/fixed-ceilings.mjs create mode 100644 scripts/verify/untyped-budget-refusal-baseline.json create mode 100644 src/domain/native/elfReadBudgets.ts create mode 100644 tests/evaluation/fixedCeilingGuard.test.ts diff --git a/docs/il2cpp-metadata.md b/docs/il2cpp-metadata.md index 9bcbeccf12..eccc1415a9 100644 --- a/docs/il2cpp-metadata.md +++ b/docs/il2cpp-metadata.md @@ -499,7 +499,7 @@ the metadata's own fault, so linking refuses it as malformed metadata with `invalid-method-definition-token` (see [failures](#failures)), not as a conflict. Rows may repeat across images, since each image numbers its own. -Slice-selection failures name `binary_architecture`: an architecture the universal file does not hold, an ambiguous one, or one given for a thin file. A metadata failure found while linking names the metadata's path, not the binary's. Capacity refusals remain typed resource errors whose `reported_limits` name the exceeded budget (`boundary`, the capacity reason) and its `maximum`, with `details.refusal.unit` naming the unit the budget counts (`"entries"`, `"bytes"` or `"frames"`). Failed linking preserves the metadata source identity, validated counts, selected binary path/architecture and its SHA-256 when observed, plus prior producer observations. It never publishes an incomplete native table as complete. The binary input is bounded to 1 GiB. The virtual-pointer index has the same 1 GiB estimated representation allowance ([#14175](https://github.com/morluto/rea/issues/14175) reports a real Unity 6 arm64 build that exceeds it), reserving 2 KiB per distinct virtual destination before insertion for retained Maps and finish-time lookup storage. Repeated declarations of one destination share that reservation. This conservative allocation accounting is separate from actual process RSS and the report allowance; exhaustion returns a typed `native-index-capacity` refusal before another destination is retained. +Slice-selection failures name `binary_architecture`: an architecture the universal file does not hold, an ambiguous one, or one given for a thin file. A metadata failure found while linking names the metadata's path, not the binary's. Capacity refusals remain typed resource errors whose `reported_limits` name the exceeded budget (`boundary`, the capacity reason) and its `maximum`, with `details.refusal.unit` naming the unit the budget counts (`"entries"`, `"bytes"` or `"frames"`). Failed linking preserves the metadata source identity, validated counts, selected binary path/architecture and its SHA-256 when observed, plus prior producer observations. It never publishes an incomplete native table as complete. The binary input is bounded to 1 GiB. The ELF virtual-pointer index has its own per-call allowance, `max_native_index_bytes` (CLI `--max-native-index-bytes`, needs `binary_path`), which defaults to 1 GiB of estimated representation and reserves 2 KiB per distinct virtual destination before insertion for retained Maps and finish-time lookup storage. The default admits 524,288 destinations; a build with more, such as the Unity 6 arm64 `libil2cpp.so` with 559,802 relocations in [#14175](https://github.com/morluto/rea/issues/14175), needs a larger value on the next call. Repeated declarations of one destination share that reservation. This conservative allocation accounting is separate from actual process RSS, host memory and the report allowance; exhaustion returns a typed `native-index-capacity` refusal before another destination is retained, with `reported_limits.boundary` `virtual-pointer-index-bytes` and `details.limit` naming `max_native_index_bytes`, its effective value, its default and its range (1 to `Number.MAX_SAFE_INTEGER`). Scans yield cooperatively in bounded batches. Name-address retention and reverse-trie construction are each limited to 65,536 entries/nodes and fallback module-array candidates to 64 (`native-index-capacity`); exceeding capacity does not prove absence. Rendered type text has a 64 MiB UTF-8 cache-workspace guard, separate from the 64 MiB encoded-report admission, and 64 nested rendering frames (`native-type-text-capacity` / `type-nesting-capacity`). Genuine cycles are malformed; unsupported type kinds are explicit coverage failures. Native row/text admission runs before allocation or retention. Unused generic parameter names are read on demand from the same stable metadata snapshot. There is no cross-inspection file cache; validated immutable Evidence is reused for session views. diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index aa22f35bd1..a51efc865a 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -93,6 +93,14 @@ page runs a fresh discovery on that device. Graph tools accept per-call traversal bounds (`max_depth` and `max_nodes` on `get_call_graph` and `trace_call_path`). +`inspect_elf_notes` and `inspect_elf_debug_link` refuse a file above +`max_file_bytes`, a decoded section-name table above it, or more notes than +`max_entries` with `details.limit` naming that field +(`control_kind: "parameter"`), its effective value, default and range. `inspect_il2cpp_metadata` +accepts `max_native_index_bytes` (default 1 GiB) for the estimated ELF pointer +index of `binary_path`; its refusal reports the same kind of limit. See +[IL2CPP metadata](../il2cpp-metadata.md#native-method-addresses). + ### Producer limits Operations with an owned producer accept an optional @@ -283,6 +291,23 @@ and raising a provider deadline cannot make the client wait longer. The failure names the limit and the effective value. Say this release has no runtime override, and name what does not raise it. Do not invent a setting. +Every fixed ceiling a refusal declares (`fixedAllowanceOptions`, +`fixedProducerInputAllowance`, `artifactFixedLimitFailure` or an inline +`fixedAllowance`) is listed in +[`fixed-ceiling-registry.json`](https://github.com/morluto/rea/blob/main/scripts/verify/fixed-ceiling-registry.json) +under its file and allowance, with its class and reason: `format`, +`protocol`, `representation`, `derived` (grows with the admitted input or +another control), `forwarding` (relays a ceiling declared elsewhere), or +`pending` with the issue that tracks giving it a control. +`npm run lint` runs `scripts/verify/fixed-ceilings.mjs`, which fails on an +unregistered declaration and on a stale entry. A resource or admission limit +is not a fixed ceiling: give it a setting or per-call parameter and report +`details.limit`. The same script counts refusals whose only recovery is an +authored `remediationAction`, with no `limit`, `fixedAllowance` or +`measuredExhaustion`, against `scripts/verify/untyped-budget-refusal-baseline.json`; +that count may only shrink, and `--shrink-baselines` lowers it +([#14234](https://github.com/morluto/rea/issues/14234)). + JSON values stop at `MAX_JSON_DEPTH` (1000) in [`jsonValue.ts`](https://github.com/morluto/rea/blob/main/src/domain/jsonValue.ts): "JSON value exceeds maximum nesting depth of 1000. This release has no runtime diff --git a/docs/reference/rea-limit-inventory.md b/docs/reference/rea-limit-inventory.md index 71f873cb44..fc54d08646 100644 --- a/docs/reference/rea-limit-inventory.md +++ b/docs/reference/rea-limit-inventory.md @@ -206,3 +206,32 @@ tables above and compares them with `ANALYSIS_SETTINGS` or the owner constant the parser enforces. A mismatch names the limit and both values. A cell that is only `Number.MAX_SAFE_INTEGER` or `MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS` means that export. `unset` means the code default is null. + +## Per-call request parameters and fixed ceilings + +Request parameters are not `REA_` limits and are not in `ANALYSIS_SETTINGS`; +each operation's schema owns its bounds, and a refusal reports +`details.limit` with `control_kind: "parameter"` and `applies_at: "next_call"`. +These parameters report that limit: + +| Operation | Parameter | Default | Floor | Maximum | Owner | +| --------------------------------------------- | ------------------------ | ---------- | ----: | ------------------------: | ------------------------------------- | +| `inspect_il2cpp_metadata` | `max_native_index_bytes` | 1073741824 | 1 | `Number.MAX_SAFE_INTEGER` | `src/domain/il2cpp/il2cppMetadata.ts` | +| `inspect_elf_notes`, `inspect_elf_debug_link` | `max_file_bytes` | 67108864 | 64 | 536870912 | `src/domain/native/elfReadBudgets.ts` | +| `inspect_elf_notes`, `inspect_elf_debug_link` | `max_entries` | 128 | 1 | 256 | `src/domain/native/elfReadBudgets.ts` | + +Refusals that still name a per-call control only in prose are counted by +`scripts/verify/fixed-ceilings.mjs` against +`scripts/verify/untyped-budget-refusal-baseline.json` and tracked in +[#14234](https://github.com/morluto/rea/issues/14234). + +Fixed ceilings are listed with their class and reason in +`scripts/verify/fixed-ceiling-registry.json`, which `npm run lint` checks with +`scripts/verify/fixed-ceilings.mjs`; see +[keep a fixed ceiling honest](limits-and-recovery.md#keep-a-fixed-ceiling-honest). +Entries classed `pending` are resource limits awaiting a control, tracked in +[#14235](https://github.com/morluto/rea/issues/14235) (native readers, +including IL2CPP's remaining allowances), +[#14236](https://github.com/morluto/rea/issues/14236) (archive and container +readers) and [#14237](https://github.com/morluto/rea/issues/14237) (producer +output and capture). diff --git a/package.json b/package.json index fed5c7bbb6..44d5632d3c 100644 --- a/package.json +++ b/package.json @@ -152,7 +152,7 @@ "build:termux:run": "npm run compile:termux && npm run artifacts:skills", "format": "oxfmt .", "format:check": "oxfmt --check .", - "lint": "node scripts/ci/static-check-report.mjs lint && npm run verify:module-boundaries && node scripts/verify/rea-numeric-limits.mjs", + "lint": "node scripts/ci/static-check-report.mjs lint && npm run verify:module-boundaries && node scripts/verify/rea-numeric-limits.mjs && node scripts/verify/fixed-ceilings.mjs", "lint:details": "oxlint && npm run verify:module-boundaries", "lint:fix": "oxlint --fix && npm run verify:module-boundaries", "knip": "knip --cache", diff --git a/scripts/verify/advertised-schemas/tools/inspect_il2cpp_metadata.json b/scripts/verify/advertised-schemas/tools/inspect_il2cpp_metadata.json index 32aafbe572..4120d722af 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_il2cpp_metadata.json +++ b/scripts/verify/advertised-schemas/tools/inspect_il2cpp_metadata.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "7181073b85e89641", + "input compact": "dfe942025da7fe6e", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/fixed-ceiling-guard.d.mts b/scripts/verify/fixed-ceiling-guard.d.mts new file mode 100644 index 0000000000..06e3ace260 --- /dev/null +++ b/scripts/verify/fixed-ceiling-guard.d.mts @@ -0,0 +1,5 @@ +export function fixedCeilingDeclarations( + content: string, + path: string, +): Map; +export function authoredOnlyRefusalCount(content: string, path: string): number; diff --git a/scripts/verify/fixed-ceiling-guard.mjs b/scripts/verify/fixed-ceiling-guard.mjs new file mode 100644 index 0000000000..eff6e3cf8d --- /dev/null +++ b/scripts/verify/fixed-ceiling-guard.mjs @@ -0,0 +1,155 @@ +import ts from "typescript6"; + +// A refusal names the owner of the limit that stopped it: a registered +// setting or per-call parameter (`limit`), a fixed ceiling whose format, +// protocol or representation reason is registered (`fixedAllowance`), or an +// observed exhaustion (`measuredExhaustion`). These helpers find the two +// constructions that bypass that ownership: a fixed-ceiling declaration, +// which must be listed with its reason, and a refusal whose only recovery is +// authored prose, which names no control a caller can adjust. + +/** + * Helpers that declare a fixed ceiling, with the index of the argument that + * names (or is) the allowance. A wrapper that forwards its own parameter is + * listed here so its callers are checked, not only the wrapper. + */ +const FIXED_CEILING_HELPERS = new Map([ + ["fixedAllowanceOptions", 0], + ["fixedNativeAllowance", 0], + ["fixedProducerInputAllowance", 1], + ["artifactFixedLimitFailure", 0], +]); + +/** Option keys that bind a refusal to its owner. */ +const OWNER_KEYS = new Set(["limit", "fixedAllowance", "measuredExhaustion"]); + +const propertyName = (property) => + property.name !== undefined && + (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) + ? property.name.text + : undefined; + +const normalized = (node, source) => + node.getText(source).replace(/\s+/gu, " ").trim(); + +const namedProperty = (literal, name) => + literal.properties.find( + (property) => + ts.isPropertyAssignment(property) && propertyName(property) === name, + ); + +/** The allowance a declaration names: the helper's first argument or the literal's `name`. */ +const allowanceText = (node, source) => { + if (!ts.isObjectLiteralExpression(node)) return normalized(node, source); + const name = namedProperty(node, "name"); + return name === undefined + ? normalized(node, source) + : normalized(name.initializer, source); +}; + +const parse = (content, path) => + ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true); + +/** + * Each fixed-ceiling declaration in one file, keyed by the allowance text it + * names: a call to one of `FIXED_CEILING_HELPERS`, or an inline `fixedAllowance: { ... }` + * object. Forwarding an existing allowance (`fixedAllowance: cause.fixedAllowance`) + * declares nothing and is not listed. + * + * @param {string} content + * @param {string} path + * @returns {Map} allowance text to its declaration line + */ +export const fixedCeilingDeclarations = (content, path) => { + const source = parse(content, path); + const found = new Map(); + const record = (allowance, node) => { + const text = allowanceText(allowance, source); + if (!found.has(text)) + found.set( + text, + source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1, + ); + }; + const visit = (node) => { + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + FIXED_CEILING_HELPERS.has(node.expression.text) + ) { + const allowance = + node.arguments[FIXED_CEILING_HELPERS.get(node.expression.text)]; + if (allowance !== undefined) record(allowance, node); + } + if ( + ts.isPropertyAssignment(node) && + propertyName(node) === "fixedAllowance" && + ts.isObjectLiteralExpression(node.initializer) + ) + record(node.initializer, node); + ts.forEachChild(node, visit); + }; + visit(source); + return found; +}; + +/** + * How many visible option literals author recovery without naming an owner. + * A conditional chooses between option objects, so each branch counts. + */ +const authoredOnly = (options) => { + if (options === undefined) return 0; + if (ts.isParenthesizedExpression(options)) + return authoredOnly(options.expression); + if (ts.isConditionalExpression(options)) + return authoredOnly(options.whenTrue) + authoredOnly(options.whenFalse); + return ts.isObjectLiteralExpression(options) && + !options.properties.some( + (property) => + ts.isSpreadAssignment(property) || + OWNER_KEYS.has(propertyName(property)), + ) && + options.properties.some( + (property) => propertyName(property) === "remediationAction", + ) + ? 1 + : 0; +}; + +/** + * Count refusals whose only recovery is an authored `remediationAction`: a + * `new AnalysisResourceConstraintError(...)` (options are the fifth argument) + * or `parseLimitConstraint(...)` (options are the fourth). Options built by a + * helper, a variable or a spread are trusted, as the typed-refusal lint rule + * trusts them. + * + * @param {string} content + * @param {string} path + * @returns {number} + */ +export const authoredOnlyRefusalCount = (content, path) => { + if ( + !content.includes("AnalysisResourceConstraintError") && + !content.includes("parseLimitConstraint") + ) + return 0; + const source = parse(content, path); + let count = 0; + const visit = (node) => { + if ( + ts.isNewExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === "AnalysisResourceConstraintError" + ) + count += authoredOnly(node.arguments?.[4]); + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === "parseLimitConstraint" + ) + count += authoredOnly(node.arguments[3]); + ts.forEachChild(node, visit); + }; + visit(source); + return count; +}; diff --git a/scripts/verify/fixed-ceiling-registry.json b/scripts/verify/fixed-ceiling-registry.json new file mode 100644 index 0000000000..06ce016af1 --- /dev/null +++ b/scripts/verify/fixed-ceiling-registry.json @@ -0,0 +1,607 @@ +{ + "src/adb/AdbCommand.ts": { + "name": { + "class": "forwarding", + "reason": "Relays the live adb capture allowance named by its caller; the ceiling is declared where the command's budget is chosen." + }, + "{ name, kind: \"live\" as const, ...facts }": { + "class": "forwarding", + "reason": "Relays the live adb capture allowance named by its caller; the ceiling is declared where the command's budget is chosen." + } + }, + "src/adb/AdbConfiguration.ts": { + "`The adb version-output capture allowance of ${String(VERSION_MAX_OUTPUT_BYTES)} bytes (this release has no runtime override)`": { + "class": "protocol", + "reason": "Bounds the reply to `adb version`, a short fixed-format banner; no analysis input passes through it." + } + }, + "src/android/JadxSession.ts": { + "`The external DEX ${failure.stage} representation allowance`": { + "class": "pending", + "issue": 14237, + "reason": "External DEX representation retained from the JADX worker is a resource policy without a per-call control." + } + }, + "src/apkSignature/apkSignatureFailures.ts": { + "\"The decoded APK signing report allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "APK signing-block pair, signer, entry and report counts are REA resource policies, not APK Signature Scheme maxima." + }, + "`The APK Signature Scheme ${scheme} allowance of ${String(maximum)} ${name} (this release has no runtime override)`": { + "class": "pending", + "issue": 14235, + "reason": "APK signing-block pair, signer, entry and report counts are REA resource policies, not APK Signature Scheme maxima." + }, + "`The APK Signing Block allowance of ${String(maximum)} pairs (this release has no runtime override)`": { + "class": "pending", + "issue": 14235, + "reason": "APK signing-block pair, signer, entry and report counts are REA resource policies, not APK Signature Scheme maxima." + }, + "`The APK v1 allowance of ${String(limit)} signers (this release has no runtime override)`": { + "class": "pending", + "issue": 14235, + "reason": "APK signing-block pair, signer, entry and report counts are REA resource policies, not APK Signature Scheme maxima." + }, + "`The APK v1 allowance of ${String(maximum)} META-INF signing entries (this release has no runtime override)`": { + "class": "pending", + "issue": 14235, + "reason": "APK signing-block pair, signer, entry and report counts are REA resource policies, not APK Signature Scheme maxima." + } + }, + "src/apktool/ApktoolConfiguration.ts": { + "\"The apktool version-output capture allowance (decode_timeout_ms does not raise it)\"": { + "class": "protocol", + "reason": "Bounds the reply to `apktool --version`, a short fixed-format banner; no analysis input passes through it." + } + }, + "src/apktool/ApktoolProvider.ts": { + "\"The apktool output capture allowance (decode_timeout_ms does not raise it)\"": { + "class": "pending", + "issue": 14237, + "reason": "apktool output capture is a producer budget without a per-call control." + } + }, + "src/application/ntfs/NtfsJournalService.ts": { + "\"The NTFS journal file allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "The NTFS journal file allowance bounds bytes read, a resource policy." + } + }, + "src/artifacts/AndroidBootImageArtifactReader.ts": { + "ceiling.name": { + "class": "forwarding", + "reason": "Projects the boot-image parser's own named ceiling (`ceiling.name`); the value is declared by that parser." + } + }, + "src/artifacts/DenoStandaloneArtifactReader.ts": { + "\"The Deno compile retained metadata allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Deno retained metadata bytes are a resource policy." + } + }, + "src/artifacts/WxapkgArtifactReader.ts": { + "\"The wxapkg directory-and-chunk I/O work allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "wxapkg directory, member-table and I/O allowances are resource policies." + } + }, + "src/artifacts/WxapkgStructures.ts": { + "\"The wxapkg directory representation allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "wxapkg directory, member-table and I/O allowances are resource policies." + }, + "\"The wxapkg member table allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "wxapkg directory, member-table and I/O allowances are resource policies." + } + }, + "src/artifacts/apple/AppleAssetCatalogAnalysis.ts": { + "\"The assetutil capture allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "assetutil output capture is a producer budget without a per-call control." + } + }, + "src/artifacts/deno/DenoSectionLayout.ts": { + "`The Deno compile ${scope} allowance`": { + "class": "pending", + "issue": 14236, + "reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima." + }, + "`The Deno compile ${scope} record allowance`": { + "class": "pending", + "issue": 14236, + "reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima." + } + }, + "src/artifacts/deno/DenoStandaloneLocation.ts": { + "parserLimit.name": { + "class": "forwarding", + "reason": "Projects a Deno parser limit declared at its owner (`parserLimit.name`)." + } + }, + "src/artifacts/deno/DenoVirtualFs.ts": { + "\"The Deno compile virtual filesystem depth allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima." + }, + "\"The Deno compile virtual filesystem entry allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima." + }, + "\"The Deno compile virtual filesystem retained name allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima." + } + }, + "src/artifacts/dotnet/DotnetBundle.ts": { + "\"The .NET bundle exact integer range\"": { + "class": "representation", + "reason": "A bundle offset or size above Number.MAX_SAFE_INTEGER cannot be represented exactly as a JavaScript number." + } + }, + "src/artifacts/nodeSea/NodeSeaLocation.ts": { + "\"Node SEA duplicate-blob verification allowance\"": { + "class": "derived", + "reason": "Duplicate-blob verification work is bounded by the carrier's own file size, so the bound grows with the admitted input." + } + }, + "src/artifacts/releaseExposure/releaseExposureFailures.ts": { + "\"The release exposure input allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "The release exposure input allowance bounds bytes read, a resource policy." + } + }, + "src/browser/WebBundleAnalysisWorker.ts": { + "\"The web-bundle worker transfer allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "Web-bundle worker transfer bytes are a resource policy." + } + }, + "src/browser/execution/CdpRuntimeRetention.ts": { + "allowance": { + "class": "forwarding", + "reason": "Relays the live runtime-retention allowance its caller names." + } + }, + "src/browser/history/playwrightTrace/PlaywrightTraceDecoder.ts": { + "`The Playwright trace archive input allowance of ${String(PLAYWRIGHT_TRACE_LIMITS.archiveBytes)} bytes`": { + "class": "pending", + "issue": 14236, + "reason": "Playwright trace archive input and record parser allowances are resource policies." + } + }, + "src/browser/history/playwrightTrace/TraceStream.ts": { + "nesting ? \"The Playwright trace record nesting allowance\" : \"The Playwright trace record parser allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Playwright trace archive input and record parser allowances are resource policies." + } + }, + "src/captures/TsharkCaptureProvider.ts": { + "\"The packet-field discovery record allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "Packet-field discovery record capture is a producer budget." + } + }, + "src/domain/analysisErrorCore.ts": { + "text(recovery.fixedAllowance.name)": { + "class": "forwarding", + "reason": "Copies a declared fixed allowance while redacting its text; declares no ceiling." + } + }, + "src/domain/analysisView/WebNetworkProjectionAccumulator.ts": { + "\"The analysis-view projection allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "The analysis-view projection allowance is a resource policy." + } + }, + "src/domain/apiContract/GraphqlDocuments.ts": { + "`The GraphQL AST nesting allowance of ${String(GRAPHQL_CONTRACT_LIMITS.astDepth)} levels`": { + "class": "pending", + "issue": 14236, + "reason": "GraphQL AST nesting depth is a resource policy unless a recursion-stack reason is stated." + } + }, + "src/domain/fixedAllowanceRemediation.ts": { + "allowance": { + "class": "forwarding", + "reason": "The fixed-ceiling helpers themselves; each caller names its own allowance." + } + }, + "src/domain/native/nativeDeadlines.ts": { + "allowance": { + "class": "forwarding", + "reason": "`fixedNativeAllowance` relays the allowance its caller names." + } + }, + "src/electron/ElectronFuseFailures.ts": { + "fileSize ? \"the Electron fuse input allowance\" : \"The Electron fuse sentinel inventory\"": { + "class": "pending", + "issue": 14235, + "reason": "Electron fuse input bytes and sentinel inventory are resource policies." + } + }, + "src/erlang/BeamProvider.ts": { + "\"BEAM table row ceiling\"": { + "class": "pending", + "issue": 14235, + "reason": "The BEAM table row ceiling is a resource policy." + } + }, + "src/flutter/FlutterBuildProvider.ts": { + "\"The Flutter ABI inventory allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies." + }, + "\"The Flutter APK expansion allowance (derived from the APK size)\"": { + "class": "derived", + "reason": "Expansion work is derived from the admitted APK's own size." + }, + "\"The Flutter APK metadata read allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies." + }, + "\"The Flutter library path allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies." + }, + "\"The Flutter snapshot-hash candidate allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies." + }, + "\"the Flutter APK snapshot allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies." + }, + "\"the Flutter cumulative extraction allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies." + }, + "\"the Flutter library read allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies." + } + }, + "src/ghidra/GhidraExecutableHeader.ts": { + "\"The header parser's exactly representable executable extent\"": { + "class": "representation", + "reason": "An executable extent above Number.MAX_SAFE_INTEGER cannot be represented exactly." + } + }, + "src/ghidra/GhidraInstallationProperties.ts": { + "\"The Ghidra installation-properties read allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Bounds the read of an installation's properties file; a resource policy on an operator-owned file." + } + }, + "src/go/GoBinaryProvider.ts": { + "\"The Go structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Projects the shared native structural decoding allowance (BinaryResourceFailure), a resource policy." + } + }, + "src/ida/IdaMcpConnection.ts": { + "{ ...outputLimit.ceiling, narrowing: \"Request a smaller result from IDA, such as a narrower address range or fewer items.\", }": { + "class": "protocol", + "reason": "REA bounds each stdio message from the upstream IDA MCP server at a fixed frame size; the transport, not the analysis, sets it." + } + }, + "src/il2cpp/Il2cppGhidraSeeds.ts": { + "name": { + "class": "pending", + "issue": 14235, + "reason": "IL2CPP metadata input, native-link candidate and Ghidra seed allowances are resource policies; the ELF pointer index became max_native_index_bytes." + } + }, + "src/il2cpp/Il2cppMetadataProvider.ts": { + "\"The IL2CPP native-link allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "IL2CPP metadata input, native-link candidate and Ghidra seed allowances are resource policies; the ELF pointer index became max_native_index_bytes." + }, + "\"the fixed IL2CPP input allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "IL2CPP metadata input, native-link candidate and Ghidra seed allowances are resource policies; the ELF pointer index became max_native_index_bytes." + } + }, + "src/java/MavenGradleMetadataProvider.ts": { + "Object.entries(REPORT_ALLOWANCE_SUBJECTS).find( ([key]) => key === name, )?.[1](maximum) ?? name": { + "class": "pending", + "issue": 14236, + "reason": "Maven and Gradle XML node and report allowances are resource policies." + } + }, + "src/kuna/KunaProjectReader.ts": { + "`Kuna's buffered function-text allowance of ${String(KUNA_FUNCTION_TEXT_BYTES)} bytes`": { + "class": "pending", + "issue": 14237, + "reason": "Kuna's buffered function-text allowance is a resource policy." + } + }, + "src/native/NativeCommandAnalysisError.ts": { + "\"The native command output capture allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "Native command output capture is a producer budget without a per-call control." + } + }, + "src/native/SignatureTargetBinding.ts": { + "\"The exactly representable file size\"": { + "class": "representation", + "reason": "A file size above Number.MAX_SAFE_INTEGER cannot be represented exactly." + } + }, + "src/native/apple/AppleIpsProvider.ts": { + "`The IPS ${name.replaceAll(\"_\", \" \")} allowance`": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/dwarf/DwarfUnitsProvider.ts": { + "\"The native structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + }, + "DWARF_DECOMPRESSED_SECTION_ALLOWANCE": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/elf/ElfDebugLinkProvider.ts": { + "\"The ELF structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + }, + "\"The whole-file debug candidate read allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "The streamed candidate is hashed in bounded chunks; its 0xffffffff-byte whole-file ceiling states no format reason, so it is a policy awaiting a control or a stated reason." + }, + "ELF_NOTE_TEXT_ALLOWANCE": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/elf/ElfDependenciesProvider.ts": { + "\"The ELF structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "ELF dependency entry allowances are resource policies; the text budget is derived from the admitted image length." + }, + "text ? \"The ELF dependency text budget fixed by the admitted image length\" : `The ELF dependency ${limit.name} allowance`": { + "class": "pending", + "issue": 14235, + "reason": "ELF dependency entry allowances are resource policies; the text budget is derived from the admitted image length." + } + }, + "src/native/elf/ElfNotesProvider.ts": { + "ELF_NOTE_TEXT_ALLOWANCE": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/elf/ElfUnwindRangesProvider.ts": { + "\"The ELF structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/elf/KernelModuleProvider.ts": { + "\"The ELF structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/exports/NativeExportsProvider.ts": { + "\"The native export inventory allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + }, + "\"The native export retained-text allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + }, + "\"The native export structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/hardening/BinaryHardeningProvider.ts": { + "\"The binary hardening structural allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/initializers/NativeInitializersProvider.ts": { + "\"The native initializer structural allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/parsers/lipo.ts": { + "\"The lipo field retention allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "lipo field retention is a producer capture budget." + } + }, + "src/native/parsers/plist.ts": { + "\"The native plist input allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + }, + "\"The native plist nesting allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + }, + "`The native ${encoding} plist decode allowance`": { + "class": "pending", + "issue": 14235, + "reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control." + } + }, + "src/native/pe/PeCertificatesProvider.ts": { + "selected.name": { + "class": "pending", + "issue": 14235, + "reason": "PE structural and retained-text allowances are resource policies (the PE file-size admission is #14167)." + } + }, + "src/native/pe/PeImportsProvider.ts": { + "\"The PE import retained-text allowance (max_file_bytes, max_dlls and max_functions do not raise it)\"": { + "class": "pending", + "issue": 14235, + "reason": "PE structural and retained-text allowances are resource policies (the PE file-size admission is #14167)." + }, + "\"The PE structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "PE structural and retained-text allowances are resource policies (the PE file-size admission is #14167)." + } + }, + "src/native/pe/PeLoadConfigProvider.ts": { + "\"The PE structural decoding allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "PE structural and retained-text allowances are resource policies (the PE file-size admission is #14167)." + } + }, + "src/native/pe/PeResourcesProvider.ts": { + "\"The PE resource metadata allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "PE resource metadata retention is a resource policy (the PE file-size admission is #14167)." + } + }, + "src/pcap/PcapCommand.ts": { + "\"The packet-tool output capture allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "tshark JSON decoding, expansion, retained-fact, output and snapshot allowances are producer budgets." + } + }, + "src/pcap/PcapOutput.ts": { + "\"The packet-inventory retained-fact allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "tshark JSON decoding, expansion, retained-fact, output and snapshot allowances are producer budgets." + }, + "\"The tshark JSON decoding allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "tshark JSON decoding, expansion, retained-fact, output and snapshot allowances are producer budgets." + }, + "\"The tshark JSON expansion allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "tshark JSON decoding, expansion, retained-fact, output and snapshot allowances are producer budgets." + } + }, + "src/pcap/PcapSnapshot.ts": { + "\"the owned capture snapshot allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "tshark JSON decoding, expansion, retained-fact, output and snapshot allowances are producer budgets." + } + }, + "src/process/ArtifactAnalysisResources.ts": { + "`The retained command-output allowance of ${String(limits.output_bytes)} bytes (this release has no runtime override)`": { + "class": "pending", + "issue": 14237, + "reason": "Retained command output is a producer budget without a per-call control." + }, + "allowanceName": { + "class": "forwarding", + "reason": "Declares a producer input allowance only for callers that offer no budget parameter; the value is the caller's selected maximum." + } + }, + "src/process/capture/ProcessSensitiveOutput.ts": { + "\"Sensitive terminal redaction\"": { + "class": "pending", + "issue": 14237, + "reason": "Sensitive terminal redaction state is a resource policy." + } + }, + "src/resources/ArtifactPaths.ts": { + "\"The artifact path depth allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Artifact path depth and tree-node allowances are resource policies." + }, + "\"The artifact path tree allowance\"": { + "class": "pending", + "issue": 14236, + "reason": "Artifact path depth and tree-node allowances are resource policies." + } + }, + "src/rust/RustBinaryProvider.ts": { + "\"The WebAssembly section-walk allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Rust container, dependency and WebAssembly section-walk allowances are resource policies." + }, + "\"This Rust dependency parser allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Rust container, dependency and WebAssembly section-walk allowances are resource policies." + }, + "\"This native container parser allowance\"": { + "class": "pending", + "issue": 14235, + "reason": "Rust container, dependency and WebAssembly section-walk allowances are resource policies." + } + }, + "src/signals/SigrokRecordingProvider.ts": { + "\"The sigrok decoder-discovery line allowance\"": { + "class": "pending", + "issue": 14237, + "reason": "sigrok decoder-discovery line capture is a producer budget." + } + }, + "src/sqlite/SqliteDatabaseFailures.ts": { + "`The SQLite worker diagnostic capture allowance of ${String(SQLITE_DATABASE_LIMITS.diagnosticBytes)} bytes (this release has no runtime override; worker_timeout_ms does not raise it)`": { + "class": "pending", + "issue": 14237, + "reason": "SQLite worker diagnostic capture is a producer budget." + } + } +} diff --git a/scripts/verify/fixed-ceilings.d.mts b/scripts/verify/fixed-ceilings.d.mts new file mode 100644 index 0000000000..604d8db3fb --- /dev/null +++ b/scripts/verify/fixed-ceilings.d.mts @@ -0,0 +1,18 @@ +export const FIXED_CEILING_CLASSES: ReadonlySet; +export function compareFixedCeilings( + declarations: ReadonlyMap>, + registry: Record< + string, + Record + >, +): string[]; +export function compareAuthoredOnlyRefusals( + counts: ReadonlyMap, + baseline: Record, + shrink: boolean, +): { failures: string[]; baseline: Record }; +export function checkAuthoredOnlyBaseline( + path: string, + counts: ReadonlyMap, + shrink: boolean, +): Promise; diff --git a/scripts/verify/fixed-ceilings.mjs b/scripts/verify/fixed-ceilings.mjs new file mode 100644 index 0000000000..aa1e0c187d --- /dev/null +++ b/scripts/verify/fixed-ceilings.mjs @@ -0,0 +1,211 @@ +import { readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { join, relative, sep } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { + compareCountedBaseline, + reconcileBaselineFile, +} from "./counted-baseline.mjs"; +import { + authoredOnlyRefusalCount, + fixedCeilingDeclarations, +} from "./fixed-ceiling-guard.mjs"; + +// Every fixed ceiling a refusal declares (`fixedAllowanceOptions`, +// `fixedProducerInputAllowance`, `artifactFixedLimitFailure` or an inline +// `fixedAllowance: { ... }`) must be listed in fixed-ceiling-registry.json +// under its file and allowance text, with the reason it cannot be adjusted: +// +// - `format`: a format or specification fact (a field width, a spec maximum). +// - `protocol`: a transport or protocol frame REA does not own. +// - `representation`: an exact runtime representation bound. +// - `derived`: grows with the admitted input or another named control. +// - `forwarding`: relays a ceiling declared at another site. +// - `pending`: a resource limit that should become adjustable; it names the +// issue that tracks giving it a control. +// +// A resource or admission limit (bytes read, rows, nesting, worker heap, +// expansion, index allowances) is not a fixed ceiling: give it a setting or +// per-call parameter and report `details.limit` instead +// (docs/reference/limits-and-recovery.md). An entry whose declaration is gone +// is stale and fails, so the registry cannot hide a removed ceiling. +// +// The same scan counts refusals whose only recovery is an authored +// `remediationAction` (no `limit`, `fixedAllowance` or `measuredExhaustion`) +// against a shrink-only per-file baseline (#14234). Both checks parse +// TypeScript, so they run from `npm run lint` after dependencies are +// installed rather than from the dependency-free architecture guards. + +const root = fileURLToPath(new URL("../../", import.meta.url)); +const registryPath = join(root, "scripts/verify/fixed-ceiling-registry.json"); +const BASELINE = "scripts/verify/untyped-budget-refusal-baseline.json"; + +/** Classes that may justify a fixed ceiling, plus `pending`. */ +export const FIXED_CEILING_CLASSES = new Set([ + "format", + "protocol", + "representation", + "derived", + "forwarding", + "pending", +]); + +const sourceFiles = async (dir) => { + const output = []; + for (const entry of await readdir(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) output.push(...(await sourceFiles(path))); + else if ( + entry.name.endsWith(".ts") && + !/\.(?:test|spec|fixture)\.ts$/u.test(entry.name) + ) + output.push(path); + } + return output; +}; + +/** + * Compare declarations with the registry. Returns failure lines. + * + * @param {ReadonlyMap>} declarations path to allowance text to line + * @param {Record>} registry + * @returns {string[]} + */ +export const compareFixedCeilings = (declarations, registry) => { + const failures = []; + for (const [path, found] of declarations) + for (const [allowance, line] of found) { + const entry = registry[path]?.[allowance]; + if (entry === undefined) { + failures.push( + `${path}:${String(line)} declares fixed ceiling ${allowance}, which is not in scripts/verify/fixed-ceiling-registry.json. Give a resource limit a setting or per-call parameter and report details.limit; register a format, protocol, representation, derived or forwarding ceiling with its reason, or a pending one with its issue.`, + ); + continue; + } + if (!FIXED_CEILING_CLASSES.has(entry.class)) + failures.push( + `${path}: ${allowance} has class ${JSON.stringify(entry.class)}; use one of ${[...FIXED_CEILING_CLASSES].join(", ")}.`, + ); + if (typeof entry.reason !== "string" || entry.reason.trim() === "") + failures.push(`${path}: ${allowance} states no reason.`); + if (entry.class === "pending" && !Number.isSafeInteger(entry.issue)) + failures.push( + `${path}: pending ceiling ${allowance} names no tracking issue.`, + ); + if (entry.class !== "pending" && entry.issue !== undefined) + failures.push( + `${path}: ${allowance} is ${String(entry.class)} and cannot name a pending issue.`, + ); + } + for (const [path, entries] of Object.entries(registry)) + for (const allowance of Object.keys(entries)) + if (!declarations.get(path)?.has(allowance)) + failures.push( + `scripts/verify/fixed-ceiling-registry.json lists ${path}: ${allowance}, which no longer declares a fixed ceiling; remove the stale entry.`, + ); + return failures; +}; + +/** + * Compare authored-only refusal counts with their shrink-only baseline. + * Returns failure lines and the baseline after any shrinking. + * + * @param {ReadonlyMap} counts + * @param {Record} baseline + * @param {boolean} shrink + * @returns {{ failures: string[], baseline: Record }} + */ +export const compareAuthoredOnlyRefusals = (counts, baseline, shrink) => { + const compared = compareCountedBaseline(counts, baseline, shrink); + const lines = (differences) => + differences + .map( + ({ path, count, allowed }) => + ` ${path}: ${String(count)} (baseline ${String(allowed)})`, + ) + .join("\n"); + const failures = []; + if (compared.grown.length > 0) + failures.push( + `Budget refusal with only authored recovery; bind \`limit\` to its setting or per-call parameter, use a registered fixedAllowanceOptions ceiling, or declare measuredExhaustion (#14234):\n${lines(compared.grown)}`, + ); + if (compared.stale.length > 0) + failures.push( + `Authored-only refusals were removed; lower ${BASELINE} with \`node scripts/verify/fixed-ceilings.mjs --shrink-baselines\`:\n${lines(compared.stale)}`, + ); + return { failures, baseline: compared.baseline }; +}; + +/** The baseline file's text, or undefined once its last count was removed. */ +const readBaselineText = async (path) => { + try { + return await readFile(path, "utf8"); + } catch (cause) { + if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") + return undefined; + throw cause; + } +}; + +/** + * Compare the authored-only counts with the baseline file at `path` and, when + * shrinking, rewrite it or delete it once no count remains. An absent file is + * an empty baseline. Returns failure lines. + * + * @param {string} path + * @param {ReadonlyMap} counts + * @param {boolean} shrink + * @returns {Promise} + */ +export const checkAuthoredOnlyBaseline = async (path, counts, shrink) => { + const text = await readBaselineText(path); + const refusals = compareAuthoredOnlyRefusals( + counts, + text === undefined ? {} : JSON.parse(text), + shrink, + ); + const failures = [...refusals.failures]; + const file = reconcileBaselineFile(text, refusals.baseline, shrink); + if (file.action === "write") await writeFile(path, file.text); + else if (file.action === "delete") await rm(path); + else if (file.action === "reject") + failures.push( + `${BASELINE} is not in its written form (paths sorted by code unit), or has no counts left; rewrite or remove it with \`node scripts/verify/fixed-ceilings.mjs --shrink-baselines\`.`, + ); + return failures; +}; + +const main = async () => { + const declarations = new Map(); + const authored = new Map(); + for (const file of await sourceFiles(join(root, "src"))) { + const path = relative(root, file).split(sep).join("/"); + const content = await readFile(file, "utf8"); + const found = fixedCeilingDeclarations(content, path); + if (found.size > 0) declarations.set(path, found); + const count = authoredOnlyRefusalCount(content, path); + if (count > 0) authored.set(path, count); + } + const registry = JSON.parse(await readFile(registryPath, "utf8")); + const failures = compareFixedCeilings(declarations, registry); + failures.push( + ...(await checkAuthoredOnlyBaseline( + join(root, BASELINE), + authored, + process.argv.includes("--shrink-baselines"), + )), + ); + if (failures.length > 0) { + console.error(failures.join("\n")); + process.exitCode = 1; + return; + } + let pending = 0; + for (const entries of Object.values(registry)) + for (const entry of Object.values(entries)) + if (entry.class === "pending") pending++; + console.log( + `Fixed ceilings: ${String([...declarations.values()].reduce((sum, found) => sum + found.size, 0))} declarations registered; ${String(pending)} pending a control. Authored-only refusals: ${String([...authored.values()].reduce((sum, count) => sum + count, 0))}.`, + ); +}; + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) await main(); diff --git a/scripts/verify/untyped-budget-refusal-baseline.json b/scripts/verify/untyped-budget-refusal-baseline.json new file mode 100644 index 0000000000..d0b569f86b --- /dev/null +++ b/scripts/verify/untyped-budget-refusal-baseline.json @@ -0,0 +1,84 @@ +{ + "src/android/AndroidMappingFile.ts": 2, + "src/android/JadxAnalysis.ts": 1, + "src/android/JadxSession.ts": 1, + "src/apkSignature/apkSignatureFailures.ts": 1, + "src/application/JsonAuthenticationHeadroom.ts": 1, + "src/application/JsonInputFile.ts": 3, + "src/application/apiContract/ApiContractRead.ts": 1, + "src/application/apiContract/ApiContractService.ts": 1, + "src/application/apiContract/GraphqlContractImport.ts": 1, + "src/application/binaryDiagnostics/ByteEntropyService.ts": 1, + "src/application/decompileDirectory/exportTree.ts": 1, + "src/application/environment/environmentExport.ts": 1, + "src/application/environment/environmentState.ts": 1, + "src/application/environment/environmentStateAnswer.ts": 1, + "src/application/environment/environmentStateStore.ts": 2, + "src/application/environment/environmentTools.ts": 1, + "src/application/investigation/InvestigationRetention.ts": 1, + "src/application/reverse/ReverseEngineeringService.ts": 1, + "src/artifacts/DesktopApplicationReader.ts": 1, + "src/browser/WebBundleAnalysisWorker.ts": 1, + "src/browser/history/playwrightTrace/PlaywrightTraceDecoder.ts": 1, + "src/browser/history/playwrightTrace/TraceFailure.ts": 1, + "src/browser/history/playwrightTrace/TraceInventory.ts": 1, + "src/browser/history/playwrightTrace/TraceLines.ts": 2, + "src/cli/cliJsonInput.ts": 2, + "src/cli/cliResultOutput.ts": 2, + "src/cli/environmentCommands.ts": 1, + "src/cli/jsonLinesOutput.ts": 1, + "src/cutter/CutterBridgeClient.ts": 1, + "src/desktop/AgentEnvComputer.ts": 1, + "src/desktop/BuildComputerController.ts": 2, + "src/domain/analysisView/androidSymbolView.ts": 1, + "src/domain/analysisView/nativeFunctionMatchingView.ts": 1, + "src/domain/analysisView/nativeInstructionReferencesView.ts": 1, + "src/domain/analysisView/nativeProcedureReferencesView.ts": 1, + "src/domain/analysisView/recordedArrayView.ts": 2, + "src/domain/analysisView/webSourceLocationView.ts": 1, + "src/domain/apiContract/GraphqlDocuments.ts": 1, + "src/domain/apiContract/GraphqlInventory.ts": 1, + "src/domain/apiContract/parseApiContract.ts": 1, + "src/domain/pngVisualDiff.ts": 1, + "src/domain/wasm/wasmInterfaceBudget.ts": 1, + "src/firmware/FirmwareFiles.ts": 2, + "src/firmware/devicetree/DevicetreeProvider.ts": 2, + "src/ghidra/GhidraLanguageCatalog.ts": 1, + "src/gpu/GpuCodeObjectsProvider.ts": 2, + "src/hopper/HopperCallerReconciliation.ts": 1, + "src/il2cpp/Il2cppMetadataProvider.ts": 2, + "src/java/MavenGradleMetadataProvider.ts": 1, + "src/javascript/analysis/JavaScriptAnalysisTransfer.ts": 1, + "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 8, + "src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts": 1, + "src/javascript/recovery/RecoveryFiles.ts": 1, + "src/javascript/sourceMaps/SourceMapCommand.ts": 1, + "src/jeb/JebProvider.ts": 1, + "src/kuna/KunaJsonStream.ts": 1, + "src/kuna/KunaProjectCache.ts": 1, + "src/kuna/KunaSessionClient.ts": 1, + "src/main/StdioStartupInput.ts": 1, + "src/model/ModelFormat.ts": 1, + "src/native/LldbCallTracer.ts": 1, + "src/native/apple/AppleIpsProvider.ts": 1, + "src/native/dwarf/DwarfUnitsProvider.ts": 1, + "src/native/elf/ElfDependenciesProvider.ts": 2, + "src/native/elf/ElfUnwindRangesProvider.ts": 2, + "src/native/elf/KernelBuildConfigProvider.ts": 1, + "src/native/exports/NativeExportsProvider.ts": 1, + "src/native/hardening/BinaryHardeningProvider.ts": 1, + "src/native/initializers/NativeInitializersProvider.ts": 1, + "src/native/pe/PeBinaryFailure.ts": 1, + "src/native/pe/PeResourcesProvider.ts": 1, + "src/native/pwntools/PwntoolsDecoder.ts": 1, + "src/native/windows/WindowsShortcutProvider.ts": 2, + "src/nuget/NugetNupkgProvider.ts": 1, + "src/process/capture/ProcessNormalization.ts": 1, + "src/server/ErrorEvidenceTransport.ts": 2, + "src/server/ProgressiveToolCatalog.ts": 1, + "src/server/ToolResultDelivery.ts": 2, + "src/sqlite/SqliteDatabaseProvider.ts": 1, + "src/sqlite/SqliteDatabaseSnapshot.ts": 1, + "src/sqlite/SqliteDatabaseWorkerExecution.ts": 2, + "src/v8/V8CodeCacheProvider.ts": 1 +} diff --git a/src/cli/il2cppCommands.ts b/src/cli/il2cppCommands.ts index 66ad4d63ce..640bbc3723 100644 --- a/src/cli/il2cppCommands.ts +++ b/src/cli/il2cppCommands.ts @@ -83,6 +83,10 @@ export const registerIl2cppCommands = ( description: "Also link generic method instances (Type$$Method) and include them in --ghidra-seeds; needs --binary", }, + max_native_index_bytes: { + description: + "Estimated bytes for an ELF --binary's relocated-pointer index (default 1073741824); raise when linking stops at this allowance; needs --binary", + }, }, cliOptions: { ghidraSeeds: localPathStringSchema diff --git a/src/domain/il2cpp/il2cppMetadata.ts b/src/domain/il2cpp/il2cppMetadata.ts index b59c22a0b8..b2761b7b3a 100644 --- a/src/domain/il2cpp/il2cppMetadata.ts +++ b/src/domain/il2cpp/il2cppMetadata.ts @@ -7,6 +7,7 @@ import { } from "../localPath.js"; import { canonicalBase64Schema } from "../stringPatterns.js"; import type { MachoSliceArchitecture } from "../apple/machoTargetSelection.js"; +import type { AnalysisParameterLimit } from "../analysisSettings.js"; import { firstDeclaringTypeCycle } from "./il2cppDeclaringTypes.js"; /** The public `binary_architecture` values, in the native reader's spelling. */ @@ -25,6 +26,33 @@ export const IL2CPP_SLICE_SELECTORS = { >; export type Il2cppBinaryArchitecture = keyof typeof IL2CPP_SLICE_SELECTORS; +/** + * Estimated representation bytes admitted for an ELF binary's virtual pointer + * index when `max_native_index_bytes` is omitted. The index reserves a fixed + * logical charge per distinct relocated address, so this default admits + * 524,288 addresses. It is an REA admission policy, not a format limit. + */ +export const DEFAULT_IL2CPP_NATIVE_INDEX_BYTES = 1024 * 1024 * 1024; + +/** + * The per-call control that bounded the ELF virtual pointer index, named by + * its contract field; each adapter names the option that sets it. The + * accounting is exact safe-integer arithmetic, so the control has no smaller + * maximum; host heap remains an independent constraint. + */ +export const il2cppNativeIndexLimit = ( + effectiveBytes: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter: "max_native_index_bytes", + effective_value: effectiveBytes, + unit: "bytes", + minimum: 1, + maximum: Number.MAX_SAFE_INTEGER, + default_value: DEFAULT_IL2CPP_NATIVE_INDEX_BYTES, + applies_at: "next_call", +}); + /** Unsigned little-endian signature observed at file offset zero. */ export const IL2CPP_METADATA_MAGIC = 0xfab11baf; @@ -135,6 +163,14 @@ export const inspectIl2cppMetadataInputSchema = requirePresence( .describe( "Also link generic method instances (genericMethodTable rows) to code addresses with Il2CppDumper-style Type$$Method names; needs binary_path", ), + max_native_index_bytes: z + .int() + .positive() + .max(Number.MAX_SAFE_INTEGER) + .optional() + .describe( + `Estimated bytes admitted for an ELF binary_path's relocated-pointer index, charged per distinct relocated address; omitted means ${String(DEFAULT_IL2CPP_NATIVE_INDEX_BYTES)} (1 GiB). Raise it on the next call when linking stops at this allowance; no restart. Host memory and the binary file allowance stay independent. Needs binary_path`, + ), }), [ { @@ -148,6 +184,12 @@ export const inspectIl2cppMetadataInputSchema = requirePresence( requires: "binary_path", message: "generic_instances links generic methods in binary_path.", }, + { + when: "max_native_index_bytes", + requires: "binary_path", + message: + "max_native_index_bytes bounds the pointer index of binary_path.", + }, ], ); diff --git a/src/domain/native/elfDebugLink.ts b/src/domain/native/elfDebugLink.ts index a35ce6e3dd..eae673f0c6 100644 --- a/src/domain/native/elfDebugLink.ts +++ b/src/domain/native/elfDebugLink.ts @@ -4,6 +4,11 @@ import { digestSchema } from "../digests.js"; import { absoluteLocalPathStringSchema } from "../localPath.js"; import { ELF_OBJECT_TYPE_NAMES } from "./elfNotes.js"; import { coverageStatusSchema } from "../coverage.js"; +import { + DEFAULT_ELF_READ_FILE_BYTES, + MINIMUM_ELF_READ_FILE_BYTES, + type ElfReadBudgets, +} from "./elfReadBudgets.js"; const uint = z.number().int().min(0).max(0xffffffff); const crc32Hex = z.string().regex(/^[0-9a-f]{8}$/u); @@ -15,6 +20,20 @@ export const MAX_INSPECT_ELF_DEBUG_LINK_FILE_BYTES = 536870912; export const MAX_INSPECT_ELF_DEBUG_LINK_ENTRIES = 256; /** Default note entry budget; admits distribution glibc and its SystemTap probe notes. */ export const DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES = 128; + +/** The per-call budgets `inspect_elf_debug_link` accepts, shared by its schema and refusals. */ +export const ELF_DEBUG_LINK_READ_BUDGETS: ElfReadBudgets = { + max_file_bytes: { + minimum: MINIMUM_ELF_READ_FILE_BYTES, + maximum: MAX_INSPECT_ELF_DEBUG_LINK_FILE_BYTES, + default_value: DEFAULT_ELF_READ_FILE_BYTES, + }, + max_entries: { + minimum: 1, + maximum: MAX_INSPECT_ELF_DEBUG_LINK_ENTRIES, + default_value: DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES, + }, +}; /** Retained debuglink and debugaltlink file-name length. */ export const MAX_ELF_DEBUG_LINK_NAME_BYTES = 4096; /** Retained build-id length for debugaltlink and GNU notes. */ @@ -182,16 +201,16 @@ export const inspectElfDebugLinkInputSchema = z.strictObject({ max_file_bytes: z .number() .int() - .min(64) - .max(MAX_INSPECT_ELF_DEBUG_LINK_FILE_BYTES) - .default(67108864) + .min(ELF_DEBUG_LINK_READ_BUDGETS.max_file_bytes.minimum) + .max(ELF_DEBUG_LINK_READ_BUDGETS.max_file_bytes.maximum) + .default(ELF_DEBUG_LINK_READ_BUDGETS.max_file_bytes.default_value) .describe("Maximum stable artifact bytes to read (default 64 MiB)"), max_entries: z .number() .int() - .min(1) - .max(MAX_INSPECT_ELF_DEBUG_LINK_ENTRIES) - .default(DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES) + .min(ELF_DEBUG_LINK_READ_BUDGETS.max_entries.minimum) + .max(ELF_DEBUG_LINK_READ_BUDGETS.max_entries.maximum) + .default(ELF_DEBUG_LINK_READ_BUDGETS.max_entries.default_value) .describe( "Maximum note entries to examine while reading GNU build-ids; an image exceeding the budget fails without partial success, and a candidate exceeding it leaves its build-id check unavailable", ), diff --git a/src/domain/native/elfNotes.ts b/src/domain/native/elfNotes.ts index edb96e9f5b..0aee1d5513 100644 --- a/src/domain/native/elfNotes.ts +++ b/src/domain/native/elfNotes.ts @@ -3,6 +3,11 @@ import { z } from "zod"; import { digestSchema } from "../digests.js"; import { jsonObjectSchema } from "../jsonValue.js"; import { absoluteLocalPathStringSchema } from "../localPath.js"; +import { + DEFAULT_ELF_READ_FILE_BYTES, + MINIMUM_ELF_READ_FILE_BYTES, + type ElfReadBudgets, +} from "./elfReadBudgets.js"; const uint = z.number().int().min(0).max(0xffffffff); const range = z.strictObject({ offset: uint, bytes: uint }); @@ -19,6 +24,20 @@ export const MAX_INSPECT_ELF_NOTE_ENTRIES = 256; */ export const DEFAULT_INSPECT_ELF_NOTE_ENTRIES = 128; +/** The per-call budgets `inspect_elf_notes` accepts, shared by its schema and refusals. */ +export const ELF_NOTES_READ_BUDGETS: ElfReadBudgets = { + max_file_bytes: { + minimum: MINIMUM_ELF_READ_FILE_BYTES, + maximum: MAX_INSPECT_ELF_NOTE_FILE_BYTES, + default_value: DEFAULT_ELF_READ_FILE_BYTES, + }, + max_entries: { + minimum: 1, + maximum: MAX_INSPECT_ELF_NOTE_ENTRIES, + default_value: DEFAULT_INSPECT_ELF_NOTE_ENTRIES, + }, +}; + export const ELF_NOTE_TYPE_NAMES = [ "gnu_abi_tag", "gnu_hwcap", @@ -130,16 +149,16 @@ export const inspectElfNotesInputSchema = z.strictObject({ max_file_bytes: z .number() .int() - .min(64) - .max(MAX_INSPECT_ELF_NOTE_FILE_BYTES) - .default(67108864) + .min(ELF_NOTES_READ_BUDGETS.max_file_bytes.minimum) + .max(ELF_NOTES_READ_BUDGETS.max_file_bytes.maximum) + .default(ELF_NOTES_READ_BUDGETS.max_file_bytes.default_value) .describe("Maximum stable artifact bytes to read (default 64 MiB)"), max_entries: z .number() .int() - .min(1) - .max(MAX_INSPECT_ELF_NOTE_ENTRIES) - .default(DEFAULT_INSPECT_ELF_NOTE_ENTRIES) + .min(ELF_NOTES_READ_BUDGETS.max_entries.minimum) + .max(ELF_NOTES_READ_BUDGETS.max_entries.maximum) + .default(ELF_NOTES_READ_BUDGETS.max_entries.default_value) .describe( "Maximum note entries to examine across every table; exceeding the budget fails without partial success", ), diff --git a/src/domain/native/elfPointerRelocations.test.ts b/src/domain/native/elfPointerRelocations.test.ts index 6a509c502c..da52c32592 100644 --- a/src/domain/native/elfPointerRelocations.test.ts +++ b/src/domain/native/elfPointerRelocations.test.ts @@ -772,7 +772,9 @@ it("refuses pointer workspace growth before inserting the next virtual destinati failure: expect.objectContaining({ kind: "limit", format: "elf-pointer-relocations", - limit: { name: "native-index-capacity", maximum: 4096 }, + // The caller selected this allowance, so it names it separately + // from the loader's fixed capacities. + limit: { name: "virtual-pointer-index-bytes", maximum: 4096 }, }), unit: "bytes", message: expect.stringContaining("4096 estimated representation bytes"), diff --git a/src/domain/native/elfPointerRelocations.ts b/src/domain/native/elfPointerRelocations.ts index a0676b0102..b6dcc122e6 100644 --- a/src/domain/native/elfPointerRelocations.ts +++ b/src/domain/native/elfPointerRelocations.ts @@ -31,6 +31,13 @@ import { ParseFailureError } from "../parseFailure.js"; /** The ParseFailure format of ELF loader pointer interpretation. */ export const ELF_POINTER_RELOCATION_FORMAT = "elf-pointer-relocations"; +/** + * Limit name of the caller-selected virtual pointer index allowance, so a + * consumer can name its own control for it. The loader's fixed allowances keep + * `native-index-capacity` as their limit name. + */ +export const ELF_VIRTUAL_POINTER_INDEX_LIMIT = "virtual-pointer-index-bytes"; + /** * Shared loader interpretation; language adapters choose their public errors. * The stable `reason` names the loader rule; `native-index-capacity` is a @@ -53,6 +60,7 @@ export class ElfPointerRelocationFailure extends ParseFailureError< message: string, maximum: number, unit: "entries" | "bytes", + limitName?: typeof ELF_VIRTUAL_POINTER_INDEX_LIMIT, ); constructor( readonly reason: @@ -63,11 +71,12 @@ export class ElfPointerRelocationFailure extends ParseFailureError< message: string, maximum?: number, unit?: "entries" | "bytes", + limitName: string = reason, ) { const facts = { format: ELF_POINTER_RELOCATION_FORMAT, detail: message }; super( maximum !== undefined - ? { ...facts, kind: "limit", limit: { name: reason, maximum } } + ? { ...facts, kind: "limit", limit: { name: limitName, maximum } } : reason === "malformed-container" ? { ...facts, kind: "malformed" } : { @@ -1059,6 +1068,8 @@ class ElfVirtualWriteIndex { readonly word: 4 | 8, readonly little: boolean, readonly maximumBytes: number, + /** Set when the caller selected `maximumBytes` and names its own control. */ + readonly selectedLimit?: typeof ELF_VIRTUAL_POINTER_INDEX_LIMIT, ) {} add({ address, @@ -1077,6 +1088,7 @@ class ElfVirtualWriteIndex { `ELF virtual pointer index exceeds ${this.maximumBytes} estimated representation bytes (${ELF_POINTER_INDEX_ENTRY_BYTES} reserved per virtual address, including lookup workspace)`, this.maximumBytes, "bytes", + this.selectedLimit, ); this.#reservedBytes += ELF_POINTER_INDEX_ENTRY_BYTES; } @@ -1299,6 +1311,8 @@ export function* readElfPointerRelocationsSteps( /** Value-only consumers keep input-bounded file-backed writes without per-record * provenance, with a separate allowance for unresolved and zero-fill state. + * `maximumIndexBytes` is the caller's selected allowance: its refusal carries + * `ELF_VIRTUAL_POINTER_INDEX_LIMIT` so the caller can name its control. */ export function* readElfPointerValuesSteps( bytes: Buffer, @@ -1310,6 +1324,7 @@ export function* readElfPointerValuesSteps( input.bits === 64 ? 8 : 4, input.little, maximumIndexBytes, + ELF_VIRTUAL_POINTER_INDEX_LIMIT, ); const zeroFill = new Set(); const steps = readElfRelocationWritesSteps(bytes, input, { diff --git a/src/domain/native/elfReadBudgets.ts b/src/domain/native/elfReadBudgets.ts new file mode 100644 index 0000000000..faf1e5b118 --- /dev/null +++ b/src/domain/native/elfReadBudgets.ts @@ -0,0 +1,38 @@ +import type { AnalysisParameterLimit } from "../analysisSettings.js"; + +/** A caller-selected ELF reader budget: its schema bounds and omitted value. */ +export interface ElfReadBudgetBounds { + readonly minimum: number; + readonly maximum: number; + readonly default_value: number; +} + +/** The per-call read budgets an ELF note reader accepts. */ +export interface ElfReadBudgets { + readonly max_file_bytes: ElfReadBudgetBounds; + readonly max_entries: ElfReadBudgetBounds; +} + +/** Smallest `max_file_bytes`: an ELF64 file header. */ +export const MINIMUM_ELF_READ_FILE_BYTES = 64; + +/** `max_file_bytes` when omitted. */ +export const DEFAULT_ELF_READ_FILE_BYTES = 64 * 1024 * 1024; + +/** + * The per-call control that stopped an ELF reader, named by its contract + * field; each adapter names the option that sets it. The schema owns the same + * bounds, so the reported range is the one the next call accepts. + */ +export const elfReadBudgetLimit = ( + budgets: ElfReadBudgets, + parameter: keyof ElfReadBudgets, + effectiveValue: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter, + effective_value: effectiveValue, + unit: parameter === "max_file_bytes" ? "bytes" : "count", + ...budgets[parameter], + applies_at: "next_call", +}); diff --git a/src/il2cpp/Il2cppBinaryFile.ts b/src/il2cpp/Il2cppBinaryFile.ts index c30310bbed..4a3920aae4 100644 --- a/src/il2cpp/Il2cppBinaryFile.ts +++ b/src/il2cpp/Il2cppBinaryFile.ts @@ -78,6 +78,8 @@ export type Il2cppBinaryReadOptions = Pick< > & { /** Also link genericMethodTable rows; unrequested paths read no generic table. */ readonly genericInstances?: boolean; + /** Caller's ELF pointer index allowance (`max_native_index_bytes`). */ + readonly maxNativeIndexBytes?: number; }; const assertGenericLinkLayout = ( @@ -101,7 +103,12 @@ export function* linkIl2cppBinarySteps( ): Generator { assertGenericLinkLayout(metadata, options); yield; - return yield* linkImageSteps(openImageSteps(bytes), metadata, facts, options); + return yield* linkImageSteps( + openImageSteps(bytes, undefined, options.maxNativeIndexBytes), + metadata, + facts, + options, + ); } export const linkIl2cppBinaryCooperative = async ( @@ -115,7 +122,7 @@ export const linkIl2cppBinaryCooperative = async ( await pause(); const container = await readIl2cppBinaryContainerCooperative(bytes, pause); const steps = linkImageSteps( - openImageSteps(bytes, container), + openImageSteps(bytes, container, options.maxNativeIndexBytes), metadata, facts, options, diff --git a/src/il2cpp/Il2cppBinaryFormat.ts b/src/il2cpp/Il2cppBinaryFormat.ts index 081d33a54c..1abbb5701d 100644 --- a/src/il2cpp/Il2cppBinaryFormat.ts +++ b/src/il2cpp/Il2cppBinaryFormat.ts @@ -1,6 +1,9 @@ import { ParseFailureError } from "../domain/parseFailure.js"; -/** Existing selected-binary allowance also bounds its retained pointer workspace. */ +/** + * Selected-binary file allowance. The ELF pointer index has its own per-call + * control, `max_native_index_bytes`. + */ export const IL2CPP_BINARY_BYTES = 1024 * 1024 * 1024; export const IL2CPP_BINARY_FAILURE_REASONS = { @@ -79,12 +82,15 @@ export class Il2cppBinaryFormatFailure extends ParseFailureError< message: string, maximum: number, unit: NativeBudgetUnit, + limitName?: string, ); constructor( readonly reason: Il2cppBinaryFailureReason, message: string, maximum?: number, unit?: NativeBudgetUnit, + /** The exceeded budget's name; defaults to the reason for a fixed budget. */ + limitName: string = reason, ) { const detail = `${reason}: ${message}`; super( @@ -93,7 +99,7 @@ export class Il2cppBinaryFormatFailure extends ParseFailureError< kind: "limit", format: IL2CPP_BINARY_FORMAT, detail, - limit: { name: reason, maximum }, + limit: { name: limitName, maximum }, } : isUnsupported(reason as Il2cppBinaryFormatReason) ? { diff --git a/src/il2cpp/Il2cppBinaryImage.ts b/src/il2cpp/Il2cppBinaryImage.ts index a32604324a..d2610cad8e 100644 --- a/src/il2cpp/Il2cppBinaryImage.ts +++ b/src/il2cpp/Il2cppBinaryImage.ts @@ -34,10 +34,8 @@ import { ElfPointerRelocationFailure, type ElfVirtualPointerWrites, } from "../domain/native/elfPointerRelocations.js"; -import { - Il2cppBinaryFormatFailure, - IL2CPP_BINARY_BYTES, -} from "./Il2cppBinaryFormat.js"; +import { DEFAULT_IL2CPP_NATIVE_INDEX_BYTES } from "../domain/il2cpp/il2cppMetadata.js"; +import { Il2cppBinaryFormatFailure } from "./Il2cppBinaryFormat.js"; /** Selection failures name the binary's architecture input and IL2CPP's public spellings. */ const IL2CPP_SLICE_SELECTION_INPUT: SliceSelectionInput = { @@ -126,10 +124,14 @@ export const readIl2cppBinaryContainerCooperative = async ( } }; -/** Open one thin image; a universal Mach-O slice is selected before this. */ +/** + * Open one thin image; a universal Mach-O slice is selected before this. + * `maximumIndexBytes` is the caller's ELF pointer index allowance. + */ export function* openImageSteps( image: Buffer, preparedContainer?: BinaryContainer, + maximumIndexBytes: number = DEFAULT_IL2CPP_NATIVE_INDEX_BYTES, ): Generator { const container = preparedContainer ?? readContainer(image); if (container.bits !== 64 || container.byte_order !== "little") @@ -150,7 +152,7 @@ export function* openImageSteps( mappings: container.mappings, zeroFills: container.zero_fills, }, - IL2CPP_BINARY_BYTES, + maximumIndexBytes, { symbolResolution: "image-definitions" }, ); } catch (cause) { @@ -161,6 +163,7 @@ export function* openImageSteps( cause.message, cause.failure.limit.maximum, cause.unit, + cause.failure.limit.name, ); if (cause.reason !== "native-index-capacity") throw new Il2cppBinaryFormatFailure(cause.reason, cause.message); diff --git a/src/il2cpp/Il2cppMetadataProvider.ts b/src/il2cpp/Il2cppMetadataProvider.ts index e3d42af2c8..ff723f445a 100644 --- a/src/il2cpp/Il2cppMetadataProvider.ts +++ b/src/il2cpp/Il2cppMetadataProvider.ts @@ -50,9 +50,11 @@ import { } from "../domain/analysisErrorCore.js"; import { il2cppMetadataSchema, + il2cppNativeIndexLimit, type Il2cppMetadata, type Il2cppMetadataProviderInput, } from "../domain/il2cpp/il2cppMetadata.js"; +import { ELF_VIRTUAL_POINTER_INDEX_LIMIT } from "../domain/native/elfPointerRelocations.js"; import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; @@ -120,6 +122,18 @@ const failureForPrimary = ( const { cause, origin } = facts; if (origin === "owned-or-classified" && cause instanceof AnalysisError) return cause; + if ( + cause instanceof Il2cppBinaryFormatFailure && + isParseLimit(cause, IL2CPP_BINARY_FORMAT) && + cause.failure.limit.name === ELF_VIRTUAL_POINTER_INDEX_LIMIT + ) { + const selected = cause.failure.limit.maximum; + return parseLimitConstraint(OPERATION, "memory", cause, { + retryable: false, + limit: il2cppNativeIndexLimit(selected), + remediationAction: `The ELF pointer index allowance is max_native_index_bytes = ${String(selected)} bytes. Pass a larger max_native_index_bytes (up to ${String(Number.MAX_SAFE_INTEGER)}) on the next ${OPERATION} call with the same binary_path; no restart is required. Host memory and the binary file allowance are independent. Repeating the unchanged request fails the same way.`, + }); + } if ( cause instanceof Il2cppBinaryFormatFailure && isParseLimit(cause, IL2CPP_BINARY_FORMAT) @@ -598,6 +612,9 @@ export class Il2cppMetadataProvider implements Il2cppMetadataPort { { ...admission, genericInstances: input.generic_instances === true, + ...(input.max_native_index_bytes === undefined + ? {} + : { maxNativeIndexBytes: input.max_native_index_bytes }), }, async () => { await this.yieldControl(); diff --git a/src/native/elf/ElfDebugLinkProvider.ts b/src/native/elf/ElfDebugLinkProvider.ts index efaf48d107..dd3276e84e 100644 --- a/src/native/elf/ElfDebugLinkProvider.ts +++ b/src/native/elf/ElfDebugLinkProvider.ts @@ -23,6 +23,7 @@ import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js import { ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, + ELF_DEBUG_LINK_READ_BUDGETS, MAX_ELF_DEBUG_CANDIDATE_BYTES, MAX_INSPECT_ELF_DEBUG_LINK_ENTRIES, MAX_INSPECT_ELF_DEBUG_LINK_FILE_BYTES, @@ -46,6 +47,7 @@ import { } from "./ElfDebugLink.js"; import { ELF_NOTE_TEXT_ALLOWANCE } from "./ElfNoteParser.js"; import { elfSectionNameBudget } from "../../domain/native/elfSectionNameTable.js"; +import { elfReadBudgetLimit } from "../../domain/native/elfReadBudgets.js"; const OPERATION = "inspect_elf_debug_link"; const HEADER_PREFIX_BYTES = 4096; @@ -353,6 +355,11 @@ const elfDebugLinkFailure = ( if (isParseLimit(failure, "elf") && sectionNameBudget !== undefined) return parseLimitConstraint(OPERATION, "memory", failure, { retryable: false, + limit: elfReadBudgetLimit( + ELF_DEBUG_LINK_READ_BUDGETS, + "max_file_bytes", + input.max_file_bytes, + ), remediationAction: sectionNameBudgetRemediation( sectionNameBudget.required, field, @@ -378,6 +385,11 @@ const elfDebugLinkFailure = ( entryBudget ? { retryable: false, + limit: elfReadBudgetLimit( + ELF_DEBUG_LINK_READ_BUDGETS, + "max_entries", + input.max_entries, + ), remediationAction: inputBudgetRemediation( "capacity", input, @@ -419,6 +431,11 @@ const elfDebugLinkFailure = ( ) : { retryable: false, + limit: elfReadBudgetLimit( + ELF_DEBUG_LINK_READ_BUDGETS, + "max_file_bytes", + input.max_file_bytes, + ), remediationAction: inputBudgetRemediation( "file-size", input, diff --git a/src/native/elf/ElfNotesProvider.ts b/src/native/elf/ElfNotesProvider.ts index 1d78b7c6be..730c6366c4 100644 --- a/src/native/elf/ElfNotesProvider.ts +++ b/src/native/elf/ElfNotesProvider.ts @@ -21,11 +21,13 @@ import { } from "../../domain/compression/zstandardFrameAllowance.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { + ELF_NOTES_READ_BUDGETS, MAX_INSPECT_ELF_NOTE_ENTRIES, MAX_INSPECT_ELF_NOTE_FILE_BYTES, type ElfNotes, type InspectElfNotesInput, } from "../../domain/native/elfNotes.js"; +import { elfReadBudgetLimit } from "../../domain/native/elfReadBudgets.js"; import { err, ok } from "../../domain/result.js"; import { ELF_NOTES_PROVIDER } from "../../domain/investigationProviders.js"; import { elfSectionNameBudget } from "../../domain/native/elfSectionNameTable.js"; @@ -138,6 +140,11 @@ const elfNotesFailure = ( if (isParseLimit(failure, "elf") && sectionNameBudget !== undefined) return parseLimitConstraint(OPERATION, "memory", failure, { retryable: false, + limit: elfReadBudgetLimit( + ELF_NOTES_READ_BUDGETS, + "max_file_bytes", + input.max_file_bytes, + ), remediationAction: sectionNameBudgetRemediation( sectionNameBudget.required, ), @@ -151,6 +158,11 @@ const elfNotesFailure = ( entryBudget ? { retryable: false, + limit: elfReadBudgetLimit( + ELF_NOTES_READ_BUDGETS, + "max_entries", + input.max_entries, + ), remediationAction: inputBudgetRemediation("capacity", input), } : fixedAllowanceOptions(ELF_NOTE_TEXT_ALLOWANCE, "parser", { @@ -173,6 +185,11 @@ const elfNotesFailure = ( ), { retryable: false, + limit: elfReadBudgetLimit( + ELF_NOTES_READ_BUDGETS, + "max_file_bytes", + input.max_file_bytes, + ), remediationAction: inputBudgetRemediation("file-size", input), }, ), diff --git a/tests/boundary/filesystem/elfDebugLink.test.ts b/tests/boundary/filesystem/elfDebugLink.test.ts index 3eeb5ae319..8171cdf752 100644 --- a/tests/boundary/filesystem/elfDebugLink.test.ts +++ b/tests/boundary/filesystem/elfDebugLink.test.ts @@ -189,11 +189,32 @@ describe("ELF debug-link stable filesystem boundary", () => { const tooSmall = await service.inspect({ path, max_file_bytes: 64 }); if (tooSmall.ok) throw new Error("Expected resource budget failure"); expect(tooSmall.error._tag).toBe("AnalysisResourceConstraintError"); + expect(projectAnalysisError(tooSmall.error).details).toMatchObject({ + limit: { + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: 64, + minimum: 64, + maximum: 536870912, + default_value: 67108864, + }, + }); const tooMany = await service.inspect({ path, max_entries: 1 }); if (tooMany.ok) throw new Error("Expected entry budget failure"); if (!(tooMany.error instanceof AnalysisResourceConstraintError)) throw new Error("Expected entry budget failure"); expect(tooMany.error.remediationAction).toContain("smaller image"); + expect(tooMany.error.limit).toEqual({ + control_kind: "parameter", + parameter: "max_entries", + effective_value: 1, + unit: "count", + minimum: 1, + maximum: 256, + default_value: 128, + applies_at: "next_call", + }); + expect((await service.inspect({ path, max_entries: 2 })).ok).toBe(true); const cancelled = await service.inspect( { path }, { signal: AbortSignal.abort() }, diff --git a/tests/boundary/filesystem/elfNotes.test.ts b/tests/boundary/filesystem/elfNotes.test.ts index fa1e4b38dd..7a0ec19fce 100644 --- a/tests/boundary/filesystem/elfNotes.test.ts +++ b/tests/boundary/filesystem/elfNotes.test.ts @@ -2,6 +2,7 @@ import { symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { createElfNotesService } from "../../../src/composition/binaryDiagnostics/elfNotes.js"; +import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { elfNoteFixture } from "../../../src/native/elf/ElfNotes.fixture.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -43,6 +44,36 @@ describe("ELF note stable filesystem boundary", () => { const tooSmall = await service.inspect({ path, max_file_bytes: 64 }); if (tooSmall.ok) throw new Error("Expected resource budget failure"); expect(tooSmall.error._tag).toBe("AnalysisResourceConstraintError"); + // The refusal names the per-call control that stopped it, so a caller + // can raise it without parsing the remediation text. + expect(projectAnalysisError(tooSmall.error).details).toMatchObject({ + limit: { + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: 64, + unit: "bytes", + minimum: 64, + maximum: 536870912, + default_value: 67108864, + applies_at: "next_call", + }, + }); + const fewEntries = await service.inspect({ path, max_entries: 1 }); + if (fewEntries.ok) throw new Error("Expected note entry budget failure"); + expect(projectAnalysisError(fewEntries.error).details).toMatchObject({ + limit: { + control_kind: "parameter", + parameter: "max_entries", + effective_value: 1, + unit: "count", + minimum: 1, + maximum: 256, + default_value: 128, + applies_at: "next_call", + }, + }); + // Both controls admit the same file once raised. + expect((await service.inspect({ path, max_entries: 256 })).ok).toBe(true); const cancelled = await service.inspect( { path }, { signal: AbortSignal.abort() }, diff --git a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts index c5750e12c8..db04b5a476 100644 --- a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts +++ b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts @@ -16,7 +16,10 @@ import { Il2cppMetadataProvider } from "../../../src/il2cpp/Il2cppMetadataProvid import { inspectIl2cppMetadataV108 } from "../../../src/il2cpp/Il2cppMetadataV108.js"; import { Il2cppGhidraSeedWriter } from "../../../src/il2cpp/Il2cppGhidraSeedWriter.js"; import { Il2cppMetadataService } from "../../../src/application/il2cpp/Il2cppMetadataService.js"; -import { il2cppMetadataSchema } from "../../../src/domain/il2cpp/il2cppMetadata.js"; +import { + il2cppMetadataSchema, + inspectIl2cppMetadataInputSchema, +} from "../../../src/domain/il2cpp/il2cppMetadata.js"; import * as zstandard from "../../../src/domain/compression/zstandardExactFrame.js"; import { createElfFixture, @@ -1241,6 +1244,72 @@ it("refuses generic rows that exceed the report budget and keeps the requested p } }); +it("bounds the ELF pointer index by the caller's max_native_index_bytes", async () => { + const root = await createTestTempDirectory("rea-il2cpp-index-budget-"); + const path = join(root, "global-metadata.dat"); + const binaryPath = join(root, "libil2cpp.so"); + await writeFile(path, createLinkedIl2cppMetadataFixture().bytes); + await writeFile(binaryPath, createElfFixture(createIl2cppBinaryFixture())); + const provider = new Il2cppMetadataProvider(); + try { + // One 2 KiB reservation admits a single relocated address; the fixture + // relocates several, so the selected allowance stops linking. + const refused = await provider.inspect({ + path, + binary_path: binaryPath, + max_native_index_bytes: 2048, + }); + if (refused.ok) throw new Error("Expected the pointer index refusal"); + expect(refused.error).toBeInstanceOf(AnalysisResourceConstraintError); + expect(refused.error).toMatchObject({ + resource: "memory", + retryable: false, + fixedAllowance: undefined, + reportedLimits: { + boundary: "virtual-pointer-index-bytes", + maximum: 2048, + }, + limit: { + control_kind: "parameter", + parameter: "max_native_index_bytes", + effective_value: 2048, + unit: "bytes", + minimum: 1, + maximum: Number.MAX_SAFE_INTEGER, + default_value: 1024 * 1024 * 1024, + applies_at: "next_call", + }, + }); + // The same complete pair links once the caller raises the allowance, + // and the default admits it without any selection. + expect( + ( + await provider.inspect({ + path, + binary_path: binaryPath, + max_native_index_bytes: 1024 * 1024, + }) + ).ok, + ).toBe(true); + expect((await provider.inspect({ path, binary_path: binaryPath })).ok).toBe( + true, + ); + } finally { + await provider.close(); + } +}); + +it("refuses max_native_index_bytes without binary_path", () => { + const parsed = inspectIl2cppMetadataInputSchema.safeParse({ + path: "/tmp/global-metadata.dat", + max_native_index_bytes: 4096, + }); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues).toEqual([ + expect.objectContaining({ path: ["max_native_index_bytes"] }), + ]); +}); + it("reports the exceeded native-link maximum in the public refusal", async () => { const root = await createTestTempDirectory("rea-il2cpp-link-limit-"); const path = join(root, "global-metadata.dat"); diff --git a/tests/evaluation/fixedCeilingGuard.test.ts b/tests/evaluation/fixedCeilingGuard.test.ts new file mode 100644 index 0000000000..0f0d2baed0 --- /dev/null +++ b/tests/evaluation/fixedCeilingGuard.test.ts @@ -0,0 +1,134 @@ +import { access, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it } from "vitest"; +import { + authoredOnlyRefusalCount, + fixedCeilingDeclarations, +} from "../../scripts/verify/fixed-ceiling-guard.mjs"; +import { + checkAuthoredOnlyBaseline, + compareAuthoredOnlyRefusals, + compareFixedCeilings, +} from "../../scripts/verify/fixed-ceilings.mjs"; +import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; + +const PATH = "src/probe/Probe.ts"; + +it("finds each fixed-ceiling declaration by the allowance it names", () => { + const found = fixedCeilingDeclarations( + [ + 'const a = fixedAllowanceOptions("The probe table allowance", "count", { limit: 4 });', + // The producer input helper takes the bytes first and the name second. + 'const b = fixedProducerInputAllowance(MAX_PROBE_BYTES, "The probe input allowance");', + 'const c = artifactFixedLimitFailure({ name: "The probe path allowance", kind: "parser" }, "x");', + 'const d = { fixedAllowance: { name:\n "The inline allowance", kind: "capture" } };', + // Forwarding an existing allowance declares nothing. + "const e = { fixedAllowance: cause.fixedAllowance };", + // A wrapper's callers declare their own allowances. + 'const f = fixedNativeAllowance("The probe native allowance", "parser", 8, "bytes");', + ].join("\n"), + PATH, + ); + expect([...found.keys()]).toEqual([ + '"The probe table allowance"', + '"The probe input allowance"', + '"The probe path allowance"', + '"The inline allowance"', + '"The probe native allowance"', + ]); + expect(found.get('"The inline allowance"')).toBe(4); +}); + +it("counts refusals whose only recovery is authored prose", () => { + const authored = [ + 'new AnalysisResourceConstraintError(op, "memory", m, {}, { retryable: false, remediationAction: "Raise max_entries." });', + 'parseLimitConstraint(op, "capacity", cause, { remediationAction: "Raise max_depth." });', + // A conditional chooses between option objects; each branch counts. + 'parseLimitConstraint(op, "capacity", cause, entries ? { remediationAction: "Raise max_entries." } : fixedAllowanceOptions("x", "parser"));', + ].join("\n"); + expect(authoredOnlyRefusalCount(authored, PATH)).toBe(3); + const owned = [ + 'new AnalysisResourceConstraintError(op, "memory", m, {}, { limit, remediationAction: "Raise it." });', + 'parseLimitConstraint(op, "memory", cause, { ...fixedAllowanceOptions("x", "parser") });', + 'new AnalysisResourceConstraintError(op, "capacity", m, {}, { measuredExhaustion: true, remediationAction: "Wait." });', + // Options built elsewhere are trusted, as the typed-refusal lint rule trusts them. + 'parseLimitConstraint(op, "memory", cause, recovery(input));', + ].join("\n"); + expect(authoredOnlyRefusalCount(owned, PATH)).toBe(0); +}); + +it("requires every declaration to be registered with a class and reason", () => { + const declarations = new Map([ + [ + PATH, + new Map([ + ['"The probe table allowance"', 3], + ['"The probe frame"', 9], + ]), + ], + ]); + expect( + compareFixedCeilings(declarations, { + [PATH]: { + '"The probe frame"': { + class: "protocol", + reason: "The stdio frame floor.", + }, + }, + }), + ).toEqual([ + expect.stringContaining( + `${PATH}:3 declares fixed ceiling "The probe table allowance"`, + ), + ]); + expect( + compareFixedCeilings(declarations, { + [PATH]: { + '"The probe table allowance"': { class: "pending", reason: "Policy." }, + '"The probe frame"': { class: "bytes", reason: "" }, + '"A removed allowance"': { class: "format", reason: "Gone." }, + }, + }), + ).toEqual([ + expect.stringContaining("names no tracking issue"), + expect.stringContaining('has class "bytes"'), + expect.stringContaining("states no reason"), + expect.stringContaining("remove the stale entry"), + ]); +}); + +it("lets the authored-only refusal count shrink but never grow", () => { + const grown = compareAuthoredOnlyRefusals( + new Map([[PATH, 2]]), + { [PATH]: 1 }, + false, + ); + expect(grown.failures).toEqual([ + expect.stringContaining(`${PATH}: 2 (baseline 1)`), + ]); + expect( + compareAuthoredOnlyRefusals(new Map(), { [PATH]: 1 }, false).failures, + ).toEqual([expect.stringContaining("--shrink-baselines")]); + expect(compareAuthoredOnlyRefusals(new Map(), { [PATH]: 1 }, true)).toEqual({ + failures: [], + baseline: {}, + }); +}); + +it("deletes the baseline when its last authored-only refusal is removed", async () => { + const root = await createTestTempDirectory("rea-fixed-ceiling-baseline-"); + const path = join(root, "untyped-budget-refusal-baseline.json"); + await writeFile(path, `${JSON.stringify({ [PATH]: 1 }, null, 2)}\n`); + // Without shrinking, the removed refusal is reported as stale. + expect(await checkAuthoredOnlyBaseline(path, new Map(), false)).toEqual([ + expect.stringContaining("--shrink-baselines"), + ]); + // Shrinking removes the file, and the next run treats it as empty. + expect(await checkAuthoredOnlyBaseline(path, new Map(), true)).toEqual([]); + await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" }); + expect(await checkAuthoredOnlyBaseline(path, new Map(), false)).toEqual([]); + // A new refusal still fails against the absent baseline. + expect( + await checkAuthoredOnlyBaseline(path, new Map([[PATH, 1]]), false), + ).toEqual([expect.stringContaining(`${PATH}: 1 (baseline 0)`)]); +});