Merge branch 'w5c-10634' into w5c-10757

This commit is contained in:
morluto committed 2026-11-15 00:51:59 -05:00
commit d56a025841
115 files changed
+3622 -1002

No files matched your search

+19
View File
@@ -130,6 +130,18 @@ MAX_FRAME_BYTES, BRIDGE_MAX_REQUEST_BYTES_SOURCE = (
)
def _bridge_source_sha256() -> str | None:
"""Digest this plugin file so REA can tell its packaged copy from another one."""
try:
with open(__file__, "rb") as source:
return hashlib.sha256(source.read()).hexdigest()
except (NameError, OSError):
return None
BRIDGE_SOURCE_SHA256 = _bridge_source_sha256()
def _bridge_max_request_bytes_recovery():
return (
"The effective REA_BRIDGE_MAX_REQUEST_BYTES value is %d bytes "
@@ -544,6 +556,8 @@ class _RequestDispatcher(QObject):
"ok": False,
"error": "active-document-generation-changed",
"execution_state": "not_started",
"document_generation": self.generation,
"output_truncated": False,
})
self._record_command_completion(request_id, "not_started")
request["_event"].set()
@@ -554,6 +568,8 @@ class _RequestDispatcher(QObject):
"ok": False,
"error": "invalid-command",
"execution_state": "not_started",
"document_generation": self.generation,
"output_truncated": False,
})
self._record_command_completion(request_id, "not_started")
request["_event"].set()
@@ -575,6 +591,7 @@ class _RequestDispatcher(QObject):
"cutter_version": self.cutter_version,
"identity_status": "partial",
"execution_state": "complete",
"output_truncated": False,
})
self._record_command_completion(request_id, "complete")
else:
@@ -586,6 +603,7 @@ class _RequestDispatcher(QObject):
"cutter_version": self.cutter_version,
"identity_status": "partial",
"execution_state": "unknown",
"output_truncated": False,
"message": "The command raised an exception; it may have produced partial effects. Do not retry automatically.",
})
self._record_command_completion(request_id, "failed")
@@ -655,6 +673,7 @@ class _BridgeServer(threading.Thread):
"cutter_version": self.dispatcher.cutter_version,
"identity_status": "partial",
"max_request_bytes": MAX_FRAME_BYTES,
"bridge_source_sha256": BRIDGE_SOURCE_SHA256,
}
if os.name == "nt":
_write_windows_descriptor(self.directory, self.descriptor, json.dumps(payload).encode("utf-8"))
@@ -1575,6 +1575,14 @@ because a JSON number cannot carry the sign of zero. `inspect_plist` and
Builder node attributes use the same value. Positive zero and integer zero,
including an `<integer>-0</integer>` literal, remain the number `0`.
A dictionary that declares a key more than once keeps one value in the JSON
result, the last one. When `inspect_plist` decodes binary, XML or OpenStep
source directly, it reads each dictionary's keys before they collapse and adds
a limitation with the count of affected dictionaries and replaced values and the
first repeated key names. Other plist readers may keep a different value. JSON
sources and plists decoded through a `plutil` conversion are not checked:
those parsers keep one value per key before REA sees the result.
Known non-finite reals are reported as
`{ "$plist_type": "real", "value": "nan" | "+infinity" | "-infinity" }`.
These are canonical numeric labels, not a claim about original source spelling.
+1 -1
View File
@@ -453,7 +453,7 @@ The builds checked are listed after the module search rules above.
| `generic-method-registration-not-found` | input error | No CodeRegistration layout bounds every genericMethodTable row, or the generic tables are unreadable. |
| `ambiguous-generic-method-registration` | input error | More than one CodeRegistration layout bounds every genericMethodTable row. |
Format failures name `binary_path` and slice-selection failures name `binary_architecture`; capacity refusals remain typed resource errors. 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, 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.
Format failures name `binary_path` and slice-selection failures name `binary_architecture`; capacity refusals remain typed resource errors whose reported limits name the exceeded budget (`boundary`, the capacity reason) and its maximum in the unit the budget counts (`maximum_entries`, `maximum_bytes` or `maximum_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, 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.
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.
+15
View File
@@ -156,6 +156,11 @@ Each container reader declares its own traversal coverage, including complete
coverage. A traversal that ends without that declaration, or that stops before
its reader finishes, is `unknown` with a limitation naming the reader format;
a complete traversal of one container never covers another.
ZIP members are listed from the central directory. Coverage is `complete` only
when its records account for every byte before the directory (a well-formed
APK signing block is accounted for); otherwise coverage is `unknown` and a
limitation gives the unaccounted bytes, which may hold local entries the
directory does not list.
PyInstaller inventory also preserves distinct table rows that share a logical
path, including decoded children beneath a colliding file/directory path.
Inventory coverage describes observed archive facts; extraction still refuses
@@ -1915,6 +1920,16 @@ occurrence (logical path `.`), recorded as a `dfu-crc32` pair. Under
listed and extractable as observed-untrusted bytes, and `extract_artifact`
returns the root record with the extracted files' records.
A universal Mach-O is inventoried from `lipo -detailed_info`, cross-checked
against REA's own parse of the FAT table. When the two disagree, the default
policy fails with `integrity`. Under `record-and-continue` the disagreement is
reported as an integrity limitation and the slices are enumerated from the FAT
table, whose bytes are authoritative; lipo's ranges are not used, but a matched
row's retained field evidence stays on its slice. A slice lipo did not match is
named from its own CPU identity, qualified by its FAT offset when that name
repeats. When REA cannot parse the FAT table, lipo's rows are inventoried and a
count disagreement makes coverage `unknown`. A malformed FAT table still fails.
If native DMG child traversal is unavailable after carrier identification,
the typed failure retains a revalidated root-only inventory under
`details.partial_observation.inventory`, with unknown child coverage and the
+12
View File
@@ -269,6 +269,13 @@ they use `%LOCALAPPDATA%\REA\CutterBridge` on Windows when `LOCALAPPDATA` is set
and `~/.cache/rea/cutter-bridge` otherwise. The two processes must resolve the
same directory for discovery to find the published sessions.
The plugin publishes the SHA-256 of its own file on its session descriptor.
Discovery reports each session's `bridge_source`: `packaged` when it matches
REA's packaged `bridge/cutter/rea_bridge.py`, `modified` when it differs, and
`unknown` when the plugin predates this field. `cutter_command` refuses a
`modified` session before sending anything and names the packaged plugin to
copy into Cutter's `plugins/python` directory. An `unknown` session still runs.
The client and plugin must support the current v2 handshake; older peers are
rejected before dispatch because they cannot preserve cross-caller recovery proof.
The client checks the final encoded request against
@@ -305,6 +312,11 @@ At most 8 connection threads run. A further accept is closed, and a failure to s
A command reply that does not fit keeps its completion state and document
generation, and reports an oversized path as unknown. Cutter response frames use this same ceiling and
also exclude the terminating LF. A command response the client discards because it exceeds that ceiling stays an unknown execution and sets `output_truncated`, so Evidence records the omitted output. Hopper response reads are unchanged.
`cutter_command` reports `output_truncated` and `document_generation` as `null`
when the plugin did not declare them, for example when no reply was read, the
reply was malformed, or an older plugin omitted them. A null generation means
the document may have changed; list sessions again before choosing an
`expected_generation`. Evidence carries a limitation for each unknown field.
Each bridge request waits 25000 ms. The Cutter hello frame still must arrive
within 1 second. The authenticated command frame is read with one second per
mebibyte of `REA_BRIDGE_MAX_REQUEST_BYTES`, and that read never waits longer
@@ -7,6 +7,5 @@
"src/model/ModelArtifactProvider.ts": 1,
"src/native/NativeMacOSProvider.ts": 1,
"src/native/NativePlistSource.ts": 1,
"src/server/http/NodeHttpRequestOwner.ts": 1,
"src/sqlite/SqliteDatabaseWorkerExecution.ts": 1
}
@@ -181,8 +181,7 @@
"src/browser/assets/WebArtifactReads.ts": 1,
"src/domain/xmlDocument.ts": 1,
"src/native/AppleMachoSelection.ts": 1,
"src/native/MachoCommandNames.ts": 1,
"src/python/PythonPyc.errors.ts": 1
"src/native/MachoCommandNames.ts": 1
},
"parser-json-parse": {
"src/android/JadxProtocol.ts": 2,
@@ -391,5 +390,8 @@
"src/domain/apiContract/parseGraphqlContract.ts": 1,
"src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts": 2,
"src/wasm/WabtFailures.ts": 1
},
"wall-clock-deadline": {
"src/browser/PlaywrightScenarioRequest.ts": 1
}
}
+12
View File
@@ -225,6 +225,18 @@ checkCounted(
["src/domain/analysisErrorCore.ts"],
);
// A deadline is a monotonic budget owned by `Deadline` in src/domain/deadline;
// a wall-clock sum moves with clock changes and has no finalize phase. The
// remaining copy converts a monotonic budget for a browser page, which can
// only read its own wall clock.
checkCounted(
"wall-clock deadline computation (use Deadline from src/domain/deadline)",
"wall-clock-deadline",
files,
/Date\.now\(\)\s*\+/gu,
[],
);
// Byte-format parsers read untrusted input. Bounds, truncation and failure
// kind belong to BinaryReader (src/native/metadata/BinaryContainer.ts) and
// the ParseFailure algebra (src/domain/parseFailure.ts), not to each parser.
+175 -66
View File
@@ -16,6 +16,7 @@ import type { MachoSlice } from "../domain/apple/dylibResolution.js";
import {
machoArchitectureFamily,
machoCpuSubtypeBase,
machoKnownArm32Subtype,
} from "../domain/apple/machoCpuIdentity.js";
import { readMachoImage, type ReadAt } from "./apple/MachoLoadCommandReader.js";
import {
@@ -24,6 +25,7 @@ import {
sameArtifactEntry,
type ArtifactEntry,
type ArtifactReader,
type ArtifactReaderTraversal,
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import { streamChunkToBuffer } from "./StreamBytes.js";
@@ -31,6 +33,7 @@ import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
import { readArtifactFileChunks } from "./readArtifactFileChunks.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
import type { ArtifactIntegrityPolicyName } from "../domain/artifactIntegrityPolicy.js";
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
export class MachOSliceArtifactReader implements ArtifactReader {
@@ -46,6 +49,8 @@ export class MachOSliceArtifactReader implements ArtifactReader {
>();
#closed = false;
#closePromise: Promise<void> | undefined;
/** Coverage of the latest enumeration, reported when its iterator ends. */
#coverage: ArtifactReaderTraversal = { status: "complete", limitations: [] };
constructor(
private readonly path: string,
@@ -54,6 +59,8 @@ export class MachOSliceArtifactReader implements ArtifactReader {
environment,
),
source?: StableRegularFileDescriptor,
/** Caller choice when lipo's slice records disagree with the FAT table. */
private readonly integrity: ArtifactIntegrityPolicyName = "fail",
) {
this.#source = new ArtifactFileSource(path, "Universal Mach-O", source);
}
@@ -67,8 +74,12 @@ export class MachOSliceArtifactReader implements ArtifactReader {
try {
yield* enumeration;
this.#assertOpen(signal);
// Every FAT slice is listed; a disagreement with lipo fails the traversal.
options?.onCoverage?.({ status: "complete", limitations: [] });
// Every FAT slice is listed. A disagreement with lipo fails the
// traversal unless the caller chose to record it.
options?.onCoverage?.({
status: this.#coverage.status,
limitations: [...this.#coverage.limitations],
});
} finally {
this.#enumerations.delete(enumeration);
}
@@ -79,6 +90,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
): AsyncGenerator<ArtifactEntry, void> {
this.#assertOpen(signal);
this.#entries.clear();
this.#coverage = { status: "complete", limitations: [] };
const source = await this.#ensureSource();
await this.#source.readSelectedPath();
this.#assertOpen(signal);
@@ -158,22 +170,29 @@ export class MachOSliceArtifactReader implements ArtifactReader {
"unavailable",
`Mach-O structural slice index is unsupported: ${structural.reason}`,
);
// lipo is an independent witness of the FAT table. Under
// record-and-continue a disagreement is recorded and REA's own FAT parse,
// when available, is the authority for slice identity and ranges.
const disagreements: string[] = [];
const disagree = (message: string): void => {
if (this.integrity === "fail")
throw new ArtifactReaderFailure("integrity", message);
disagreements.push(message);
};
const hiddenArchitectures = architectures.filter(({ hidden }) => hidden);
const visibleArchitectures = architectures.filter(({ hidden }) => !hidden);
if (
lipo.hiddenArchitectureCount !== null &&
lipo.hiddenArchitectureCount !== hiddenArchitectures.length
)
throw new ArtifactReaderFailure(
"integrity",
disagree(
"lipo hidden architecture count disagrees with its architecture rows",
);
if (
lipo.declaredArchitectureCount !== null &&
lipo.declaredArchitectureCount !== visibleArchitectures.length
)
throw new ArtifactReaderFailure(
"integrity",
disagree(
"lipo declared architecture count disagrees with its visible rows",
);
if (
@@ -189,6 +208,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
const hiddenSlices =
structural.status === "parsed" ? (structural.hiddenSlices ?? []) : [];
const matchingSlices = new Map<LipoArchitecture, MachoSlice>();
const unmatchedRowLimitations: string[] = [];
if (slices !== null) {
if (
slices.length !== visibleArchitectures.length ||
@@ -201,8 +221,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
(lipo.hiddenArchitectureCount !== null &&
lipo.hiddenArchitectureCount !== hiddenSlices.length)
)
throw new ArtifactReaderFailure(
"integrity",
disagree(
"lipo declared and hidden architecture counts disagree with the Mach-O FAT table",
);
for (const [reportedRows, observedRows] of [
@@ -214,16 +233,62 @@ export class MachOSliceArtifactReader implements ArtifactReader {
const match = unmatched.findIndex((observed) =>
lipoMatchesSlice(reported, observed, observedRows.length === 1),
);
if (match < 0)
throw new ArtifactReaderFailure(
"integrity",
if (match < 0) {
disagree(
`lipo slice metadata disagrees with the Mach-O FAT table: ${reported.name} (cputype=${reported.cpu_type ?? "unknown"}, cpusubtype=${reported.cpu_subtype ?? "unknown"}, offset=${reported.file_offset ?? "unknown"}, size=${reported.size ?? "unknown"}, alignment=${reported.alignment ?? "unknown"})`,
);
// The row has no slice to carry its retained field evidence.
unmatchedRowLimitations.push(...lipoRowEvidence(reported));
continue;
}
const [observed] = unmatched.splice(match, 1);
if (observed !== undefined) matchingSlices.set(reported, observed);
}
}
}
if (disagreements.length > 0 && slices !== null) {
this.#coverage = {
status: "complete",
limitations: [
`Integrity limitation: lipo slice metadata disagrees with the Mach-O FAT table (${disagreements.join("; ")}). Slices were enumerated from REA's FAT table parse; lipo's ranges were not used.`,
...unmatchedRowLimitations,
],
};
const matchedRows = new Map(
Array.from(matchingSlices, ([reported, observed]) => [
observed,
reported,
]),
);
const names = new Set<string>();
for (const slice of [...slices, ...hiddenSlices]) {
this.#assertOpen(signal);
const reported = matchedRows.get(slice);
yield this.#sliceEntry(
uniqueSliceName(
reported?.name ?? structuralSliceName(slice),
slice.slice_offset,
names,
),
slice.slice_offset,
slice.slice_size,
fileSize,
// lipo's ranges are not used, but its retained field evidence for a
// matched row still describes this slice.
reported === undefined ? [] : lipoRowEvidence(reported),
);
}
return;
}
// Without a FAT parse, lipo's rows are the only slice list; a count
// disagreement means a slice may be missing from them.
if (disagreements.length > 0)
this.#coverage = {
status: "unknown",
limitations: [
`Integrity limitation: lipo's architecture counts disagree with its own records (${disagreements.join("; ")}). No structural FAT parse was available, so slice ranges are based on lipo's records and the slice list may be incomplete.`,
],
};
for (const architecture of architectures) {
this.#assertOpen(signal);
const structuralSlice = matchingSlices.get(architecture);
@@ -234,67 +299,67 @@ export class MachOSliceArtifactReader implements ArtifactReader {
"integrity",
"lipo omitted a universal slice byte range",
);
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(sliceSize) ||
offset < 0 ||
sliceSize <= 0 ||
!Number.isSafeInteger(offset + sliceSize) ||
offset + sliceSize > fileSize
)
throw new ArtifactReaderFailure(
"integrity",
`lipo reported an out-of-bounds Mach-O slice: ${architecture.name}`,
);
const entry: ArtifactEntry = {
path: `slices/${architecture.name}`,
kind: "slice",
declaredSize: sliceSize,
compressedSize: null,
executable: true,
encrypted: false,
byteOffset: offset,
declaredIntegrity: null,
unpacked: false,
limitations: [
...architecture.limitations,
...(structural.status === "not-mach-o"
yield this.#sliceEntry(architecture.name, offset, sliceSize, fileSize, [
...architecture.limitations,
...(structural.status === "not-mach-o"
? [
"Structural Mach-O facts were unavailable; slice range is based on lipo output.",
]
: structural.status === "unsupported"
? [
"Structural Mach-O facts were unavailable; slice range is based on lipo output.",
]
: structural.status === "unsupported"
? [
`Structural Mach-O facts were unsupported (${structural.reason}); slice range is based on lipo output.`,
]
: []),
...(architecture.file_offset === null || architecture.size === null
? [
architecture.fields.offset.kind === "uninterpretable" ||
architecture.fields.size.kind === "uninterpretable"
? "Slice range was derived from structural Mach-O facts because lipo's range declarations could not all be interpreted."
: "Slice range was derived from structural Mach-O facts because lipo omitted it.",
`Structural Mach-O facts were unsupported (${structural.reason}); slice range is based on lipo output.`,
]
: []),
...(architecture.cpu_type !== null &&
architecture.cpu_type_code === null
? [
`lipo CPU type is retained as unnormalized source text: ${architecture.cpu_type}`,
]
: []),
...(architecture.cpu_subtype !== null &&
architecture.cpu_subtype_code === null
? [
`lipo CPU subtype is retained as unnormalized source text: ${architecture.cpu_subtype}${architecture.capabilities === null ? "" : `; capabilities ${architecture.capabilities}`}`,
]
: []),
],
adapterKey: `${String(offset)}:${String(sliceSize)}`,
};
this.#entries.set(entry.adapterKey, copyArtifactEntry(entry));
yield entry;
...(architecture.file_offset === null || architecture.size === null
? [
architecture.fields.offset.kind === "uninterpretable" ||
architecture.fields.size.kind === "uninterpretable"
? "Slice range was derived from structural Mach-O facts because lipo's range declarations could not all be interpreted."
: "Slice range was derived from structural Mach-O facts because lipo omitted it.",
]
: []),
...lipoCpuSourceLimitations(architecture),
]);
}
}
/** Inventory one slice range after checking it lies within the artifact. */
#sliceEntry(
name: string,
offset: number,
sliceSize: number,
fileSize: number,
limitations: readonly string[],
): ArtifactEntry {
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(sliceSize) ||
offset < 0 ||
sliceSize <= 0 ||
!Number.isSafeInteger(offset + sliceSize) ||
offset + sliceSize > fileSize
)
throw new ArtifactReaderFailure(
"integrity",
`Mach-O slice range is outside the artifact: ${name}`,
);
const entry: ArtifactEntry = {
path: `slices/${name}`,
kind: "slice",
declaredSize: sliceSize,
compressedSize: null,
executable: true,
encrypted: false,
byteOffset: offset,
declaredIntegrity: null,
unpacked: false,
limitations: [...limitations],
adapterKey: `${String(offset)}:${String(sliceSize)}`,
};
this.#entries.set(entry.adapterKey, copyArtifactEntry(entry));
return entry;
}
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
const operation = this.#open(entry, signal);
this.#pendingOpens.add(operation);
@@ -561,6 +626,50 @@ export class MachOSliceArtifactReader implements ArtifactReader {
}
}
/** lipo CPU declarations REA retained as text because it could not normalize them. */
const lipoCpuSourceLimitations = (architecture: LipoArchitecture): string[] => [
...(architecture.cpu_type !== null && architecture.cpu_type_code === null
? [
`lipo CPU type is retained as unnormalized source text: ${architecture.cpu_type}`,
]
: []),
...(architecture.cpu_subtype !== null &&
architecture.cpu_subtype_code === null
? [
`lipo CPU subtype is retained as unnormalized source text: ${architecture.cpu_subtype}${architecture.capabilities === null ? "" : `; capabilities ${architecture.capabilities}`}`,
]
: []),
];
/**
* Every source fact one lipo row carries beyond the ranges REA replaced:
* its uninterpretable fields and its unnormalized CPU declarations.
*/
const lipoRowEvidence = (architecture: LipoArchitecture): string[] => [
...architecture.limitations,
...lipoCpuSourceLimitations(architecture),
];
/** The most specific name a FAT slice's own CPU identity supports. */
const structuralSliceName = (slice: MachoSlice): string =>
((slice.fat_cpu_type ?? slice.cpu_type) === 12
? machoKnownArm32Subtype(slice.fat_cpu_subtype ?? slice.cpu_subtype)
: undefined) ?? slice.architecture;
/**
* Keep slice paths distinct: two FAT slices can share an identity name, so a
* repeated name is qualified by the slice's FAT offset, which is unique.
*/
const uniqueSliceName = (
name: string,
offset: number,
used: Set<string>,
): string => {
const unique = used.has(name) ? `${name}@${String(offset)}` : name;
used.add(unique);
return unique;
};
/** Compare lipo's independent ranges with structurally parsed slice identity. */
const readStructuralSlices = async (
file: FileHandle,
+43
View File
@@ -859,6 +859,49 @@ it("joins an admitted ZIP enumeration before reader close completes", async () =
}
});
it("joins the final member accounting read before closing its source", async () => {
const fixture = await admittedZip();
const reached = createDeferred<void>();
const release = createDeferred<void>();
const reader = new ZipArtifactReader(fixture.path, "zip", undefined, fixture);
const traversal = reader.entries()[Symbol.asyncIterator]();
let next: Promise<IteratorResult<ArtifactEntry>> | undefined;
const nativeRead = fixture.positional.read.bind(fixture.positional);
const reads = vi.spyOn(fixture.positional, "read");
try {
expect((await traversal.next()).done).toBe(false);
reads.mockImplementation(async (...args) => {
if (args[3] === 0) {
reached.resolve();
await release.promise;
}
return nativeRead(...args);
});
next = traversal.next();
await awaitAcknowledgement(
reached.promise,
next,
"ZIP member accounting read",
);
let closed = false;
const closing = reader.close().then(() => {
closed = true;
});
await Promise.resolve();
expect(closed).toBe(false);
release.resolve();
await expect(next).rejects.toMatchObject({ reason: "unavailable" });
await closing;
expect(closed).toBe(true);
} finally {
release.resolve();
await next?.catch(() => undefined);
await reader.close();
reads.mockRestore();
await fixture.handle.close();
}
});
it("joins a late ZIP producer and closes the source despite an enumeration cleanup failure", async () => {
const directory = await createTestTempDirectory("rea-zip-mixed-cleanup-");
const path = join(directory, "mixed.zip");
+95 -5
View File
@@ -37,8 +37,14 @@ import {
sameArtifactEntry,
type ArtifactEntry,
type ArtifactReader,
type ArtifactReaderTraversal,
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import {
accountZipMemberRegion,
type ZipLocalRecord,
type ZipMemberRegionAccount,
} from "./ZipMemberRegion.js";
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
import { artifactExpansionBudgetBytes } from "../domain/artifactExpansionBudget.js";
import { artifactReaderLimitFailure } from "./ArtifactReaderLimits.js";
@@ -175,6 +181,8 @@ export class ZipArtifactReader implements ArtifactReader {
readonly #reader: ZipReader<string>;
readonly #streams = new Map<Readable, Promise<void>>();
readonly #enumerations = new Set<AsyncGenerator<Entry, void>>();
/** Running traversal steps, including the final accounting pass, that close joins. */
readonly #traversalSteps = new Set<Promise<unknown>>();
#closing = false;
#closePromise: Promise<void> | undefined;
readonly #entries = new Map<
@@ -194,14 +202,40 @@ export class ZipArtifactReader implements ArtifactReader {
this.#reader = new ZipReader(this.#source, ZIP_READER_OPTIONS);
}
async *entries(
entries(
signal?: AbortSignal,
options?: ArtifactTraversalOptions,
): AsyncIterable<ArtifactEntry> {
const traversal = this.#enumerate(signal, options);
const steps = this.#traversalSteps;
// Close joins a running step without ending the traversal, so the
// caller's next step still observes the close instead of completion.
const step = <T>(running: Promise<T>): Promise<T> => {
steps.add(running);
const settled = () => {
steps.delete(running);
};
running.then(settled, settled);
return running;
};
const iterator: AsyncIterator<ArtifactEntry, void> = {
next: () => step(traversal.next()),
return: (value) => step(traversal.return(value)),
throw: (cause: unknown) => step(traversal.throw(cause)),
};
return { [Symbol.asyncIterator]: () => iterator };
}
async *#enumerate(
signal?: AbortSignal,
options?: ArtifactTraversalOptions,
): AsyncGenerator<ArtifactEntry, void> {
this.#assertOpen(signal);
let index = 0;
// A traversal owns its accounting, including overlapping or repeated passes.
let declaredFileBytes = 0n;
// Every directory record, listed or not, claims its local entry's bytes.
const records: ZipLocalRecord[] = [];
const enumeration = typedZipFailures(
this.#reader.getEntriesGenerator({ decodeText: decodeZipEntryText }),
);
@@ -210,6 +244,14 @@ export class ZipArtifactReader implements ArtifactReader {
for await (const entry of enumeration) {
await this.#source.verify();
this.#assertOpen(signal);
records.push({
offset: entry.offset,
compressedSize: entry.compressedSize,
uncompressedSize: entry.uncompressedSize,
crc32: entry.crc32,
zip64: entry.zip64,
dataDescriptor: entry.bitFlag?.dataDescriptor ?? false,
});
// ZIP member identity is its directory occurrence, not its filename.
// Logical path uniqueness belongs to the artifact inventory boundary.
const metadata = projectZipEntry(entry, index++);
@@ -251,11 +293,24 @@ export class ZipArtifactReader implements ArtifactReader {
yield metadata;
}
this.#assertOpen(signal);
// The listing comes from the central directory; local entries it does
// not reference are only visible as bytes no record accounts for.
const directoryOffset = this.#reader.directoryOffset;
const account =
directoryOffset === undefined
? undefined
: await accountZipMemberRegion(
records,
directoryOffset,
(at, length) => this.#source.readUint8Array(at, length),
);
this.#assertOpen(signal);
await this.#source.verify();
this.#assertOpen(signal);
options?.onCoverage?.({ status: "complete", limitations: [] });
options?.onCoverage?.(zipListingCoverage(account));
} finally {
this.#enumerations.delete(enumeration);
await enumeration.return();
}
}
@@ -309,9 +364,15 @@ export class ZipArtifactReader implements ArtifactReader {
output.destroy(
new ArtifactReaderFailure("unavailable", "ZIP reader closed"),
);
const outcomes = await Promise.allSettled([
...this.#streams.values(),
...Array.from(this.#enumerations, (enumeration) => enumeration.return()),
// A joined traversal step reports its own failure to its caller.
const [outcomes] = await Promise.all([
Promise.allSettled([
...this.#streams.values(),
...Array.from(this.#enumerations, (enumeration) =>
enumeration.return(),
),
]),
Promise.allSettled(this.#traversalSteps),
]);
this.#enumerations.clear();
// best-effort cleanup: zip-reader close must not mask prior extraction state.
@@ -341,6 +402,35 @@ export class ZipArtifactReader implements ArtifactReader {
}
}
/** Coverage of a central-directory listing, given the member region's byte account. */
const zipListingCoverage = (
account: ZipMemberRegionAccount | undefined,
): ArtifactReaderTraversal => {
if (account === undefined)
return {
status: "unknown",
limitations: [
"ZIP central directory offset was not established; bytes outside the listed members were not accounted for.",
],
};
const limitations = [
...(account.unaccountedRanges === 0
? []
: [
`ZIP central directory does not account for ${String(account.unaccountedBytes)} byte(s) in ${String(account.unaccountedRanges)} range(s) before it, first at offset ${String(account.firstUnaccountedOffset)}; local entries it does not list may exist there.`,
]),
...(account.unlocatedHeaders === 0
? []
: [
`${String(account.unlocatedHeaders)} ZIP central directory record(s) point at no local file header; the bytes they claim were not accounted for.`,
]),
];
return {
status: limitations.length === 0 ? "complete" : "unknown",
limitations,
};
};
const projectZipEntry = (
entry: Entry,
index: number,
+374
View File
@@ -0,0 +1,374 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { crc32 } from "node:zlib";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import type { ArtifactReaderTraversal } from "./ArtifactReader.js";
import { scanReader } from "./inventory/scanReader.js";
import { ZipArtifactReader } from "./ZipArtifactReader.js";
import { accountZipMemberRegion } from "./ZipMemberRegion.js";
interface Member {
readonly name: string;
readonly data: Buffer;
/** Whether the central directory lists this local entry. */
readonly listed: boolean;
}
const member = (name: string, listed = true): Member => ({
name,
data: Buffer.from(`${name} bytes`),
listed,
});
const localEntry = ({ name, data }: Member): Buffer => {
const header = Buffer.alloc(30);
header.writeUInt32LE(0x04034b50, 0);
header.writeUInt16LE(20, 4);
header.writeUInt32LE(crc32(data), 14);
header.writeUInt32LE(data.length, 18);
header.writeUInt32LE(data.length, 22);
header.writeUInt16LE(Buffer.byteLength(name), 26);
return Buffer.concat([header, Buffer.from(name), data]);
};
const centralRecord = ({ name, data }: Member, offset: number): Buffer => {
const record = Buffer.alloc(46);
record.writeUInt32LE(0x02014b50, 0);
record.writeUInt16LE(20, 4);
record.writeUInt16LE(20, 6);
record.writeUInt32LE(crc32(data), 16);
record.writeUInt32LE(data.length, 20);
record.writeUInt32LE(data.length, 24);
record.writeUInt16LE(Buffer.byteLength(name), 28);
record.writeUInt32LE(offset, 42);
return Buffer.concat([record, Buffer.from(name)]);
};
/**
* A stored ZIP. Unlisted members keep their local entry but no directory
* record, unless `trailingRecords` keeps their record past the EOCD count.
*/
const zip = (
members: readonly Member[],
options: { prefix?: Buffer; gap?: Buffer; trailingRecords?: boolean } = {},
): Buffer => {
const prefix = options.prefix ?? Buffer.alloc(0);
const locals: Buffer[] = [prefix];
const listed: Buffer[] = [];
const trailing: Buffer[] = [];
let offset = prefix.length;
for (const item of members) {
const local = localEntry(item);
if (item.listed) listed.push(centralRecord(item, offset));
else if (options.trailingRecords === true)
trailing.push(centralRecord(item, offset));
locals.push(local);
offset += local.length;
}
if (options.gap !== undefined) {
locals.push(options.gap);
offset += options.gap.length;
}
const directory = Buffer.concat([...listed, ...trailing]);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(listed.length, 8);
end.writeUInt16LE(listed.length, 10);
end.writeUInt32LE(directory.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...locals, directory, end]);
};
/** An APK Signature Scheme v2 block shape: size, pairs, size, magic. */
const apkSigningBlock = (magic = "APK Sig Block 42"): Buffer => {
const pairs = Buffer.alloc(12);
pairs.writeBigUInt64LE(4n, 0);
const size = BigInt(pairs.length + 8 + 16);
const leading = Buffer.alloc(8);
leading.writeBigUInt64LE(size);
return Buffer.concat([leading, pairs, leading, Buffer.from(magic, "latin1")]);
};
const list = async (
bytes: Buffer | Uint8Array,
): Promise<{ paths: string[]; coverage: ArtifactReaderTraversal[] }> => {
const directory = await createTestTempDirectory("rea-zip-member-region-");
const path = join(directory, "fixture.zip");
await writeFile(path, bytes);
const reader = new ZipArtifactReader(path, "zip");
const paths: string[] = [];
const coverage: ArtifactReaderTraversal[] = [];
try {
for await (const entry of reader.entries(undefined, {
onCoverage: (value) => coverage.push(value),
}))
paths.push(entry.path);
} finally {
await reader.close();
}
return { paths, coverage };
};
const complete = { status: "complete", limitations: [] };
const unaccounted = (bytes: number, ranges: number, first: number) => ({
status: "unknown",
limitations: [
`ZIP central directory does not account for ${String(bytes)} byte(s) in ${String(ranges)} range(s) before it, first at offset ${String(first)}; local entries it does not list may exist there.`,
],
});
/** Bytes of `localEntry(member("hidden.txt"))`. */
const HIDDEN_ENTRY_BYTES = 30 + 10 + 16;
/** Bytes of `localEntry(member("a.txt"))`, the offset after it. */
const A_ENTRY_BYTES = 30 + 5 + 11;
describe("ZIP listing coverage against the member region", () => {
it("counts a missing header's uncovered region only once", async () => {
const valid = localEntry(member("a.txt"));
const bytes = Buffer.concat([Buffer.alloc(200), valid]);
const records = [
{
offset: 100,
compressedSize: 0,
uncompressedSize: 0,
crc32: 0,
zip64: false,
dataDescriptor: false,
},
{
offset: 200,
compressedSize: member("a.txt").data.length,
uncompressedSize: member("a.txt").data.length,
crc32: crc32(member("a.txt").data),
zip64: false,
dataDescriptor: false,
},
];
expect(
await accountZipMemberRegion(records, bytes.length, async (at, length) =>
bytes.subarray(at, at + length),
),
).toMatchObject({
unaccountedBytes: 200,
unaccountedRanges: 1,
firstUnaccountedOffset: 0,
unlocatedHeaders: 1,
});
});
it("accounts for a validated data descriptor before an unlisted entry", async () => {
const first = member("a.txt");
const local = localEntry(first);
const descriptor = Buffer.alloc(16);
descriptor.writeUInt32LE(0x08074b50, 0);
descriptor.writeUInt32LE(crc32(first.data), 4);
descriptor.writeUInt32LE(first.data.length, 8);
descriptor.writeUInt32LE(first.data.length, 12);
const hidden = localEntry(member("hidden.txt", false));
const bytes = Buffer.concat([local, descriptor, hidden]);
const records = [
{
offset: 0,
compressedSize: first.data.length,
uncompressedSize: first.data.length,
crc32: crc32(first.data),
zip64: false,
dataDescriptor: true,
},
];
expect(
await accountZipMemberRegion(records, bytes.length, async (at, length) =>
bytes.subarray(at, at + length),
),
).toMatchObject({
unaccountedBytes: hidden.length,
unaccountedRanges: 1,
firstUnaccountedOffset: local.length + descriptor.length,
});
});
it("accounts for an unsigned data descriptor whose CRC equals the descriptor signature", async () => {
const first = member("a.txt");
const local = localEntry(first);
// CRC 0x08074b50 makes the unsigned descriptor start with the signature bytes.
const descriptor = Buffer.alloc(12);
descriptor.writeUInt32LE(0x08074b50, 0);
descriptor.writeUInt32LE(first.data.length, 4);
descriptor.writeUInt32LE(first.data.length, 8);
const bytes = Buffer.concat([local, descriptor]);
const records = [
{
offset: 0,
compressedSize: first.data.length,
uncompressedSize: first.data.length,
crc32: 0x08074b50,
zip64: false,
dataDescriptor: true,
},
];
expect(
await accountZipMemberRegion(records, bytes.length, async (at, length) =>
bytes.subarray(at, at + length),
),
).toMatchObject({ unaccountedBytes: 0, unaccountedRanges: 0 });
// With room for a signed layout, the unsigned layout still matches.
const padded = Buffer.concat([bytes, Buffer.alloc(4)]);
expect(
await accountZipMemberRegion(records, padded.length, async (at, length) =>
padded.subarray(at, at + length),
),
).toMatchObject({
unaccountedBytes: 4,
unaccountedRanges: 1,
firstUnaccountedOffset: bytes.length,
});
});
it("accounts for an AE-2 data descriptor whose directory reports no CRC", async () => {
const first = member("a.txt");
const local = localEntry(first);
const descriptor = Buffer.alloc(16);
descriptor.writeUInt32LE(0x08074b50, 0);
descriptor.writeUInt32LE(first.data.length, 8);
descriptor.writeUInt32LE(first.data.length, 12);
const bytes = Buffer.concat([local, descriptor]);
const record = {
offset: 0,
compressedSize: first.data.length,
uncompressedSize: first.data.length,
crc32: undefined,
zip64: false,
dataDescriptor: true,
};
const read = async (at: number, length: number) =>
bytes.subarray(at, at + length);
expect(
await accountZipMemberRegion([record], bytes.length, read),
).toMatchObject({ unaccountedBytes: 0, unaccountedRanges: 0 });
// Sizes still have to match.
expect(
await accountZipMemberRegion(
[{ ...record, compressedSize: first.data.length + 1 }],
bytes.length,
read,
),
).toMatchObject({ unaccountedRanges: 1 });
});
});
describe("ZIP listing coverage from the central directory", () => {
it("declares complete coverage when directory records cover every byte", async () => {
expect(await list(zip([member("a.txt"), member("b.txt")]))).toEqual({
paths: ["a.txt", "b.txt"],
coverage: [complete],
});
});
it("declares complete coverage for writer-produced data descriptors", async () => {
const writer = new ZipWriter(new Uint8ArrayWriter(), {
dataDescriptor: true,
dataDescriptorSignature: true,
});
await writer.add("a.txt", new TextReader("a".repeat(500)));
await writer.add("b.txt", new TextReader("b"));
expect((await list(await writer.close())).coverage).toEqual([complete]);
});
it.each([
[
"between listed members",
[member("a.txt"), member("hidden.txt", false), member("b.txt")],
A_ENTRY_BYTES,
],
[
"before the first listed member",
[member("hidden.txt", false), member("a.txt")],
0,
],
[
"after the last listed member",
[member("a.txt"), member("hidden.txt", false)],
A_ENTRY_BYTES,
],
] as const)(
"reports a local entry the central directory omits %s as unknown",
async (_placement, members, first) => {
const { paths, coverage } = await list(zip(members));
expect(paths).not.toContain("hidden.txt");
expect(coverage).toEqual([unaccounted(HIDDEN_ENTRY_BYTES, 1, first)]);
},
);
it("reports a directory record past the end record's declared count as unknown", async () => {
const { paths, coverage } = await list(
zip([member("a.txt"), member("hidden.txt", false)], {
trailingRecords: true,
}),
);
expect(paths).toEqual(["a.txt"]);
expect(coverage).toEqual([
unaccounted(HIDDEN_ENTRY_BYTES, 1, A_ENTRY_BYTES),
]);
});
it("reports bytes prepended before the first member as unknown", async () => {
const prefix = Buffer.from("#!/bin/sh\nexit 0\n");
expect((await list(zip([member("a.txt")], { prefix }))).coverage).toEqual([
unaccounted(prefix.length, 1, 0),
]);
});
it("accounts for a well-formed APK signing block before the directory", async () => {
expect(
(await list(zip([member("a.txt")], { gap: apkSigningBlock() }))).coverage,
).toEqual([complete]);
});
it("does not account for a block whose footer magic differs", async () => {
const gap = apkSigningBlock("APK Sig Block 41");
expect((await list(zip([member("a.txt")], { gap }))).coverage).toEqual([
unaccounted(gap.length, 1, A_ENTRY_BYTES),
]);
});
it("does not hide an unlisted local entry inside malformed signing-block framing", async () => {
const hidden = localEntry(member("hidden.txt", false));
const size = BigInt(hidden.length + 24);
const framing = Buffer.alloc(8);
framing.writeBigUInt64LE(size);
const block = Buffer.concat([
framing,
hidden,
framing,
Buffer.from("APK Sig Block 42"),
]);
expect(
(await list(zip([member("a.txt")], { gap: block }))).coverage,
).toEqual([unaccounted(block.length, 1, A_ENTRY_BYTES)]);
});
it("carries the unaccounted region into the artifact inventory", async () => {
const directory = await createTestTempDirectory("rea-zip-member-region-");
const path = join(directory, "fixture.zip");
await writeFile(
path,
zip([member("a.txt"), member("hidden.txt", false), member("b.txt")]),
);
const reader = new ZipArtifactReader(path, "zip");
try {
const result = await scanReader(reader, [reader]);
expect(result.occurrences.map((item) => item.logical_path)).toEqual([
"a.txt",
"b.txt",
]);
expect(result.traversal).toEqual(
unaccounted(HIDDEN_ENTRY_BYTES, 1, A_ENTRY_BYTES),
);
} finally {
await reader.close();
}
});
});
+189
View File
@@ -0,0 +1,189 @@
import { BinaryReader } from "../native/metadata/BinaryContainer.js";
import {
apkSigningPairEnd,
APK_SIGNING_BLOCK_MAX_PAIRS,
} from "../domain/apkSignature/apkSigningBlock.js";
/** One central-directory record's claim on the member region before the directory. */
export interface ZipLocalRecord {
/** Offset of the record's local file header. */
readonly offset: number;
readonly compressedSize: number;
readonly uncompressedSize: number;
/** Undefined when the directory reader reports none, as for AES entries. */
readonly crc32: number | undefined;
readonly zip64: boolean;
/** The general-purpose flag that places a data descriptor after the data. */
readonly dataDescriptor: boolean;
}
/** What the central directory's records leave unexplained before the directory. */
export interface ZipMemberRegionAccount {
readonly unaccountedBytes: number;
readonly unaccountedRanges: number;
readonly firstUnaccountedOffset: number | undefined;
/** Records whose local file header could not be located. */
readonly unlocatedHeaders: number;
}
const LOCAL_HEADER_BYTES = 30;
const LOCAL_HEADER_SIGNATURE = 0x04034b50;
const DATA_DESCRIPTOR_SIGNATURE = 0x08074b50;
/** The APK Signature Scheme v2+ block sits between the last member and the directory. */
const APK_SIGNING_BLOCK_MAGIC = "APK Sig Block 42";
const APK_SIGNING_BLOCK_FOOTER_BYTES = 24;
/** Adjacent small members share one read; a large member costs one read. */
const READ_WINDOW_BYTES = 64 * 1024;
/**
* Account for every byte before the central directory with the local records
* the directory lists. Unaccounted bytes may hold local entries the central
* directory omits, so a listing built from it cannot claim them.
*/
export const accountZipMemberRegion = async (
records: readonly ZipLocalRecord[],
directoryOffset: number,
read: (offset: number, length: number) => Promise<Uint8Array>,
): Promise<ZipMemberRegionAccount> => {
let window:
| { readonly start: number; readonly bytes: Uint8Array }
| undefined;
const view = async (offset: number, length: number) => {
if (
window === undefined ||
offset < window.start ||
offset + length > window.start + window.bytes.length
)
window = {
start: offset,
bytes: await read(
offset,
Math.max(
length,
Math.min(READ_WINDOW_BYTES, directoryOffset - offset),
),
),
};
const at = offset - window.start;
return new BinaryReader(
Buffer.from(window.bytes.buffer, window.bytes.byteOffset + at, length),
true,
"zip",
);
};
let unaccountedBytes = 0;
let unaccountedRanges = 0;
let firstUnaccountedOffset: number | undefined;
let unlocatedHeaders = 0;
let cursor = 0;
let descriptor: ZipLocalRecord | undefined;
const gap = async (end: number) => {
if (end <= cursor) return;
if (descriptor !== undefined)
cursor += await dataDescriptorBytes(descriptor, cursor, end, view);
descriptor = undefined;
const size = end - cursor;
if (size <= 0) return;
unaccountedBytes += size;
unaccountedRanges += 1;
firstUnaccountedOffset ??= cursor;
};
for (const record of [...records].sort((a, b) => a.offset - b.offset)) {
if (record.offset + LOCAL_HEADER_BYTES > directoryOffset) {
unlocatedHeaders += 1;
continue;
}
const header = await view(record.offset, LOCAL_HEADER_BYTES);
if (header.u32(0) !== LOCAL_HEADER_SIGNATURE) {
unlocatedHeaders += 1;
continue;
}
await gap(record.offset);
const end =
record.offset +
LOCAL_HEADER_BYTES +
header.u16(26) +
header.u16(28) +
record.compressedSize;
// Overlapping records are refused when their data is read.
if (end > cursor) {
cursor = end;
descriptor = record.dataDescriptor ? record : undefined;
}
}
await gap(await apkSigningBlockStart(cursor, directoryOffset, view));
return {
unaccountedBytes,
unaccountedRanges,
firstUnaccountedOffset,
unlocatedHeaders,
};
};
/**
* The bytes of the record's data descriptor at `at`, or 0 when none matches.
* The descriptor signature is optional and an unsigned descriptor's CRC may
* equal it, so both layouts are tried against the recorded CRC and sizes.
* An entry whose directory reports no CRC (zip.js omits it for AES entries,
* whose AE-2 CRC is zero) is matched on its sizes alone.
*/
const dataDescriptorBytes = async (
record: ZipLocalRecord,
at: number,
end: number,
view: (offset: number, length: number) => Promise<BinaryReader>,
): Promise<number> => {
const body = record.zip64 ? 20 : 12;
const signed =
end - at >= body + 4 &&
(await view(at, 4)).u32(0) === DATA_DESCRIPTOR_SIGNATURE;
for (const prefix of signed ? [4, 0] : [0]) {
if (end - at < prefix + body) continue;
const data = await view(at + prefix, body);
const compressed = record.zip64 ? data.word(4, 64) : BigInt(data.u32(4));
const uncompressed = record.zip64 ? data.word(12, 64) : BigInt(data.u32(8));
if (
(record.crc32 === undefined || data.u32(0) === record.crc32) &&
compressed === BigInt(record.compressedSize) &&
uncompressed === BigInt(record.uncompressedSize)
)
return prefix + body;
}
return 0;
};
/** Where a well-formed APK signing block ending at the directory starts, else the directory. */
const apkSigningBlockStart = async (
cursor: number,
directoryOffset: number,
view: (offset: number, length: number) => Promise<BinaryReader>,
): Promise<number> => {
if (directoryOffset - cursor < APK_SIGNING_BLOCK_FOOTER_BYTES + 8)
return directoryOffset;
const footer = await view(
directoryOffset - APK_SIGNING_BLOCK_FOOTER_BYTES,
APK_SIGNING_BLOCK_FOOTER_BYTES,
);
const magic = new TextDecoder("latin1").decode(
footer.range(8, 16, "APK signing block magic"),
);
if (magic !== APK_SIGNING_BLOCK_MAGIC) return directoryOffset;
const size = footer.word(0, 64);
if (size < 24n) return directoryOffset;
const start = BigInt(directoryOffset) - size - 8n;
if (start < BigInt(cursor)) return directoryOffset;
const header = await view(Number(start), 8);
if (header.word(0, 64) !== size) return directoryOffset;
let offset = Number(start) + 8;
const pairsEnd = directoryOffset - APK_SIGNING_BLOCK_FOOTER_BYTES;
let count = 0;
while (offset < pairsEnd) {
if (pairsEnd - offset < 8 || count++ >= APK_SIGNING_BLOCK_MAX_PAIRS)
return directoryOffset;
const length = (await view(offset, 8)).word(0, 64);
const next = apkSigningPairEnd(length, offset, pairsEnd);
if (next === undefined) return directoryOffset;
offset = next;
}
return Number(start);
};
@@ -1,6 +1,10 @@
import { readBinaryPlistLayout } from "./BinaryPlistLayout.js";
import { parseBinary } from "plist";
import { markPlistDictionary } from "../../domain/apple/plistUid.js";
import {
createPlistDuplicateKeyCollector,
type PlistDuplicateKeys,
} from "../../domain/apple/plistDuplicateKeys.js";
import { byteOrderMarkEncoding } from "../../domain/textByteOrderMark.js";
import {
binaryPlistObjectEnd,
@@ -74,6 +78,20 @@ const scalarOccurrence = (
return value;
};
/**
* Keys each stored dictionary declares more than once. The decoded value
* keeps one property per key, the last, so this reads the planned source keys.
*/
export const binaryPlistDuplicateKeys = (
plan: PlistDecodePreflight,
): PlistDuplicateKeys => {
const duplicates = createPlistDuplicateKeyCollector();
for (const container of plan.binaryValuePlan?.containers ?? [])
if (container.kind === "dictionary" && container.keys !== undefined)
duplicates.dictionary(container.keys);
return duplicates.result();
};
/** Decode validated source containers without losing dictionary keys or alias occurrence identity. */
export const decodeBinaryPlistValue = (
bytes: Buffer,
+7
View File
@@ -1,4 +1,5 @@
import type { AsarHeaderAdmission } from "../config/asarHeaderAdmission.js";
import type { ArtifactIntegrityPolicyName } from "../domain/artifactIntegrityPolicy.js";
import {
ARTIFACT_FORMAT_IDS,
type ArtifactFormatId,
@@ -61,6 +62,11 @@ export interface ArtifactReaderConstruction {
readonly espFlashSelection?: EspFlashSelection | undefined;
/** Caller-selected root spelling; only ASAR companion lookup consumes this. */
readonly selectedPath?: string | undefined;
/**
* Caller choice for a contradiction between a reader's independent witness
* and the container's own bytes; universal Mach-O lipo records consume it.
*/
readonly integrity?: ArtifactIntegrityPolicyName | undefined;
}
export interface FormatDescriptor {
@@ -356,6 +362,7 @@ const NON_ZIP_FORMATS = {
options.environment,
undefined,
sourceOf(options),
options.integrity,
),
}),
"mach-o": described("mach-o", plain),
@@ -730,6 +730,7 @@ const createReader = async (
| "resourceScope"
| "espFlashSelection"
| "readerLimits"
| "integrityPolicy"
>,
manifest: ArtifactGraphManifest,
transferredSource?: ActiveArtifactInventorySource,
@@ -791,6 +792,7 @@ const createReader = async (
admission: transferredSource?.admission,
espFlashSelection: input.espFlashSelection,
readerLimits: input.readerLimits,
integrity: input.integrityPolicy,
asarHeaderAdmission:
containerFormat === "asar"
? (input.asarHeaderAdmission ??
+3
View File
@@ -1,6 +1,7 @@
import type { ArtifactReaderAdmission } from "../ArtifactReaderAdmission.js";
import type { ArtifactReaderLimits } from "../../domain/artifactReaderLimits.js";
import type { AsarHeaderAdmission } from "../../config/asarHeaderAdmission.js";
import type { ArtifactIntegrityPolicyName } from "../../domain/artifactIntegrityPolicy.js";
import type {
ArtifactReader,
ArtifactReaderTraversal,
@@ -23,6 +24,7 @@ export const createReader = (
asarHeaderAdmission?: AsarHeaderAdmission,
selectedPath?: string,
readerLimits?: ArtifactReaderLimits,
integrity?: ArtifactIntegrityPolicyName,
): ArtifactReader | undefined => {
if (
artifactFormatDescriptor(format)?.requiresDarwin === true &&
@@ -36,6 +38,7 @@ export const createReader = (
asarHeaderAdmission,
selectedPath,
readerLimits,
integrity,
});
};
+1
View File
@@ -145,6 +145,7 @@ const scanCanonical = async (
options.asarHeaderAdmission,
selectedPath,
options.readerLimits,
options.integrity,
);
} catch (cause: unknown) {
readerCreationFailure = { cause };
-27
View File
@@ -410,33 +410,6 @@ describe("CDP accessibility inventory and identity", () => {
});
});
it.each([undefined, { length: 1 }])(
"keeps an omitted or non-array node inventory unknown: %s",
(nodes) => {
const completeness = new CdpCaptureCompleteness();
const capture = captureAccessibility([{ nodes }], {
includeText: true,
completeness,
});
expect(capture).toMatchObject({
total: 0,
nodes: [],
hasUnobservedChildren: false,
});
expect(completeness.snapshot()).toMatchObject({
unavailable_sections: ["accessibility"],
excluded: [
{
section: "accessibility",
reason: "invalid_protocol_value",
count: null,
},
],
});
},
);
it("retains valid nodes and counts malformed inventory entries", () => {
const completeness = new CdpCaptureCompleteness();
const capture = captureAccessibility(
+22 -34
View File
@@ -2,13 +2,12 @@ import type { InspectWebPageInput } from "../domain/browserObservation.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import type { WebPageInspection } from "../domain/browserObservationSchemas.js";
import type { CdpFrameTree, CdpResourceTree } from "./protocol/CdpFrameTree.js";
import type { CdpCommandResult } from "./protocol/CdpCommands.js";
import {
allowedSanitizedUrl,
admitRecords,
numberValue,
recordValue,
recordsValue,
requiredRecord,
cdpStringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
@@ -210,6 +209,17 @@ export interface DomCapture extends DomMetadataCapture {
readonly nodes: WebPageInspection["dom"]["nodes"];
}
/** The DOM section of a snapshot whose reply was malformed: nothing was admitted. */
export const emptyDomCapture: DomCapture = {
total: 0,
nodeValueLengthUnit: "utf16-code-units",
nodes: [],
urls: [],
agentHints: [],
excludedUrls: 0,
unresolvedSvgNodes: 0,
};
// Bound retained projections and outstanding CDP reads independently of page size.
// Eight leaves room for the session's other cancellation listeners.
const DOM_METADATA_BATCH_SIZE = 8;
@@ -222,7 +232,7 @@ interface PendingDomMetadata {
/** Project one snapshot, requesting bounded batches of SVG identity facts. */
export function* captureDom(
result: unknown,
root: CdpCommandResult<"DOMSnapshot.captureSnapshot">,
allowedOrigins: ReadonlySet<string>,
input: InspectWebPageInput,
completeness?: CdpCaptureCompleteness,
@@ -231,18 +241,13 @@ export function* captureDom(
DomCapture,
readonly (boolean | undefined)[]
> {
const root = requiredRecord(result);
const strings = Array.isArray(root.strings)
? root.strings.map(cdpStringValue)
: [];
const strings = root.strings.map(cdpStringValue);
const nodes: WebPageInspection["dom"]["nodes"] = [];
const urls: WebPageInspection["metadata"]["dom_urls"] = [];
const agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
let excludedUrls = 0;
let total = 0;
let unresolvedSvgNodes = 0;
if (!Array.isArray(root.strings))
excludeDocumentEvidence(completeness, "invalid_protocol_value", null);
for (const document of snapshotDocuments(root.documents, (count) =>
excludeDocumentEvidence(completeness, "invalid_protocol_value", count),
)) {
@@ -362,7 +367,7 @@ export function* captureDom(
}
/** Skipped document facts also make their derived URL and hint inventory incomplete. */
const excludeDocumentEvidence = (
export const excludeDocumentEvidence = (
completeness: CdpCaptureCompleteness | undefined,
reason: BrowserExclusionReason,
count: number | null = 1,
@@ -371,24 +376,16 @@ const excludeDocumentEvidence = (
completeness?.exclude("metadata", reason, count);
};
/**
* Read DOMSnapshot documents. A snapshot always describes at least one
* document, so a missing or empty list is invalid rather than an empty DOM.
*/
/** Admit DOMSnapshot documents one by one, counting each unusable entry. */
export const snapshotDocuments = (
value: unknown,
onInvalid: (count: number | null) => void,
): readonly UnknownRecord[] => {
if (!Array.isArray(value) || value.length === 0) {
onInvalid(null);
return [];
}
return value.flatMap((item) => {
values: CdpCommandResult<"DOMSnapshot.captureSnapshot">["documents"],
onInvalid: (count: number) => void,
): readonly UnknownRecord[] =>
values.flatMap((item) => {
const document = recordValue(item);
if (document === undefined) onInvalid(1);
return document === undefined ? [] : [document];
});
};
function* captureDomMetadata(
pending: readonly PendingDomMetadata[],
@@ -436,7 +433,7 @@ function* captureDomMetadata(
}
export const captureAccessibility = (
results: readonly unknown[],
results: readonly CdpCommandResult<"Accessibility.getFullAXTree">[],
options: {
readonly includeText: boolean;
readonly unavailable?: boolean;
@@ -448,16 +445,7 @@ export const captureAccessibility = (
readonly textCapture: WebPageInspection["accessibility"]["text_capture"];
readonly hasUnobservedChildren: boolean;
} => {
const all = results.flatMap((result) => {
const inventory = admitRecords(requiredRecord(result).nodes);
if (inventory === undefined) {
options.completeness?.exclude(
"accessibility",
"invalid_protocol_value",
null,
);
return [];
}
const all = results.flatMap(({ nodes: inventory }) => {
const nodes: {
readonly nodeId: string;
readonly parentId: string | null;
+4 -5
View File
@@ -6,6 +6,7 @@ import {
cdpStringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
import type { CdpCommandResult } from "./protocol/CdpCommands.js";
import { isJsonContentType } from "./CdpCaptureEventHelpers.js";
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
import type { NetworkState } from "./CdpCaptureEventTypes.js";
@@ -13,16 +14,14 @@ import type { NetworkState } from "./CdpCaptureEventTypes.js";
export const ingestResponseBodyShape = (
state: CdpCaptureEventsState,
requestId: string,
value: unknown,
reply: CdpCommandResult<"Network.getResponseBody"> | "malformed",
): void => {
if (!state.network.has(requestId)) return;
const result = recordValue(value);
const body = cdpStringValue(result?.body);
const base64Encoded = result?.base64Encoded;
if (body === undefined || typeof base64Encoded !== "boolean") {
if (reply === "malformed") {
invalidResponseBodyShape(state, requestId);
return;
}
const { body, base64Encoded } = reply;
const decoded = base64Encoded ? decodePaddedBase64(body) : body;
if (decoded === undefined) {
invalidResponseBodyShape(state, requestId);
+7 -2
View File
@@ -3,6 +3,7 @@ import type { CdpContextFrameClaim } from "./CdpScriptContextFacts.js";
import type { InspectWebPageInput } from "../domain/browserObservation.js";
import type { WebPageInspection } from "../domain/browserObservationSchemas.js";
import type { CdpEvent } from "./CdpConnection.js";
import type { CdpCommandResult } from "./protocol/CdpCommands.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import * as bodyShapes from "./CdpCaptureEventBodyShapes.js";
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
@@ -274,13 +275,17 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
}
}
ingestResponseBody(candidate: ResponseBodyCandidate, value: unknown): void {
/** `"malformed"` records the body shape as an invalid protocol value. */
ingestResponseBody(
candidate: ResponseBodyCandidate,
reply: CdpCommandResult<"Network.getResponseBody"> | "malformed",
): void {
if (this.currentResponseBodyRequest(candidate) === undefined) return;
this.#responseBodyExaminedOccurrences.set(
candidate.requestId,
candidate.occurrence,
);
if (this.malformedRedirectRequestIds.has(candidate.requestId)) return;
bodyShapes.ingestResponseBodyShape(this, candidate.requestId, value);
bodyShapes.ingestResponseBodyShape(this, candidate.requestId, reply);
}
}
+9 -11
View File
@@ -11,6 +11,7 @@ import { passiveNetworkCapture } from "../../tests/fixtures/passiveNetworkCaptur
import { captureStorage } from "./CdpCaptureStorage.js";
import { CdpCommandRejection } from "./CdpCommandRejection.js";
import type { CdpConnection } from "./CdpConnection.js";
import { fakeCdpSend } from "../../tests/fixtures/fakeCdpSend.js";
const NO_CACHE_COMMAND = Symbol("unsupported");
@@ -19,7 +20,7 @@ const captureWithCacheResult = async (
storageEntries: unknown = [],
): Promise<Awaited<ReturnType<typeof captureStorage>>["value"]> => {
const connection = {
send(method: string, params: Record<string, unknown>): Promise<unknown> {
send: fakeCdpSend((method, params): Promise<unknown> => {
switch (method) {
case "Storage.getUsageAndQuota":
return Promise.resolve({ usage: 1, quota: 10 });
@@ -46,7 +47,7 @@ const captureWithCacheResult = async (
default:
return Promise.reject(new Error(`Unexpected command: ${method}`));
}
},
}),
} as unknown as CdpConnection;
const { value } = await captureStorage(
{
@@ -123,10 +124,10 @@ it("keeps an omitted IndexedDB remote value unknown", async () => {
},
};
const connection = {
async send(method: string): Promise<unknown> {
send: fakeCdpSend(async (method): Promise<unknown> => {
if (!(method in replies)) throw new Error(method);
return replies[method];
},
}),
} as unknown as CdpConnection;
const { value } = await captureStorage(
{
@@ -192,10 +193,7 @@ it.each(["indexed_db", "cache"] as const)(
"CacheStorage.requestCachedResponse": { response: { body: "" } },
};
const connection = {
async send(
method: string,
params: Record<string, unknown>,
): Promise<unknown> {
send: fakeCdpSend(async (method, params): Promise<unknown> => {
if (
method === "IndexedDB.requestData" ||
method === "CacheStorage.requestEntries"
@@ -225,7 +223,7 @@ it.each(["indexed_db", "cache"] as const)(
}
if (!(method in replies)) throw new Error(method);
return replies[method];
},
}),
} as unknown as CdpConnection;
const { value } = await captureStorage(
{
@@ -277,10 +275,10 @@ const captureCookies = async (
"Network.getCookies": { cookies },
};
const connection = {
async send(method: string): Promise<unknown> {
send: fakeCdpSend(async (method): Promise<unknown> => {
if (!(method in replies)) throw new Error(method);
return replies[method];
},
}),
} as unknown as CdpConnection;
const { value } = await captureStorage(
{
+45 -42
View File
@@ -2,18 +2,17 @@ import type { InspectWebPageInput } from "../domain/browserObservation.js";
import type { WebPageInspection } from "../domain/browserObservationSchemas.js";
import type { BrowserExclusionReason } from "../domain/browserCompleteness.js";
import { CdpConnection } from "./CdpConnection.js";
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
import type { Result } from "../domain/result.js";
import {
optionalCdpCommand,
type CdpOptionalCommandGap,
} from "./CdpOptionalCommand.js";
import {
captureStorageFingerprints,
type CapturedCache,
type CapturedStorageItems,
} from "./CdpCaptureStorageFingerprints.js";
import {
numberValue,
recordValue,
recordsValue,
cdpStringValue,
} from "./CdpCaptureValues.js";
import { recordsValue, cdpStringValue } from "./CdpCaptureValues.js";
/** Capture redacted storage metadata for an authorized page and its origin. */
export const captureStorage = async (
@@ -30,13 +29,11 @@ export const captureStorage = async (
readonly keysExclusion: BrowserExclusionReason | undefined;
}> => {
const origin = new URL(pageUrl).origin;
const quota = recordValue(
await optionalCdpCommand(
context,
"Storage.getUsageAndQuota",
{ origin },
limitations,
),
const quota = await optionalCdpCommand(
context,
"Storage.getUsageAndQuota",
{ origin },
limitations,
);
const local = context.input.include_storage_keys
? await storageItems(context, origin, true, limitations)
@@ -44,7 +41,7 @@ export const captureStorage = async (
const session = context.input.include_storage_keys
? await storageItems(context, origin, false, limitations)
: emptyStorageItems;
const indexedRaw = context.input.include_storage_keys
const indexedReply = context.input.include_storage_keys
? await optionalCdpCommand(
context,
"IndexedDB.requestDatabaseNames",
@@ -52,9 +49,11 @@ export const captureStorage = async (
limitations,
)
: undefined;
const indexedValues = recordValue(indexedRaw)?.databaseNames;
const indexed = stringArray(indexedValues);
const cacheRaw = context.input.include_storage_keys
const indexedValues = indexedReply?.ok
? indexedReply.value.databaseNames
: undefined;
const indexed = stringArray(indexedValues ?? []);
const cacheReply = context.input.include_storage_keys
? await optionalCdpCommand(
context,
"CacheStorage.requestCacheNames",
@@ -62,8 +61,8 @@ export const captureStorage = async (
limitations,
)
: undefined;
const cacheField = recordValue(cacheRaw)?.caches;
const caches = capturedCaches(recordsValue(cacheField));
const cacheValues = cacheReply?.ok ? cacheReply.value.caches : undefined;
const caches = capturedCaches(recordsValue(cacheValues ?? []));
const fingerprints = context.input.include_storage_fingerprints
? await captureStorageFingerprints({
context,
@@ -76,21 +75,20 @@ export const captureStorage = async (
limitations,
})
: { items: [], complete: false };
// A malformed or partly unusable name list is an incomplete enumeration
// rather than an empty one.
const structuredStorageComplete =
indexedRaw !== undefined &&
Array.isArray(indexedValues) &&
indexedValues !== undefined &&
indexed.length === indexedValues.length &&
// Like IndexedDB names, a missing, non-array or partly unusable cache
// list is an incomplete enumeration rather than an empty one.
Array.isArray(cacheField) &&
caches.length === cacheField.length &&
cacheValues !== undefined &&
caches.length === cacheValues.length &&
caches.every(({ id }) => id !== undefined);
const keysExclusion = !context.input.include_storage_keys
? undefined
: local.exclusion === "provider_unavailable" ||
session.exclusion === "provider_unavailable" ||
indexedRaw === undefined ||
cacheRaw === undefined
commandUnavailable(indexedReply) ||
commandUnavailable(cacheReply)
? "provider_unavailable"
: !local.complete || !session.complete || !structuredStorageComplete
? "invalid_protocol_value"
@@ -99,8 +97,8 @@ export const captureStorage = async (
keysExclusion,
value: {
origin,
usage_bytes: numberValue(quota?.usage) ?? null,
quota_bytes: numberValue(quota?.quota) ?? null,
usage_bytes: quota.ok ? quota.value.usage : null,
quota_bytes: quota.ok ? quota.value.quota : null,
local_storage_keys: local.items.map(({ key }) => key),
session_storage_keys: session.items.map(({ key }) => key),
indexed_db_names: [...indexed],
@@ -137,20 +135,21 @@ const storageItems = async (
isLocalStorage: boolean,
limitations: string[],
): Promise<StorageItemsCapture> => {
const raw = await optionalCdpCommand(
const reply = await optionalCdpCommand(
context,
"DOMStorage.getDOMStorageItems",
{ storageId: { securityOrigin: origin, isLocalStorage } },
limitations,
);
const entries = recordValue(raw)?.entries;
if (raw === undefined || !Array.isArray(entries))
if (!reply.ok)
return {
items: [],
complete: false,
exclusion:
raw === undefined ? "provider_unavailable" : "invalid_protocol_value",
exclusion: commandUnavailable(reply)
? "provider_unavailable"
: "invalid_protocol_value",
};
const { entries } = reply.value;
const items = entries.flatMap((entry) => {
if (!Array.isArray(entry)) return [];
const key = cdpStringValue(entry[0]);
@@ -165,10 +164,14 @@ const storageItems = async (
};
};
const stringArray = (value: unknown): readonly string[] =>
Array.isArray(value)
? value.flatMap((item) => {
const text = cdpStringValue(item);
return text === undefined ? [] : [text];
})
: [];
const stringArray = (values: readonly unknown[]): readonly string[] =>
values.flatMap((item) => {
const text = cdpStringValue(item);
return text === undefined ? [] : [text];
});
const commandUnavailable = (
reply: Result<unknown, CdpOptionalCommandGap> | undefined,
): boolean =>
reply === undefined ||
(!reply.ok && reply.error._tag === "CdpCommandUnavailable");
+25 -51
View File
@@ -117,21 +117,17 @@ const addCookies = async (
run.limitations.push(
"Cookie fingerprints cover cookies applicable to the current main-frame URL, not every path on its origin.",
);
const raw = await optionalCdpCommand(
const reply = await optionalCdpCommand(
run.context,
"Network.getCookies",
{ urls: [pageUrl] },
run.limitations,
);
if (raw === undefined) {
run.state.complete = false;
return;
}
const cookieValues = recordValue(raw)?.cookies;
if (!Array.isArray(cookieValues)) {
if (!reply.ok) {
run.state.complete = false;
return;
}
const cookieValues = reply.value.cookies;
const cookies = recordsValue(cookieValues);
if (cookies.length !== cookieValues.length) run.state.complete = false;
for (const cookie of cookies) {
@@ -169,34 +165,25 @@ const addIndexedDb = async (
names: readonly string[],
): Promise<void> => {
for (const databaseName of names) {
const raw = await optionalCdpCommand(
const reply = await optionalCdpCommand(
run.context,
"IndexedDB.requestDatabase",
{ securityOrigin: origin, databaseName },
run.limitations,
);
const database = recordValue(recordValue(raw)?.databaseWithObjectStores);
if (raw === undefined || database === undefined) {
if (!reply.ok) {
run.state.complete = false;
continue;
}
if (cdpStringValue(database.name) !== databaseName) {
run.state.complete = false;
continue;
}
if (!Array.isArray(database.objectStores)) {
const database = reply.value.databaseWithObjectStores;
if (database.name !== databaseName) {
run.state.complete = false;
continue;
}
const stores = recordsValue(database.objectStores);
if (stores.length !== database.objectStores.length)
run.state.complete = false;
const version =
typeof database.version === "number" &&
Number.isSafeInteger(database.version) &&
database.version >= 0
? database.version
: undefined;
const { version } = database;
if (version === undefined) {
const limitation =
"An IndexedDB schema fingerprint is incomplete because its database version is unavailable, invalid, or outside exact integer precision.";
@@ -290,7 +277,7 @@ const addIndexedDbRecords = async (
): Promise<void> => {
let skipCount = 0;
while (true) {
const raw = await optionalCdpCommand(
const reply = await optionalCdpCommand(
run.context,
"IndexedDB.requestData",
{
@@ -302,18 +289,11 @@ const addIndexedDbRecords = async (
},
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
return;
}
if (
!Array.isArray(result.objectStoreDataEntries) ||
typeof result.hasMore !== "boolean"
) {
if (!reply.ok) {
run.state.complete = false;
return;
}
const result = reply.value;
const examinedCount = result.objectStoreDataEntries.length;
const entries = recordsValue(result.objectStoreDataEntries);
if (entries.length !== result.objectStoreDataEntries.length)
@@ -335,7 +315,7 @@ const addIndexedDbRecords = async (
key !== undefined && primaryKey !== undefined && value !== undefined,
});
}
if (result.hasMore !== true) return;
if (!result.hasMore) return;
if (
examinedCount === 0 ||
skipCount > Number.MAX_SAFE_INTEGER - examinedCount
@@ -352,38 +332,31 @@ const addCaches = async (
caches: readonly CapturedCache[],
): Promise<void> => {
for (const cache of caches) {
if (cache.id === undefined) {
const cacheId = cache.id;
if (cacheId === undefined) {
run.state.complete = false;
continue;
}
let skipCount = 0;
let returnCount: number | undefined;
while (returnCount === undefined || skipCount < returnCount) {
const raw = await optionalCdpCommand(
const reply = await optionalCdpCommand(
run.context,
"CacheStorage.requestEntries",
{ cacheId: cache.id, skipCount, pageSize: STORAGE_ENTRY_PAGE_SIZE },
{ cacheId, skipCount, pageSize: STORAGE_ENTRY_PAGE_SIZE },
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
break;
}
if (
!Array.isArray(result.cacheDataEntries) ||
typeof result.returnCount !== "number" ||
!Number.isSafeInteger(result.returnCount) ||
result.returnCount < 0
) {
if (!reply.ok) {
run.state.complete = false;
break;
}
const result = reply.value;
const examinedCount = result.cacheDataEntries.length;
const entries = recordsValue(result.cacheDataEntries);
if (entries.length !== result.cacheDataEntries.length)
run.state.complete = false;
for (const entry of entries) await addCacheEntry(run, cache, entry);
for (const entry of entries)
await addCacheEntry(run, { name: cache.name, id: cacheId }, entry);
returnCount = result.returnCount;
if (skipCount + examinedCount >= returnCount) break;
if (
@@ -400,7 +373,7 @@ const addCaches = async (
const addCacheEntry = async (
run: FingerprintRun,
cache: CapturedCache,
cache: { readonly name: string; readonly id: string },
entry: Readonly<Record<string, unknown>>,
): Promise<void> => {
const requestURL = cdpStringValue(entry.requestURL);
@@ -426,14 +399,15 @@ const addCacheEntry = async (
run.state.complete = false;
return;
}
const raw = await optionalCdpCommand(
const reply = await optionalCdpCommand(
run.context,
"CacheStorage.requestCachedResponse",
{ cacheId: cache.id, requestURL, requestHeaders },
run.limitations,
);
const body = cdpStringValue(recordValue(recordValue(raw)?.response)?.body);
const decoded = body === undefined ? undefined : decodePaddedBase64(body);
const decoded = reply.ok
? decodePaddedBase64(reply.value.response.body)
: undefined;
const complete = decoded !== undefined;
if (!complete) run.state.complete = false;
addFingerprint(run.state, {
-8
View File
@@ -1,5 +1,4 @@
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
@@ -42,13 +41,6 @@ export const resourceContentSize = (
: err({ _tag: "InvalidCdpResourceSize" });
};
export const requiredRecord = (value: unknown): UnknownRecord => {
const record = recordValue(value);
if (record === undefined)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
return record;
};
export const isHttpUrl = (value: string | undefined): boolean => {
if (value === undefined) return false;
try {
+13 -11
View File
@@ -11,11 +11,11 @@ import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { delayWithCancellation, cdpStringValue } from "./CdpCaptureValues.js";
import {
delayWithCancellation,
requiredRecord,
cdpStringValue,
} from "./CdpCaptureValues.js";
CdpMalformedReply,
type CdpCommandResult,
} from "./protocol/CdpCommands.js";
import {
cdpFrameUrl,
snapshotDocuments,
@@ -776,17 +776,19 @@ const captureDom = async (
completeness: CdpCaptureCompleteness,
): Promise<ElectronPageInspection["dom"]> => {
const nodeValueLengthUnit = "utf8-bytes";
const result = requiredRecord(
await context.connection.send(
const invalid = (count: number | null) =>
completeness.exclude("dom", "invalid_protocol_value", count);
let result: CdpCommandResult<"DOMSnapshot.captureSnapshot">;
try {
result = await context.connection.send(
"DOMSnapshot.captureSnapshot",
{ computedStyles: [], includePaintOrder: false, includeDOMRects: false },
context.sessionId,
context.signal,
),
);
const invalid = (count: number | null) =>
completeness.exclude("dom", "invalid_protocol_value", count);
if (!Array.isArray(result.strings)) {
);
} catch (cause: unknown) {
// A malformed snapshot leaves the DOM unknown rather than empty.
if (!(cause instanceof CdpMalformedReply)) throw cause;
invalid(null);
return {
total_nodes: 0,
+2 -2
View File
@@ -37,13 +37,13 @@ export const captureElectronWorkers = async (input: {
{},
input.limitations,
);
if (result === undefined) {
if (!result.ok) {
input.completeness.unavailable("workers");
return [];
}
const workers: ElectronPageInspection["workers"] = [];
// A missing target list or a non-record entry is unreadable, not empty.
const targetInfos = recordValue(result)?.targetInfos;
const targetInfos = recordValue(result.value)?.targetInfos;
if (!Array.isArray(targetInfos)) {
input.completeness.exclude("workers", "invalid_protocol_value", null);
return [];
+30 -9
View File
@@ -1,8 +1,22 @@
import type { CdpSendParams, CdpSendResult } from "./protocol/CdpCommands.js";
import { err, ok, type Result } from "../domain/result.js";
import {
CdpMalformedReply,
type CdpSendParams,
type CdpSendResult,
} from "./protocol/CdpCommands.js";
import { CdpCommandRejection } from "./CdpCommandRejection.js";
import { CdpConnection } from "./CdpConnection.js";
/** Execute an optional CDP method while preserving transport and cancellation failures. */
/** Why an optional command left its section without a reply. */
export type CdpOptionalCommandGap =
| { readonly _tag: "CdpCommandUnavailable" }
| { readonly _tag: "CdpMalformedReply"; readonly reply: CdpMalformedReply };
/**
* Execute an optional CDP method. "Method not found" and a reply that fails
* its result schema are returned as gaps for the caller's section to record;
* transport and cancellation failures still propagate.
*/
export const optionalCdpCommand = async <M extends string>(
context: {
readonly connection: CdpConnection;
@@ -12,18 +26,25 @@ export const optionalCdpCommand = async <M extends string>(
method: M,
parameters: CdpSendParams<M>,
limitations: string[],
): Promise<CdpSendResult<M> | undefined> => {
): Promise<Result<CdpSendResult<M>, CdpOptionalCommandGap>> => {
try {
return await context.connection.send(
method,
parameters,
context.sessionId,
context.signal,
return ok(
await context.connection.send(
method,
parameters,
context.sessionId,
context.signal,
),
);
} catch (cause: unknown) {
if (cause instanceof CdpMalformedReply) {
const limitation = `${method} returned a malformed result; the section that reads it is incomplete.`;
if (!limitations.includes(limitation)) limitations.push(limitation);
return err({ _tag: "CdpMalformedReply", reply: cause });
}
if (!(cause instanceof CdpCommandRejection) || cause.code !== -32_601)
throw cause;
limitations.push(`${method} was unavailable from this browser target.`);
return undefined;
return err({ _tag: "CdpCommandUnavailable" });
}
};
+47 -19
View File
@@ -19,11 +19,16 @@ import {
captureDom,
captureFrames,
captureResources,
emptyDomCapture,
excludeDocumentEvidence,
type CapturedResource,
type DomCapture,
} from "./CdpCaptureDocuments.js";
import { observedFrameUrl } from "./protocol/CdpFrameTree.js";
import { CdpMalformedReply } from "./protocol/CdpCommands.js";
import {
CdpMalformedReply,
type CdpCommandResult,
} from "./protocol/CdpCommands.js";
import { capturedSvgNodeKind } from "./CdpCaptureDomNamespaces.js";
import {
allowedSanitizedUrl,
@@ -267,9 +272,11 @@ const captureJsonResponseBodies = async (
state.events.responseBodyUnavailable(candidate);
continue;
}
let result: unknown;
let reply: Awaited<
ReturnType<typeof optionalCdpCommand<"Network.getResponseBody">>
>;
try {
result = await optionalCdpCommand(
reply = await optionalCdpCommand(
state.context,
"Network.getResponseBody",
{ requestId: candidate.requestId },
@@ -289,8 +296,11 @@ const captureJsonResponseBodies = async (
);
continue;
}
if (result !== undefined) {
state.events.ingestResponseBody(candidate, result);
if (reply.ok || reply.error._tag === "CdpMalformedReply") {
state.events.ingestResponseBody(
candidate,
reply.ok ? reply.value : "malformed",
);
continue;
}
for (const remaining of requests.slice(index))
@@ -331,16 +341,28 @@ const authorizeObservationWindow = async (
const capturePageDom = async (state: CaptureState): Promise<DomCapture> => {
const { context, allowedOrigins } = state;
const result = await context.connection.send(
"DOMSnapshot.captureSnapshot",
{
computedStyles: [],
includePaintOrder: false,
includeDOMRects: false,
},
context.sessionId,
context.signal,
);
let result: CdpCommandResult<"DOMSnapshot.captureSnapshot">;
try {
result = await context.connection.send(
"DOMSnapshot.captureSnapshot",
{
computedStyles: [],
includePaintOrder: false,
includeDOMRects: false,
},
context.sessionId,
context.signal,
);
} catch (cause: unknown) {
// A malformed snapshot leaves the DOM and its derived metadata unknown.
if (!(cause instanceof CdpMalformedReply)) throw cause;
excludeDocumentEvidence(
state.events.completeness,
"invalid_protocol_value",
null,
);
return emptyDomCapture;
}
const capture = captureDom(
result,
allowedOrigins,
@@ -464,17 +486,23 @@ const accessibilityForFrames = async (
frames: readonly { readonly frame_id: string }[],
): Promise<ReturnType<typeof captureAccessibility>> => {
const { context, limitations, events } = state;
const results: unknown[] = [];
const results: CdpCommandResult<"Accessibility.getFullAXTree">[] = [];
let unavailable = false;
for (const frame of frames) {
const result = await optionalCdpCommand(
const reply = await optionalCdpCommand(
context,
"Accessibility.getFullAXTree",
{ frameId: frame.frame_id },
limitations,
);
if (result === undefined) unavailable = true;
else results.push(result);
if (reply.ok) results.push(reply.value);
else if (reply.error._tag === "CdpCommandUnavailable") unavailable = true;
else
events.completeness.exclude(
"accessibility",
"invalid_protocol_value",
null,
);
}
if (unavailable) events.completeness.unavailable("accessibility");
const capture = captureAccessibility(results, {
+6 -4
View File
@@ -36,14 +36,16 @@ export const captureWorkers = async (
limitations,
);
const items: WebPageInspection["workers"] = [];
if (result === undefined) completeness.unavailable("workers");
const targets = admitRecords(recordValue(result)?.targetInfos);
if (result !== undefined && targets === undefined) {
if (!result.ok) completeness.unavailable("workers");
const targets = result.ok
? admitRecords(recordValue(result.value)?.targetInfos)
: [];
if (targets === undefined) {
completeness.exclude("workers", "invalid_protocol_value", null);
return items;
}
let malformedEntries = 0;
for (const entry of targets ?? []) {
for (const entry of targets) {
const parsed = parseCdpWorkerTarget(entry);
if (!parsed.ok) {
malformedEntries += 1;
+4 -1
View File
@@ -127,7 +127,10 @@ export const discoverWebMcp = async (
{},
limitations,
);
const available = enabled !== undefined;
// WebMCP.enable is an acknowledgement; a malformed one is a protocol error.
if (!enabled.ok && enabled.error._tag === "CdpMalformedReply")
throw enabled.error.reply;
const available = enabled.ok;
if (!available) {
completeness.unavailable("webmcp_tools");
} else
@@ -411,12 +411,15 @@ describe("request route cleanup", () => {
const page = fakePage({});
const secrets = resolved(parsed);
const cancel = new AbortController();
const began = Date.now();
const began = performance.now();
const unroute = vi.spyOn(page, "unroute").mockImplementation(async () => {
if (end === "cancellation")
cancel.abort("cancelled during final route cleanup");
else {
const now = vi.spyOn(Date, "now").mockReturnValue(began + 5001);
// The step deadline is monotonic; move that clock past it.
const now = vi
.spyOn(performance, "now")
.mockReturnValue(began + 6_000);
onTestFinished(() => now.mockRestore());
}
});
+20 -21
View File
@@ -1,3 +1,4 @@
import { Deadline } from "../domain/deadline.js";
import { jsonStringByteLength } from "../domain/jsonStringByteLength.js";
import { jsonValueByteLength } from "../domain/jsonValueByteLength.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -197,7 +198,12 @@ interface PageRequest {
readonly method: string;
readonly headers: [string, string][];
readonly body: string | undefined;
readonly deadline: number | undefined;
/**
* The step deadline on the page's wall clock. The host keeps a monotonic
* deadline and converts what is left of it when the request is built,
* because the page cannot read the host's monotonic clock.
*/
readonly deadlineEpochMs: number | undefined;
/** Return the response text up to this many characters, for a step that saves values from it. */
readonly readLimit: number | undefined;
}
@@ -224,9 +230,9 @@ const sendFromPage = (
"Request steps require a page without a controlling service worker so cancellation can guard dispatch.",
};
const remaining =
request.deadline === undefined
request.deadlineEpochMs === undefined
? undefined
: request.deadline - Date.now();
: request.deadlineEpochMs - Date.now();
if (remaining !== undefined && remaining <= 0)
return { error: "The request ran out of time before it was sent." };
const controller = new AbortController();
@@ -305,7 +311,7 @@ export const performScenarioRequest = async (input: {
const deadline =
action.timeout_ms === undefined
? undefined
: Date.now() + action.timeout_ms;
: Deadline.after(action.timeout_ms);
const pageOrigin = originOf(page.url());
if (pageOrigin !== startOrigin)
throw new ScenarioRequestError(
@@ -355,8 +361,7 @@ export const performScenarioRequest = async (input: {
if (action.json !== undefined && !hasContentType)
appendHeader("content-type", "application/json");
// A step the boundary abandoned, or whose time ran out while values were read, sends nothing.
const remaining = deadline === undefined ? undefined : deadline - Date.now();
if (signal?.aborted === true || (remaining !== undefined && remaining <= 0))
if (signal?.aborted === true || deadline?.expired() === true)
throw new ScenarioRequestError(
`Request step ${action.step_id} ran out of time before its request was sent.`,
);
@@ -369,7 +374,8 @@ export const performScenarioRequest = async (input: {
method: action.method,
headers,
body: json === undefined ? undefined : JSON.stringify(json),
deadline,
deadlineEpochMs:
deadline === undefined ? undefined : Date.now() + deadline.remainingMs(),
readLimit:
action.save.length > 0 ? MAX_SAVED_RESPONSE_CHARACTERS : undefined,
};
@@ -381,7 +387,7 @@ export const performScenarioRequest = async (input: {
method: action.method,
headers: [],
body: request.body ?? null,
deadline: deadline ?? null,
deadlineEpochMs: request.deadlineEpochMs ?? null,
readLimit: request.readLimit ?? null,
},
envelopeLimit,
@@ -419,10 +425,7 @@ export const performScenarioRequest = async (input: {
await route.fallback();
return;
}
if (
signal?.aborted === true ||
(deadline !== undefined && Date.now() >= deadline)
)
if (signal?.aborted === true || deadline?.expired() === true)
await route.abort("aborted");
else {
await route.fallback();
@@ -563,13 +566,10 @@ const namesResponse = (
/** Publication must still belong to the step after its last asynchronous boundary. */
const assertResponseSaveActive = (
stepId: string,
deadline: number | undefined,
deadline: Deadline | undefined,
signal: AbortSignal | undefined,
): void => {
if (
signal?.aborted === true ||
(deadline !== undefined && Date.now() >= deadline)
)
if (signal?.aborted === true || deadline?.expired() === true)
throw new ScenarioRequestError(
`Step ${stepId} ended before its saved response was read, so nothing was saved.`,
);
@@ -579,7 +579,7 @@ const assertResponseSaveActive = (
const beforeStepEnds = <T>(
work: Promise<T>,
stepId: string,
deadline: number | undefined,
deadline: Deadline | undefined,
signal: AbortSignal | undefined,
): Promise<T> =>
new Promise<T>((resolve, reject) => {
@@ -597,8 +597,7 @@ const beforeStepEnds = <T>(
);
};
work.catch(() => undefined);
const remaining =
deadline === undefined ? undefined : deadline - Date.now();
const remaining = deadline?.remainingMs();
if (
signal?.aborted === true ||
(remaining !== undefined && remaining <= 0)
@@ -643,7 +642,7 @@ export const awaitSavedResponse = (
},
): SavedResponseWait => {
const { stepId, spec, startOrigin, timeout, secrets, signal } = step;
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
const deadline = timeout === undefined ? undefined : Deadline.after(timeout);
const pattern = pathPattern(spec.path);
const started = new Set<Request>();
const protectResponse = secrets.responseProtector(stepId, spec.save);
+3 -8
View File
@@ -1,4 +1,5 @@
import { captureBudgets } from "../CaptureBudgets.js";
import { readLeb128, ULEB64 } from "../../../domain/leb128.js";
import { err, ok, type Result } from "../../../domain/result.js";
import { setImmediate } from "node:timers/promises";
import type { ProtobufField } from "../../../domain/protobufWire.js";
@@ -35,14 +36,8 @@ export const readProtobufVarint = (
start: number,
end = bytes.length,
): { value: bigint; end: number } | undefined => {
let value = 0n;
for (let index = 0; index < 10 && start + index < end; index++) {
const byte = bytes[start + index]!;
if (index === 9 && byte > 1) return undefined;
value |= BigInt(byte & 127) << BigInt(index * 7);
if (byte < 128) return { value, end: start + index + 1 };
}
return undefined;
const read = readLeb128(bytes, start, end, ULEB64);
return "failure" in read ? undefined : { value: read.value, end: read.next };
};
const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
+55
View File
@@ -80,6 +80,25 @@ const preciseCoverageReply = z.object({
),
});
/**
* An inventory whose entries the reading section admits one by one, so one
* malformed entry is counted there as a gap instead of rejecting the reply.
*/
const inventory = z.array(z.unknown());
/**
* IndexedDB versions are exact non-negative integers. An omitted or other value
* leaves only the version unknown; the database's stores stay readable.
*/
const indexedDbVersion = z
.unknown()
.transform((value) =>
typeof value === "number" && Number.isSafeInteger(value) && value >= 0
? value
: undefined,
)
.optional();
/**
* One result schema per command REA sends. Each schema is the only reader of
* that command's raw reply; consumers receive its parsed output.
@@ -103,6 +122,21 @@ const CDP_COMMAND_REPLIES = {
object: z.object({ objectId: z.string().min(1) }),
}),
"DOMDebugger.getEventListeners": eventListenersReply,
"Accessibility.getFullAXTree": z.object({ nodes: inventory }),
"CacheStorage.requestCacheNames": z.object({ caches: inventory }),
"CacheStorage.requestCachedResponse": z.object({
response: z.object({ body: z.string() }),
}),
"CacheStorage.requestEntries": z.object({
cacheDataEntries: inventory,
returnCount: z.int().min(0),
}),
"DOMSnapshot.captureSnapshot": z.object({
// A snapshot always describes at least one document.
documents: inventory.min(1),
strings: inventory,
}),
"DOMStorage.getDOMStorageItems": z.object({ entries: inventory }),
"Debugger.disable": acknowledgement,
"Debugger.enable": acknowledgement,
"Debugger.evaluateOnCallFrame": z.object({
@@ -118,8 +152,25 @@ const CDP_COMMAND_REPLIES = {
"Emulation.setFocusEmulationEnabled": acknowledgement,
"Emulation.setLocaleOverride": acknowledgement,
"Emulation.setTimezoneOverride": acknowledgement,
"IndexedDB.requestData": z.object({
objectStoreDataEntries: inventory,
hasMore: z.boolean(),
}),
"IndexedDB.requestDatabase": z.object({
databaseWithObjectStores: z.object({
name: z.string(),
version: indexedDbVersion,
objectStores: inventory,
}),
}),
"IndexedDB.requestDatabaseNames": z.object({ databaseNames: inventory }),
"Network.disable": acknowledgement,
"Network.enable": acknowledgement,
"Network.getCookies": z.object({ cookies: inventory }),
"Network.getResponseBody": z.object({
body: z.string(),
base64Encoded: z.boolean(),
}),
"Page.addScriptToEvaluateOnNewDocument": z.object({
identifier: z.string(),
}),
@@ -147,6 +198,10 @@ const CDP_COMMAND_REPLIES = {
"Runtime.releaseObjectGroup": acknowledgement,
"Runtime.runIfWaitingForDebugger": acknowledgement,
"Storage.getStorageKey": z.object({ storageKey: z.string() }),
"Storage.getUsageAndQuota": z.object({
usage: z.number(),
quota: z.number(),
}),
"Target.attachToTarget": z.object({ sessionId: z.string().min(1) }),
"Target.detachFromTarget": acknowledgement,
"Target.getTargetInfo": z.object({
@@ -1,20 +1,4 @@
{
"src/browser/CdpCaptureStorage.ts": {
"Storage.getUsageAndQuota": 1,
"IndexedDB.requestDatabaseNames": 1,
"CacheStorage.requestCacheNames": 1,
"DOMStorage.getDOMStorageItems": 1
},
"src/browser/CdpCaptureStorageFingerprints.ts": {
"Network.getCookies": 1,
"IndexedDB.requestDatabase": 1,
"IndexedDB.requestData": 1,
"CacheStorage.requestEntries": 1,
"CacheStorage.requestCachedResponse": 1
},
"src/browser/CdpElectronInspection.ts": {
"DOMSnapshot.captureSnapshot": 1
},
"src/browser/CdpElectronWorkers.ts": {
"Target.getTargets": 1
},
@@ -22,11 +6,6 @@
"Browser.getVersion": 1,
"Target.getTargets": 1
},
"src/browser/CdpPageCapture.ts": {
"Network.getResponseBody": 2,
"DOMSnapshot.captureSnapshot": 1,
"Accessibility.getFullAXTree": 1
},
"src/browser/CdpPageCaptureWorkers.ts": {
"Target.getTargets": 1
},
+59 -86
View File
@@ -1,7 +1,3 @@
import { z } from "incur";
import { cliDecimalField } from "./options.js";
import { producerLimitsOption } from "./producerLimitsOption.js";
import { pwntoolsProducerLimitsSchema } from "../domain/native/pwntoolsResourceLimits.js";
import {
createByteEntropyService,
createRecordedCrashService,
@@ -22,17 +18,11 @@ import {
createNativeExportsService,
} from "../composition/binaryDiagnostics.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { inspectBinaryLayoutInputSchema } from "../domain/native/binaryLayout.js";
import { inspectRecordedCrashInputSchema } from "../domain/native/recordedCrash.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { withEvidenceCallerInputPath } from "../domain/evidence.js";
import { BYTE_ENTROPY_PROVIDER } from "../domain/investigationProviders.js";
import { localPathStringSchema } from "../domain/localPath.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../contracts/native/binaryDiagnosticsToolContracts.js";
import { contractNamed } from "./contractCliDescription.js";
import {
@@ -319,81 +309,64 @@ export const registerBinaryDiagnosticsCommands = (
},
deliverWithService(createNativeExportsService, "rea-native-exports"),
);
const service = createBinaryLayoutService(environment);
cli.command(CLI_COMMANDS.inspectBinaryLayout, {
description:
"Inspect binary file/linked layout without executing the selected object",
args: z.object({
path: localPathStringSchema.describe(
"Local ELF binary or relocatable object",
),
}),
options: z.object({
producerLimits: producerLimitsOption(pwntoolsProducerLimitsSchema),
pwntoolsTimeoutMs: cliDecimalField(
inspectBinaryLayoutInputSchema.shape.pwntools_timeout_ms,
),
}),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectBinaryLayout, async () => {
const result = await service.inspectAndClose(
{
path: absoluteCallerPath(args.path),
...(options.producerLimits === undefined
? {}
: { producer_limits: options.producerLimits }),
...(options.pwntoolsTimeoutMs === undefined
? {}
: { pwntools_timeout_ms: options.pwntoolsTimeoutMs }),
},
{ signal },
);
return result.ok
? withEvidenceCallerInputPath(result.value, args.path)
: projectAnalysisError(result.error);
}),
),
});
const producerLimitsHelp =
"JSON producer budget overrides. Keys and units follow this operation's producer_limits contract; changes apply on this call without restart and preserve tighter inherited OS limits.";
const layout = createBinaryLayoutService(environment);
registerContractCommand(
cli,
logger,
contract("inspect_binary_layout"),
{
command: CLI_COMMANDS.inspectBinaryLayout,
description:
"Inspect binary file/linked layout without executing the selected object",
positionals: ["path"],
callerPaths: ["path"],
jsonText: ["producer_limits"],
fields: {
path: { description: "Local ELF binary or relocatable object" },
producer_limits: { description: producerLimitsHelp },
},
omit: {
detail:
"One-shot output is complete Evidence; this command has no summary delivery",
},
},
async (input, { signal, callerInputs }) => {
const result = await layout.inspectAndClose(input, { signal });
return result.ok
? withEvidenceCallerInputPath(result.value, callerInputs.path)
: projectAnalysisError(result.error);
},
);
const recorded = createRecordedCrashService(environment);
cli.command(CLI_COMMANDS.inspectRecordedCrash, {
description:
"Inspect supplied core registers/signals and optional debugger mapping evidence",
args: z.object({
path: localPathStringSchema.describe(
"Local Linux ELF64 amd64 or AArch64 little-endian core",
),
}),
options: z.object({
producerLimits: producerLimitsOption(pwntoolsProducerLimitsSchema),
debuggerContext: z
.boolean()
.default(false)
.describe("Add BYO core-only GDB/pwndbg mapping candidates"),
pwntoolsTimeoutMs: cliDecimalField(
inspectRecordedCrashInputSchema.shape.pwntools_timeout_ms,
),
}),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectRecordedCrash, async () => {
const result = await recorded.inspectAndClose(
{
path: absoluteCallerPath(args.path),
include_debugger_context: options.debuggerContext,
...(options.producerLimits === undefined
? {}
: { producer_limits: options.producerLimits }),
...(options.pwntoolsTimeoutMs === undefined
? {}
: { pwntools_timeout_ms: options.pwntoolsTimeoutMs }),
},
{ signal },
);
return result.ok
? withEvidenceCallerInputPath(result.value, args.path)
: projectAnalysisError(result.error);
}),
),
});
registerContractCommand(
cli,
logger,
contract("inspect_recorded_crash"),
{
command: CLI_COMMANDS.inspectRecordedCrash,
description:
"Inspect supplied core registers/signals and optional debugger mapping evidence",
positionals: ["path"],
callerPaths: ["path"],
jsonText: ["producer_limits"],
fields: {
path: {
description: "Local Linux ELF64 amd64 or AArch64 little-endian core",
},
producer_limits: { description: producerLimitsHelp },
include_debugger_context: {
name: "debuggerContext",
description: "Add BYO core-only GDB/pwndbg mapping candidates",
},
},
},
async (input, { signal, callerInputs }) => {
const result = await recorded.inspectAndClose(input, { signal });
return result.ok
? withEvidenceCallerInputPath(result.value, callerInputs.path)
: projectAnalysisError(result.error);
},
);
};
+50 -1
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { localPathStringSchema } from "../domain/localPath.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { analysisEvidenceDeliveryOptions } from "./analysisEvidenceDelivery.js";
import { safeParseJson } from "../domain/safeJson.js";
import { cliDecimalShape } from "./options.js";
/**
@@ -50,6 +51,11 @@ export interface CliContractProjection<Field extends string> {
* resolves it with `absoluteCallerPath` before the contract sees it.
*/
readonly callerPaths?: readonly Field[];
/**
* Structured fields taken as one JSON text argument. The text is decoded
* at argv parsing and then admitted by the contract field's own schema.
*/
readonly jsonText?: readonly Field[];
readonly fields?: { readonly [Key in Field]?: CliFieldProjection };
/**
* Optional fields this one-shot command does not expose, each with the
@@ -105,6 +111,8 @@ export interface ContractCliParameter {
readonly decimal: boolean;
/** Resolved with `absoluteCallerPath` before the contract sees it. */
readonly callerPath: boolean;
/** The value is JSON text decoded into the contract field. */
readonly jsonText: boolean;
/** Selects CLI Evidence delivery and is not analysis input. */
readonly delivery: boolean;
}
@@ -196,6 +204,39 @@ const core = (value: z.ZodType): z.ZodType => {
* Accept only field forms argv can carry, so a new contract field cannot
* reach the CLI with an unreviewed spelling.
*/
const kebabCase = (key: string): string =>
key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);
/**
* JSON text for a structured contract field. Argv carries text; the decoded
* value is admitted by the contract field itself, so `--schema` advertises
* the contract's structure.
*/
const jsonTextField = (declared: z.ZodType, flag: string): z.ZodType => {
const value =
declared instanceof z.ZodOptional || declared instanceof z.ZodExactOptional
? (declared.unwrap() as z.ZodType)
: declared;
const expected =
core(value) instanceof z.ZodObject ? "a JSON object" : "valid JSON";
const decoded = z
.string()
.transform((text, context) => {
const parsed = safeParseJson(text);
if (parsed.ok) return parsed.value;
context.addIssue({
code: "custom",
message: `${flag} must be ${expected}`,
});
return z.NEVER;
})
.pipe(value);
const admitted = admitsOmission(declared) ? decoded.optional() : decoded;
return declared.description === undefined
? admitted
: admitted.describe(declared.description);
};
const assertArgvField = (
contract: string,
field: string,
@@ -312,6 +353,9 @@ export const describeContractCommand = <Contract extends ProjectedContract>(
const fieldProjections: Readonly<
Record<string, CliFieldProjection | undefined>
> = projection.fields ?? {};
const jsonTextFields: ReadonlySet<string> = new Set(
projection.jsonText ?? [],
);
const omitted: Readonly<Record<string, string>> = Object.fromEntries(
Object.entries(projection.omit ?? {}).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
@@ -320,6 +364,7 @@ export const describeContractCommand = <Contract extends ProjectedContract>(
for (const field of [
...positionals,
...callerPaths,
...jsonTextFields,
...Object.keys(fieldProjections),
...Object.keys(omitted),
])
@@ -335,8 +380,11 @@ export const describeContractCommand = <Contract extends ProjectedContract>(
const projected = fieldProjections[field];
const callerPath = callerPaths.has(field);
const delivery = evidenceDelivery && field === "detail";
const jsonText = jsonTextFields.has(field);
const key = projected?.name ?? camelCase(field);
let schema: z.ZodType;
if (delivery) schema = analysisEvidenceDeliveryOptions.detail;
else if (jsonText) schema = jsonTextField(declared, kebabCase(key));
else if (callerPath) {
schema = admitsOmission(declared)
? localPathStringSchema.optional()
@@ -353,7 +401,7 @@ export const describeContractCommand = <Contract extends ProjectedContract>(
const value = core(declared);
return {
field,
key: projected?.name ?? camelCase(field),
key,
positional: positionals.includes(field),
alias: projected?.alias,
description,
@@ -363,6 +411,7 @@ export const describeContractCommand = <Contract extends ProjectedContract>(
decimal: value instanceof z.ZodNumber,
callerPath,
delivery,
jsonText,
};
};
const parameters = [
+4 -2
View File
@@ -28,10 +28,12 @@ export const cutterCommandResultSchema = z.strictObject({
execution_state: z.enum(["not_started", "complete", "failed", "unknown"]),
error: z.string().nullable(),
message: z.string().nullable(),
output_truncated: z.boolean(),
/** Null when the bridge did not declare whether output was omitted. */
output_truncated: z.boolean().nullable(),
cutter_version: z.string().nullable(),
current_file: z.string().nullable(),
document_generation: z.int().nonnegative(),
/** Null when the bridge did not report the generation after the command. */
document_generation: z.int().nonnegative().nullable(),
identity_status: z.literal("partial"),
});
+54 -12
View File
@@ -42,6 +42,10 @@ import {
} from "../domain/cutterDiscovery.js";
import { err, ok, type Result } from "../domain/result.js";
import { cutterBridgeMac } from "./cutterBridgeMac.js";
import {
cutterBridgeSource,
packagedCutterPluginPath,
} from "./CutterBridgeSource.js";
import { CutterBridgeResponseFrames } from "./cutterAuthenticatedResponse.js";
import { requireWindowsNativeAuthority } from "../windows/WindowsNativeLoader.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
@@ -60,7 +64,12 @@ import { currentAnalysisOperationSnapshot } from "../domain/analysisOperationSna
import type { AnalysisSettingsReader } from "../domain/analysisSettings.js";
const descriptorSchema = z.object({
...cutterSessionSchema.shape,
...cutterSessionSchema.omit({ bridge_source: true }).shape,
bridge_source_sha256: z
.string()
.regex(/^[0-9a-f]{64}$/)
.nullable()
.optional(),
host: z.literal("127.0.0.1"),
port: z.int().min(1).max(65535),
token: z.string().min(20),
@@ -95,6 +104,17 @@ const responseSchema = z.object({
.regex(/^[0-9a-f]{16}$/)
.optional(),
});
/** A session runs a plugin whose bytes differ from the packaged copy. */
const modifiedPluginRefusal = (): AnalysisCapabilityUnavailableError => {
const remediation = `Copy ${packagedCutterPluginPath()} into Cutter's plugins/python directory, restart Cutter, and list sessions again. No command was sent.`;
return new AnalysisCapabilityUnavailableError(
"cutter",
"cutter_command",
"The Cutter session runs a REA plugin whose source differs from the packaged plugin, so its protocol cannot be trusted to match this REA release.",
{ remediationAction: remediation, userMessage: remediation },
);
};
const acknowledgementSchema = z.object({
ok: z.literal(true),
acknowledged: z.boolean(),
@@ -229,13 +249,15 @@ export interface CutterBridgeExecution {
readonly requestId: string;
readonly output: unknown;
readonly currentFile: string | null;
readonly documentGeneration: number;
/** Generation the bridge reported after the command; null when it did not. */
readonly documentGeneration: number | null;
readonly identityStatus: "partial";
readonly cutterVersion: string | null;
readonly executionState: CutterBridgeExecutionState;
readonly error: string | null;
readonly message: string | null;
readonly outputTruncated: boolean;
/** Whether output was omitted; null when the bridge did not declare it. */
readonly outputTruncated: boolean | null;
readonly completionToken?: string;
}
@@ -383,6 +405,12 @@ export class CutterBridgeClient {
mismatches.push(advertised);
return undefined;
}
// Classify outside the per-peer catch: an unreadable packaged plugin
// is REA's own failure and must not read as an absent session.
const bridgeSource = cutterBridgeSource(
descriptor.bridge_source_sha256,
"list_cutter_sessions",
);
try {
const status = responseSchema.safeParse(
await this.#request(
@@ -414,6 +442,7 @@ export class CutterBridgeClient {
cutter_version:
status.data.cutter_version ?? descriptor.cutter_version,
identity_status: "partial" as const,
bridge_source: bridgeSource,
};
} catch (cause) {
if (cause instanceof AnalysisResourceConstraintError) throw cause;
@@ -468,6 +497,13 @@ export class CutterBridgeClient {
this.#requestLimit();
const descriptor = await this.#find(input.sessionId, input.signal);
assertBridgeActive(input.signal, "cutter_command");
if (
cutterBridgeSource(
descriptor.bridge_source_sha256,
"cutter_command",
) === "modified"
)
throw modifiedPluginRefusal();
const advertised =
descriptor.max_request_bytes ?? DEFAULT_BRIDGE_MAX_REQUEST_BYTES;
if (advertised !== this.#requestLimit().maximumBytes)
@@ -513,15 +549,17 @@ export class CutterBridgeClient {
requestId,
output: null,
currentFile: descriptor.current_file,
documentGeneration: input.expectedGeneration,
// No reply was read, so the generation after the command is unknown.
documentGeneration: null,
identityStatus: "partial",
cutterVersion: descriptor.cutter_version,
executionState: "unknown",
error: "transport-response-missing",
message: `${cause.message}; the command may have completed; do not retry automatically`,
// The carried limit is the framed response ceiling. The command was
// sent, and the discarded response is omitted output.
outputTruncated: cause.limit !== undefined,
// The carried limit is the framed response ceiling: the command was
// sent and its discarded response is omitted output. Any other
// missing reply leaves truncation unknown.
outputTruncated: cause.limit === undefined ? null : true,
...(completionToken === undefined ? {} : { completionToken }),
};
}
@@ -531,14 +569,14 @@ export class CutterBridgeClient {
requestId,
output: null,
currentFile: descriptor.current_file,
documentGeneration: input.expectedGeneration,
documentGeneration: null,
identityStatus: "partial",
cutterVersion: descriptor.cutter_version,
executionState: "unknown",
error: "malformed-bridge-response",
message:
"Cutter may have completed the command, but its response was invalid; do not retry automatically",
outputTruncated: false,
outputTruncated: null,
...(completionToken === undefined ? {} : { completionToken }),
};
const response = parsed.data;
@@ -589,14 +627,18 @@ export class CutterBridgeClient {
response.current_file === undefined
? descriptor.current_file
: response.current_file,
documentGeneration:
response.document_generation ?? input.expectedGeneration,
// An undeclared generation or truncation stays unknown: the command
// may have changed the document, and an omitted flag is not "false".
documentGeneration: response.document_generation ?? null,
identityStatus: "partial",
cutterVersion: response.cutter_version ?? descriptor.cutter_version,
executionState,
error: response.ok ? null : (response.error ?? "cutter-command-failed"),
message: response.message ?? null,
outputTruncated: response.output_truncated ?? false,
// A command that never started produced no output to omit.
outputTruncated:
response.output_truncated ??
(executionState === "not_started" ? false : null),
...(completionToken === undefined ? {} : { completionToken }),
};
} catch (cause) {
+10 -1
View File
@@ -200,10 +200,19 @@ export class CutterBridgeService {
"Command completion or its output could not be confirmed; do not retry automatically because the command may have produced partial or persistent effects.",
]
: []),
...(output.outputTruncated
...(output.outputTruncated === true
? [
"The command completed or may have completed, but output exceeded the bridge transport limit and was omitted.",
]
: output.outputTruncated === null
? [
"The bridge did not declare whether output was omitted, so the output may be incomplete.",
]
: []),
...(output.documentGeneration === null
? [
"The bridge did not report the document generation after this command; list Cutter sessions again before selecting an expected_generation.",
]
: []),
],
},
+40
View File
@@ -0,0 +1,40 @@
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { expect, it } from "vitest";
import { cutterBridgeSource } from "./CutterBridgeSource.js";
const packaged = new URL("../../bridge/cutter/rea_bridge.py", import.meta.url);
const packagedSha256 = createHash("sha256")
.update(readFileSync(packaged))
.digest("hex");
it("classifies a session's plugin against the packaged plugin bytes", () => {
expect(cutterBridgeSource(packagedSha256, "list_cutter_sessions")).toBe(
"packaged",
);
expect(cutterBridgeSource("0".repeat(64), "list_cutter_sessions")).toBe(
"modified",
);
expect(cutterBridgeSource(undefined, "list_cutter_sessions")).toBe("unknown");
expect(cutterBridgeSource(null, "list_cutter_sessions")).toBe("unknown");
});
it("reports an unreadable packaged plugin as REA's own typed failure", () => {
const missing = new URL("./missing-rea-bridge.py", import.meta.url);
expect(() =>
cutterBridgeSource("0".repeat(64), "list_cutter_sessions", missing),
).toThrow(
expect.objectContaining({
_tag: "AnalysisCapabilityUnavailableError",
operation: "list_cutter_sessions",
remediationAction: expect.stringContaining("Reinstall REA"),
}),
);
expect(
cutterBridgeSource(undefined, "list_cutter_sessions", missing),
"a plugin without a digest needs no packaged comparison",
).toBe("unknown");
});
+60
View File
@@ -0,0 +1,60 @@
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import type { CutterBridgeSource } from "../domain/cutterDiscovery.js";
const PACKAGED_PLUGIN = new URL(
"../../bridge/cutter/rea_bridge.py",
import.meta.url,
);
/** Packaged plugin path a user copies into Cutter's `plugins/python` directory. */
export const packagedCutterPluginPath = (plugin = PACKAGED_PLUGIN): string =>
fileURLToPath(plugin);
const packagedDigests = new Map<string, string>();
/**
* SHA-256 of the packaged Cutter plugin bytes. The user copies the plugin into
* Cutter, so REA compares the digest the running plugin publishes with this
* one instead of trusting its protocol version alone. An unreadable packaged
* plugin is a broken REA installation, reported as such rather than hiding
* the live session that asked for the comparison.
*/
const packagedCutterPluginDigest = (operation: string, plugin: URL): string => {
const cached = packagedDigests.get(plugin.href);
if (cached !== undefined) return cached;
let bytes: Buffer;
try {
bytes = readFileSync(plugin);
} catch (cause: unknown) {
const remediation = `Reinstall REA so ${packagedCutterPluginPath(plugin)} is present and readable, then retry. REA could not compare the running Cutter plugin with it, and no command was sent.`;
throw new AnalysisCapabilityUnavailableError(
"cutter",
operation,
"REA's packaged Cutter plugin could not be read, so the running plugin's source cannot be identified.",
{ cause, remediationAction: remediation, userMessage: remediation },
);
}
const digest = createHash("sha256").update(bytes).digest("hex");
packagedDigests.set(plugin.href, digest);
return digest;
};
/**
* Classify the plugin a session runs. A plugin that publishes no digest
* predates source identity, so its source is unknown rather than modified.
*/
export const cutterBridgeSource = (
advertisedSha256: string | null | undefined,
operation: string,
plugin = PACKAGED_PLUGIN,
): CutterBridgeSource => {
if (advertisedSha256 === undefined || advertisedSha256 === null)
return "unknown";
return advertisedSha256 === packagedCutterPluginDigest(operation, plugin)
? "packaged"
: "modified";
};
+3 -2
View File
@@ -6,6 +6,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
import { z } from "zod";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import { Deadline } from "../domain/deadline.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import { StructuredContentMcpClient } from "../providers/StructuredContentMcpClient.js";
import { validateMcpHttpResponse } from "../providers/Utf8McpResponse.js";
@@ -640,7 +641,7 @@ export class AgentEnvComputer {
}
async #waitReady(signal: AbortSignal): Promise<void> {
const deadline = Date.now() + READY_TIMEOUT_MS;
const deadline = Deadline.after(READY_TIMEOUT_MS);
for (;;) {
const status = readinessSchema.parse(
await this.#request(
@@ -652,7 +653,7 @@ export class AgentEnvComputer {
if (status.ready) return;
const waiting = status.checks.filter((check) => !check.ok);
const failed = waiting.find((check) => check.final === true);
if (failed !== undefined || Date.now() > deadline)
if (failed !== undefined || deadline.expired())
throw new ComputerStartFailure(
this.redacted(
failed === undefined
+4 -3
View File
@@ -2,6 +2,7 @@ import { setTimeout as delay } from "node:timers/promises";
import { isOneColourPng } from "../browser/PngVisualDiff.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { Deadline } from "../domain/deadline.js";
/** How often REA retakes a first screenshot the desktop has not drawn on, and the time the retries share. */
const DRAWN_POLL_MS = 500;
@@ -31,15 +32,15 @@ export const drawnScreenshot = async <Shot extends Screenshot>(
take: (signal: AbortSignal) => Promise<Shot>,
signal: AbortSignal,
): Promise<Shot> => {
const deadline = Date.now() + DRAWN_WAIT_MS;
const deadline = Deadline.after(DRAWN_WAIT_MS);
let shot = await take(signal);
while (!shot.isError && undrawn(shot)) {
const left = deadline - Date.now();
const left = deadline.remainingMs();
if (left <= 0) break;
await delay(Math.min(DRAWN_POLL_MS, left), undefined, { signal });
const retry = AbortSignal.any([
signal,
AbortSignal.timeout(Math.max(1, deadline - Date.now())),
AbortSignal.timeout(Math.max(1, deadline.remainingMs())),
]);
try {
shot = await take(retry);
+19 -5
View File
@@ -28,7 +28,17 @@ const ZIP64_ENTRIES_SENTINEL = 0xffff;
/** "APK Sig Block 42" — the 16-byte block magic (JAR/APK signing block spec). */
const BLOCK_MAGIC = "APK Sig Block 42";
/** A single pair is at least 12 bytes (uint64 length + uint32 id); cap the count. */
const MAX_PAIRS = 4096;
export const APK_SIGNING_BLOCK_MAX_PAIRS = 4096;
/** Validate one size-prefixed pair without reading or allocating its value. */
export const apkSigningPairEnd = (
length: bigint,
offset: number,
end: number,
): number | undefined => {
if (length < 4n || length > BigInt(end - offset - 8)) return undefined;
return offset + 8 + Number(length);
};
/** Well-known APK Signing Block pair IDs. */
export const APK_BLOCK_ID = {
@@ -348,17 +358,21 @@ export const locateApkSigningBlock = (
const pairsEnd = cdOffset - 24; // stop before trailing size + magic
while (cursor < pairsEnd) {
const length = u64(dv, cursor);
if (length === null || length < 4 || cursor + 8 + length > pairsEnd + 0)
const next =
length === null
? undefined
: apkSigningPairEnd(BigInt(length), cursor, pairsEnd);
if (length === null || next === undefined)
return err({
kind: "malformed-block",
offset: cursor,
detail: "pair length out of range",
});
if (pairs.length >= MAX_PAIRS)
if (pairs.length >= APK_SIGNING_BLOCK_MAX_PAIRS)
return err({
kind: "budget-exceeded",
resource: "signing-block-pairs",
limit: MAX_PAIRS,
limit: APK_SIGNING_BLOCK_MAX_PAIRS,
});
const id = dv.getUint32(cursor + 8, true);
const valueStart = cursor + 12;
@@ -366,7 +380,7 @@ export const locateApkSigningBlock = (
id,
value: bytes.subarray(valueStart, valueStart + (length - 4)),
});
cursor += 8 + length;
cursor = next;
}
return ok({ blockStart, pairs });
};
+75
View File
@@ -0,0 +1,75 @@
/**
* Keys a property list declares more than once within one dictionary.
*
* A decoded dictionary holds one value per key, so a repeated declaration
* replaces an earlier one. The decoder that sees each dictionary's source keys
* records them here before that collapse.
*/
export interface PlistDuplicateKeys {
/** Dictionaries that declare at least one key more than once. */
readonly dictionaries: number;
/** Declarations replaced by a later declaration of the same key. */
readonly replaced: number;
/** The first distinct repeated key names, in source order. */
readonly names: readonly string[];
/** Whether a further distinct repeated name exists beyond `names`. */
readonly namesOmitted: boolean;
}
/** Repeated key names kept for the limitation text; the counts stay exact. */
const NAMED_DUPLICATE_KEYS = 8;
/** UTF-16 units of one key shown in the limitation; longer keys are shortened. */
const SHOWN_KEY_LENGTH = 64;
/** Receives each dictionary's source keys before the decoder collapses them. */
export interface PlistDuplicateKeyCollector {
/** Record one dictionary's keys in source order. */
dictionary(keys: Iterable<string>): void;
result(): PlistDuplicateKeys;
}
/** Collect repeated keys across the dictionaries of one decode. */
export const createPlistDuplicateKeyCollector =
(): PlistDuplicateKeyCollector => {
let dictionaries = 0;
let replaced = 0;
const names = new Set<string>();
let namesOmitted = false;
return {
/** Record one dictionary's keys in source order. */
dictionary(keys: Iterable<string>): void {
const seen = new Set<string>();
let repeated = false;
for (const key of keys) {
if (!seen.has(key)) {
seen.add(key);
continue;
}
repeated = true;
replaced += 1;
if (names.size < NAMED_DUPLICATE_KEYS) names.add(key);
else if (!names.has(key)) namesOmitted = true;
}
if (repeated) dictionaries += 1;
},
result(): PlistDuplicateKeys {
return { dictionaries, replaced, names: [...names], namesOmitted };
},
};
};
/** One key as shown in the limitation, marked when shortened. */
const shownKey = (name: string): string =>
name.length <= SHOWN_KEY_LENGTH
? JSON.stringify(name)
: `${JSON.stringify(name.slice(0, SHOWN_KEY_LENGTH))} (shortened from ${String(name.length)} characters)`;
/** The decode limitation for repeated keys, or none when no key repeats. */
export const plistDuplicateKeyLimitations = (
duplicates: PlistDuplicateKeys,
): string[] =>
duplicates.replaced === 0
? []
: [
`${String(duplicates.dictionaries)} dictionary(ies) declare a key more than once (${duplicates.names.map(shownKey).join(", ")}${duplicates.namesOmitted ? ", ..." : ""}). REA kept the last value for each key; ${String(duplicates.replaced)} earlier value(s) are not reported, and other plist readers may keep a different one.`,
];
+12
View File
@@ -1,5 +1,16 @@
import { z } from "zod";
/**
* Which plugin source a session runs: the packaged copy, a different one, or
* unknown when the plugin predates source identity.
*/
export const cutterBridgeSourceSchema = z.enum([
"packaged",
"modified",
"unknown",
]);
export type CutterBridgeSource = z.infer<typeof cutterBridgeSourceSchema>;
/** Observed Cutter session identity without bridge transport credentials. */
export const cutterSessionSchema = z.strictObject({
session_id: z.string().uuid(),
@@ -8,6 +19,7 @@ export const cutterSessionSchema = z.strictObject({
current_file: z.string().nullable(),
cutter_version: z.string().nullable(),
identity_status: z.literal("partial"),
bridge_source: cutterBridgeSourceSchema,
});
/** Discovery facts retained independently of descriptor cleanup. */
+61
View File
@@ -0,0 +1,61 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { Deadline } from "./deadline.js";
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date", "performance"] });
});
afterEach(() => {
vi.useRealTimers();
});
it.each([-3_600_000, 3_600_000])(
"keeps the work budget when the wall clock jumps by %i ms",
(jump) => {
const deadline = Deadline.after(1_000);
vi.advanceTimersByTime(250);
vi.setSystemTime(Date.now() + jump);
expect(deadline.remainingMs()).toBe(750);
expect(deadline.expired()).toBe(false);
vi.advanceTimersByTime(750);
expect(deadline.remainingMs()).toBe(0);
expect(deadline.expired()).toBe(true);
},
);
it("starts the finalize budget when finalization begins, after work expired", () => {
const deadline = Deadline.after(100, { finalizeMs: 500 });
vi.advanceTimersByTime(300);
expect(deadline.expired()).toBe(true);
const finalize = deadline.beginFinalize();
expect(finalize.remainingMs()).toBe(500);
vi.advanceTimersByTime(499);
expect(finalize.expired()).toBe(false);
vi.advanceTimersByTime(1);
expect(finalize.expired()).toBe(true);
expect(finalize.beginFinalize().remainingMs()).toBe(0);
});
it("shares one finalize window across repeated beginFinalize calls", () => {
const deadline = Deadline.after(100, { finalizeMs: 500 });
const first = deadline.beginFinalize();
vi.advanceTimersByTime(300);
const second = deadline.beginFinalize();
expect(second).toBe(first);
expect(second.remainingMs()).toBe(200);
});
it("grants no finalize budget unless one is declared", () => {
expect(Deadline.after(100).beginFinalize().expired()).toBe(true);
});
it.each([-1, Number.NaN, Number.POSITIVE_INFINITY, 2_147_483_648])(
"rejects a budget outside the Node timer range (%d)",
(milliseconds) => {
expect(() => Deadline.after(milliseconds)).toThrow(RangeError);
expect(() => Deadline.after(1, { finalizeMs: milliseconds })).toThrow(
RangeError,
);
},
);
+67
View File
@@ -0,0 +1,67 @@
import { MAX_NODE_TIMER_DELAY_MS } from "./analysisResourceLimits.js";
const validBudget = (name: string, milliseconds: number): number => {
if (
!Number.isFinite(milliseconds) ||
milliseconds < 0 ||
milliseconds > MAX_NODE_TIMER_DELAY_MS
)
throw new RangeError(
`${name} must be a finite millisecond count from 0 to ${String(MAX_NODE_TIMER_DELAY_MS)}`,
);
return milliseconds;
};
/**
* One monotonic deadline with a work budget and a separate finalize budget.
*
* The work budget starts when the deadline is created. The finalize budget
* starts when finalization begins, so work that used its whole budget, or
* overran it, still gets a bounded window to drain output, record evidence and
* release what it owns. Wall-clock changes never move either budget.
*/
export class Deadline {
readonly #endsAt: number;
#finalize: Deadline | undefined;
private constructor(
/** Work budget in milliseconds. */
readonly workMs: number,
/** Budget a finalizer gets once work stops, in milliseconds. */
readonly finalizeMs: number,
) {
this.#endsAt = performance.now() + workMs;
}
/** A deadline whose work budget starts now. Omitting `finalizeMs` grants none. */
static after(
workMs: number,
options: { readonly finalizeMs?: number } = {},
): Deadline {
return new Deadline(
validBudget("Deadline work budget", workMs),
validBudget("Deadline finalize budget", options.finalizeMs ?? 0),
);
}
/** Whole milliseconds of work budget left; zero once it has elapsed. */
remainingMs(): number {
return Math.max(0, Math.ceil(this.#endsAt - performance.now()));
}
/** Whether the work budget has elapsed. */
expired(): boolean {
return performance.now() >= this.#endsAt;
}
/**
* Start the finalize budget, whether or not work expired. The first call
* starts it; later calls return the same deadline, so cleanup stages share
* one window instead of each restarting it. The result grants no further
* budget.
*/
beginFinalize(): Deadline {
this.#finalize ??= new Deadline(this.finalizeMs, 0);
return this.#finalize;
}
}
+6 -10
View File
@@ -1,17 +1,13 @@
import { readLeb128, ULEB32 } from "./leb128.js";
/** Read a bounded 32-bit ULEB value within an ELF attribute scope. */
export const readElfAttributeUleb = (
bytes: Uint8Array,
offset: number,
end: number,
): { readonly value: number; readonly next: number } | undefined => {
let value = 0;
for (let index = 0; index < 5 && offset + index < end; index += 1) {
const byte = bytes[offset + index]!;
value += (byte & 0x7f) * 2 ** (7 * index);
if ((byte & 0x80) === 0)
return value <= 0xffffffff
? { value, next: offset + index + 1 }
: undefined;
}
return undefined;
const read = readLeb128(bytes, offset, end, ULEB32);
return "failure" in read
? undefined
: { value: Number(read.value), next: read.next };
};
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { keyedBy, uniqueKeyed } from "./keyedCollection.js";
const sections = [
{ name: "__text", id: 0 },
{ name: null, id: 1 },
{ name: "__data", id: 2 },
{ name: "__text", id: 3 },
];
describe("keyed collections", () => {
const keyed = keyedBy(sections, ({ name }) => name);
it("retains every keyed declaration in source order and names repeats", () => {
expect(keyed.entries.map(({ key, ordinal }) => [key, ordinal])).toEqual([
["__text", 0],
["__data", 1],
["__text", 2],
]);
expect(keyed.duplicates).toEqual(["__text"]);
});
it("selects a single declaration, or nothing when absent", () => {
expect(uniqueKeyed(keyed, "__data")).toEqual({
ok: true,
value: sections[2],
});
expect(uniqueKeyed(keyed, "__bss")).toEqual({
ok: true,
value: undefined,
});
});
it("refuses to choose among repeated declarations", () => {
expect(uniqueKeyed(keyed, "__text")).toEqual({
ok: false,
error: { kind: "duplicate", key: "__text", ordinals: [0, 2] },
});
});
});
+67
View File
@@ -0,0 +1,67 @@
import { err, ok, type Result } from "./result.js";
/** One keyed member of a parsed table, at its position among keyed members. */
export interface KeyedEntry<T> {
readonly key: string;
readonly ordinal: number;
readonly value: T;
}
/**
* The keyed members of one parsed table or object, in source order, with
* every repeated key retained. A lookup states what a repeat means through
* its selector, instead of inheriting `find` (first) or `Map.set` (last).
*/
export interface Keyed<T> {
readonly entries: readonly KeyedEntry<T>[];
/** Keys declared more than once, in the order they first repeat. */
readonly duplicates: readonly string[];
}
/** A key the format allows once, declared more than once. */
export interface DuplicateKey {
readonly kind: "duplicate";
readonly key: string;
/** Ordinals of every declaration of the key. */
readonly ordinals: readonly number[];
}
/**
* Key the members of a parsed table. Members without a key (null or
* undefined), such as an unnamed section, are not keyed and cannot be
* selected by key.
*/
export const keyedBy = <T>(
values: Iterable<T>,
keyOf: (value: T) => string | null | undefined,
): Keyed<T> => {
const entries: KeyedEntry<T>[] = [];
const seen = new Set<string>();
const duplicates = new Set<string>();
for (const value of values) {
const key = keyOf(value);
if (key === undefined || key === null) continue;
if (seen.has(key)) duplicates.add(key);
seen.add(key);
entries.push({ key, ordinal: entries.length, value });
}
return { entries, duplicates: [...duplicates] };
};
/**
* The single declaration of a key the format allows once: undefined when
* absent, and a typed failure carrying every ordinal when repeated.
*/
export const uniqueKeyed = <T>(
keyed: Keyed<T>,
key: string,
): Result<T | undefined, DuplicateKey> => {
const matches = keyed.entries.filter((entry) => entry.key === key);
if (matches.length > 1)
return err({
kind: "duplicate",
key,
ordinals: matches.map(({ ordinal }) => ordinal),
});
return ok(matches[0]?.value);
};
+81
View File
@@ -0,0 +1,81 @@
import { expect, it } from "vitest";
import { readLeb128, SLEB64, ULEB32, ULEB64 } from "./leb128.js";
const read = (bytes: readonly number[], encoding = ULEB64) =>
readLeb128(Uint8Array.from(bytes), 0, bytes.length, encoding);
it.each([
[[0x00], ULEB64, 0n],
[[0xe5, 0x8e, 0x26], ULEB64, 624_485n],
[[0x7f], SLEB64, -1n],
[[0xc0, 0xbb, 0x78], SLEB64, -123_456n],
[[0xff, 0xff, 0xff, 0xff, 0x0f], ULEB32, 0xffff_ffffn],
[
[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01],
ULEB64,
0xffff_ffff_ffff_ffffn,
],
[
[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f],
SLEB64,
-(2n ** 63n),
],
[
[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00],
SLEB64,
2n ** 63n - 1n,
],
] as const)("decodes %j", (bytes, encoding, value) => {
expect(read(bytes, encoding)).toEqual({ value, next: bytes.length });
});
it.each([
["a 33-bit value in 32 bits", [0xff, 0xff, 0xff, 0xff, 0x1f], ULEB32, 4],
["a sixth byte in 32 bits", [0x80, 0x80, 0x80, 0x80, 0x80, 0x00], ULEB32, 5],
[
"a 65-bit value",
[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02],
ULEB64,
9,
],
[
"a sign that does not repeat",
[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01],
SLEB64,
9,
],
] as const)("refuses %s as overflow", (_, bytes, encoding, at) => {
expect(read(bytes, encoding)).toEqual({ failure: "overflow", at });
});
it("refuses an encoding that runs past its end as truncated", () => {
expect(read([0x80, 0x80])).toEqual({ failure: "truncated", at: 2 });
expect(readLeb128(Uint8Array.from([0x80, 0x00]), 0, 1, ULEB64)).toEqual({
failure: "truncated",
at: 1,
});
});
it("accepts padding only where the format allows it, and only as the sign", () => {
const padded = [
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0x80, 0x00,
];
expect(read(padded)).toEqual({ failure: "overflow", at: 10 });
expect(read(padded, { ...ULEB64, padding: true })).toEqual({
value: 0xffff_ffff_ffff_ffffn,
next: padded.length,
});
expect(
read([0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x01], {
...ULEB64,
padding: true,
}),
).toEqual({ failure: "overflow", at: 10 });
expect(
read([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f], {
...SLEB64,
padding: true,
}),
).toEqual({ value: -1n, next: 11 });
});
+81
View File
@@ -0,0 +1,81 @@
/**
* The one LEB128 decoder. Formats differ only in the integer width, the sign,
* and whether redundant padding bytes may extend an encoding; each states
* those choices here instead of re-deriving the overflow rules.
*/
export interface Leb128Encoding {
readonly signed: boolean;
/** Width of the integer the encoding must fit. */
readonly bits: 32 | 64;
/**
* Whether bytes that only repeat the sign (or zero) may extend the encoding
* past `ceil(bits / 7)` bytes. Mach-O opcode operands allow this; DWARF,
* ELF attribute, Go and protobuf readers stop at the minimal width.
*/
readonly padding?: boolean;
}
/** Why no value was decoded: the bytes ended first, or the value or encoding exceeds `bits`. */
export type Leb128Failure = "truncated" | "overflow";
export type Leb128Read =
| { readonly value: bigint; readonly next: number }
| {
readonly failure: Leb128Failure;
/** Offset of the byte that overflowed, or of the end the encoding ran past. */
readonly at: number;
};
export const ULEB32: Leb128Encoding = { signed: false, bits: 32 };
export const ULEB64: Leb128Encoding = { signed: false, bits: 64 };
export const SLEB64: Leb128Encoding = { signed: true, bits: 64 };
/**
* Decode one LEB128 integer from `bytes[offset, end)`.
*
* Bits beyond `bits` must repeat the sign (signed) or be zero (unsigned);
* otherwise the read fails as `overflow` and never wraps.
*/
export const readLeb128 = (
bytes: Uint8Array,
offset: number,
end: number,
encoding: Leb128Encoding,
): Leb128Read => {
const { signed, bits } = encoding;
const limit = Math.min(end, bytes.length);
const maximumBytes =
encoding.padding === true ? Number.POSITIVE_INFINITY : Math.ceil(bits / 7);
let value = 0n;
let shift = 0;
let negative = false;
for (let index = offset, count = 0; ; index++, count++) {
if (count >= maximumBytes) return { failure: "overflow", at: index };
if (index < 0 || index >= limit) return { failure: "truncated", at: index };
const byte = bytes[index]!;
const payload = byte & 0x7f;
if (shift >= bits) {
// A padding byte carries no value bits; it can only repeat the sign.
if (payload !== (negative ? 0x7f : 0))
return { failure: "overflow", at: index };
} else if (shift + 7 > bits) {
const kept = bits - shift;
const high = payload >> kept;
if (signed) {
negative = ((payload >> (kept - 1)) & 1) === 1;
if (high !== (negative ? 0x7f >> kept : 0))
return { failure: "overflow", at: index };
} else if (high !== 0) return { failure: "overflow", at: index };
value |= BigInt(payload & ((1 << kept) - 1)) << BigInt(shift);
} else value |= BigInt(payload) << BigInt(shift);
shift += 7;
if ((byte & 0x80) === 0) {
if (signed) {
if (shift < bits) {
if ((payload & 0x40) !== 0) value -= 1n << BigInt(shift);
} else if (negative) value -= 1n << BigInt(bits);
}
return { value, next: index + 1 };
}
}
};
+37 -2
View File
@@ -5,9 +5,14 @@ import { PlistNestingLimitError } from "./apple/plistValue.js";
import { parseXmlPropertyList as parseWithNumbers } from "./propertyListKeys.js";
// Numeric source facts have separate source-type and ambiguity controls.
// Repeated keys stay visible so a last-value-wins case also shows its count.
const parseXmlPropertyList = (text: string) => {
const { numberLiterals: _numbers, ...parsed } = parseWithNumbers(text);
return parsed;
const {
numberLiterals: _numbers,
duplicateKeys,
...parsed
} = parseWithNumbers(text);
return duplicateKeys.replaced === 0 ? parsed : { ...parsed, duplicateKeys };
};
const plist = (body: string) =>
@@ -73,6 +78,12 @@ it("preserves last-value-wins for prototype keys split across character-data nod
);
expect(parseXmlPropertyList(text)).toEqual({
value: { ["__proto__"]: "omitted" },
duplicateKeys: {
dictionaries: 1,
replaced: 1,
names: ["__proto__"],
namesOmitted: false,
},
});
});
@@ -108,6 +119,12 @@ it.each([
.join("");
expect(parseXmlPropertyList(plist(`<dict>${entries}</dict>`))).toEqual({
value: { ab: 3 },
duplicateKeys: {
dictionaries: 1,
replaced: 2,
names: ["ab"],
namesOmitted: false,
},
});
});
@@ -118,6 +135,12 @@ it("keeps empty keys and alias-looking source keys distinct", () => {
"<key>ma<?ignored value?><![CDATA[in]]></key><integer>42</integer>";
expect(parseXmlPropertyList(plist(`<dict>${entries}</dict>`))).toEqual({
value: { "": 3, __rea_plist_key_0__: "literal", main: 42 },
duplicateKeys: {
dictionaries: 1,
replaced: 2,
names: [""],
namesOmitted: false,
},
});
});
@@ -163,6 +186,12 @@ it("preserves OpenStep __proto__ keys and duplicate assignment semantics", () =>
kept: "__proto__",
list: ["__proto__"],
},
duplicateKeys: {
dictionaries: 1,
replaced: 3,
names: ["__proto__"],
namesOmitted: false,
},
});
const nested = (result.value as { nested: object }).nested;
expect(Object.getPrototypeOf(nested)).toBe(Object.prototype);
@@ -177,6 +206,12 @@ it("preserves OpenStep compound keys that coerce to __proto__", () => {
),
).toEqual({
value: { ["__proto__"]: "b", "__pro,to__": "c", list: ["__proto__"] },
duplicateKeys: {
dictionaries: 1,
replaced: 1,
names: ["__proto__"],
namesOmitted: false,
},
});
});
+16 -7
View File
@@ -8,21 +8,30 @@ import {
type PlistNumberLiterals,
} from "./apple/plistNumbers.js";
import { MAX_PLIST_DEPTH } from "./apple/plistValue.js";
import {
createPlistDuplicateKeyCollector,
type PlistDuplicateKeys,
} from "./apple/plistDuplicateKeys.js";
/** Values and numeric source facts decoded together; OpenStep numbers remain unknown. */
export interface ParsedPropertyList {
readonly value: unknown;
readonly numberLiterals: PlistNumberLiterals;
/** Keys a dictionary declared more than once; `value` keeps the last. */
readonly duplicateKeys: PlistDuplicateKeys;
}
/** Decode XML or the existing OpenStep container form, retaining every dictionary key. */
export const parseXmlPropertyList = (
text: string,
maximumDepth = MAX_PLIST_DEPTH,
): ParsedPropertyList =>
startsOpenStepPropertyList(text)
? {
value: decodeOpenStepPropertyList(text, maximumDepth),
numberLiterals: createPlistNumberCollector().result(true),
}
: decodeXmlPropertyList(text, maximumDepth);
): ParsedPropertyList => {
if (!startsOpenStepPropertyList(text))
return decodeXmlPropertyList(text, maximumDepth);
const duplicates = createPlistDuplicateKeyCollector();
return {
value: decodeOpenStepPropertyList(text, maximumDepth, duplicates),
numberLiterals: createPlistNumberCollector().result(true),
duplicateKeys: duplicates.result(),
};
};
+5
View File
@@ -2,6 +2,7 @@ import { parseOpenStep } from "plist";
import { MAX_PLIST_DEPTH, PlistNestingLimitError } from "./apple/plistValue.js";
import { markPlistDictionary } from "./apple/plistUid.js";
import type { PlistDuplicateKeyCollector } from "./apple/plistDuplicateKeys.js";
const OPEN_STEP_SYNTAX_CODES = [
"unterminated_block_comment",
@@ -223,6 +224,7 @@ const skipTrivia = (text: string, start: number, strict = true): number => {
export const decodeOpenStepPropertyList = (
text: string,
maximumDepth = MAX_PLIST_DEPTH,
duplicates?: PlistDuplicateKeyCollector,
): unknown => {
let cursor = 0;
const trivia = () => {
@@ -240,6 +242,7 @@ export const decodeOpenStepPropertyList = (
assertDepth(depth);
cursor += 1;
const dictionary: Record<string, unknown> = {};
const keys: string[] = [];
markPlistDictionary(dictionary);
while (true) {
trivia();
@@ -250,6 +253,7 @@ export const decodeOpenStepPropertyList = (
);
if (text[cursor] === "}") {
cursor += 1;
duplicates?.dictionary(keys);
return dictionary;
}
const key = value(depth + 1, true);
@@ -258,6 +262,7 @@ export const decodeOpenStepPropertyList = (
throw new OpenStepPropertyListError("expected_equals", cursor);
cursor += 1;
const entry = value(depth + 1);
keys.push(String(key));
Object.defineProperty(dictionary, String(key), {
value: entry,
enumerable: true,
+4
View File
@@ -4,6 +4,7 @@ import type { Node } from "@xmldom/xmldom";
import { readXmlPlistSource } from "./propertyListXmlSource.js";
import { createPlistNumberCollector } from "./apple/plistNumbers.js";
import { createPlistDuplicateKeyCollector } from "./apple/plistDuplicateKeys.js";
import { UnknownPlistScalar } from "./apple/unknownPlistScalar.js";
import { MAX_PLIST_DEPTH } from "./apple/plistValue.js";
import {
@@ -23,6 +24,7 @@ export const decodeXmlPropertyList = (
if (root?.nodeName !== "plist")
throw new TypeError("malformed document. First element should be <plist>");
const numbers = createPlistNumberCollector();
const duplicates = createPlistDuplicateKeyCollector();
const textNode = (node: Node) => node.nodeType === node.TEXT_NODE;
const characterNode = (node: Node) =>
textNode(node) || node.nodeType === node.CDATA_SECTION_NODE;
@@ -92,6 +94,7 @@ export const decodeXmlPropertyList = (
}
if (key !== undefined)
throw new TypeError("Missing value for key while parsing <dict/>");
duplicates.dictionary(entries.map(([name]) => name));
// Dictionary names are data, including __proto__.
const value = Object.fromEntries(entries);
// XML archives use Foundation's CF$UID convention; a UID key is data.
@@ -190,5 +193,6 @@ export const decodeXmlPropertyList = (
return {
value: values.length === 1 ? values[0] : values,
numberLiterals: numbers.result(),
duplicateKeys: duplicates.result(),
};
};
+31 -90
View File
@@ -47,20 +47,19 @@ import {
type DebuggerAdmissionLimit,
} from "../config/debuggerSessionLimits.js";
import {
closeOwnedDebuggerSessions,
configurableDeadlineGuidance,
debuggerAdmissionDiagnostics,
debuggerAdmissionRecovery,
debuggerResourceConstraintError,
fixedDeadlineGuidance,
readLinuxProcessStartTime,
retainedDebuggerCleanupFailure,
stopOwnedDebuggerProcess,
type OwnedDebuggerDetachResult,
type OwnedInferiorIdentity,
type ProcessStartTimeReader,
verifyOwnedInferiorsEnded,
} from "../process/ownedDebuggerSession.js";
import { OwnedDebuggerSessionRegistry } from "../process/OwnedDebuggerSessionRegistry.js";
import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js";
const STARTUP_TIMEOUT_MS = 10_000;
@@ -546,9 +545,7 @@ interface GdbSession {
cleanupStarted: boolean;
/** close_gdb_session started cleanup, so a successful retry releases the ID. */
closeRequested: boolean;
stopAttempt: ReturnType<typeof stopOwnedDebuggerProcess> | undefined;
readonly pending: Map<number, PendingCommand>;
readonly cleanupFailures: Set<AnalysisError>;
readonly lines: string[];
readonly bufferChunks: Buffer[];
bufferTail: Buffer | undefined;
@@ -575,7 +572,7 @@ const gdbCloseUnavailable = (): AnalysisInputError =>
/** Owns persistent GDB/MI sessions independently from the active binary target. */
export class GdbSessionManager {
readonly #sessions = new Map<string, GdbSession>();
readonly #sessions: OwnedDebuggerSessionRegistry<GdbSession>;
readonly #activeStarts = new Map<
AbortController,
Promise<
@@ -590,7 +587,6 @@ export class GdbSessionManager {
readonly #launchCommandDeadline: DebuggerAdmissionLimit;
readonly #startupTimeoutMs: number;
readonly #platform: NodeJS.Platform;
readonly #stopProcess: typeof stopOwnedDebuggerProcess;
readonly #spawnProcess: typeof spawnOwnedProviderProcess;
readonly #verifyInferiorOutputSink: (
pid: string,
@@ -634,7 +630,6 @@ export class GdbSessionManager {
if (!parsed.ok) throw parsed.error;
return parsed.value;
}
#sessionReservations = 0;
#closing = false;
#closePromise: Promise<void> | undefined;
@@ -661,7 +656,17 @@ export class GdbSessionManager {
this.#launchCommandDeadline = limits.commandDeadline;
this.#startupTimeoutMs = options.startupTimeoutMs ?? STARTUP_TIMEOUT_MS;
this.#platform = options.platform ?? process.platform;
this.#stopProcess = options.stopProcess ?? stopOwnedDebuggerProcess;
const stopProcess = options.stopProcess ?? stopOwnedDebuggerProcess;
this.#sessions = new OwnedDebuggerSessionRegistry({
provider: "gdb",
displayName: "GDB",
closeOperation: "close_gdb_session",
sealSession: (session) => {
session.cleanupStarted = true;
},
stopProcess: (session) => stopProcess(session, "GDB"),
stopFailurePrefix: "Owned GDB shutdown failed",
});
this.#spawnProcess = options.spawnProcess ?? spawnOwnedProviderProcess;
this.#verifyInferiorOutputSink =
options.verifyInferiorOutputSink ?? verifyGdbInferiorOutputSink;
@@ -757,7 +762,7 @@ export class GdbSessionManager {
cause: signal.reason,
}),
);
const occupied = this.#sessions.size + this.#sessionReservations;
const occupied = this.#sessions.occupied();
if (occupied >= this.#maxSessions.value)
return err(
debuggerResourceConstraintError(
@@ -772,13 +777,7 @@ export class GdbSessionManager {
},
),
);
this.#sessionReservations += 1;
let reservationHeld = true;
const releaseReservation = (): void => {
if (!reservationHeld) return;
reservationHeld = false;
this.#sessionReservations -= 1;
};
const releaseReservation = this.#sessions.reserve();
try {
return await this.#startReserved(releaseReservation, signal, options);
} finally {
@@ -894,9 +893,7 @@ export class GdbSessionManager {
noInferiorVerified: true,
cleanupStarted: false,
closeRequested: false,
stopAttempt: undefined,
pending: new Map(),
cleanupFailures: new Set(),
lines: [],
bufferChunks: [],
bufferTail: undefined,
@@ -1057,7 +1054,7 @@ export class GdbSessionManager {
// Before publication no target command can run. Once usable, the
// inferior state is no longer inferred from startup phase.
session.noInferiorVerified = false;
this.#sessions.set(id, session);
this.#sessions.add(session);
releaseReservation();
return ok({ session_id: id, mi_version: miVersion });
} catch (cause) {
@@ -1142,9 +1139,9 @@ export class GdbSessionManager {
};
const stopped = await this.#stopDebuggerOnly(session);
if (stopped.status === "incomplete") {
this.#sessions.set(id, session);
this.#sessions.add(session);
releaseReservation();
const cleanupFailure = this.#retainCleanupFailure(
const cleanupFailure = this.#sessions.retainCleanupFailure(
session,
"start_gdb_session",
stopped.reason,
@@ -1383,7 +1380,7 @@ export class GdbSessionManager {
const stopped = await this.#stopDebuggerOnly(session);
if (stopped.status === "incomplete")
return err(
this.#retainCleanupFailure(
this.#sessions.retainCleanupFailure(
session,
"gdb_console",
stopped.reason,
@@ -1419,14 +1416,14 @@ export class GdbSessionManager {
"gdb_console",
);
if (!completed.ok && completed.error.cleanupIncomplete)
session.cleanupFailures.add(completed.error);
this.#sessions.retain(session, completed.error);
return completed;
} catch (cause) {
const error =
cause instanceof AnalysisError
? cause
: new AnalysisCancelledError("gdb_console", { cause });
if (error.cleanupIncomplete) session.cleanupFailures.add(error);
if (error.cleanupIncomplete) this.#sessions.retain(session, error);
return err(error);
}
}
@@ -1572,13 +1569,13 @@ export class GdbSessionManager {
const stopped = await this.#stopDebuggerOnly(session);
if (stopped.status === "incomplete")
return err(
this.#retainCleanupFailure(
this.#sessions.retainCleanupFailure(
session,
"close_gdb_session",
stopped.reason,
),
);
this.#sessions.delete(sessionId);
this.#sessions.remove(session);
return ok({ target_state: targetState });
},
undefined,
@@ -1597,35 +1594,20 @@ export class GdbSessionManager {
const stopped = await this.#stopDebuggerOnly(session);
if (stopped.status === "incomplete")
return err(
this.#retainCleanupFailure(
this.#sessions.retainCleanupFailure(
session,
"close_gdb_session",
stopped.reason,
),
);
this.#sessions.delete(session.id);
this.#sessions.remove(session);
return ok({ target_state: "unknown" });
}
async retryCleanupFailures(): Promise<Result<null, AnalysisError>> {
for (const session of this.#sessions.values()) {
if (session.cleanupFailures.size === 0) continue;
const stopped = await this.#stopDebuggerOnly(session);
if (stopped.status === "incomplete")
return err(
[...session.cleanupFailures].at(-1) ??
this.#retainCleanupFailure(
session,
"close_gdb_session",
stopped.reason,
),
);
// The caller still holds a published session's ID; keep it addressable
// so commands and status report why it stopped until it is closed.
if (!session.ready || session.closeRequested)
this.#sessions.delete(session.id);
}
return ok(null);
return this.#sessions.retryCleanupFailures(
(session) => session.ready && !session.closeRequested,
);
}
async closeAll(): Promise<void> {
@@ -1646,11 +1628,7 @@ export class GdbSessionManager {
await Promise.all(
[...this.#sessions.values()].map((session) => session.commandTail),
);
await closeOwnedDebuggerSessions(
this.#sessions,
(session) => this.#stopDebuggerOnly(session),
"GDB",
);
await this.#sessions.closeAll();
}
async #serialize<Value>(
@@ -1979,44 +1957,7 @@ export class GdbSessionManager {
#stopDebuggerOnly(
session: GdbSession,
): ReturnType<typeof stopOwnedDebuggerProcess> {
session.cleanupStarted = true;
if (session.stopAttempt !== undefined) return session.stopAttempt;
const attempt = Promise.resolve()
.then(() => this.#stopProcess(session, "GDB"))
.catch((cause: unknown) => ({
status: "incomplete" as const,
reason: `Owned GDB shutdown failed: ${gdbErrorMessage(cause)}`,
}))
.then((stopped) => {
if (stopped.status !== "incomplete") {
for (const failure of session.cleanupFailures)
failure.resolveCleanup();
session.cleanupFailures.clear();
}
return stopped;
})
.finally(() => {
if (session.stopAttempt === attempt) session.stopAttempt = undefined;
});
session.stopAttempt = attempt;
return attempt;
}
#retainCleanupFailure(
session: GdbSession,
operation: string,
reason: string,
options: AnalysisErrorOptions = {},
): AnalysisError {
const failure = retainedDebuggerCleanupFailure(
{ provider: "gdb", displayName: "GDB" },
operation,
reason,
[session.id],
options,
);
session.cleanupFailures.add(failure);
return failure;
return this.#sessions.stop(session);
}
async #detachInferior(
@@ -2326,7 +2267,7 @@ export class GdbSessionManager {
cause: signal?.reason,
partialObservation: evidence,
});
const cleanupFailure = this.#retainCleanupFailure(
const cleanupFailure = this.#sessions.retainCleanupFailure(
session,
"gdb_console",
stopped.reason,
+27 -11
View File
@@ -122,6 +122,12 @@ import {
} from "./GhidraCheckpoint.js";
const SHUTDOWN_TIMEOUT_MS = 10_000;
/**
* Bound for draining launcher output into failure evidence. A failed startup
* gets it as its finalize budget, separate from the startup budget it may
* have exhausted.
*/
const OUTPUT_DRAIN_MS = 1_000;
const SESSION_ROOT = ghidraSessionRoot();
type GhidraStartupAttempt = SharedStartupAttempt<GhidraStartResult>;
@@ -818,7 +824,11 @@ export class GhidraClient {
primary: GhidraSessionError,
deadline?: ProviderStartupDeadline,
): Promise<GhidraStartResult> {
await this.#drainOutputBounded(deadline?.signal);
const finalization = deadline?.finalize();
await this.#drainOutputBounded(
finalization?.signal,
finalization?.deadline.remainingMs(),
);
const refreshed = this.#failure(
primary.kind,
primary.message,
@@ -935,6 +945,7 @@ export class GhidraClient {
const deadline = new ProviderStartupDeadline(
this.#options.readStartupTimeoutMs?.() ?? this.#options.startupTimeoutMs,
signal,
{ finalizeMs: OUTPUT_DRAIN_MS },
);
try {
const result = await this.#startWithin(deadline);
@@ -1686,19 +1697,24 @@ export class GhidraClient {
});
}
#drainOutputBounded(signal?: AbortSignal): Promise<boolean> {
#drainOutputBounded(
signal?: AbortSignal,
budgetMs = OUTPUT_DRAIN_MS,
): Promise<boolean> {
if (this.#outputDrainPromise !== undefined) return this.#outputDrainPromise;
const process = this.#process;
if (process === undefined) return Promise.resolve(true);
const pending = process.waitForOutputClose(1_000, signal).then((closed) => {
if (this.#process !== process) return;
if (!closed) this.#outputDrainIncomplete = true;
const snapshot = process.snapshot();
this.#processSnapshot = this.#outputDrainIncomplete
? { ...snapshot, diagnosticTruncated: true, outputIncomplete: true }
: snapshot;
return closed;
});
const pending = process
.waitForOutputClose(budgetMs, signal)
.then((closed) => {
if (this.#process !== process) return;
if (!closed) this.#outputDrainIncomplete = true;
const snapshot = process.snapshot();
this.#processSnapshot = this.#outputDrainIncomplete
? { ...snapshot, diagnosticTruncated: true, outputIncomplete: true }
: snapshot;
return closed;
});
this.#outputDrainPromise = pending.then((closed) => closed ?? false);
return this.#outputDrainPromise;
}
+23
View File
@@ -44,6 +44,29 @@ const parseFunctionValueFixture = (
return parsed.ok ? { ok: true as const, value: parsed.value.value } : parsed;
};
it("names the failing fields when a function reply or its envelope misses its contract", () => {
const dossier = ghidraFunctionDossier() as Record<string, JsonValue>;
const envelope = parseGhidraFunctionResult("analyze_function", {
value: dossier,
limitations: "none",
});
expect(envelope.ok ? undefined : envelope.error.diagnostics).toMatchObject({
contract_issues: expect.arrayContaining([
expect.objectContaining({ path: ["limitations"], code: "invalid_type" }),
]),
});
const reply = parseGhidraFunctionResult("analyze_function", {
value: { ...dossier, pseudocode: 7 },
limitations: [],
});
expect(reply.ok ? undefined : reply.error.diagnostics).toMatchObject({
contract_issues: expect.arrayContaining([
expect.objectContaining({ path: ["pseudocode"], received: "number" }),
]),
});
});
describe("Ghidra unresolved call locations", () => {
it("rejects a noncanonical unresolved call site rather than retaining unverifiable location evidence", () => {
expect(
+14 -2
View File
@@ -48,6 +48,7 @@ import {
} from "../domain/relationshipCoverage.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { outputContractDiagnostics } from "../domain/native/nativeProviderOutput.js";
import {
ghidraIdentifierSchema,
ghidraInputAddressSchema,
@@ -409,7 +410,12 @@ export const parseGhidraFunctionResult = (
new AnalysisOutputError(
operation,
"Ghidra bridge returned an invalid function observation envelope for this operation",
envelope.success ? undefined : { cause: envelope.error },
envelope.success
? undefined
: {
cause: envelope.error,
diagnostics: outputContractDiagnostics(envelope.error, value),
},
),
);
observation = envelope.data;
@@ -452,7 +458,13 @@ export const parseGhidraFunctionResult = (
new AnalysisOutputError(
operation,
"Ghidra bridge output did not match the function-analysis contract",
{ cause: parsed.error },
{
cause: parsed.error,
diagnostics: outputContractDiagnostics(
parsed.error,
observation.value,
),
},
),
);
};
+20
View File
@@ -97,6 +97,26 @@ it.each(["list_procedures", "search_procedures"] as const)(
},
);
it("names the failing fields when an inventory reply misses its contract", () => {
const parsed = parseGhidraInventoryResult(
"list_procedures",
[{ address: 16, value: "secret-name" }],
null,
);
const error = parsed.ok ? undefined : parsed.error;
expect(error?.diagnostics).toMatchObject({
contract_issues: expect.arrayContaining([
expect.objectContaining({
path: [0, "address"],
code: "invalid_type",
received: "number",
}),
]),
});
expect(JSON.stringify(error?.diagnostics)).not.toContain("secret-name");
});
describe("native load-image result projection", () => {
it("omits raw bridge output when the observation keeps every reported fact", () => {
const observations = JSON.parse(
+6 -4
View File
@@ -26,6 +26,7 @@ import {
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { projectBinaryOverview } from "../domain/native/nativeSegments.js";
import { outputContractDiagnostics } from "../domain/native/nativeProviderOutput.js";
import {
availableFunctionBodySchema,
functionBodyEntryAgrees,
@@ -391,7 +392,7 @@ export function parseGhidraInventoryResult(
const parsed = resultSchemas.inspect_native_load_image.safeParse(value);
return parsed.success
? ok({ value: normalizeNativeLoadImageObservation(parsed.data) })
: err(inventoryOutputFailure(operation, parsed.error));
: err(inventoryOutputFailure(operation, parsed.error, value));
}
if (operation === "set_address_name" || operation === "set_addresses_names") {
return parseGhidraAddressNameResult(operation, value, namingRequest);
@@ -406,15 +407,16 @@ export function parseGhidraInventoryResult(
? { rawResult: value }
: {}),
})
: err(inventoryOutputFailure(operation, parsed.error));
: err(inventoryOutputFailure(operation, parsed.error, value));
}
const inventoryOutputFailure = (
operation: GhidraInventoryOperation,
cause: unknown,
cause: z.ZodError,
value: JsonValue,
): AnalysisOutputError =>
new AnalysisOutputError(
operation,
"Ghidra bridge output did not match the inventory contract",
{ cause },
{ cause, diagnostics: outputContractDiagnostics(cause, value) },
);
+31 -37
View File
@@ -1,3 +1,4 @@
import { readLeb128, ULEB64 } from "../domain/leb128.js";
import type {
FileMapping,
ZeroFillMapping,
@@ -349,44 +350,37 @@ const readInlineExtent = (
remaining: number,
maximumBytes: number,
): { readonly location: GoStringLocation; readonly next: number } => {
let length = 0n;
for (let index = 0; index < 10; index++) {
if (index >= remaining)
throw new BinaryFormatFailure(
"malformed",
"Go build-info varint is truncated",
);
const byte = reader.bytes[offset + index] ?? 0;
if (index === 9 && byte > 1)
throw new BinaryFormatFailure(
"malformed",
"Go build-info varint overflows 64 bits",
);
length |= BigInt(byte & 127) << BigInt(index * 7);
if ((byte & 128) === 0) {
if (length > BigInt(remaining - index - 1))
throw new BinaryFormatFailure(
"malformed",
"Go build-info string range is truncated",
);
if (length > BigInt(maximumBytes))
throw new BinaryResourceFailure(
"build-info",
maximumBytes,
`Go build-info string length exceeds max_build_info_bytes=${String(maximumBytes)}`,
);
const size = Number(length);
const start = offset + index + 1;
return {
location: { offset: start, bytes: size },
next: start + size,
};
}
}
throw new BinaryFormatFailure(
"malformed",
"Go build-info varint is unterminated",
const read = readLeb128(
reader.bytes,
offset,
offset + Math.max(0, remaining),
ULEB64,
);
if ("failure" in read)
throw new BinaryFormatFailure(
"malformed",
read.failure === "truncated"
? "Go build-info varint is truncated"
: "Go build-info varint overflows 64 bits",
);
const start = read.next;
const length = read.value;
if (length > BigInt(remaining - (start - offset)))
throw new BinaryFormatFailure(
"malformed",
"Go build-info string range is truncated",
);
if (length > BigInt(maximumBytes))
throw new BinaryResourceFailure(
"build-info",
maximumBytes,
`Go build-info string length exceeds max_build_info_bytes=${String(maximumBytes)}`,
);
const size = Number(length);
return {
location: { offset: start, bytes: size },
next: start + size,
};
};
interface PointerStringContext {
+24 -16
View File
@@ -5,6 +5,7 @@ import {
mappedFileOffset,
type BinaryContainer,
} from "../native/metadata/BinaryContainer.js";
import { keyedBy, uniqueKeyed } from "../domain/keyedCollection.js";
export interface GoBuildInfoSearchRange extends FileMapping {
/** Native file mapping containing inline strings after a named Mach-O header. */
@@ -58,13 +59,28 @@ export const goBuildInfoSearch = (
container.format,
);
const named: GoBuildInfoSearchRange[] = [];
for (const section of container.sections) {
if (section.format === "elf" && section.name === ".go.buildinfo") {
if (named.length !== 0)
throw new BinaryFormatFailure(
"malformed",
"ELF contains ambiguous build-info sections",
);
// The build-info section is declared once; a repeat leaves Go's reader
// with no defined choice, whatever the repeated sections contain.
const selected = uniqueKeyed(
keyedBy(container.sections, (section) =>
section.format === "elf"
? section.name
: section.format === "macho"
? section.section_name
: undefined,
),
container.format === "elf" ? ".go.buildinfo" : "__go_buildinfo",
);
if (!selected.ok)
throw new BinaryFormatFailure(
"malformed",
container.format === "elf"
? "ELF contains ambiguous build-info sections"
: "Mach-O has ambiguous build-info sections",
);
const section = selected.value;
if (section !== undefined) {
if (section.format === "elf") {
if (section.type !== 1)
throw new BinaryFormatFailure(
"malformed",
@@ -97,10 +113,7 @@ export const goBuildInfoSearch = (
"ELF build-info section disagrees with its load mapping",
);
named.push(search);
} else if (
section.format === "macho" &&
section.section_name === "__go_buildinfo"
) {
} else if (section.format === "macho") {
if (section.segment_unmapped)
throw new BinaryFormatFailure(
"malformed",
@@ -139,10 +152,5 @@ export const goBuildInfoSearch = (
named.push(search);
}
}
if (named.length > 1)
throw new BinaryFormatFailure(
"malformed",
"Mach-O has ambiguous build-info sections",
);
return named.length > 0 ? named : fallbackSearchRanges(container);
};
+8
View File
@@ -39,6 +39,9 @@ type Il2cppBinaryFormatReason = Exclude<
Il2cppBinaryCapacityReason
>;
/** What a native-link budget counts, so its maximum is reported with its unit. */
export type NativeBudgetUnit = "entries" | "bytes" | "frames";
/** The ParseFailure format of a native image linked against IL2CPP metadata. */
export const IL2CPP_BINARY_FORMAT = "il2cpp-binary";
@@ -55,16 +58,20 @@ const isUnsupported = (reason: Il2cppBinaryFormatReason) =>
export class Il2cppBinaryFormatFailure extends ParseFailureError<
"malformed" | "unsupported" | "limit"
> {
/** What the exceeded maximum counts; set only for a capacity reason. */
readonly unit: NativeBudgetUnit | undefined;
constructor(reason: Il2cppBinaryFormatReason, message: string);
constructor(
reason: Il2cppBinaryCapacityReason,
message: string,
maximum: number,
unit: NativeBudgetUnit,
);
constructor(
readonly reason: Il2cppBinaryFailureReason,
message: string,
maximum?: number,
unit?: NativeBudgetUnit,
) {
const detail = `${reason}: ${message}`;
super(
@@ -84,6 +91,7 @@ export class Il2cppBinaryFormatFailure extends ParseFailureError<
}
: { kind: "malformed", format: IL2CPP_BINARY_FORMAT, detail },
);
this.unit = unit;
this.name = "Il2cppBinaryFormatFailure";
}
}
+8 -6
View File
@@ -94,6 +94,7 @@ export function* openImageSteps(image: Buffer): Generator<void, NativeImage> {
"native-index-capacity",
cause.message,
cause.failure.limit.maximum,
"bytes",
);
if (cause instanceof BinaryFormatFailure)
throw new Il2cppBinaryFormatFailure(
@@ -126,14 +127,15 @@ export function* openImageSteps(image: Buffer): Generator<void, NativeImage> {
);
} catch (cause) {
if (cause instanceof ElfPointerRelocationFailure) {
if (cause.failure.kind === "limit" && cause.unit !== undefined)
throw new Il2cppBinaryFormatFailure(
"native-index-capacity",
cause.message,
cause.failure.limit.maximum,
cause.unit,
);
if (cause.reason !== "native-index-capacity")
throw new Il2cppBinaryFormatFailure(cause.reason, cause.message);
if (cause.maximum !== undefined)
throw new Il2cppBinaryFormatFailure(
cause.reason,
cause.message,
cause.maximum,
);
}
if (cause instanceof BinaryFormatFailure)
throw new Il2cppBinaryFormatFailure("malformed-container", cause.message);
+4
View File
@@ -113,6 +113,7 @@ function* nameAddresses(
"native-index-capacity",
`module-name trie exceeds its ${TOTAL_NAME_OCCURRENCES}-node workspace`,
TOTAL_NAME_OCCURRENCES,
"entries",
);
let node = root;
const bytes = Buffer.from(name, "utf8");
@@ -125,6 +126,7 @@ function* nameAddresses(
"native-index-capacity",
`module-name trie exceeds its ${TOTAL_NAME_OCCURRENCES}-node workspace`,
TOTAL_NAME_OCCURRENCES,
"entries",
);
next = { next: new Map(), owners: [] };
node.next.set(bytes[at]!, next);
@@ -165,6 +167,7 @@ function* nameAddresses(
"native-index-capacity",
`native name-address index exceeds ${TOTAL_NAME_OCCURRENCES} entries`,
TOTAL_NAME_OCCURRENCES,
"entries",
);
found.set(address, node.owners);
}
@@ -535,6 +538,7 @@ function* findModuleArrayByCode(
"native-index-capacity",
`module-array index exceeds ${MODULE_ARRAY_CANDIDATES} entries`,
MODULE_ARRAY_CANDIDATES,
"entries",
);
}
}
+2
View File
@@ -107,6 +107,7 @@ const createTypeRenderer = (
"native-type-text-capacity",
`rendered type text workspace exceeds ${TYPE_TEXT_BYTES} UTF-8 bytes`,
TYPE_TEXT_BYTES,
"bytes",
);
beforeText?.(bytes);
};
@@ -133,6 +134,7 @@ const createTypeRenderer = (
"type-nesting-capacity",
`type rendering exceeds ${TYPE_DEPTH} nested frames`,
TYPE_DEPTH,
"frames",
);
active.add(address);
try {
+11 -2
View File
@@ -83,12 +83,21 @@ const failureForPrimary = (
const { cause, origin } = facts;
if (origin === "owned-or-classified" && cause instanceof AnalysisError)
return cause;
if (cause instanceof Il2cppBinaryFormatFailure && cause.kind === "limit")
if (
cause instanceof Il2cppBinaryFormatFailure &&
cause.failure.kind === "limit"
)
return new AnalysisResourceConstraintError(
OPERATION,
cause.reason === "native-type-text-capacity" ? "memory" : "capacity",
cause.message,
{},
// The producing site states what its maximum counts.
{
boundary: cause.reason,
...(cause.unit === undefined
? {}
: { [`maximum_${cause.unit}`]: cause.failure.limit.maximum }),
},
{
cause,
...fixedAllowanceOptions(
+3 -2
View File
@@ -16,6 +16,7 @@ import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
import { basename, join } from "node:path";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { Deadline } from "../domain/deadline.js";
import {
AnalysisArtifactChangedError,
cancelledBy,
@@ -274,7 +275,7 @@ export const exportKunaProject = async (
configuration,
request.deadline,
);
const deadline = Date.now() + acceptedDeadline.ms;
const deadline = Deadline.after(acceptedDeadline.ms);
const input = join(request.workspace, "input", basename(request.targetPath));
await mkdir(join(request.workspace, "input"), { mode: 0o700 });
await mkdir(request.output, { recursive: true, mode: 0o700 });
@@ -301,7 +302,7 @@ export const exportKunaProject = async (
arguments: arguments_,
workspace: request.workspace,
operation: KUNA_EXPORT_OPERATION,
timeoutMs: deadline - Date.now(),
timeoutMs: deadline.remainingMs(),
deadline: acceptedDeadline,
outputBytes,
signal,
+30
View File
@@ -478,6 +478,36 @@ const legacyRebaseInput = (stream: Buffer) => {
};
};
it("charges a padded rebase operand that exhausts the work budget", () => {
// Work is bounded by twice the source bytes (0x20000). Each padded
// SET_SEGMENT_AND_OFFSET_ULEB stream charges ~51 KiB, so the third exhausts
// the budget and a later valid stream must not run on uncharged work.
const data = Buffer.alloc(0x10000);
const padding = 0xc800;
const padded = Buffer.concat([
Buffer.from([0x11, 0x20]),
Buffer.alloc(padding, 0x80),
Buffer.from([0, 0]),
]);
padded.copy(data, 0x2000);
const valid = Buffer.from([0x11, 0x20, 0x80, 0x02, 0x51, 0]);
valid.copy(data, 0xf000);
const stream = { offset: 0x2000, size: padded.length };
const fixups = parsePointerFixups(
data,
{
chained: null,
binds: [],
rebases: [stream, stream, stream, { offset: 0xf000, size: valid.length }],
dylibs: [],
},
[{ address: BASE, size: 0x2000n, offset: 0, executable: false }],
BASE,
);
expect(fixups).toMatchObject({ examined: 4, decoded: 2 });
expect(fixups.issues).toHaveLength(2);
});
it("marks only opcode-selected pointer slots rebased, including target zero", () => {
// SET_TYPE(pointer), SET_SEGMENT(offset 0x100), DO once,
// ADD_ADDR(0x10), DO once, DONE.
+40 -41
View File
@@ -5,6 +5,7 @@ import {
unsupportedInput,
} from "../domain/parseFailure.js";
import type { Segment } from "./AppleMachoSelection.js";
import { readLeb128, type Leb128Read } from "../domain/leb128.js";
import { issue } from "./AppleDispatchDecodeFacts.js";
import type { DecodeIssue } from "./AppleDispatchDecodeFacts.js";
import { decodeMachoName, type MachoName } from "./AppleMachoNames.js";
@@ -887,6 +888,16 @@ const chainedFixups = (
};
};
/** Mach-O opcode operands are 64-bit, and padding may extend their encoding. */
const MACHO_ULEB = { signed: false, bits: 64, padding: true } as const;
const MACHO_SLEB = { signed: true, bits: 64, padding: true } as const;
/** The offset after the last byte read, including an overflowing byte. */
const consumedEnd = (read: Leb128Read): number =>
"failure" in read
? read.at + (read.failure === "overflow" ? 1 : 0)
: read.next;
const uleb = (
bytes: Buffer,
cursor: { at: number },
@@ -894,28 +905,29 @@ const uleb = (
stream: "bind" | "rebase" = "bind",
rebaseWork?: { workRemaining: number },
): bigint => {
let value = 0n;
let shift = 0;
for (;;) {
if (cursor.at >= end)
throw truncatedInput("macho", `Truncated ${stream} opcode operand`);
if (rebaseWork !== undefined) {
if (rebaseWork.workRemaining === 0)
throw malformedInput(
"macho",
"Legacy rebase parsing exceeded the source-derived work budget",
);
rebaseWork.workRemaining--;
}
const byte = bytes[cursor.at++] ?? 0;
const slice = byte & 0x7f;
if ((shift === 63 && slice > 1) || (shift === 64 && slice !== 0))
throw malformedInput("macho", `Oversized ${stream} opcode operand`);
if (shift < 64) value |= BigInt(slice) << BigInt(shift);
// Padding may extend the encoding, but never the represented integer.
shift = Math.min(64, shift + 7);
if ((byte & 0x80) === 0) return value;
const start = cursor.at;
// A rebase operand reads no further than its remaining work allows, so a
// padded operand cannot be rescanned past the budget by a later stream.
const bound =
rebaseWork === undefined
? end
: Math.min(end, start + rebaseWork.workRemaining);
const read = readLeb128(bytes, start, bound, MACHO_ULEB);
cursor.at = consumedEnd(read);
if (rebaseWork !== undefined) {
// Each byte read is charged, including those of a failed operand.
rebaseWork.workRemaining -= cursor.at - start;
if ("failure" in read && read.failure === "truncated" && read.at < end)
throw malformedInput(
"macho",
"Legacy rebase parsing exceeded the source-derived work budget",
);
}
if ("failure" in read)
throw read.failure === "truncated"
? truncatedInput("macho", `Truncated ${stream} opcode operand`)
: malformedInput("macho", `Oversized ${stream} opcode operand`);
return read.value;
};
interface RebaseFacts {
@@ -1176,26 +1188,13 @@ function* parseLegacyRebasesSteps(
}
const sleb = (bytes: Buffer, cursor: { at: number }, end: number): bigint => {
let value = 0n;
let shift = 0;
let byte = 0;
do {
if (cursor.at >= end)
throw truncatedInput("macho", "Truncated bind opcode operand");
byte = bytes[cursor.at++] ?? 0;
const slice = byte & 0x7f;
if (
(shift === 63 && slice !== 0 && slice !== 0x7f) ||
(shift === 64 && slice !== (value < 0n ? 0x7f : 0))
)
throw malformedInput("macho", "Oversized bind opcode operand");
if (shift < 64)
value = BigInt.asIntN(64, value | (BigInt(slice) << BigInt(shift)));
shift = Math.min(64, shift + 7);
} while ((byte & 0x80) !== 0);
return shift < 64 && (byte & 0x40) !== 0
? value - (1n << BigInt(shift))
: value;
const read = readLeb128(bytes, cursor.at, end, MACHO_SLEB);
cursor.at = consumedEnd(read);
if ("failure" in read)
throw read.failure === "truncated"
? truncatedInput("macho", "Truncated bind opcode operand")
: malformedInput("macho", "Oversized bind opcode operand");
return read.value;
};
/** Registers of the `LC_DYLD_INFO` bind state machine. */
+2 -4
View File
@@ -501,8 +501,7 @@ export const inspectAndroidJniLibrary = async (
});
if (
cause instanceof BinaryResourceFailure ||
(cause instanceof ElfPointerRelocationFailure &&
cause.reason === "native-index-capacity")
(cause instanceof ElfPointerRelocationFailure && cause.kind === "limit")
)
return err({ kind: "capacity", message: cause.message });
if (cause instanceof BinaryFormatFailure)
@@ -512,8 +511,7 @@ export const inspectAndroidJniLibrary = async (
});
if (cause instanceof ElfPointerRelocationFailure)
return err({
kind:
cause.reason === "malformed-container" ? "malformed" : "unsupported",
kind: cause.kind === "malformed" ? "malformed" : "unsupported",
message: cause.message,
});
throw cause;
+3 -23
View File
@@ -1,4 +1,5 @@
import { admitElfLoadSegment } from "../../domain/elfProgramHeader.js";
import { readLeb128, SLEB64, ULEB64 } from "../../domain/leb128.js";
import { assertArtifactReadActive } from "../../artifacts/ArtifactFileOperation.js";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { readElfDynamicEntry } from "../../domain/elfDynamicEntry.js";
@@ -474,29 +475,8 @@ export const parseElfUnwindRanges = (
end: number,
signed: boolean,
): { readonly value: bigint; readonly next: number } | null => {
let result = 0n;
let shift = 0n;
let pos = offset;
let byte = 0;
while (pos < end && pos < bytes.length && shift <= 63n) {
byte = bytes[pos] ?? 0;
pos += 1;
// At bit 63 only one value bit remains; signed padding repeats that bit.
const payload = byte & 0x7f;
if (
shift === 63n &&
(signed ? payload !== 0 && payload !== 0x7f : payload > 1)
)
return null;
result |= BigInt(payload) << shift;
shift += 7n;
if ((byte & 0x80) === 0) {
// Ten-byte signed operands have 70 encoded bits, including sign padding.
if (signed && (byte & 0x40) !== 0) result |= -1n << shift;
return { value: result, next: pos };
}
}
return null;
const read = readLeb128(bytes, offset, end, signed ? SLEB64 : ULEB64);
return "failure" in read ? null : read;
};
const safeInt = (value: bigint): number | null =>
value >= BigInt(Number.MIN_SAFE_INTEGER) &&
+7 -7
View File
@@ -645,13 +645,13 @@ const loadWrites = async (
}
return { writes, clobbered, trustRaw: true };
} catch (cause) {
if (!(cause instanceof ElfPointerRelocationFailure)) throw cause;
if (cause.reason === "native-index-capacity")
throw new BinaryResourceFailure(
"structure",
16 * 1024 * 1024,
cause.message,
);
// A budget stop is not a malformed table; the provider reports it with
// the maximum the failing index declared.
if (
!(cause instanceof ElfPointerRelocationFailure) ||
cause.kind === "limit"
)
throw cause;
note(scan, cause.message);
return { writes: new Map(), clobbered: new Set(), trustRaw: false };
}
@@ -199,13 +199,13 @@ const failurePrimary = (
if (identityFailure !== undefined) return identityFailure;
if (
cause instanceof ElfPointerRelocationFailure &&
cause.reason === "native-index-capacity"
cause.failure.kind === "limit"
)
return new AnalysisResourceConstraintError(
OPERATION,
"capacity",
`Selected artifact ${input.path}: ${cause.message}`,
{ boundary: "structure" },
{ boundary: "structure", maximum: cause.failure.limit.maximum },
{
cause,
...fixedAllowanceOptions(
@@ -397,7 +397,12 @@ it("refuses pointer workspace growth before inserting the next virtual destinati
expect(() => pointerValues(relativeValues(), 4096)).toThrow(
expect.objectContaining({
reason: "native-index-capacity",
maximum: 4096,
failure: expect.objectContaining({
kind: "limit",
format: "elf-pointer-relocations",
limit: { name: "native-index-capacity", maximum: 4096 },
}),
unit: "bytes",
message: expect.stringContaining("4096 estimated representation bytes"),
}),
);
+35 -6
View File
@@ -11,11 +11,21 @@ import {
isZeroFilledSpan,
type ElfDynamicSegment,
} from "./BinaryContainer.js";
import { ParseFailureError } from "../../domain/parseFailure.js";
/** Shared loader interpretation; language adapters choose their public errors. */
export class ElfPointerRelocationFailure extends Error {
/** The exceeded workspace bound, set only for `native-index-capacity`. */
readonly maximum: number | undefined;
/** The ParseFailure format of ELF loader pointer interpretation. */
export const ELF_POINTER_RELOCATION_FORMAT = "elf-pointer-relocations";
/**
* Shared loader interpretation; language adapters choose their public errors.
* The stable `reason` names the loader rule; `native-index-capacity` is a
* ParseFailure `limit` carrying the exceeded maximum.
*/
export class ElfPointerRelocationFailure extends ParseFailureError<
"malformed" | "unsupported" | "limit"
> {
/** What the limit's maximum counts, set only for `native-index-capacity`. */
readonly unit: "entries" | "bytes" | undefined;
constructor(
reason:
| "malformed-container"
@@ -27,6 +37,7 @@ export class ElfPointerRelocationFailure extends Error {
reason: "native-index-capacity",
message: string,
maximum: number,
unit: "entries" | "bytes",
);
constructor(
readonly reason:
@@ -36,9 +47,23 @@ export class ElfPointerRelocationFailure extends Error {
| "native-index-capacity",
message: string,
maximum?: number,
unit?: "entries" | "bytes",
) {
super(message);
this.maximum = maximum;
const facts = { format: ELF_POINTER_RELOCATION_FORMAT, detail: message };
super(
maximum !== undefined
? { ...facts, kind: "limit", limit: { name: reason, maximum } }
: reason === "malformed-container"
? { ...facts, kind: "malformed" }
: {
...facts,
kind: "unsupported",
// A pointer the loader encodes in an unread form still ships.
undecodedContent: reason === "unsupported-pointer-encoding",
},
);
this.unit = unit;
this.name = "ElfPointerRelocationFailure";
}
}
export interface ElfPointerRelocationSource {
@@ -269,6 +294,7 @@ function* dynamicTags(
"native-index-capacity",
"ELF dynamic directory exceeds the 16 MiB structural allowance",
16 * 1024 * 1024,
"bytes",
);
if (
declaration.size % BigInt(width) !== 0n ||
@@ -677,6 +703,7 @@ class ElfVirtualWriteIndex {
"native-index-capacity",
`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.#reservedBytes += ELF_POINTER_INDEX_ENTRY_BYTES;
}
@@ -828,6 +855,7 @@ export function* readElfPointerRelocationsSteps(
"native-index-capacity",
`ELF sparse relocation index exceeds ${MAX_RELOCATION_RECORDS} retained writes`,
MAX_RELOCATION_RECORDS,
"entries",
);
writes.push(write);
index.add(write);
@@ -895,6 +923,7 @@ export function* readElfPointerValuesSteps(
"native-index-capacity",
`ELF unresolved and zero-fill overlay exceeds ${MAX_RELOCATION_RECORDS} entries`,
MAX_RELOCATION_RECORDS,
"entries",
);
}
next = steps.next();
+65
View File
@@ -12,6 +12,7 @@ import {
UnsupportedBinaryPlistUidError,
} from "../../artifacts/apple/PlistScalars.js";
import { plistDuplicateKeyLimitations } from "../../domain/apple/plistDuplicateKeys.js";
import {
parsePlistBinary,
readPlistJson,
@@ -990,3 +991,67 @@ it.each(["\n", "\r\n", "\r", "\u2028", "\u2029"])(
});
},
);
const duplicateKeyLimitation = (names: string, replaced: number) =>
`1 dictionary(ies) declare a key more than once (${names}). REA kept the last value for each key; ${String(replaced)} earlier value(s) are not reported, and other plist readers may keep a different one.`;
it("records binary dictionary keys declared more than once before the decoded value collapses them", () => {
const bytes = Buffer.from(buildBinary({ a: 1, b: 2, c: 3 }));
// Rename the stored key "b" to "a": the dictionary now declares "a" twice.
const key = bytes.indexOf(Buffer.from([0x51, 0x62]));
expect(key).toBeGreaterThan(0);
bytes[key + 1] = 0x61;
const parsed = parsePlistBinary(bytes);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.value).toEqual({ a: 2, c: 3 });
expect(parsed.value.limitations).toEqual([duplicateKeyLimitation('"a"', 1)]);
});
it("records XML source dictionary keys declared more than once", () => {
const parsed = parsePlistXmlSource(
Buffer.from(
"<plist><dict><key>a</key><string>first</string><key>b</key><string>kept</string><key>a</key><string>last</string></dict></plist>",
),
);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.value).toEqual({ a: "last", b: "kept" });
expect(parsed.value.limitations).toEqual([duplicateKeyLimitation('"a"', 1)]);
});
it("reports no duplicate-key limitation when every key is distinct", () => {
const parsed = parsePlistXmlSource(
Buffer.from(
"<plist><dict><key>a</key><string>x</string><key>b</key><dict><key>a</key><string>y</string></dict></dict></plist>",
),
);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.limitations).toEqual([]);
});
it("counts OpenStep dictionary keys declared more than once", () => {
expect(
parseXmlPropertyList("{ a = 1; a = 2; b = { c = 3; c = 4; c = 5; }; }")
.duplicateKeys,
).toEqual({
dictionaries: 2,
replaced: 3,
names: ["c", "a"],
namesOmitted: false,
});
});
it("lists each repeated key once, shortens long keys and marks omitted names", () => {
const long = "k".repeat(100);
const nine = Array.from({ length: 9 }, (_, index) => `n${String(index)}`);
const entries = [long, long, long, ...nine.flatMap((name) => [name, name])]
.map((key, index) => `"${key}" = ${String(index)};`)
.join(" ");
const parsed = parseXmlPropertyList(`{ ${entries} }`).duplicateKeys;
expect(parsed).toMatchObject({ replaced: 11, namesOmitted: true });
expect(plistDuplicateKeyLimitations(parsed)[0]).toContain(
`"${"k".repeat(64)}" (shortened from 100 characters), "n0"`,
);
// One key repeated three times names no further key.
const single = parseXmlPropertyList("{ a = 1; a = 2; a = 3; }").duplicateKeys;
expect(plistDuplicateKeyLimitations(single)[0]).toContain('("a").');
});
+13 -1
View File
@@ -1,4 +1,11 @@
import { decodeBinaryPlistValue } from "../../artifacts/apple/BinaryPlistMaterializer.js";
import {
binaryPlistDuplicateKeys,
decodeBinaryPlistValue,
} from "../../artifacts/apple/BinaryPlistMaterializer.js";
import {
plistDuplicateKeyLimitations,
type PlistDuplicateKeys,
} from "../../domain/apple/plistDuplicateKeys.js";
import {
AnalysisOutputError,
@@ -312,12 +319,14 @@ const projectPlistXml = (
): Result<ParsedPlist, PlistParseError> => {
let projected: ProjectedPlistValue;
let literals: PlistNumberLiterals;
let duplicateKeys: PlistDuplicateKeys;
try {
const decoded = parseXmlPropertyList(
output,
MAX_NATIVE_PLIST_NESTING_DEPTH,
);
literals = decoded.numberLiterals;
duplicateKeys = decoded.duplicateKeys;
projected = projectPlistValue(
decoded.value,
undefined,
@@ -347,6 +356,7 @@ const projectPlistXml = (
...projectedScalarLimitations(projected),
...(literals.incomplete ? [incompletePlistNumberLimitation] : []),
...numberLimitations(exactIntegerCount, ambiguousNumberCount),
...plistDuplicateKeyLimitations(duplicateKeys),
],
});
};
@@ -381,6 +391,7 @@ export const parsePlistBinary = (
);
const scalarMetadata = scanBinaryPlistScalars(bytes, expansion);
const decoded = decodeBinaryPlistValue(bytes, expansion, scalarMetadata);
const duplicateKeys = binaryPlistDuplicateKeys(expansion);
const projected = projectPlistValue(
decoded,
undefined,
@@ -401,6 +412,7 @@ export const parsePlistBinary = (
),
]),
...numbers.limitations(),
...plistDuplicateKeyLimitations(duplicateKeys),
],
});
} catch (cause: unknown) {
+106
View File
@@ -502,8 +502,10 @@ describe.skipIf(process.platform === "win32")(
const release = join(directory, "release");
const finished = join(directory, "finished.json");
await mkdir(scratch);
// The stop signal reaches the whole group; this descendant outlives it.
const childSource = [
'const fs = require("node:fs");',
'process.on("SIGTERM", () => {});',
`fs.writeFileSync(${JSON.stringify(ready)}, String(process.pid));`,
"setInterval(() => {",
` if (!fs.existsSync(${JSON.stringify(release)})) return;`,
@@ -635,6 +637,110 @@ describe.skipIf(process.platform === "win32")(
},
);
describe.skipIf(process.platform === "win32")(
"execFileOutput process group",
() => {
it("stops a running launcher's descendants with it", async () => {
const directory = await createTestTempDirectory("rea-exec-group-stop-");
const ready = join(directory, "descendant.pid");
const marker = join(directory, "descendant-marker");
const childSource = [
'const fs = require("node:fs");',
`fs.writeFileSync(${JSON.stringify(ready)}, String(process.pid));`,
`setInterval(() => fs.existsSync(${JSON.stringify(marker)}), 10);`,
].join("\n");
const script = [
'const { spawn } = require("node:child_process");',
`spawn(process.execPath, ["-e", ${JSON.stringify(childSource)}], { stdio: "inherit" });`,
"setInterval(() => {}, 1000);",
].join("\n");
const controller = new AbortController();
const execution = execFileOutput(process.execPath, ["-e", script], {
stopSignal: "SIGTERM",
signal: controller.signal,
}).catch((cause: unknown) => cause);
let killFailure: unknown;
try {
expect(await waitForFile(ready)).toBe(true);
controller.abort("caller stopped");
let timer: NodeJS.Timeout | undefined;
const outcome = await Promise.race([
execution,
new Promise((resolve) => {
timer = setTimeout(
() => resolve("descendant kept the pipes"),
4_000,
);
}),
]).finally(() => clearTimeout(timer));
expect(outcome).toMatchObject({
_tag: "ExecFileOutputCancelledError",
cause: "caller stopped",
});
} finally {
controller.abort("test cleanup");
const pid = Number(await readFile(ready, "utf8").catch(() => ""));
killFailure = await stopOwnedDescendant(pid, marker);
await execution;
}
if (killFailure !== undefined) throw killFailure;
});
it("escalates to the group when the launcher and its worker ignore the stop signal", async () => {
const directory = await createTestTempDirectory(
"rea-exec-group-escalate-",
);
const ready = join(directory, "descendant.pid");
const marker = join(directory, "descendant-marker");
const ignoreStop =
'process.on("SIGTERM", () => {}); setInterval(() => {}, 1000);';
const childSource = [
'const fs = require("node:fs");',
ignoreStop,
`fs.writeFileSync(${JSON.stringify(ready)}, String(process.pid));`,
`setInterval(() => fs.existsSync(${JSON.stringify(marker)}), 10);`,
].join("\n");
const script = [
'const { spawn } = require("node:child_process");',
ignoreStop,
`spawn(process.execPath, ["-e", ${JSON.stringify(childSource)}], { stdio: "inherit" });`,
].join("\n");
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const controller = new AbortController();
const execution = execFileOutput(process.execPath, ["-e", script], {
stopSignal: "SIGTERM",
signal: controller.signal,
}).catch((cause: unknown) => cause);
let killFailure: unknown;
try {
expect(await waitForFile(ready)).toBe(true);
controller.abort("caller stopped");
// Both processes ignore SIGTERM; only the grace SIGKILL ends them.
await vi.advanceTimersByTimeAsync(5_000);
vi.useRealTimers();
let timer: NodeJS.Timeout | undefined;
const outcome = await Promise.race([
execution,
new Promise((resolve) => {
timer = setTimeout(() => resolve("worker kept the pipes"), 4_000);
}),
]).finally(() => clearTimeout(timer));
expect(outcome).toMatchObject({
_tag: "ExecFileOutputCancelledError",
cause: "caller stopped",
});
} finally {
vi.useRealTimers();
controller.abort("test cleanup");
const pid = Number(await readFile(ready, "utf8").catch(() => ""));
killFailure = await stopOwnedDescendant(pid, marker);
await execution;
}
if (killFailure !== undefined) throw killFailure;
});
},
);
describe("execFileOutput failure metadata", () => {
it("preserves raw byte counts on a failed command with invalid UTF-8", async () => {
const failure: unknown = await execFileOutput(process.execPath, [
+36 -10
View File
@@ -11,13 +11,17 @@ type ExecFileOutputOptions = Omit<
> & {
readonly maxBuffer?: number;
/**
* Signal that stops the process on abort or timeout. The promise then
* settles only after that process's stdio pipes close, so a caller can
* remove files the command wrote. A descendant that inherited those pipes
* keeps them open until it exits; destroying the readers is not
* process-family completion and must not unblock this settlement. A process
* still running after a grace period is killed. Without this signal, Node's
* execFile sends SIGTERM on abort and rejects before the process exits.
* Signal that stops the process on abort or timeout. On POSIX the command
* leads its own process group, and the stop signal goes to that group
* while its leader is unreaped, so launcher scripts and their workers stop
* together. The promise then settles only after the stdio pipes close, so
* a caller can remove files the command wrote. A descendant that inherited
* those pipes keeps them open until it exits; destroying the readers is not
* process-family completion and must not unblock this settlement. A group
* whose leader is still running after a grace period is killed. Once the
* leader has been reaped its PID no longer identifies the group, so no
* further group signal is sent. Without this signal, Node's execFile sends
* SIGTERM to the direct child on abort and rejects before it exits.
*/
readonly stopSignal?: NodeJS.Signals;
/** Wait for inherited copies of an extra drained descriptor to close. Requires stopSignal. */
@@ -296,6 +300,9 @@ const startStoppableCommand = (
? ["ignore", "pipe", "pipe", "pipe"]
: ["ignore", "pipe", "pipe"],
killSignal: stopSignal,
// POSIX detach starts a new session, so the command leads a process group
// REA can stop as one family. Windows detach would only open a console.
detached: process.platform !== "win32",
});
child.on("error", (error: Error) => {
processError ??= error;
@@ -307,12 +314,31 @@ const startStoppableCommand = (
const pipe = stdio?.[3];
if (pipe != null && "resume" in pipe) pipe.resume();
}
let signalled = false;
/**
* Signal the command's process group while its leader is unreaped. Node
* sets exitCode or signalCode in the same callback that reaps the leader,
* so until then the leader's PID still names the group this call created.
*/
const signalFamily = (signalName: NodeJS.Signals): void => {
if (child.exitCode !== null || child.signalCode !== null) return;
const pid = child.pid;
if (process.platform !== "win32" && pid !== undefined)
try {
process.kill(-pid, signalName);
signalled = true;
return;
} catch {
// The leader left its group; it is still the direct child.
}
if (child.kill(signalName)) signalled = true;
};
// The first stop request names the failure; a later one is not resent.
const stop = (reason: "abort" | "timeout" | "output-limit"): void => {
if (stopped !== undefined || rootFailed || processError !== null) return;
stopped = reason;
child.kill(stopSignal);
grace = setTimeout(() => child.kill("SIGKILL"), STOP_GRACE_MS);
signalFamily(stopSignal);
grace = setTimeout(() => signalFamily("SIGKILL"), STOP_GRACE_MS);
};
const onAbort = (): void => {
stop("abort");
@@ -362,7 +388,7 @@ const startStoppableCommand = (
);
Reflect.set(processError, "code", code);
Reflect.set(processError, "signal", exitSignal);
Reflect.set(processError, "killed", child.killed);
Reflect.set(processError, "killed", signalled);
}
if (processError !== null) Reflect.set(processError, "cmd", invocation);
if (outputError !== undefined) Reflect.set(outputError, "cmd", invocation);
+204
View File
@@ -0,0 +1,204 @@
import type {
AnalysisError,
AnalysisErrorOptions,
} from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import {
closeOwnedDebuggerSessions,
retainedDebuggerCleanupFailure,
type OwnedDebuggerStopResult,
} from "./ownedDebuggerSession.js";
/** What the registry needs from a persistent debugger session it owns. */
export interface RegisteredDebuggerSession {
readonly id: string;
readonly launched: {
readonly process: { readonly pid?: number | undefined };
};
readonly supervisor: { ref(): void; unref(): void };
}
export interface OwnedDebuggerSessionRegistryOptions<Session> {
/** Provider id used for retained capability failures. */
readonly provider: string;
/** Debugger name shown in cleanup failures, such as "GDB". */
readonly displayName: string;
/** Operation a retained failure names when no caller operation applies. */
readonly closeOperation: string;
/** Seal the session against new commands; runs on every stop request. */
readonly sealSession: (session: Session) => void;
/** Stop the owned debugger process; protocol hooks stay with the adapter. */
readonly stopProcess: (session: Session) => Promise<OwnedDebuggerStopResult>;
/** Prefix for a stop that threw instead of reporting an outcome. */
readonly stopFailurePrefix: string;
}
/**
* Owns the persistent sessions of one debugger: the published session map,
* start reservations against its capacity, one in-flight stop per session,
* cleanup failures retained until a stop is confirmed, cleanup retry, and
* closing every session. Each debugger keeps its protocol, detach and
* stop-reason policy.
*/
export class OwnedDebuggerSessionRegistry<
Session extends RegisteredDebuggerSession,
> {
readonly #options: OwnedDebuggerSessionRegistryOptions<Session>;
readonly #sessions = new Map<string, Session>();
readonly #cleanupFailures = new WeakMap<Session, Set<AnalysisError>>();
readonly #stopAttempts = new WeakMap<
Session,
Promise<OwnedDebuggerStopResult>
>();
#reservations = 0;
constructor(options: OwnedDebuggerSessionRegistryOptions<Session>) {
this.#options = options;
}
get(id: string): Session | undefined {
return this.#sessions.get(id);
}
has(id: string): boolean {
return this.#sessions.has(id);
}
values(): IterableIterator<Session> {
return this.#sessions.values();
}
/** Publish a started session under its ID. */
add(session: Session): void {
this.#sessions.set(session.id, session);
}
/** Forget a session whose owned cleanup completed; a replacement is kept. */
remove(session: Session): void {
if (this.#sessions.get(session.id) === session)
this.#sessions.delete(session.id);
}
/** Published sessions plus starts holding a reservation. */
occupied(): number {
return this.#sessions.size + this.#reservations;
}
/** Reserve one capacity slot for a start; the release is idempotent. */
reserve(): () => void {
this.#reservations += 1;
let held = true;
return () => {
if (!held) return;
held = false;
this.#reservations -= 1;
};
}
/** Whether a stop of this session is in flight. */
stopping(session: Session): boolean {
return this.#stopAttempts.has(session);
}
/**
* Stop the owned debugger process, sharing one attempt between concurrent
* callers. A confirmed stop resolves every retained cleanup failure.
*/
stop(session: Session): Promise<OwnedDebuggerStopResult> {
this.#options.sealSession(session);
const active = this.#stopAttempts.get(session);
if (active !== undefined) return active;
const attempt = Promise.resolve()
.then(() => this.#options.stopProcess(session))
.catch((cause: unknown): OwnedDebuggerStopResult => ({
status: "incomplete",
reason: `${this.#options.stopFailurePrefix}: ${cause instanceof Error ? cause.message : String(cause)}`,
}))
.then((stopped) => {
if (stopped.status !== "incomplete") {
const retained = this.#cleanupFailures.get(session);
for (const failure of retained ?? []) failure.resolveCleanup();
retained?.clear();
}
return stopped;
})
.finally(() => {
if (this.#stopAttempts.get(session) === attempt)
this.#stopAttempts.delete(session);
});
this.#stopAttempts.set(session, attempt);
return attempt;
}
/** Keep a failure whose cleanup is incomplete until a stop is confirmed. */
retain(session: Session, failure: AnalysisError): AnalysisError {
let retained = this.#cleanupFailures.get(session);
if (retained === undefined) {
retained = new Set();
this.#cleanupFailures.set(session, retained);
}
retained.add(failure);
return failure;
}
/** Retain the failure of an operation that could not confirm the stop. */
retainCleanupFailure(
session: Session,
operation: string,
reason: string,
options: AnalysisErrorOptions = {},
): AnalysisError {
return this.retain(
session,
retainedDebuggerCleanupFailure(
{
provider: this.#options.provider,
displayName: this.#options.displayName,
},
operation,
reason,
[session.id],
options,
),
);
}
/**
* Stop each session that retains a cleanup failure. A session that stops
* is forgotten unless `keepAddressable` holds: the caller still holds a
* published session's ID, so status keeps reporting why it stopped until
* it is closed.
*/
async retryCleanupFailures(
keepAddressable: (session: Session) => boolean,
): Promise<Result<null, AnalysisError>> {
for (const session of this.#sessions.values()) {
const retained = this.#cleanupFailures.get(session);
if (retained === undefined || retained.size === 0) continue;
const stopped = await this.stop(session);
if (stopped.status === "incomplete")
return err(
[...retained].at(-1) ??
this.retainCleanupFailure(
session,
this.#options.closeOperation,
stopped.reason,
),
);
if (!keepAddressable(session)) this.remove(session);
}
return ok(null);
}
/**
* Stop every session; sessions whose stop is incomplete stay registered for
* retry. Callers block new starts and drain in-flight ones first.
*/
closeAll(): Promise<void> {
return closeOwnedDebuggerSessions(
this.#sessions,
(session) => this.stop(session),
this.#options.displayName,
);
}
}
+20
View File
@@ -303,3 +303,23 @@ it("reports no remaining time after terminal expiry near the monotonic boundary"
vi.useRealTimers();
}
});
it("finalizes an expired startup under its own budget and the caller's signal", async () => {
const caller = new AbortController();
const deadline = new ProviderStartupDeadline(100, caller.signal, {
finalizeMs: 1_000,
});
try {
await vi.advanceTimersByTimeAsync(100);
expect(deadline.signal.aborted).toBe(true);
expect(deadline.interruption).toBe("timeout");
const finalization = deadline.finalize();
// Startup expiry does not interrupt finalization; only the caller does.
expect(finalization.signal).toBe(caller.signal);
expect(finalization.signal?.aborted).toBe(false);
expect(finalization.deadline.remainingMs()).toBe(1_000);
} finally {
deadline.dispose();
}
});
+36 -12
View File
@@ -1,3 +1,5 @@
import { Deadline } from "../domain/deadline.js";
/** Result of an abort-aware interval wait. */
export type AbortableWaitResult = "elapsed" | "aborted";
@@ -22,15 +24,24 @@ export const waitForAbortableDelay = (
});
};
/** The window a startup failure finalizes under. */
export interface StartupFinalization {
/** Monotonic finalize budget, started when finalization began. */
readonly deadline: Deadline;
/** The caller's signal. Startup expiry does not interrupt finalization. */
readonly signal: AbortSignal | undefined;
}
/**
* One absolute deadline shared by every phase of a provider startup handshake.
* One absolute deadline shared by every phase of a provider startup handshake,
* with a separate finalize budget for the work a failed startup still owes.
*
* The deadline owns its timer and the listener attached to an optional caller
* signal. Adapters must dispose it after startup succeeds or fails.
*/
export class ProviderStartupDeadline {
readonly #controller = new AbortController();
readonly #deadlineAt: number;
readonly #budget: Deadline;
readonly #externalSignal: AbortSignal | undefined;
readonly #onExternalAbort: () => void;
#timer: NodeJS.Timeout | undefined;
@@ -39,14 +50,15 @@ export class ProviderStartupDeadline {
constructor(
readonly timeoutMs: number,
signal?: AbortSignal,
options: { readonly finalizeMs?: number } = {},
) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
throw new RangeError("Provider startup timeout must be positive");
this.#deadlineAt = performance.now() + timeoutMs;
this.#budget = Deadline.after(timeoutMs, options);
this.#externalSignal = signal;
this.#onExternalAbort = () => {
if (this.#controller.signal.aborted) return;
if (performance.now() >= this.#deadlineAt) {
if (this.#budget.expired()) {
this.#interruption = "timeout";
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
@@ -72,8 +84,7 @@ export class ProviderStartupDeadline {
/** First control path that interrupted startup, if any. */
get interruption(): "cancelled" | "timeout" | undefined {
return (
this.#interruption ??
(performance.now() >= this.#deadlineAt ? "timeout" : undefined)
this.#interruption ?? (this.#budget.expired() ? "timeout" : undefined)
);
}
@@ -83,7 +94,7 @@ export class ProviderStartupDeadline {
// deadline, so an elapsed timer must not report time left to spend. A
// terminal timeout also cannot regain budget after later clock queries.
if (this.#interruption === "timeout") return 0;
return Math.max(0, Math.ceil(this.#deadlineAt - performance.now()));
return this.#budget.remainingMs();
}
/**
@@ -96,7 +107,8 @@ export class ProviderStartupDeadline {
const startedAt = performance.now();
// Absolute target: the earlier of the requested polling interval and the
// absolute monotonic deadline.
const targetAt = Math.min(startedAt + milliseconds, this.#deadlineAt);
const targetAt =
startedAt + Math.min(milliseconds, this.#budget.remainingMs());
const poll = (): Promise<AbortableWaitResult> => {
const budget = this.remainingMs();
const residual = Math.max(0, targetAt - performance.now());
@@ -105,12 +117,11 @@ export class ProviderStartupDeadline {
this.signal,
).then((result) => {
if (result === "aborted") return "aborted";
const now = performance.now();
// The monotonic deadline expired: a full-budget wait resolves as an
// abort so polling stops at the boundary.
if (now >= this.#deadlineAt) return "aborted";
if (this.#budget.expired()) return "aborted";
// The polling interval elapsed without expiring the deadline.
if (now >= targetAt) return "elapsed";
if (performance.now() >= targetAt) return "elapsed";
// A timer fired before the absolute target; keep waiting.
return poll();
});
@@ -118,6 +129,19 @@ export class ProviderStartupDeadline {
return poll();
}
/**
* Begin finalizing a failed or interrupted startup. The finalize budget
* starts now and only the caller's signal interrupts it, so work that
* exhausted the startup budget can still drain evidence and release what it
* owns.
*/
finalize(): StartupFinalization {
return {
deadline: this.#budget.beginFinalize(),
signal: this.#externalSignal,
};
}
/** Release the deadline timer and external abort listener. */
dispose(): void {
this.#clearTimer();
@@ -145,7 +169,7 @@ export class ProviderStartupDeadline {
this.#timer = setTimeout(() => {
this.#timer = undefined;
if (this.#controller.signal.aborted) return;
if (performance.now() >= this.#deadlineAt) {
if (this.#budget.expired()) {
this.#interruption = "timeout";
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
+2 -10
View File
@@ -1,15 +1,7 @@
import type { PYTHON_PYC_LIMIT_MAXIMA } from "../domain/python/pythonPyc.js";
/** Distinguish corrupt recognized pycs from magics outside parser coverage. */
export class PythonPycFormatFailure extends Error {
constructor(
readonly kind: "malformed" | "unsupported",
message: string,
) {
super(message);
this.name = "PythonPycFormatFailure";
}
}
/** The ParseFailure format of a standalone CPython pyc. */
export const PYTHON_PYC_FORMAT = "python-pyc";
/** Resource boundary exceeded while walking marshal objects. */
export class PythonPycResourceFailure extends Error {
+27 -26
View File
@@ -11,10 +11,8 @@ import {
pythonPycHeader,
} from "./PythonPyc.fixture.js";
import { parsePythonPyc } from "./PythonPycParser.js";
import {
PythonPycFormatFailure,
PythonPycResourceFailure,
} from "./PythonPyc.errors.js";
import { PythonPycResourceFailure } from "./PythonPyc.errors.js";
import { ParseFailureError } from "../domain/parseFailure.js";
const defaults = inspectPythonPycInputSchema.parse({
path: "/artifacts/sample.pyc",
@@ -133,7 +131,7 @@ it("decodes a hash-based header and a FLAG_REF top-level code object", () => {
it("rejects truncated marshal without partial success", () => {
expect(() => parse(pythonPycFixture("py311").subarray(0, 20))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
});
@@ -169,8 +167,13 @@ it("keeps CPython 3.16 pre-release magics outside standalone decoder coverage",
it("does not qualify a magic outside the pinned identity table", () => {
expect(() => parse(pythonPycHeader(1))).toThrow(
expect.objectContaining({
kind: "unsupported",
message: expect.stringMatching(/not a pinned CPython identity.*header/iu),
failure: expect.objectContaining({
kind: "unsupported",
format: "python-pyc",
detail: expect.stringMatching(
/not a pinned CPython identity.*header/iu,
),
}),
}),
);
});
@@ -481,10 +484,10 @@ it("charges long digits to the string budget and keeps large previews bounded",
expect(root(report).consts[1]).toMatchObject({ kind: "int", value: null });
expect(pythonPycSchema.safeParse(report).success).toBe(true);
expect(() => parse(withConsts([marshalLong([1, 0])]))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
expect(() => parse(withConsts([marshalLong([0x8000])]))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
});
@@ -522,10 +525,10 @@ it("decodes marshal strings with CPython surrogatepass rules", () => {
});
expect(() =>
parse(withConsts([marshalUnicode(Buffer.from([0xf0, 0x90, 0x80]))])),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
expect(() =>
parse(withConsts([marshalUnicode(Buffer.from([0xc0, 0x80]))])),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
});
it.each([0x73, 0x74, 0x75, 0x61, 0x41, 0x28, 0x5b, 0x3c, 0x3e])(
@@ -533,7 +536,7 @@ it.each([0x73, 0x74, 0x75, 0x61, 0x41, 0x28, 0x5b, 0x3c, 0x3e])(
(tag) => {
expect(() =>
parse(withConsts([Buffer.concat([Buffer.from([tag]), i32(-1)])])),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
},
);
@@ -589,7 +592,7 @@ it("rejects a code object whose location tables are not bytes", () => {
marshalCode("py311", { exceptiontableObject: Buffer.from([0x53]) }),
]),
),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
});
it("hashes one shared byte string no matter how many times it is referenced", () => {
@@ -658,7 +661,7 @@ it("rejects constant tables whose copies exceed max_objects", () => {
it("rejects NULL tuple items and mismatched local kinds", () => {
expect(() => parse(withConsts([Buffer.from([0x30])]))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
expect(
root(parse(withConsts([Buffer.from([0x7b, 0x4e, 0x54, 0x30])]))).consts[0],
@@ -676,7 +679,7 @@ it("rejects NULL tuple items and mismatched local kinds", () => {
}),
]),
),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
const matched = parse(
Buffer.concat([
pythonPycHeader(3531),
@@ -881,7 +884,7 @@ it("reads marshal version 0 text floats inside a code object", () => {
]);
for (const text of ["1.5x", "", "0x1.8p1", " 1.5"]) {
expect(() => parse(withConsts([textFloat(text)]))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
}
});
@@ -993,10 +996,10 @@ it("applies Python container rules before reporting lengths", () => {
]),
]),
),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
expect(() =>
parse(withConsts([setOf(Buffer.concat([Buffer.from([0x5b]), u32(0)]))])),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
});
it("rejects a shared tuple key before its expansion doubles without bound", () => {
@@ -1164,14 +1167,12 @@ it("rejects code keys and members whose consts are unhashable", () => {
Buffer.concat([Buffer.from([0x7b]), key, int, Buffer.from([0x30])]);
for (const key of [code(list), code(tuple(int, list)), code(code(list))]) {
expect(() => parse(withConsts([setOf(0x3c, key)]))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
expect(() => parse(withConsts([setOf(0x3e, key)]))).toThrow(
PythonPycFormatFailure,
);
expect(() => parse(withConsts([dictKey(key)]))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
expect(() => parse(withConsts([dictKey(key)]))).toThrow(ParseFailureError);
}
const cyclic = Buffer.concat([
Buffer.from([0x29 | 0x80, 1]),
@@ -1183,7 +1184,7 @@ it("rejects code keys and members whose consts are unhashable", () => {
}),
]);
expect(() => parse(withConsts([cyclic, setOf(0x3c, marshalRef(1))]))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
// A set inside a tuple that reaches the unfinished tuple, directly, inside
@@ -1211,7 +1212,7 @@ it("rejects code keys and members whose consts are unhashable", () => {
]),
]),
),
).toThrow(PythonPycFormatFailure);
).toThrow(ParseFailureError);
const unhashed = parse(withConsts([tuple(code(list))]));
expect(unhashed.coverage.status).toBe("complete");
@@ -1522,7 +1523,7 @@ it("rejects negative CPython code counts and keeps them out of the schema", () =
"stacksize",
] as const) {
expect(() => parse(negative("py311", { [field]: 0xffffffff }))).toThrow(
PythonPycFormatFailure,
ParseFailureError,
);
}
expect(() => parse(negative("py37", { nlocals: 0xffffffff }))).toThrow(
+4 -3
View File
@@ -15,8 +15,9 @@ import {
type PythonPycCodeObject,
type PythonPycConst,
} from "../domain/python/pythonPyc.js";
import { malformedInput, unsupportedInput } from "../domain/parseFailure.js";
import {
PythonPycFormatFailure,
PYTHON_PYC_FORMAT,
PythonPycResourceFailure,
} from "./PythonPyc.errors.js";
import { pythonPycBytecodeIdentity } from "./PythonPycBytecodeEquality.js";
@@ -179,7 +180,7 @@ type NameTable = {
};
const malformed = (message: string): never => {
throw new PythonPycFormatFailure("malformed", message);
throw malformedInput(PYTHON_PYC_FORMAT, message);
};
/** Locals CPython's 3.11+ validator counts toward `co_varnames`. */
@@ -193,7 +194,7 @@ const fastLocalCount = (kinds: Buffer): number => {
};
const unsupported = (message: string): never => {
throw new PythonPycFormatFailure("unsupported", message);
throw unsupportedInput(PYTHON_PYC_FORMAT, message);
};
const digests = new WeakMap<Buffer, string>();
+5 -24
View File
@@ -19,21 +19,15 @@ import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import type { PythonPycPort } from "../application/python/PythonPycPort.js";
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisInputError,
AnalysisResourceConstraintError,
AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import {
PYTHON_PYC_LIMIT_MAXIMA,
type InspectPythonPycInput,
} from "../domain/python/pythonPyc.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok } from "../domain/result.js";
import {
PythonPycFormatFailure,
PythonPycResourceFailure,
} from "./PythonPyc.errors.js";
import { PythonPycResourceFailure } from "./PythonPyc.errors.js";
import { parseFailureAnalysisError } from "../domain/parseFailureAnalysisError.js";
import { parsePythonPyc } from "./PythonPycParser.js";
const OPERATION = "inspect_python_pyc";
@@ -83,21 +77,8 @@ const failureForPrimary = (
cause.reported_limits,
{ cause, ...parserLimitRecovery(cause.reported_limits) },
);
if (cause instanceof PythonPycFormatFailure)
return cause.kind === "unsupported"
? new AnalysisUnsupportedTargetError(
OPERATION,
input.path,
cause.message,
{ cause },
)
: new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: "invalid_format",
message: `Selected pyc ${input.path}: ${cause.message}`,
},
]);
const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause);
if (formatFailure !== undefined) return formatFailure;
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure
+42 -97
View File
@@ -1,5 +1,6 @@
import { RIZIN_DEBUGGER_PROVIDER_IDENTITY } from "./RizinDebuggerProviderIdentity.js";
import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js";
import { Deadline } from "../domain/deadline.js";
import { randomUUID } from "node:crypto";
import { isUtf8 } from "node:buffer";
import { open, readlink, realpath, stat } from "node:fs/promises";
@@ -49,18 +50,17 @@ import {
type DebuggerAdmissionLimit,
} from "../config/debuggerSessionLimits.js";
import {
closeOwnedDebuggerSessions,
configurableDeadlineGuidance,
debuggerAdmissionRecovery,
debuggerResourceConstraintError,
fixedDeadlineGuidance,
stopOwnedDebuggerProcess,
readLinuxProcessStartTime,
retainedDebuggerCleanupFailure,
verifyOwnedInferiorsEnded,
type OwnedInferiorIdentity,
type OwnedDebuggerDetachResult,
} from "../process/ownedDebuggerSession.js";
import { OwnedDebuggerSessionRegistry } from "../process/OwnedDebuggerSessionRegistry.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";
import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js";
@@ -220,8 +220,6 @@ interface RizinDebugSession {
verifyInferiorsEndedAfterExit: () => Promise<boolean>;
readonly detachInferior: () => Promise<OwnedDebuggerDetachResult>;
cleanupCommandTurnHeld: boolean;
stopAttempt: ReturnType<typeof stopOwnedDebuggerProcess> | undefined;
readonly cleanupFailures: Set<AnalysisError>;
pendingCommandCount: number;
invalidUtf8Observed: boolean;
closing: boolean;
@@ -275,10 +273,9 @@ class RizinFrameTimeoutError extends Error {
/** Owns persistent Rizin debugger processes independently from BinarySession. */
export class RizinDebugSessionManager {
readonly #sessions = new Map<string, RizinDebugSession>();
readonly #sessions: OwnedDebuggerSessionRegistry<RizinDebugSession>;
readonly #ttyResources = new ArtifactResourceScope();
#activeStarts = 0;
#sessionReservations = 0;
readonly #environment: Readonly<NodeJS.ProcessEnv>;
#closingAll = false;
readonly #startDrainWaiters: Array<() => void> = [];
@@ -289,7 +286,6 @@ export class RizinDebugSessionManager {
readonly #maxPendingCommands: DebuggerAdmissionLimit;
readonly #launchCommandOutput: DebuggerAdmissionLimit;
readonly #platform: NodeJS.Platform;
readonly #stopProcess: typeof stopOwnedDebuggerProcess;
readonly #spawnProcess: typeof spawnOwnedProviderProcess;
constructor(
@@ -311,7 +307,19 @@ export class RizinDebugSessionManager {
this.#maxPendingCommands = limits.maxPendingCommands;
this.#launchCommandOutput = limits.maxCommandOutputBytes;
this.#platform = options.platform ?? process.platform;
this.#stopProcess = options.stopProcess ?? stopOwnedDebuggerProcess;
const stopProcess = options.stopProcess ?? stopOwnedDebuggerProcess;
const platform = this.#platform;
this.#sessions = new OwnedDebuggerSessionRegistry({
provider: "rizin",
displayName: "Rizin",
closeOperation: "close_rizin_debug_session",
sealSession: (session) => {
session.closing = true;
},
stopProcess: (session) =>
stopProcess(session, "Rizin debugger", { platform }),
stopFailurePrefix: "Owned Rizin debugger shutdown failed",
});
this.#spawnProcess = options.spawnProcess ?? spawnOwnedProviderProcess;
}
@@ -373,7 +381,7 @@ export class RizinDebugSessionManager {
},
]),
);
const occupied = this.#sessions.size + this.#sessionReservations;
const occupied = this.#sessions.occupied();
if (occupied >= this.#maxSessions.value)
return err(
debuggerResourceConstraintError(
@@ -389,13 +397,7 @@ export class RizinDebugSessionManager {
),
);
this.#activeStarts += 1;
this.#sessionReservations += 1;
let reserved = true;
const releaseReservation = () => {
if (!reserved) return;
reserved = false;
this.#sessionReservations -= 1;
};
const releaseReservation = this.#sessions.reserve();
try {
return await this.#start(input, signal, releaseReservation);
} finally {
@@ -605,8 +607,6 @@ export class RizinDebugSessionManager {
? this.#detachInferiorUnlocked(session)
: this.#detachInferior(session),
cleanupCommandTurnHeld: false,
stopAttempt: undefined,
cleanupFailures: new Set(),
pendingCommandCount: 0,
invalidUtf8Observed: false,
closing: false,
@@ -636,7 +636,7 @@ export class RizinDebugSessionManager {
commandOutputDropped: false,
discardingOversizedFrame: false,
};
this.#sessions.set(id, session);
this.#sessions.add(session);
releaseReservation();
launched.process.stdout?.on("data", (chunk: Buffer | string) =>
this.#receive(session, Buffer.from(chunk)),
@@ -680,7 +680,7 @@ export class RizinDebugSessionManager {
: undefined;
const stopped = await this.#stopDebuggerOnly(session);
const capturedOutput = this.#startupCapturedOutput(session);
if (stopped.status !== "incomplete") this.#sessions.delete(id);
if (stopped.status !== "incomplete") this.#sessions.remove(session);
let primary: AnalysisError;
if (cancellation !== undefined)
primary = rizinCancellation(
@@ -1150,13 +1150,13 @@ export class RizinDebugSessionManager {
const stopped = await this.#stopDebuggerOnly(session);
if (stopped.status === "incomplete")
return err(
this.#retainCleanupFailure(
this.#sessions.retainCleanupFailure(
session,
"close_rizin_debug_session",
stopped.reason,
),
);
this.#sessions.delete(sessionId);
this.#sessions.remove(session);
return ok({ target_state: "unknown" });
}
@@ -1176,24 +1176,9 @@ export class RizinDebugSessionManager {
bindArtifactFileCleanup(cause, error);
return err(error);
}
for (const session of this.#sessions.values()) {
if (session.cleanupFailures.size === 0) continue;
const stopped = await this.#stopDebuggerOnly(session);
if (stopped.status === "incomplete")
return err(
[...session.cleanupFailures].at(-1) ??
this.#retainCleanupFailure(
session,
"close_rizin_debug_session",
stopped.reason,
),
);
// The caller still holds a published session's ID; keep it addressable
// so commands and status report why it stopped until it is closed.
if (!session.published || session.closeRequested)
this.#sessions.delete(session.id);
}
return ok(null);
return this.#sessions.retryCleanupFailures(
(session) => session.published && !session.closeRequested,
);
}
async closeAll(): Promise<void> {
@@ -1202,13 +1187,8 @@ export class RizinDebugSessionManager {
await new Promise<void>((resolve) =>
this.#startDrainWaiters.push(resolve),
);
for (const session of this.#sessions.values()) session.closing = true;
const outcomes = await Promise.allSettled([
closeOwnedDebuggerSessions(
this.#sessions,
(session) => this.#stopDebuggerOnly(session),
"Rizin",
),
this.#sessions.closeAll(),
this.#ttyResources.close(),
]);
const failures = outcomes.flatMap((outcome) =>
@@ -1372,31 +1352,9 @@ export class RizinDebugSessionManager {
}
#stopDebuggerOnly(session: RizinDebugSession, commandTurnHeld = false) {
session.closing = true;
if (session.stopAttempt !== undefined) return session.stopAttempt;
session.cleanupCommandTurnHeld = commandTurnHeld;
session.stopAttempt = Promise.resolve()
.then(() =>
this.#stopProcess(session, "Rizin debugger", {
platform: this.#platform,
}),
)
.catch((cause: unknown) => ({
status: "incomplete" as const,
reason: `Owned Rizin debugger shutdown failed: ${cause instanceof Error ? cause.message : String(cause)}`,
}))
.then((stopped) => {
if (stopped.status !== "incomplete") {
for (const failure of session.cleanupFailures)
failure.resolveCleanup();
session.cleanupFailures.clear();
}
return stopped;
})
.finally(() => {
session.stopAttempt = undefined;
});
return session.stopAttempt;
if (!this.#sessions.stopping(session))
session.cleanupCommandTurnHeld = commandTurnHeld;
return this.#sessions.stop(session);
}
async #detachInferior(
@@ -1668,7 +1626,7 @@ export class RizinDebugSessionManager {
}
return stopped.status === "incomplete"
? err(
this.#retainCleanupFailure(
this.#sessions.retainCleanupFailure(
session,
"rizin_debug_command",
stopped.reason,
@@ -1691,10 +1649,15 @@ export class RizinDebugSessionManager {
});
if (stopped.status !== "incomplete") return primary;
if (primary instanceof AnalysisCancelledError)
return this.#retainCleanupFailure(session, operation, stopped.reason, {
cause: primary,
});
const cleanup = this.#retainCleanupFailure(
return this.#sessions.retainCleanupFailure(
session,
operation,
stopped.reason,
{
cause: primary,
},
);
const cleanup = this.#sessions.retainCleanupFailure(
session,
operation,
stopped.reason,
@@ -1704,25 +1667,7 @@ export class RizinDebugSessionManager {
cleanup,
operation,
).bindCleanupDependencies([cleanup]);
session.cleanupFailures.add(composed);
return composed;
}
#retainCleanupFailure(
session: RizinDebugSession,
operation: string,
reason: string,
options: AnalysisErrorOptions = {},
): AnalysisError {
const failure = retainedDebuggerCleanupFailure(
{ provider: "rizin", displayName: "Rizin" },
operation,
reason,
[session.id],
options,
);
session.cleanupFailures.add(failure);
return failure;
return this.#sessions.retain(session, composed);
}
async #stopAfterProtocolFailure(
@@ -1867,7 +1812,7 @@ const waitForCommandFrames = async (
signal?: AbortSignal,
): Promise<Result<RizinCommandCapture, RizinCommandInterruption>> => {
const maxCommandOutputBytes = commandOutput.value;
const deadline = Date.now() + timeoutMs;
const deadline = Deadline.after(timeoutMs);
const output: string[] = [];
let outputBytes = 0;
let outputInvalidUtf8 = false;
@@ -1948,7 +1893,7 @@ const waitForCommandFrames = async (
capture,
});
}
const remaining = deadline - Date.now();
const remaining = deadline.remainingMs();
if (remaining <= 0)
return err({
kind: "timeout",
+8 -39
View File
@@ -1,6 +1,5 @@
import { nodeCodecResult } from "../compression/NodeCodecResult.js";
import { inflateSync } from "node:zlib";
import { visit } from "jsonc-parser";
import { z } from "zod";
import { RUST_PRODUCER_DEFAULTS } from "../domain/rust/rustResourceLimits.js";
import {
@@ -10,6 +9,7 @@ import {
} from "../domain/rust/rustBinary.js";
import { jsonValueByteLength } from "../domain/jsonValueByteLength.js";
import { malformedInput, ParseFailureError } from "../domain/parseFailure.js";
import { findDuplicateJsonMember } from "../domain/jsonDuplicateMember.js";
/** Compressed zlib stream limit. */
const RUST_SECTION_BYTES = 1024 * 1024;
@@ -230,50 +230,19 @@ const parseDocument = (
throw malformedSection("Dependency JSON is not valid UTF-8", cause);
}
assertDepth(text);
let invalidJson = false;
let duplicate: string | undefined;
const objectNames: Set<string>[] = [];
visit(
text,
{
onObjectBegin: () => {
objectNames.push(new Set());
},
onObjectProperty: (name) => {
const names = objectNames.at(-1);
if (names === undefined) return;
if (names.has(name)) duplicate ??= name;
names.add(name);
},
onObjectEnd: () => {
objectNames.pop();
},
onError: () => {
invalidJson = true;
},
},
{
allowTrailingComma: false,
disallowComments: true,
},
);
if (invalidJson) {
throw malformedInput(
RUST_AUDITABLE_FORMAT,
"Dependency section JSON is invalid",
);
}
if (duplicate !== undefined)
throw malformedInput(
RUST_AUDITABLE_FORMAT,
`Dependency JSON contains duplicate field ${JSON.stringify(duplicate)}`,
);
let value: unknown;
try {
value = JSON.parse(text);
} catch (cause) {
throw malformedSection("Dependency section JSON is invalid", cause);
}
// JSON.parse keeps the last of a repeated field; the format allows one.
const duplicate = findDuplicateJsonMember(text);
if (duplicate !== undefined)
throw malformedInput(
RUST_AUDITABLE_FORMAT,
`Dependency JSON contains duplicate field ${JSON.stringify(duplicate.name)}`,
);
const version = documentVersionSchema.safeParse(value);
if (!version.success)
throw malformedSection(
+7 -3
View File
@@ -4,6 +4,7 @@ import {
type ImageSection,
} from "../native/metadata/BinaryContainer.js";
import { malformedInput, unsupportedInput } from "../domain/parseFailure.js";
import { keyedBy, uniqueKeyed } from "../domain/keyedCollection.js";
import { readBinaryContainer } from "../native/metadata/readBinaryContainer.js";
import type {
RustAuditableMetadata,
@@ -81,13 +82,16 @@ const dependencySection = (
sections: readonly ImageSection[],
): ImageSection | null => {
const expected = format === "macho" ? "__DATA,.dep-v0" : ".dep-v0";
const matches = sections.filter((section) => section.name === expected);
if (matches.length > 1)
const selected = uniqueKeyed(
keyedBy(sections, ({ name }) => name),
expected,
);
if (!selected.ok)
throw malformedInput(
RUST_AUDITABLE_FORMAT,
"Image contains more than one dependency section",
);
const section = matches[0];
const section = selected.value;
if (section === undefined) return null;
if (section.compressed)
throw unsupportedInput(
+13 -7
View File
@@ -1,7 +1,9 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { writeWebResponse } from "./nodeHttpBridge.js";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
const HTTP_RESPONSE_SOURCE = "MCP HTTP response source";
export type HttpAdmissionLifetime = "dispatch" | "response";
@@ -162,17 +164,21 @@ export class NodeHttpRequestOwner {
while (this.#bodyCleanups.size > 0)
await Promise.allSettled(this.#bodyCleanups);
if (this.#cleanupFailures.length > 0)
throw new AnalysisResourceConstraintError(
"mcp_http_response_cleanup",
"transport",
"HTTP response cleanup could not be confirmed; provider shutdown remains blocked",
{ failed_cleanup_count: this.#cleanupFailures.length },
// Unconfirmed cleanup is retained work, not a budget the caller can raise.
throw new ProviderCleanupError(
"rea",
[HTTP_RESPONSE_SOURCE],
{
reason:
"HTTP response cleanup could not be confirmed; provider shutdown remains blocked",
failed_cleanup_count: this.#cleanupFailures.length,
},
{
operation: "mcp_http_response_cleanup",
cause: new AggregateError(
this.#cleanupFailures,
"Response cleanup failed",
),
retryable: false,
},
);
}
+6 -5
View File
@@ -26,6 +26,7 @@ import { mcpAllowedHostsTextSchema } from "../../config/mcpHttpEndpoint.js";
import { parseMcpHttpArguments } from "../../main/mcpHttpArguments.js";
import { RequestTrackingMcpServer } from "../RequestTrackingMcpServer.js";
import { waitFor } from "../../../tests/support/testWait.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
const servers: StreamableHttpServer[] = [];
@@ -1408,13 +1409,13 @@ it("retains failed response cleanup and blocks provider teardown and further adm
expect((await fetch(new URL("/health", served.url))).status).toBe(503);
});
await expect(served.prepareShutdown()).rejects.toMatchObject({
_tag: "AnalysisResourceConstraintError",
reportedLimits: { failed_cleanup_count: 1 },
_tag: "ProviderAdapterError",
cleanupIncomplete: true,
cleanupResources: ["MCP HTTP response source"],
diagnostics: { failed_cleanup_count: 1 },
cause: expect.any(AggregateError),
});
await expect(served.close()).rejects.toMatchObject({
reportedLimits: { failed_cleanup_count: 1 },
});
await expect(served.close()).rejects.toBeInstanceOf(ProviderCleanupError);
expect(shutdownHooks()).toBe(0);
await expect(rawHttpRequest(new URL(served.url))).rejects.toMatchObject({
code: "ECONNREFUSED",
+12 -19
View File
@@ -1,4 +1,5 @@
import { WabtAdmissionError } from "./WabtAdmissionError.js";
import { readLeb128, ULEB32 } from "../domain/leb128.js";
/** WABT prints names with %.*s, so an embedded NUL ends their display. */
const wabtDisplayedName = (name: string | undefined): string | undefined =>
@@ -99,24 +100,16 @@ const invalidCustomNameEnd = (
): number | undefined => {
if (bytes === undefined || end > bytes.length || start >= end)
return undefined;
let length = 0;
let position = start;
for (let shift = 0; shift <= 28; shift += 7) {
const byte = bytes[position++];
if (byte === undefined || position > end || (shift === 28 && byte > 15))
return undefined;
length += (byte & 0x7f) * 2 ** shift;
if ((byte & 0x80) !== 0) continue;
const nameEnd = position + length;
if (nameEnd > end) return undefined;
try {
new TextDecoder("utf-8", { fatal: true }).decode(
bytes.subarray(position, nameEnd),
);
return undefined;
} catch {
return nameEnd;
}
const read = readLeb128(bytes, start, end, ULEB32);
if ("failure" in read) return undefined;
const nameEnd = read.next + Number(read.value);
if (nameEnd > end) return undefined;
try {
new TextDecoder("utf-8", { fatal: true }).decode(
bytes.subarray(read.next, nameEnd),
);
return undefined;
} catch {
return nameEnd;
}
return undefined;
};
@@ -411,6 +411,41 @@ describe("CdpBrowserProvider: malformed approved payloads", () => {
expect.arrayContaining(["json_body_shapes", "websocket_frames"]),
);
});
it("records a malformed response body reply as a body-shape gap", async () => {
const browser = await startFakeCdpBrowser({
commandResult: (command) =>
command.method === "Network.getResponseBody"
? { body: 7, base64Encoded: false }
: undefined,
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
// Long enough for the post-window body fetch, as in the case above.
observation_ms: 200,
include_json_body_shapes: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
status: "partial",
response: null,
});
expect(result.value.completeness.excluded).toContainEqual(
expect.objectContaining({
section: "json_body_shapes",
reason: "invalid_protocol_value",
}),
);
expect(result.value.limitations).toContain(
"Network.getResponseBody returned a malformed result; the section that reads it is incomplete.",
);
});
});
const expectSensitiveValuesAbsent = (
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more