Files
reverse-engineering-anything/src/flutter/FlutterBuildProvider.ts
T
0f6b330cb6 refactor(ghidra): classify Ghidra file failures through the shared provider classifier (#10873)
* fix(pcap): report a refused tool launch as an unavailable tool

When a capture read's tool launch was refused with EPERM, pcap reported it
as unreadable tool output (AnalysisProtocolError) instead of an unavailable
tool. Pcap also never told "not executable" apart from "missing".

Add classifyLaunchFailure in src/process as the one owner of which spawn
errnos mean missing (ENOENT, ENOTDIR) and which mean present but not
executable (EACCES, EPERM, ENOEXEC, EISDIR). Pcap, apktool and gdb used three
different errno lists; all three now use it.

* refactor(process): classify owned command outcomes through one owner

Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions.

* refactor(process): classify Java and adb launch refusals with the shared owner (#10598)

The Ghidra and JADX Java probes and adb's version probe now take
missing-versus-not-executable from classifyLaunchFailure instead of their
own errno checks. ELOOP and ENAMETOOLONG join the owner's missing set, so
adb keeps its existing classification and both Java probes now treat a
non-directory path component as a missing runtime.

* fix(pcap): preserve command launch attribution

* test(pcap): expect an unknown failing stage when a limited capture tool exits unsuccessfully

* refactor(process): classify owned command outcomes through one owner

Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions.

* test(lint): cover baselined files in the provider-failure classifier rule

* fix(apktool): report the decoder JVM's heap exhaustion as memory, not a target refusal

The supervisor now watches for a managed runtime's out-of-memory report while output streams (JVM java.lang.OutOfMemoryError, V8 'JavaScript heap out of memory'), so a retention budget cannot hide it. ProviderOutcome gains a runtime-exhausted kind and classifyProviderOutcome maps it once. Apktool decode opts in and moves to the shared classifier; Ghidra's single-purpose output token becomes the JVM runtime option and its area matching reuses the shared table.

* fix(process): keep the runtime's out-of-memory report on the memory error it supports

* fix(pcap): attribute a limited capture's exit through the prlimit wrapper

* fix(process): keep a shortened out-of-memory line marked as shortened

* fix(process): identify the refused executable for every launcher shape

Name the executable on errnos Node throws synchronously from spawn
(ENOEXEC, ENOTDIR, ...) and read the Windows native launcher's
executable-launch constraint, so pcap attributes those refusals to the
selected tool or limiter instead of an unknown stage.

* test(pcap): prove synchronous launch naming with ENOTDIR on every POSIX host

* fix(apktool): advise the JVM limit that governs the reported memory area

* fix(ghidra): read the supervisor's parsed OOM area instead of reparsing lines

* fix(sqlite,capture): read V8 heap exhaustion from streamed output, not retained stderr (#10724)

The SQLite worker and the Node capture decoders now declare runtime: "v8", so the supervisor observes V8's heap report as output streams. Both classifiers read the runtime-exhausted outcome instead of matching retained stderr, so a report beyond the retention budget, or one whose process then overflowed its output budget, is still reported as memory exhaustion.

* refactor(evm): classify EVMole worker outcomes through the shared provider classifier (#10716)

* refactor(evm): classify EVMole worker outcomes through the shared provider classifier

The EVMole worker's cancellation, deadline, output budget and CPU/file-size signals now go through classifyProviderOutcome; only the prlimit launch refusal and the reserved EFBIG exit remain in its dialect. The worker is opted into V8 exhaustion scanning so a heap report names its fixed 256 MiB heap. providerOutcomeOf now reads a launch refusal only from a spawn errno, so a private-storage or carrier read errno is no longer reported as a limiter launch failure.

* fix(evm): keep a stream failure's exit status and update Linux worker expectations

* refactor(process): read launch refusals through the launcher identity owner

* refactor(wasm): classify WABT command outcomes through the shared provider classifier (#10727)

* refactor(wasm): classify WABT command outcomes through the shared provider classifier

WABT's cancellation, command deadline, output budget, and inherited-limit signals now go through classifyProviderOutcome; its dialect keeps only the configuration-probe and launch-refusal unavailability and the unclassified-exit output error. A tool ended by SIGXCPU/SIGXFSZ or the memory limit is now a resource constraint instead of an output error, and a refused launch in the producer phase is reported as unavailable. The shared timeout context gains the analysis setting that selected the deadline, and the output-limit context may name its exceeded budget.

* fix(wasm): keep setup guidance when a WABT version probe's output cannot be collected

* refactor(providers): classify raw provider failures through one owner

* refactor(process): build classified cancellations with cancelledBy and the carried caller reason

* chore(lint): count runOwned's close-failure mapper from main in the classifier baseline

* fix(process): carry the runtime's exhaustion report on every memory error that claims it

SQLite and historical-capture memory errors recognised a streamed V8 heap report but dropped it, so a report outside retained output reached callers without its source line or omission flags. One projection, runtimeExhaustionReport, now owns that shape for the shared classifier and both consumers. Also lowers the EVMole and WABT cancellation-constructor baselines.

* fix(process): keep the provider's recovery for a native-thread exhaustion report

The shared classifier replaced the provider-supplied recovery with generic capacity advice whenever the JVM reported it could not create a native thread, dropping Apktool's launcher guidance and flipping retryable to true. The provider's recovery now wins; the capacity advice remains the fallback for providers that supply none.

* refactor(pwntools): classify pwntools failures through the shared provider classifier (#10782)

* refactor(pwntools): classify pwntools failures through the shared provider classifier

pwntools' per-site classifier is replaced by pwntoolsFailureDialect for classifyProviderFailure. Command outcomes go through classifyProviderOutcome, launch refusals through launcherRefusalOf instead of a 'spawn ' syscall prefix check, the input limit through the file dialect's fileSize, and the cleanup report through commandCleanup. The shared read cancellation now carries the reader's partial observation, and resource-signal reports accept provider detail.

* fix(pwntools): report a failed command's output once and expect resource_constraint for overflow

The shared outcome owner already attaches the command's output as capturedOutput, so the pwntools adapter fallback no longer copies the same text into diagnostics.stdout, diagnostics.stderr and diagnostics.captured_output; diagnostics keep the exit facts. Update the overflow expectations the dialect migration missed (layout provider cleanup and over-budget rows, pwntools cleanup) to resource_constraint.

* refactor(wasm): leave WABT cancellation to the shared owners

WabtFailures matched any Error named AbortError as a cancellation. No WABT path produces one: reads, path checks and owned commands report cancellation as ArtifactReaderFailure or OwnedCommandFailure, which classifyProviderFailure and classifyProviderOutcome already classify with the caller's reason. The provider's two signal checks now build the cancellation with cancelledBy. Lowers the AnalysisCancelledError constructor baseline for both WABT files to zero.

* fix(wasm): report a cancelled snapshot write as the caller's cancellation

The private snapshot write passed the caller's signal to Node's writeFile, whose abort envelope reached the dialect's unclassified output failure once the name-based AbortError guess was removed. The write now turns the envelope carrying its own signal's reason into cancelledBy at the producer.

* refactor(firmware): classify firmware failures through the shared provider classifier (#10810)

Firmware producers now report their own deadline expiry: the start check, the output inventory and launcher admission throw the phase timeout where they observe the abort, and a read the phase signal cancelled reports it through the dialect's interruption. The classifier no longer rereads a cancellation's reason as a timeout. A new readCleanup hook keeps firmware's cleanup report shape.

* refactor(captures): classify TShark, sigrok and pcap failures through the shared provider classifier

TsharkCaptureProvider and SigrokRecordingProvider replace #failure with a dialect, and PcapProvider replaces analysisFailure and the tool-identity classifier. ArtifactAnalysisResources exposes its command context and a readCleanupFailure composer so the readCleanup hook keeps each provider's cleanup report shape.

* refactor(jeb): classify JEB failures through the shared provider classifier

JEB's raw MCP failures go through classifyProviderFailure with a JEB dialect;
a typed attribution step reports a shared phase's failure under the REA
operation. Each MCP phase deadline now reports its own interruption when it
aborts, deciding a cancellation's owner from the caller's own signal instead
of comparing abort reasons. A refusal carrying the JVM's OutOfMemoryError
report becomes a resource constraint naming JEB's Java heap.

* fix(jeb): advise the JVM limit that governs the reported memory area

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* refactor(adb): report a pulled file's digest failure from its own type

* refactor(sqlite): classify worker-reply read failures through the shared provider classifier

* refactor(ida): classify IDA operation failures through the shared provider classifier

* refactor(process): let artifact-resource consumers classify through the shared provider classifier (#10867)

* test(providers): pin attribution of a cleanup-failed read's typed primary

* refactor(sqlite): classify database failures through the shared provider classifier

* refactor(providers): keep a cancelled read's partial observation and provider diagnostics

* refactor(ghidra): classify Ghidra file failures through the shared provider classifier

* refactor(ghidra): classify Ghidra failures through the shared provider classifier (#10836)

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier (#10843)

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* chore(guards): shrink the cancellation construction baseline after merging the base

* refactor(kuna): report a retained installation read's cleanup from its reader type (#10877)

* refactor(kuna): report a retained installation read's cleanup from its reader type

* refactor(process): share the JVM option that governs each reported memory area (#10881)

* refactor(ida): classify IDA operation failures through the shared provider classifier (#10859)

* refactor(ida): classify IDA operation failures through the shared provider classifier

* refactor(process): let artifact-resource consumers classify through the shared provider classifier (#10867)

* test(providers): pin attribution of a cleanup-failed read's typed primary

* fix(javascript): read analysis workers' V8 heap exhaustion from streamed output, not retained stderr (#10890)

* refactor(kuna): report a retained installation read's cleanup from its reader type

* refactor(process): share the JVM option that governs each reported memory area (#10881)

* fix(javascript): read analysis workers' V8 heap exhaustion from streamed output, not retained stderr

* test(browser): pin web-bundle heap exhaustion reported past the retained stderr budget

* refactor(process): recognise a signal's own abort through one owner (#10896)

* refactor(process): recognise a signal's own abort through one owner

* chore(verify): lower the direct cancellation construction baselines the stack's migrations removed

* refactor(sqlite): read the owned worker's heap ceiling from one limit (#10907)

* refactor(sqlite): classify the owned worker's outcomes through the shared provider classifier (#10912)

* refactor(process): call the signal abort owner directly and match NaN reasons

* chore(verify): lower the SQLite cancellation construction baseline the worker migration removed

* feat(rizin): report a shell refusal as a typed refusal record beside rejected completion (#10925)

* refactor(kuna): report installation inspection failures through one Kuna dialect (#10913)

* refactor(errors): let Hopper errors carry their own presentation so the domain presenter no longer imports them (#10944)

* refactor(process): recognise the remaining command aborts through the signal owner (#10906)

* refactor(process): recognise the remaining command aborts through the signal owner

* test(process): cover a NaN abort reason on both execFileOutput cancellation paths

* fix(process): keep a successful execFile callback when the caller aborts with a null reason

* test(process): abort execFileOutput while a released descendant still holds its pipes

* test(process): join the late-abort command in finally so a failed readiness check still releases its descendant

* refactor(errors): move Hopper errors to src/hopper and drop their tags from the domain union (#10964)

* refactor(errors): move Hopper errors to src/hopper and drop their tags from the domain union

* refactor(process): recognise SQLite, WABT and Flutter aborts through the signal owner (#10975)

* refactor(kuna): report doctor installation failures through the shared Kuna installation dialect (#10978)

* refactor(process): recognise SQLite, WABT and Flutter aborts through the signal owner

* refactor(kuna): report doctor installation failures through the shared Kuna installation dialect

* fix(kuna): keep installation facts on a composed read-and-close failure

* style(hopper): format the moved Hopper lease and cache publisher fixture

* fix(sqlite): count only the caller's own abort as a SQLite inspection cancellation (#11018)

* fix(ida): count only the caller's own abort of the busy-health pause as cancellation (#11013)

* test(kuna): assert the cleanup-incomplete doctor check by code and facts, not its wording

* refactor(errors): report an unrecognised command outcome with the outcome the classifier examined (#11003)

* refactor(errors): report an unrecognised command outcome with the outcome the classifier examined

* fix(errors): add a dialect's unclassified diagnostics to the context's instead of replacing them

* fix(evm): count only the caller's own abort as an EVMole inspection cancellation (#11011)

* fix(server): report only startup's own abort as the caller's HTTP listen cancellation (#11017)

* refactor(errors): classify domain errors from one table and generate the error catalogue from it (#11060)

docs(errors): generate the error catalogue from the classification tables

* refactor(errors): report unrecognised pcap, WABT and producer-command outcomes with the examined outcome (#11044)

* refactor(errors): report unrecognised pcap, WABT and producer-command outcomes with the examined outcome

* fix(pcap): keep the packet summary when only the DNS wire pass reports an unrecognised outcome

* refactor(ida): require the host platform for IDA MCP connections and snapshot the child environment with it (#11073)

* refactor(verify): count plain throws in parser-folder process-lifecycle owners (#11071)

JadxWorkspaceRoot and PwntoolsDecoder are exempt from parser-plain-throw because their plain throws report a private helper's process failures. The exemption left later throws in those files unchecked. A counted lifecycle-plain-throw guard now records their current throws (4 and 1); the baseline may only shrink, so a parse fault or defect added there must use ParseFailureError or invariantViolation.

* fix(native): report a signature inspection defect as an adapter failure (#11069)

withSignatureTarget wrapped every throw from the inspection callback as
AnalysisOutputError("Native output parsing failed"), so an
InternalInvariantError (a REA defect) was reported as malformed native
command output. A defect now leaves the owned work, so runOwned releases
the private signature copy first and reports the defect as the native
provider's adapter failure. If releasing the copy also fails, the defect
stays primary and the cleanup failure joins it through the shared cleanup
composition (analysisErrorWithCleanupFailure + bindCleanupDependencies).

* refactor(verify): give the javascript verifiers' roots to VerifierFixture (#11068)

* refactor(verify): give the javascript verifiers' roots to VerifierFixture

VerifierFixture.retain(reason) keeps a root that an owned command whose
cleanup is incomplete may still use, replacing each verifier's local
retain flag and cleanup closure.

* refactor(verify): give the Ghidra COM, DOS, 6502, NativeAOT and raw verifiers' workspaces to VerifierFixture (#11070)

* refactor(verify): give the Ghidra COM, DOS, 6502, NativeAOT and raw verifiers' workspaces to VerifierFixture

* refactor(verify): keep the Ghidra decompiler-failure, decompile-timeout and no-return workspaces through VerifierFixture until owned cleanup is verified (#11077)

* feat(artifacts): surface the named integrity check in public artifact errors (#11052)

* feat(artifacts): surface the named integrity check in public artifact errors

ArtifactOperationError now carries integrityCheck from the reader failure
and projects it as details.integrity_check, including with artifact
integrity details. Rebuild sites copied a different subset of reader facts
each (ProcessCli.artifactFailureFacts, withCleanup, desktop, file-operation
cleanup, resource export, DMG inventory, safe output tree); they now spread
ArtifactReaderFailure.primaryFacts(), so a new reader fact has one owner.
ArtifactIntegrityCheck moves to the domain beside ArtifactAdmissionLimit.

* test(artifacts): check rebuilt cleanup failures keep the named integrity check

* refactor(adb): report a pulled file's digest failure from its own type (#10848)

* fix(pcap): report a refused tool launch as an unavailable tool

When a capture read's tool launch was refused with EPERM, pcap reported it
as unreadable tool output (AnalysisProtocolError) instead of an unavailable
tool. Pcap also never told "not executable" apart from "missing".

Add classifyLaunchFailure in src/process as the one owner of which spawn
errnos mean missing (ENOENT, ENOTDIR) and which mean present but not
executable (EACCES, EPERM, ENOEXEC, EISDIR). Pcap, apktool and gdb used three
different errno lists; all three now use it.

* refactor(process): classify owned command outcomes through one owner

Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions.

* refactor(process): classify Java and adb launch refusals with the shared owner (#10598)

The Ghidra and JADX Java probes and adb's version probe now take
missing-versus-not-executable from classifyLaunchFailure instead of their
own errno checks. ELOOP and ENAMETOOLONG join the owner's missing set, so
adb keeps its existing classification and both Java probes now treat a
non-directory path component as a missing runtime.

* fix(pcap): preserve command launch attribution

* test(pcap): expect an unknown failing stage when a limited capture tool exits unsuccessfully

* refactor(process): classify owned command outcomes through one owner

Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions.

* test(lint): cover baselined files in the provider-failure classifier rule

* fix(apktool): report the decoder JVM's heap exhaustion as memory, not a target refusal

The supervisor now watches for a managed runtime's out-of-memory report while output streams (JVM java.lang.OutOfMemoryError, V8 'JavaScript heap out of memory'), so a retention budget cannot hide it. ProviderOutcome gains a runtime-exhausted kind and classifyProviderOutcome maps it once. Apktool decode opts in and moves to the shared classifier; Ghidra's single-purpose output token becomes the JVM runtime option and its area matching reuses the shared table.

* fix(process): keep the runtime's out-of-memory report on the memory error it supports

* fix(pcap): attribute a limited capture's exit through the prlimit wrapper

* fix(process): keep a shortened out-of-memory line marked as shortened

* fix(process): identify the refused executable for every launcher shape

Name the executable on errnos Node throws synchronously from spawn
(ENOEXEC, ENOTDIR, ...) and read the Windows native launcher's
executable-launch constraint, so pcap attributes those refusals to the
selected tool or limiter instead of an unknown stage.

* test(pcap): prove synchronous launch naming with ENOTDIR on every POSIX host

* fix(apktool): advise the JVM limit that governs the reported memory area

* fix(ghidra): read the supervisor's parsed OOM area instead of reparsing lines

* fix(sqlite,capture): read V8 heap exhaustion from streamed output, not retained stderr (#10724)

The SQLite worker and the Node capture decoders now declare runtime: "v8", so the supervisor observes V8's heap report as output streams. Both classifiers read the runtime-exhausted outcome instead of matching retained stderr, so a report beyond the retention budget, or one whose process then overflowed its output budget, is still reported as memory exhaustion.

* refactor(evm): classify EVMole worker outcomes through the shared provider classifier (#10716)

* refactor(evm): classify EVMole worker outcomes through the shared provider classifier

The EVMole worker's cancellation, deadline, output budget and CPU/file-size signals now go through classifyProviderOutcome; only the prlimit launch refusal and the reserved EFBIG exit remain in its dialect. The worker is opted into V8 exhaustion scanning so a heap report names its fixed 256 MiB heap. providerOutcomeOf now reads a launch refusal only from a spawn errno, so a private-storage or carrier read errno is no longer reported as a limiter launch failure.

* fix(evm): keep a stream failure's exit status and update Linux worker expectations

* refactor(process): read launch refusals through the launcher identity owner

* refactor(wasm): classify WABT command outcomes through the shared provider classifier (#10727)

* refactor(wasm): classify WABT command outcomes through the shared provider classifier

WABT's cancellation, command deadline, output budget, and inherited-limit signals now go through classifyProviderOutcome; its dialect keeps only the configuration-probe and launch-refusal unavailability and the unclassified-exit output error. A tool ended by SIGXCPU/SIGXFSZ or the memory limit is now a resource constraint instead of an output error, and a refused launch in the producer phase is reported as unavailable. The shared timeout context gains the analysis setting that selected the deadline, and the output-limit context may name its exceeded budget.

* fix(wasm): keep setup guidance when a WABT version probe's output cannot be collected

* refactor(providers): classify raw provider failures through one owner

* refactor(process): build classified cancellations with cancelledBy and the carried caller reason

* chore(lint): count runOwned's close-failure mapper from main in the classifier baseline

* fix(process): carry the runtime's exhaustion report on every memory error that claims it

SQLite and historical-capture memory errors recognised a streamed V8 heap report but dropped it, so a report outside retained output reached callers without its source line or omission flags. One projection, runtimeExhaustionReport, now owns that shape for the shared classifier and both consumers. Also lowers the EVMole and WABT cancellation-constructor baselines.

* fix(process): keep the provider's recovery for a native-thread exhaustion report

The shared classifier replaced the provider-supplied recovery with generic capacity advice whenever the JVM reported it could not create a native thread, dropping Apktool's launcher guidance and flipping retryable to true. The provider's recovery now wins; the capacity advice remains the fallback for providers that supply none.

* refactor(pwntools): classify pwntools failures through the shared provider classifier (#10782)

* refactor(pwntools): classify pwntools failures through the shared provider classifier

pwntools' per-site classifier is replaced by pwntoolsFailureDialect for classifyProviderFailure. Command outcomes go through classifyProviderOutcome, launch refusals through launcherRefusalOf instead of a 'spawn ' syscall prefix check, the input limit through the file dialect's fileSize, and the cleanup report through commandCleanup. The shared read cancellation now carries the reader's partial observation, and resource-signal reports accept provider detail.

* fix(pwntools): report a failed command's output once and expect resource_constraint for overflow

The shared outcome owner already attaches the command's output as capturedOutput, so the pwntools adapter fallback no longer copies the same text into diagnostics.stdout, diagnostics.stderr and diagnostics.captured_output; diagnostics keep the exit facts. Update the overflow expectations the dialect migration missed (layout provider cleanup and over-budget rows, pwntools cleanup) to resource_constraint.

* refactor(wasm): leave WABT cancellation to the shared owners

WabtFailures matched any Error named AbortError as a cancellation. No WABT path produces one: reads, path checks and owned commands report cancellation as ArtifactReaderFailure or OwnedCommandFailure, which classifyProviderFailure and classifyProviderOutcome already classify with the caller's reason. The provider's two signal checks now build the cancellation with cancelledBy. Lowers the AnalysisCancelledError constructor baseline for both WABT files to zero.

* fix(wasm): report a cancelled snapshot write as the caller's cancellation

The private snapshot write passed the caller's signal to Node's writeFile, whose abort envelope reached the dialect's unclassified output failure once the name-based AbortError guess was removed. The write now turns the envelope carrying its own signal's reason into cancelledBy at the producer.

* refactor(firmware): classify firmware failures through the shared provider classifier (#10810)

Firmware producers now report their own deadline expiry: the start check, the output inventory and launcher admission throw the phase timeout where they observe the abort, and a read the phase signal cancelled reports it through the dialect's interruption. The classifier no longer rereads a cancellation's reason as a timeout. A new readCleanup hook keeps firmware's cleanup report shape.

* refactor(captures): classify TShark, sigrok and pcap failures through the shared provider classifier

TsharkCaptureProvider and SigrokRecordingProvider replace #failure with a dialect, and PcapProvider replaces analysisFailure and the tool-identity classifier. ArtifactAnalysisResources exposes its command context and a readCleanupFailure composer so the readCleanup hook keeps each provider's cleanup report shape.

* refactor(jeb): classify JEB failures through the shared provider classifier

JEB's raw MCP failures go through classifyProviderFailure with a JEB dialect;
a typed attribution step reports a shared phase's failure under the REA
operation. Each MCP phase deadline now reports its own interruption when it
aborts, deciding a cancellation's owner from the caller's own signal instead
of comparing abort reasons. A refusal carrying the JVM's OutOfMemoryError
report becomes a resource constraint naming JEB's Java heap.

* fix(jeb): advise the JVM limit that governs the reported memory area

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* refactor(adb): report a pulled file's digest failure from its own type

* refactor(ghidra): classify Ghidra failures through the shared provider classifier (#10836)

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier (#10843)

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* chore(guards): shrink the cancellation construction baseline after merging the base

* refactor(ida): let IDA close failures read the session's later close (#10811)

* refactor(errors): read cleanup completion from dependencies instead of pushing it to dependents

AnalysisError.cleanupIncomplete becomes a getter over the error's own unresolved state and its bound dependencies. The WeakRef dependents graph and resolveCleanup's push propagation are removed, and subclasses mark their initial state through markCleanupIncomplete instead of overriding a public mutable field.

* fix(errors): settle bound dependencies before binding more

A composite whose dependencies had released but whose status was never read
stayed incomplete when a later dependency was bound.

* refactor(errors): let errors read a lease group's release instead of resolving them (#10759)

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink (#10763)

* refactor(errors): let errors read a lease group's release instead of resolving them

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink

* refactor(process): let worker cleanup errors read their root epoch's release

OwnedWorkerRuntime's root epoch is now an AnalysisCleanupReleaseClaim. Errors bound to it read its release when asked instead of the epoch pushing resolveCleanup() through weak references, and a runtime without a retained root binds an already-released owner. Removes the OwnedWorkerCleanupFailure structural type and four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(pcap): let pcap cleanup errors read command and snapshot release (#10792)

Retained pcap commands, retained snapshot failures and snapshot completion descriptors now own their release and errors read it: commands and snapshot failures implement AnalysisCleanupReleaseClaim, and a failed completion-descriptor close is retried through an AnalysisCleanupLease bound to its error. Removes four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(process): let Darwin helper cleanup errors read their owner's release

Darwin helper cache and run-token reader root cleanup now record an AnalysisCleanupRelease that every failure reports; a successful retry confirms it. Replaces the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes two resolveCleanup() and two bindCleanupDependencies() calls; both counted baselines shrink.

* refactor(ghidra): let Ghidra cleanup errors read the client's and checkpoint's release

GhidraClient and GhidraCheckpoint bind each cleanup failure to an AnalysisCleanupRelease and confirm it when a later close or retry releases everything, instead of keeping a set of failures and pushing resolveCleanup() to each. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(process): let debugger session cleanup errors read a confirmed stop

OwnedDebuggerSessionRegistry binds each retained gdb or rizin cleanup failure to the session's AnalysisCleanupRelease and confirms it when a stop is confirmed, keeping the latest failure for retry reporting, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): drop the debugger registry's unused closeOperation option

Returning the latest retained failure removed the last reader of closeOperation; remove the option and the values gdb and rizin supplied.

* refactor(server): let environment shutdown errors read a successful close

serveEnvironment binds each shutdown failure to an AnalysisCleanupRelease that a later successful close confirms, instead of pushing resolveCleanup() to a set of failures. The state-file retry test now also requires the earlier report to read the release. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): release retained screen-judge cleanup through its lease

Each retained judge or screenshot cleanup owner is wrapped in an AnalysisCleanupLease bound to its failure; close() releases the lease, which records the release the failure reads, instead of closing the owner and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(ida): let IDA close failures read the session's later close

IdaSessionClient's close failure binds an owner that is both its resource owner and its release claim, read from the client's closed state, instead of keeping weak references and pushing resolveCleanup() after a successful retry. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(javascript): let source-map codec cleanup errors read a later close (#10814)

* refactor(javascript): let source-map codec cleanup errors read a later close

OwnedCodec binds each close failure to an AnalysisCleanupRelease that a later successful close confirms, replacing the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes one resolveCleanup() and one bindCleanupDependencies() call; both counted baselines shrink.

* refactor(cutter): let pending Cutter command errors read the completion receipt (#10815)

* refactor(cutter): let pending Cutter command errors read the completion receipt

Each pending Cutter command keeps an AnalysisCleanupRelease bound to its timeout failure; the producer's terminal completion receipt confirms it instead of pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(application): let provider candidate cleanup errors read the candidate's close (#10817)

* refactor(application): let provider candidate cleanup errors read the candidate's close

AnalysisProviderRegistry keeps one AnalysisCleanupRelease per candidate whose resource close is unconfirmed; failures bind to it and a later confirmed close confirms it, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* fix(errors): bind a cleanup release claim to an error at most once

AnalysisError kept release claims in an array, so a provider whose retried close returned the same error bound the same claim again on every retry and each cleanupIncomplete read scanned the duplicates. Keep the claims in a set.

* refactor(application): let reverse-tool cleanup errors read a verified stop (#10819)

* refactor(application): let reverse-tool cleanup errors read a verified stop

Each retained provider process group in ReverseEngineeringService keeps an AnalysisCleanupRelease; its command and retry failures bind to it and a later verified stop confirms it, instead of collecting failures and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(sqlite): let SQLite worker and root cleanup errors read their release (#10821)

Each retained SQLite snapshot cleanup records an AnalysisCleanupRelease for its worker and for its runtime root; the resource failures bind to them and a verified stop or root removal confirms them, instead of pushing resolveCleanup(). Composite failures keep reading those resource failures. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let JADX and session close failures read their owner's release (#10854)

* refactor(android): let JADX cleanup errors read their retained cleanup's release

Each retained JADX cleanup records an AnalysisCleanupRelease for the admission failure's descriptor owners and one for the whole retained cleanup. The admission failure and every error the cleanup reports bind to them, and a confirmed close confirms them, instead of pushing resolveCleanup() through WeakRefs to reported errors. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let session close failures read the client's later close

A retained session cleanup records an AnalysisCleanupRelease; unowned cleanup failures the client's close reported bind to it and the successful close confirms it, instead of the session collecting them and pushing resolveCleanup(). Failures that already follow their own owner keep reading it. Adds a regression for an unowned close failure. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(browser): parse Runtime and Debugger events once by registered schemas (#10742)

* refactor(browser): parse frame lifecycle events once by a registered event schema

CdpConnection admits each event through protocol/CdpEvents.ts, which parses
the five Page frame lifecycle events once into identity facts plus a frame
URL observation, like a frame-tree node. Screenshot, page capture, the
observation timeline, WebMCP, Electron inspection and the execution window
read those facts instead of re-parsing the raw payload; CdpFrameFacts no
longer carries the raw source record. Playwright CDP session subscriptions
name an event from Playwright's protocol table, and an architecture guard
counts the remaining raw event payload reads so they can only shrink.

* refactor(browser): parse Runtime and Debugger events once by registered schemas

Register Debugger.scriptParsed, Debugger.scriptFailedToParse,
Runtime.executionContextCreated, Runtime.executionContextDestroyed and
Runtime.consoleAPICalled. Script and context payloads carry both the
tolerant facts passive capture uses and the active runtime's strict
declaration, derived from one parse, plus the declaration's byte size for
the runtime retention budget. Page capture, Electron script capture, the
V8 Inspector provider and the runtime source inventory now read the
registered payload. The cdp-raw-event-params baseline drops from 20 to 7.

* refactor(browser): admit transport events through the registered-event owner

Remove the unused cdpFrameUrl wrapper; its fragment cases now exercise
observeCdpFrameUrl. Add a connection-level test that two subscribers share
one parsed payload and the raw params.

* fix(browser): report an unserializable event declaration's size instead of throwing

JSON.stringify can throw on a declaration JSON.parse accepted (nesting
deeper than the serializer's stack). The registry sized script and context
declarations inside the connection's WebSocket callback, so such an event
escaped as an uncaught exception. The size is now a Result; the runtime
source inventory raises the failure inside its own catch, as before.

* refactor(browser): parse Network events once by registered schemas (#10743)

* refactor(browser): parse Network events once by registered schemas

Register Network.requestWillBeSent, responseReceived, loadingFinished,
loadingFailed, webSocketCreated and webSocketFrameSent/Received. The
request payload carries the tolerant facts page capture and the timeline
read plus the active runtime's strict declaration. Page capture's network
and WebSocket handlers, the timeline's request tracking and the runtime
request inventory now read the registered payload. The
cdp-raw-event-params baseline drops from 7 to 5.

* refactor(browser): drop payload helpers the capture handlers no longer use

* refactor(browser): read every CDP event payload through the registry (#10745)

* refactor(browser): read every CDP event payload through the registry

Register Target.attachedToTarget, Target.detachedFromTarget,
Page.lifecycleEvent and WebMCP.toolsAdded/toolsRemoved, and carry a
requested navigation's reason and a commit's transition type in the
frame-event payload. The timeline no longer threads raw params into its
entries: each entry receives its timestamp, frame and loader identity
explicitly. WebMCP discovery, the service-worker policy blocker and the
target-event matcher read the registered payload. With no raw reads left,
the cdp-raw-event-params guard is enforced at zero instead of counted.

* refactor(browser): drop raw payload helpers the timeline and worker blocker no longer use

* refactor(browser): type Playwright CDP session events by the registry (#10751)

PlaywrightCdpSession.on subscribes only to registered events and hands
the listener the payload parsed by its registered schema, returning the
unsubscribe function. Private storage seeding reads registered payloads,
including the events of non-flat child sessions, and applies its strict
seeding policy to the parsed facts. Its local attach, detach, nested
message and pause schemas and the storage-only script/context schemas are
removed; Debugger.paused, Runtime.executionContextsCleared and
Target.receivedMessageFromTarget join the registry.

* test(browser): admit fake policy events through the event registry

The service-worker policy now reads event.registered, but the PlaywrightScenarioSession fake connection delivered raw events, so three detached-target tests never reached the policy. The fake now admits each event with receiveCdpEvent as CdpConnection does.

* fix(browser): fail the CDP session closed when an event listener throws (#10758)

* fix(browser): fail the CDP session closed when an event listener throws

An exception from a CDP event subscriber escaped CdpTransportCore's socket message callback uncaught (for example the service-worker blocker's protocol_error on a Target event without a sessionId). The transport now stops delivery, fails the connection as a protocol error whose cause is the listener's exception, rejects pending and later commands with it, and notifies protocol-failure subscribers. The Playwright CDP session relay applies the same rule to its event listeners.

* fix(browser): report a failed service-worker policy connection at the next policy check

The policy's event listener rejects a malformed Target event, which now fails its connection. With no policy command pending, nothing reported it and later iframe targets went unprotected. The policy records its connection's protocol failure and assertBlocked, run before each scenario step, rethrows it.

* fix(browser): keep cleanup commands available after a listener failure

A listener failure no longer marks the wire as broken. The transport still rejects pending commands, notifies protocol-failure subscribers, stops delivering events and refuses reuse, but it keeps reading replies and admits commands sent in cleanup grace. The service-worker policy can then remove its init scripts, restore the main realm, detach and release its socket. Wire-level protocol errors still refuse every later command. The PlaywrightScenarioSession policy fake gains onProtocolFailure, which the policy now subscribes to.

* refactor(browser): keep raw CDP event payloads out of the received event (#10764)

* refactor(browser): keep raw CDP event payloads out of the received event

CdpReceivedEvent and CdpTransportEvent no longer carry params: receiveCdpEvent hands the raw payload only to the registered schema, so a subscriber cannot read it by property access, destructuring or computed keys. This supersedes the event.params text guard in architecture-guards, which is removed.

* refactor(browser): read registered event payloads in the JavaScript verifiers

The runtime, storage and URL-userinfo verifiers subscribe to CdpConnection, which no longer hands subscribers raw params. They now read event.registered. A test scans every scripts/ onEvent callback for raw payload reads, since the TypeScript check does not cover them. The storage verifier's pause trace records a malformed pause instead of the unregistered reason member.

* refactor(browser): track the timeline's main frame with the document tracker (#10779)

TimelineCapture kept its own mutable main frame id and replaced it on a root replacement. It now holds the CdpDocumentTracker that CdpTargetSession owns and observes the replacement document through it; every main-frame check (lifecycle, navigation, document request, redirect) reads the tracker's current frame. A characterization test pins that the replaced root's lifecycle events are no longer recorded.

* refactor(browser): select CDP events only by their registered name (#10829)

CdpReceivedEvent carried the wire method as a plain string, so a subscriber
could compare it with a misspelt or unregistered name and the check compiled
but never matched. Three owners selected Inspector.targetCrashed, an
unregistered event, that way.

Register Inspector.targetCrashed and drop the wire method from the received
event. Subscribers select events by registered.method, whose type is the
registered event names. The capture coverage start keeps reading the
wire domain, now the event's domain field.

* fix(browser): retire a policy child session that CDP reports gone

After a listener failure the connection stops delivering events, so an
iframe's Target.detachedFromTarget never retires its policy target. Cleanup
then sent Page.removeScriptToEvaluateOnNewDocument to the dead session,
kept the stale child, and every retry failed before detaching the root.

The service-worker policy owner now treats CDP's session-not-found
rejection as proof that the child is gone and retires it. The classifier
moves from CdpTargetSession to CdpCommandRejection, its owner, and the
target-session detach path uses the same one.

* refactor(browser): route target events through one session owner (#10835)

* refactor(browser): route target events through one session owner

Page capture, WebMCP discovery, screenshot capture and the runtime sources
each compared the envelope session ID themselves, while the observation
window and execution collection used cdpTargetEventMatches, which also
routes the root Target.detachedFromTarget that names the target's session.

onCdpTargetEvent in CdpTargetEvents.ts now subscribes every target consumer
with that one rule; the matcher is private and the per-subscriber
comparisons are removed. Electron inspection keeps its own filter while
its capture isolation awaits a maintainer decision.

* fix(browser): report WebMCP subframe tools whose document is unverified (#10839)

* fix(browser): report WebMCP subframe tools whose document is unverified

A committed subframe navigation kept the frame's tools silently when CDP
reported no loader at the same URL, and removed them on any URL change even
when the loader proved the same document.

Each frame now carries a CdpDocumentTracker, the session's document
identity owner. Only a proven change removes the frame's tools. An unknown
comparison keeps them visible, marks webmcp_tools attach-limited and names
the frames whose document identity could not be established.

* test(browser): prove an unverified live subframe limits WebMCP coverage

* fix(browser): key a WebMCP registration by its frame and tool name

A subframe tool kept across a committed navigation that changed the URL
but not the loader was stored under a key built from the old URL, so a
later toolsAdded for the same frame and name added a second entry.
Registrations are now keyed by frame and name; tool_key still records the
registering frame URL.

* test(browser): deliver fake CDP events through the transport's admission (#10840)

Event fakes each rebuilt the received event: CdpAgentHints typed its
listeners as raw wire events behind an unknown cast, and the Electron,
scenario-session and routing tests each wrapped receiveCdpEvent by hand.

fakeCdpEvents (tests/fixtures) is a CdpConnection.onEvent fake whose emit
admits each raw event with receiveCdpEvent and the wire byte count, so a
change to the received event shape fails at the fake instead of silently
not exercising subscribers.

* refactor(browser): own the selected page generation in one target document tracker (#10860)

* refactor(browser): own the selected page generation in one target document tracker

Page capture, screenshot, the observation window, the runtime session and
the execution window each built a document tracker or rule of their own
from root-frame navigation events. CdpTargetDocument now follows the target
session's root-frame events and the frame-tree replies its consumers read,
classifies root identity once, and reports each navigation to consumers
that decide only what it means for their evidence.

* fix(browser): report a lost scenario policy connection before the next step (#10864)

* fix(browser): report a lost scenario policy connection before the next step

The service-worker policy recorded only protocol failures. When its CDP
socket closed or its page session detached, later documents lost the
blocking script, but the scenario learned of it only when a frame check
found an unprotected realm. The owner now records the disconnect or
detach when CDP reports it; the next policy check and the next step's
action report it first.

* fix(browser): refuse an unregistered CDP command before it reaches the browser (#10868)

JavaScript verifiers can name any command, and the send owners refused an
unregistered one only when its reply arrived, after the browser had acted
on it. CdpConnection and the Playwright session now refuse the name before
sending, and the Playwright session refuses an unregistered event name
instead of subscribing to events no listener receives. The verifier text
scan stays as an early warning and documents what it cannot see.

* fix(browser): keep a proven root change and the loaderless selection's uncertainty

Two review findings on the target document owner. A root event naming
another frame with a malformed loader set `changed` but was announced as
unidentified, so the execution window failed with protocol_error and
dropped what it had collected; the owner now announces it as the proven
change it is. The runtime session compared each frame-tree reply with the
tracker's current document, which can learn a loader from an event, so a
loaderless selection followed by an event and a reply with that loader
compared as same; it now compares the reply with the selected document
through the owner, and reports target_changed as before.

* test(browser): refuse the next scenario step after the policy session detaches

* refactor(browser): read WebMCP document identity from the target document owner (#10884)

* refactor(browser): read WebMCP document identity from the target document owner

WebMCP discovery compared the first and last frame-tree roots itself and
kept a document tracker per subframe. CdpTargetDocument now follows the
selected root and each committed subframe for it: the final frame tree
feeds the owner, a root change proven by a navigation event during
discovery is target_changed as in page capture, and a subframe whose
committed document changed loses its tools. A subframe navigation without
a loader still keeps the tools and reports them as unverified.

* fix(browser): start a subframe first seen within its document with an unknown loader

A subframe absent from the initial frame tree and first seen through Page.navigatedWithinDocument had no document tracker, so a later commit started a fresh one and the tools it registered meanwhile lost the unverified-document limitation. The owner now starts such a subframe with an unknown loader.

* fix(browser): refuse a verifier's unregistered CDP event name at subscription (#10885)

JavaScript verifiers subscribed to every event with CdpConnection.onEvent
and compared registered.method with a string literal. A misspelt or
unregistered name never matched and the verifier waited until its timeout.
CdpConnection.onRegisteredEvent now takes one event name, refuses an
unregistered one before subscribing (the same registry check the Playwright
session applies), and hands the listener only that event's registered
parse. The verifiers subscribe only through it, and the evaluation test
rejects a raw onEvent subscription in scripts.

* fix(browser): keep subframe documents by frame and loader without their URLs

* refactor(domain): give strict UTF-8 decoding one owner with an explicit BOM policy (#10728)

* refactor(domain): give strict UTF-8 decoding one owner with an explicit BOM policy

* fix(domain): keep the leading-BOM behaviour every migrated UTF-8 decoder had

* refactor(domain): read the domain layer's strict UTF-8 through the BOM-policy owner (#10803)

Twelve domain decoders built their own fatal TextDecoder with ignoreBOM: true. They now use strictUtf8Decoder("preserve"), which keeps that behaviour: each reads bytes where a leading U+FEFF is content (binary-format names and fields, JSON and XML read byte-for-byte, recorded bodies, registry seeds whose kept bytes are re-emitted). The counted baseline drops from 74 to 62.

* refactor(artifacts): read artifact readers' strict UTF-8 through the BOM-policy owner (#10871)

Fourteen artifact reader modules (17 sites) built their own fatal TextDecoder. They now take it from strictUtf8Decoder with the policy each had: every one kept a leading BOM (ignoreBOM: true), so they use "preserve"; JavaScriptArtifactFiles keeps it for JavaScript and HTML entries and strips it otherwise, as before. The strict-utf8-decoder baseline drops those 17 sites.

* refactor(domain): drop TextDecoder imports left by the strict UTF-8 migration

* refactor(application): read MCP registration metadata through the strict UTF-8 owner

* refactor(formats): read binary-format readers' strict UTF-8 through the BOM-policy owner (#10903)

* refactor(formats): read binary-format readers' strict UTF-8 through the BOM-policy owner

* refactor(formats): drop the model readers' unused TextDecoder imports

* refactor(browser): read browser capture and fetch strict UTF-8 through the BOM-policy owner (#10935)

* refactor(browser): read browser capture and fetch strict UTF-8 through the BOM-policy owner

* refactor(native): read LLDB and Mach-O name strict UTF-8 through the BOM-policy owner (#10936)

* refactor(native): read LLDB and Mach-O name strict UTF-8 through the BOM-policy owner

* refactor(process): read MCP and NDJSON transport frames' strict UTF-8 through the BOM-policy owner (#10937)

* refactor(process): read MCP and NDJSON transport frames' strict UTF-8 through the BOM-policy owner

* refactor(application): read JSON and file inputs' strict UTF-8 through the BOM-policy owner (#10938)

* refactor(application): read JSON and file inputs' strict UTF-8 through the BOM-policy owner

* refactor(providers): read IDA, Electron, Ghidra and reference strict UTF-8 through the BOM-policy owner (#10939)

* refactor(providers): read IDA, Electron, Ghidra and reference strict UTF-8 through the BOM-policy owner

* refactor(evm): read the hex bytecode carrier's strict UTF-8 through the owner and refuse new local decoders (#10940)

* refactor(evm): read the hex bytecode carrier's strict UTF-8 through the BOM-policy owner

* chore(architecture): match local strict UTF-8 decoders in any option order

* fix(il2cpp): resolve ELF ABS64 and GLOB_DAT image definitions (#11075)

Derive bounded ELF ABS64 and GLOB_DAT link-image values for IL2CPP module
scanning while preserving the default conservative relocation policy.
Retain ambiguous hash declarations, validate complete hash-table mappings,
and disclose runtime-binding limitations in CLI and MCP evidence.

Validation: 408 focused tests, check:fast and docs:check passed. Public
CLI/MCP and independently linked ARM64/x86-64 ELF arithmetic were checked;
the original Unity binaries remain unavailable.

Refs #10478
Related: #10495

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(il2cpp): read ELF hash-table words through BinaryReader (#11083)

* test(pcap): check the retained DNS-pass summary by coverage, not limitation wording

* refactor(reverse): fake objdump and Rizin commands only through the owned supervisor (#11076)

* refactor(reverse): fake objdump and Rizin commands only through the owned supervisor

* test(reverse): fake launch refusals and failed exits as the owned supervisor reports them

* refactor(reverse): name objdump and Rizin command repairs through the command port (#11080)

* refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release (#10855)

* refactor(errors): read cleanup completion from dependencies instead of pushing it to dependents

AnalysisError.cleanupIncomplete becomes a getter over the error's own unresolved state and its bound dependencies. The WeakRef dependents graph and resolveCleanup's push propagation are removed, and subclasses mark their initial state through markCleanupIncomplete instead of overriding a public mutable field.

* fix(errors): settle bound dependencies before binding more

A composite whose dependencies had released but whose status was never read
stayed incomplete when a later dependency was bound.

* refactor(errors): let errors read a lease group's release instead of resolving them (#10759)

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink (#10763)

* refactor(errors): let errors read a lease group's release instead of resolving them

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink

* refactor(process): let worker cleanup errors read their root epoch's release

OwnedWorkerRuntime's root epoch is now an AnalysisCleanupReleaseClaim. Errors bound to it read its release when asked instead of the epoch pushing resolveCleanup() through weak references, and a runtime without a retained root binds an already-released owner. Removes the OwnedWorkerCleanupFailure structural type and four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(pcap): let pcap cleanup errors read command and snapshot release (#10792)

Retained pcap commands, retained snapshot failures and snapshot completion descriptors now own their release and errors read it: commands and snapshot failures implement AnalysisCleanupReleaseClaim, and a failed completion-descriptor close is retried through an AnalysisCleanupLease bound to its error. Removes four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(process): let Darwin helper cleanup errors read their owner's release

Darwin helper cache and run-token reader root cleanup now record an AnalysisCleanupRelease that every failure reports; a successful retry confirms it. Replaces the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes two resolveCleanup() and two bindCleanupDependencies() calls; both counted baselines shrink.

* refactor(ghidra): let Ghidra cleanup errors read the client's and checkpoint's release

GhidraClient and GhidraCheckpoint bind each cleanup failure to an AnalysisCleanupRelease and confirm it when a later close or retry releases everything, instead of keeping a set of failures and pushing resolveCleanup() to each. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(process): let debugger session cleanup errors read a confirmed stop

OwnedDebuggerSessionRegistry binds each retained gdb or rizin cleanup failure to the session's AnalysisCleanupRelease and confirms it when a stop is confirmed, keeping the latest failure for retry reporting, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): drop the debugger registry's unused closeOperation option

Returning the latest retained failure removed the last reader of closeOperation; remove the option and the values gdb and rizin supplied.

* refactor(server): let environment shutdown errors read a successful close

serveEnvironment binds each shutdown failure to an AnalysisCleanupRelease that a later successful close confirms, instead of pushing resolveCleanup() to a set of failures. The state-file retry test now also requires the earlier report to read the release. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): release retained screen-judge cleanup through its lease

Each retained judge or screenshot cleanup owner is wrapped in an AnalysisCleanupLease bound to its failure; close() releases the lease, which records the release the failure reads, instead of closing the owner and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(ida): let IDA close failures read the session's later close

IdaSessionClient's close failure binds an owner that is both its resource owner and its release claim, read from the client's closed state, instead of keeping weak references and pushing resolveCleanup() after a successful retry. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(javascript): let source-map codec cleanup errors read a later close (#10814)

* refactor(javascript): let source-map codec cleanup errors read a later close

OwnedCodec binds each close failure to an AnalysisCleanupRelease that a later successful close confirms, replacing the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes one resolveCleanup() and one bindCleanupDependencies() call; both counted baselines shrink.

* refactor(cutter): let pending Cutter command errors read the completion receipt (#10815)

* refactor(cutter): let pending Cutter command errors read the completion receipt

Each pending Cutter command keeps an AnalysisCleanupRelease bound to its timeout failure; the producer's terminal completion receipt confirms it instead of pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(application): let provider candidate cleanup errors read the candidate's close (#10817)

* refactor(application): let provider candidate cleanup errors read the candidate's close

AnalysisProviderRegistry keeps one AnalysisCleanupRelease per candidate whose resource close is unconfirmed; failures bind to it and a later confirmed close confirms it, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* fix(errors): bind a cleanup release claim to an error at most once

AnalysisError kept release claims in an array, so a provider whose retried close returned the same error bound the same claim again on every retry and each cleanupIncomplete read scanned the duplicates. Keep the claims in a set.

* refactor(application): let reverse-tool cleanup errors read a verified stop (#10819)

* refactor(application): let reverse-tool cleanup errors read a verified stop

Each retained provider process group in ReverseEngineeringService keeps an AnalysisCleanupRelease; its command and retry failures bind to it and a later verified stop confirms it, instead of collecting failures and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(sqlite): let SQLite worker and root cleanup errors read their release (#10821)

Each retained SQLite snapshot cleanup records an AnalysisCleanupRelease for its worker and for its runtime root; the resource failures bind to them and a verified stop or root removal confirms them, instead of pushing resolveCleanup(). Composite failures keep reading those resource failures. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(android): let JADX cleanup errors read their retained cleanup's release

Each retained JADX cleanup records an AnalysisCleanupRelease for the admission failure's descriptor owners and one for the whole retained cleanup. The admission failure and every error the cleanup reports bind to them, and a confirmed close confirms them, instead of pushing resolveCleanup() through WeakRefs to reported errors. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let session close failures read the client's later close

A retained session cleanup records an AnalysisCleanupRelease; unowned cleanup failures the client's close reported bind to it and the successful close confirms it, instead of the session collecting them and pushing resolveCleanup(). Failures that already follow their own owner keep reading it. Adds a regression for an unowned close failure. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release

Build-computer teardown, retained task readers, remote reader folders and agentenv solve sandboxes each record an AnalysisCleanupRelease that their bound failures read; a verified teardown or stop confirms it instead of pushing resolveCleanup() through WeakRef sets. Long-run job failures read whether every job they name has confirmed its stop, so a failure naming two jobs no longer reads complete when only one stops (regression added). WeakRef sets kept only where late facts (completion receipts, reader views) are still retained as diagnostics. Removes six resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let source-map and Kuna cache cleanup errors read their owner's release (#10856)

* refactor(browser): let late source-map fetch errors read their response's release

A pending source-map fetch and a response cancellation each record an AnalysisCleanupRelease that their cancellation or deadline failure reads; releasing the late response or the reader lock confirms it instead of pushing resolveCleanup(). Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let project-cache cleanup errors read each owner's release

Each retained Kuna resource owner (process, staging, hash descriptor, retired file) records a release that the errors reporting it read; an error completes once every owner it reports confirms, and retirement that moves staging to a retained file forwards the staging owner's release to the file's. Replaces the WeakRef report list, its pruning and the resolveCleanup() push. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): forbid resolveCleanup() pushes; native markers read their supervisor's release (#10857)

* refactor(providers): let an attributed client failure read its source's completed cleanup

Re-attributing a failure whose source cleanup already completed now binds a claim reading that source's release instead of pushing resolveCleanup() onto the new error; a pending source is still bound as a dependency. Resources stay as history, as before. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): let native command markers read their supervisor's release

ProviderProcessSupervisor records an AnalysisCleanupRelease that a stop proving the process ended confirms. Native command and LLDB resolver cleanup markers bind to their supervisor's release, so a verified stop by either owner completes them, instead of each owner pushing resolveCleanup() onto the markers it tracks. Removes the last two resolveCleanup() calls outside the error base; the counted baseline is empty.

* chore(verify): forbid resolveCleanup() pushes outside the error base

Every production owner now confirms a release its errors read, so the counted baseline is empty. The guard becomes an outright ban with no baseline entry.

* test(native): complete native command and LLDB markers through a direct supervisor stop

* refactor(errors): complete an error's cleanup from its owner's record and every dependency (#10892)

* refactor(errors): complete an error's cleanup from its owner's record and every dependency

* refactor(errors): complete test errors through an owner release and delete resolveCleanup() (#10898)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner (#10900)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner

* refactor(application): compose service cleanup failures through the shared owner (#10902)

* refactor(sqlite): classify worker-reply read failures through the shared provider classifier (#10849)

* fix(pcap): report a refused tool launch as an unavailable tool

When a capture read's tool launch was refused with EPERM, pcap reported it
as unreadable tool output (AnalysisProtocolError) instead of an unavailable
tool. Pcap also never told "not executable" apart from "missing".

Add classifyLaunchFailure in src/process as the one owner of which spawn
errnos mean missing (ENOENT, ENOTDIR) and which mean present but not
executable (EACCES, EPERM, ENOEXEC, EISDIR). Pcap, apktool and gdb used three
different errno lists; all three now use it.

* refactor(process): classify owned command outcomes through one owner

Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions.

* refactor(process): classify Java and adb launch refusals with the shared owner (#10598)

The Ghidra and JADX Java probes and adb's version probe now take
missing-versus-not-executable from classifyLaunchFailure instead of their
own errno checks. ELOOP and ENAMETOOLONG join the owner's missing set, so
adb keeps its existing classification and both Java probes now treat a
non-directory path component as a missing runtime.

* fix(pcap): preserve command launch attribution

* test(pcap): expect an unknown failing stage when a limited capture tool exits unsuccessfully

* refactor(process): classify owned command outcomes through one owner

Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions.

* test(lint): cover baselined files in the provider-failure classifier rule

* fix(apktool): report the decoder JVM's heap exhaustion as memory, not a target refusal

The supervisor now watches for a managed runtime's out-of-memory report while output streams (JVM java.lang.OutOfMemoryError, V8 'JavaScript heap out of memory'), so a retention budget cannot hide it. ProviderOutcome gains a runtime-exhausted kind and classifyProviderOutcome maps it once. Apktool decode opts in and moves to the shared classifier; Ghidra's single-purpose output token becomes the JVM runtime option and its area matching reuses the shared table.

* fix(process): keep the runtime's out-of-memory report on the memory error it supports

* fix(pcap): attribute a limited capture's exit through the prlimit wrapper

* fix(process): keep a shortened out-of-memory line marked as shortened

* fix(process): identify the refused executable for every launcher shape

Name the executable on errnos Node throws synchronously from spawn
(ENOEXEC, ENOTDIR, ...) and read the Windows native launcher's
executable-launch constraint, so pcap attributes those refusals to the
selected tool or limiter instead of an unknown stage.

* test(pcap): prove synchronous launch naming with ENOTDIR on every POSIX host

* fix(apktool): advise the JVM limit that governs the reported memory area

* fix(ghidra): read the supervisor's parsed OOM area instead of reparsing lines

* fix(sqlite,capture): read V8 heap exhaustion from streamed output, not retained stderr (#10724)

The SQLite worker and the Node capture decoders now declare runtime: "v8", so the supervisor observes V8's heap report as output streams. Both classifiers read the runtime-exhausted outcome instead of matching retained stderr, so a report beyond the retention budget, or one whose process then overflowed its output budget, is still reported as memory exhaustion.

* refactor(evm): classify EVMole worker outcomes through the shared provider classifier (#10716)

* refactor(evm): classify EVMole worker outcomes through the shared provider classifier

The EVMole worker's cancellation, deadline, output budget and CPU/file-size signals now go through classifyProviderOutcome; only the prlimit launch refusal and the reserved EFBIG exit remain in its dialect. The worker is opted into V8 exhaustion scanning so a heap report names its fixed 256 MiB heap. providerOutcomeOf now reads a launch refusal only from a spawn errno, so a private-storage or carrier read errno is no longer reported as a limiter launch failure.

* fix(evm): keep a stream failure's exit status and update Linux worker expectations

* refactor(process): read launch refusals through the launcher identity owner

* refactor(wasm): classify WABT command outcomes through the shared provider classifier (#10727)

* refactor(wasm): classify WABT command outcomes through the shared provider classifier

WABT's cancellation, command deadline, output budget, and inherited-limit signals now go through classifyProviderOutcome; its dialect keeps only the configuration-probe and launch-refusal unavailability and the unclassified-exit output error. A tool ended by SIGXCPU/SIGXFSZ or the memory limit is now a resource constraint instead of an output error, and a refused launch in the producer phase is reported as unavailable. The shared timeout context gains the analysis setting that selected the deadline, and the output-limit context may name its exceeded budget.
…

---------

Co-authored-by: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com>
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-16 10:59:18 +08:00

1589 lines
57 KiB
TypeScript

import { FLUTTER_PROVIDER_IDENTITY } from "./FlutterProviderIdentity.js";
import {
artifactFileCancellationCause,
assertArtifactReadActive,
ArtifactResourceScope,
AnalysisCleanupLease,
AnalysisCleanupLeaseGroup,
ArtifactReaderFailure,
type ArtifactEntry,
ZipArtifactReader,
} from "../resources/index.js";
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
import { regularFileCancellation } from "../filesystem/OwnedRegularFile.js";
import { createHash } from "node:crypto";
import { chmod, mkdtemp, open as openFile, rm, stat } from "node:fs/promises";
import { createReadStream } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
import {
type ExecutionOptions,
type ProviderAvailability,
createAnalysisExecution,
type AnalysisExecution,
} from "../ports/AnalysisProvider.js";
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
import {
MAX_FLUTTER_LIBRARY_PATH_BYTES,
dartPoolBudgetLimit,
dartPoolPolicy,
type DartPoolBudget,
type DartPoolPolicy,
type FlutterRequest,
} from "../domain/flutter/flutterBuildAnalysis.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisInputError,
AnalysisResourceConstraintError,
AnalysisUnsupportedTargetError,
AnalysisProtocolError,
cancelledBy,
carriedReason,
} from "../domain/analysisErrorCore.js";
import { isAbortWithReason } from "../process/SignalAbort.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
import {
AnalysisError,
type AnalysisPartialObservation,
} from "../domain/analysisErrorBase.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok, type Result } from "../domain/result.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
NonRegularFileReadError,
openRegularFile,
RegularFileAdmissionFailure,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import {
MAX_SNAPSHOT_HASH_CANDIDATES,
LabeledStringScanner,
SnapshotHashScanner,
} from "./FlutterPayloadScan.js";
import {
ELF_HEADER_MAX_BYTES,
readElfHeader,
readElfSymbols,
readSnapshotHeader,
} from "./DartElf.js";
import { readElfBuildIds } from "./ElfBuildId.js";
import { privateWorkspaceFailure } from "../process/privateWorkspaceFailure.js";
import { errorMessage } from "../kernel/errorMessage.js";
const APK_METADATA_READ_MAX_BYTES = 8 * 1024 * 1024;
const LIBRARY_MAX_BYTES = 256 * 1024 * 1024;
/** Cumulative cap across every library entry in one identification. */
const TOTAL_EXTRACTION_MAX_BYTES = 768 * 1024 * 1024;
/** The APK itself must fit within this budget before any copy. */
const APK_MAX_BYTES = 2 * 1024 * 1024 * 1024;
// At most 32 ABI projections (two libraries each). With bounded hashes and
// engine labels this keeps expanded result metadata below 512 KiB for ordinary
// ABI names, independently of the archive's compressed-byte budget.
const MAX_FLUTTER_ABIS = 32;
/** A complete AOT image carries exactly one VM and one isolate section. */
const SYMBOL_PAIR_COUNT = 2;
const IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
/** Each release-fixed Flutter ceiling with the value that refused the input. */
const FLUTTER_ALLOWANCES = {
apkMetadataRead: fixedAllowanceOptions(
"The Flutter APK metadata read allowance",
"parser",
{ limit: APK_METADATA_READ_MAX_BYTES, unit: "bytes" },
),
abiInventory: fixedAllowanceOptions(
"The Flutter ABI inventory allowance",
"parser",
{ limit: MAX_FLUTTER_ABIS, unit: "ABIs" },
),
libraryPath: fixedAllowanceOptions(
"The Flutter library path allowance",
"parser",
{ limit: MAX_FLUTTER_LIBRARY_PATH_BYTES, unit: "bytes" },
),
apkSnapshot: fixedAllowanceOptions(
"the Flutter APK snapshot allowance",
"input",
{ limit: APK_MAX_BYTES, unit: "bytes" },
),
libraryRead: fixedAllowanceOptions(
"the Flutter library read allowance",
"input",
{ limit: LIBRARY_MAX_BYTES, unit: "bytes" },
),
cumulativeExtraction: fixedAllowanceOptions(
"the Flutter cumulative extraction allowance",
"input",
{ limit: TOTAL_EXTRACTION_MAX_BYTES, unit: "bytes" },
),
snapshotHashCandidates: fixedAllowanceOptions(
"The Flutter snapshot-hash candidate allowance",
"parser",
{ limit: MAX_SNAPSHOT_HASH_CANDIDATES, unit: "candidates" },
),
} as const;
/**
* Stream a local file digest without retaining large files in memory.
* Aborts between chunks so a cancellation cannot run a digest to completion.
*/
const sha256File = async (
operation: string,
path: string,
signal: AbortSignal | undefined,
): Promise<string> => {
assertArtifactReadActive(signal);
const hash = createHash("sha256");
const owner = new AbortController();
const marker = {};
const abort = () => owner.abort(marker);
signal?.addEventListener("abort", abort, { once: true });
try {
const stream = createReadStream(path, { signal: owner.signal });
for await (const chunk of stream) {
if (signal?.aborted === true) throw cancelledBy(operation, signal);
hash.update(chunk as Buffer);
}
return hash.digest("hex");
} catch (cause) {
if (isAbortWithReason(cause, marker))
throw cancelledBy(operation, carriedReason(signal?.reason));
throw cause;
} finally {
signal?.removeEventListener("abort", abort);
}
};
/** One owned snapshot root: a read-only copy of the admitted input. */
interface OwnedSnapshot {
readonly root: string;
readonly path: string;
readonly bytes: number;
readonly sha256: string;
}
interface LibraryFacts {
readonly libapp: {
present: boolean;
bytes: number | null;
sha256: string | null;
elfHeaderValid: boolean | null;
sources: number;
candidates: readonly string[];
};
readonly libflutter: {
present: boolean;
bytes: number | null;
sha256: string | null;
buildId: string | null;
buildIdCandidates: readonly string[];
buildIdFailures: readonly string[];
dartVersion: string | null;
dartVersionCapped: boolean;
toolchainLines: readonly string[];
toolchainCapped: boolean;
};
}
const emptyFacts = (): LibraryFacts => ({
libapp: {
present: false,
bytes: null,
sha256: null,
elfHeaderValid: null,
sources: 0,
candidates: [],
},
libflutter: {
present: false,
bytes: null,
sha256: null,
buildId: null,
buildIdCandidates: [],
buildIdFailures: [],
dartVersion: null,
dartVersionCapped: false,
toolchainLines: [],
toolchainCapped: false,
},
});
/** Use the producing reader's cancellation facts rather than its wrapper error. */
const observedCancellation = (
cause: unknown,
): { readonly reason: unknown } | undefined => {
const file = regularFileCancellation(cause);
if (file !== undefined) return file;
if (cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
return { reason: artifactFileCancellationCause(cause) };
return undefined;
};
const mapInputFailure = (
operation: string,
path: string,
cause: unknown,
): AnalysisError => {
if (cause instanceof AnalysisError) return cause;
const cancellation = observedCancellation(cause);
if (cancellation !== undefined)
return cancelledBy(operation, carriedReason(cancellation.reason));
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
return new AnalysisAccessDeniedError(operation, path, cause.code, {
cause,
});
if (cause instanceof ArtifactReaderFailure && cause.reason === "limit")
return readerLimitFailure(operation, cause);
return new AnalysisInputError(operation, { cause }, [
{
path: ["path"],
reason: "invalid_format",
message: inputFailureMessage(path, cause),
},
]);
};
/**
* Report the ZIP reader ceiling that refused the APK. A ceiling the reader
* names (the Zstandard decoder window) keeps its name. The archive expansion
* budget is derived from the APK's size, and Flutter offers no control that
* raises it, so it is fixed for this request. The ZIP reader's remaining limit
* is the metadata read budget this provider selects.
*/
const readerLimitFailure = (
operation: string,
cause: ArtifactReaderFailure,
): AnalysisError => {
if (cause.fixedAllowance !== undefined)
return new AnalysisResourceConstraintError(
operation,
cause.boundary === "file-size" ? "file-size" : "memory",
cause.message,
null,
{ cause, retryable: false, fixedAllowance: cause.fixedAllowance },
);
if (cause.readerLimit !== undefined) {
const { effective_value: limit, required_value: required } =
cause.readerLimit;
return new AnalysisResourceConstraintError(
operation,
"memory",
`The APK's declared member sizes${required === undefined ? "" : ` (${String(required)} bytes)`} exceed its ${String(limit)}-byte expansion allowance.`,
{ max_expanded_bytes: limit },
{
cause,
...fixedAllowanceOptions(
"The Flutter APK expansion allowance (derived from the APK size)",
"parser",
{ limit, unit: cause.readerLimit.unit },
),
},
);
}
return new AnalysisResourceConstraintError(
operation,
"memory",
cause.message,
{ max_metadata_read_bytes: APK_METADATA_READ_MAX_BYTES },
{ cause, ...FLUTTER_ALLOWANCES.apkMetadataRead },
);
};
/** Name a missing or non-file selection instead of blaming package bytes. */
const inputFailureMessage = (path: string, cause: unknown): string => {
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
return `Selected APK does not exist: ${path}`;
if (cause instanceof NonRegularFileReadError)
return `Selected APK is not a regular file: ${path}`;
const message = errorMessage(cause);
return `The APK could not be read as a package: ${path}: ${message}`;
};
/**
* Provider-owned storage failures must never be attributed to caller input.
* `workspacePath` is the owned root once allocated, so a failure without its
* own errno path still names the workspace it occurred in.
*/
const mapOwnedIoFailure = (
operation: string,
cause: unknown,
workspacePath: string | null,
): AnalysisError => {
if (cause instanceof AnalysisError) return cause;
const cancellation = observedCancellation(cause);
if (cancellation !== undefined)
return cancelledBy(operation, carriedReason(cancellation.reason));
if (
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string"
)
return privateWorkspaceFailure(
FLUTTER_PROVIDER_IDENTITY.id,
operation,
cause,
workspacePath,
);
return new AnalysisProtocolError(operation, { cause });
};
/**
* ZIP format failures describe caller bytes. A system error comes from the
* provider-owned snapshot descriptor, so it propagates unchanged to the
* snapshot owner, which maps it against the owned workspace.
*/
const mapPackageFailure = (
operation: string,
path: string,
cause: unknown,
): unknown =>
cause instanceof Error && "code" in cause && typeof cause.code === "string"
? cause
: mapInputFailure(operation, path, cause);
interface FlutterLibrary {
readonly entry: ArtifactEntry;
readonly abi: string;
readonly kind: "libapp" | "libflutter";
}
/** One inventory owns occurrence ambiguity and metadata expansion for both tools. */
const collectFlutterLibraries = async (
reader: ZipArtifactReader,
operation: string,
path: string,
signal: AbortSignal | undefined,
): Promise<FlutterLibrary[]> => {
const libraries: FlutterLibrary[] = [];
const paths = new Set<string>();
const abis = new Set<string>();
try {
for await (const entry of reader.entries(signal)) {
if (entry.kind !== "file") continue;
const match = /^lib\/([^/]+)\/(libapp|libflutter)\.so$/u.exec(entry.path);
if (match === null) continue;
if (paths.has(entry.path))
throw new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: `The selected APK has duplicate Flutter library members: ${path}: ${entry.path}`,
},
]);
paths.add(entry.path);
abis.add(match[1]!);
if (
abis.size > MAX_FLUTTER_ABIS ||
Buffer.byteLength(entry.path) > MAX_FLUTTER_LIBRARY_PATH_BYTES
)
throw new AnalysisResourceConstraintError(
operation,
"memory",
"Flutter library inventory exceeds the bounded ABI projection budget",
{
max_flutter_abis: MAX_FLUTTER_ABIS,
max_library_path_bytes: MAX_FLUTTER_LIBRARY_PATH_BYTES,
},
abis.size > MAX_FLUTTER_ABIS
? FLUTTER_ALLOWANCES.abiInventory
: FLUTTER_ALLOWANCES.libraryPath,
);
libraries.push({
entry,
abi: match[1]!,
kind: match[2] === "libapp" ? "libapp" : "libflutter",
});
}
return libraries;
} catch (cause) {
throw mapPackageFailure(operation, path, cause);
}
};
/** The generator owns iterator closure, including early extraction failures. */
async function* openEntrySafely(
reader: ZipArtifactReader,
entry: ArtifactEntry,
operation: string,
path: string,
signal: AbortSignal | undefined,
): AsyncGenerator<Buffer> {
try {
yield* await reader.open(entry, signal);
} catch (cause) {
throw mapPackageFailure(operation, path, cause);
}
}
const checkApkSize = (operation: string, bytes: number): void => {
if (bytes > APK_MAX_BYTES)
throw new AnalysisResourceConstraintError(
operation,
"file-size",
`The selected APK exceeds the ${String(APK_MAX_BYTES)}-byte snapshot budget`,
{ max_apk_bytes: APK_MAX_BYTES, observed_bytes: bytes },
FLUTTER_ALLOWANCES.apkSnapshot,
);
};
/**
* Flutter build identification by pure parsing: reads `lib/<abi>/libapp.so`
* and `libflutter.so` through the hardened ZIP reader and reports the Dart
* snapshot hash, GNU build-id, and any labeled version strings verbatim.
* Runs no engine, installs nothing, and performs no external lookups.
*/
export class FlutterBuildProvider {
private readonly ownedRoots = new Map<
string,
Set<{ close(): Promise<void> }>
>();
private readonly cleanupFailures = new Map<string, readonly unknown[]>();
private readonly rootLeases = new Map<string, AnalysisCleanupLease>();
private readonly operations = new ArtifactResourceScope();
constructor() {
this.operations.addCloseHook(() => this.closeRoots());
}
/**
* Snapshot the admitted input into a provider-owned, read-only copy so a
* concurrently modified original cannot mix into one observation. The
* digest is taken from the snapshot, and every later read uses the
* snapshot path.
*/
private async ownSnapshot(
operation: string,
path: string,
signal: AbortSignal | undefined,
): Promise<OwnedSnapshot> {
let root: string;
try {
root = await mkdtemp(join(tmpdir(), "rea-flutter-"));
} catch (cause) {
// No workspace exists yet; the errno path names the attempted template.
throw mapOwnedIoFailure(operation, cause, null);
}
this.ownedRoots.set(root, new Set());
this.rootLeases.set(
root,
new AnalysisCleanupLease(async () => {
if (!(await this.cleanupRoot(root)))
throw this.cleanupError(root, operation);
}, [root]),
);
const snapshotPath = join(root, "input.apk");
const readSource = async <T>(read: () => Promise<T>): Promise<T> => {
try {
return await read();
} catch (cause) {
throw mapInputFailure(operation, path, cause);
}
};
try {
// Pin the admitted source: capture its identity before the copy and
// revalidate after, so an in-place replacement or swap mid-copy is
// refused instead of publishing mixed bytes under the original path.
// The copy itself is streamed and abort-checked so cancellation
// stops the write promptly instead of draining the whole file.
let source: OwnedFileHandle;
try {
const { handle } = await openRegularFile(path, {
symlinks: "follow",
signal,
});
source = this.ownResource(root, new OwnedFileHandle(handle));
} catch (cause) {
if (cause instanceof RegularFileAdmissionFailure) {
this.ownResource(root, cause.owner);
throw mapInputFailure(operation, path, cause.cause);
}
throw mapInputFailure(operation, path, cause);
}
const before = await readSource(() =>
source.handle.stat({ bigint: true }),
);
checkApkSize(operation, Number(before.size));
const output = this.ownResource(
root,
new OwnedFileHandle(await openFile(snapshotPath, "wx")),
);
const chunk = Buffer.alloc(64 * 1024);
let copiedBytes = 0;
while (copiedBytes <= Number(before.size)) {
assertArtifactReadActive(signal);
const { bytesRead } = await readSource(() =>
source.handle.read(
chunk,
0,
Math.min(chunk.length, Number(before.size) - copiedBytes + 1),
copiedBytes,
),
);
assertArtifactReadActive(signal);
if (bytesRead === 0) break;
copiedBytes += bytesRead;
if (BigInt(copiedBytes) > before.size)
throw new AnalysisArtifactChangedError(
operation,
path,
"Selected file grew during snapshotting",
);
await output.handle.writeFile(chunk.subarray(0, bytesRead));
}
await this.releaseResource(root, output);
const [after, currentPath] = await Promise.all([
readSource(() => source.handle.stat({ bigint: true })),
stat(path, { bigint: true }).catch((cause: unknown) => {
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
throw mapInputFailure(operation, path, cause);
throw new AnalysisArtifactChangedError(
operation,
path,
"Selected path became unavailable during snapshotting",
{ cause },
);
}),
]);
if (
BigInt(copiedBytes) !== before.size ||
!sameRegularFileState(before, after) ||
!sameRegularFileState(before, currentPath)
)
throw new AnalysisArtifactChangedError(
operation,
path,
"Selected file identity or contents changed during snapshotting",
);
await this.releaseResource(root, source);
await chmod(snapshotPath, 0o400);
const info = await stat(snapshotPath);
const sha256 = await sha256File(operation, snapshotPath, signal);
return { root, path: snapshotPath, bytes: info.size, sha256 };
} catch (cause) {
const primary = mapOwnedIoFailure(operation, cause, root);
const released = await this.discardRoot(root);
if (!released)
throw this.withCleanup(
primary,
this.cleanupError(root, operation),
operation,
);
throw primary;
}
}
private readerFor(snapshot: OwnedSnapshot): ZipArtifactReader {
return this.ownResource(
snapshot.root,
new ZipArtifactReader(snapshot.path, "apk", APK_METADATA_READ_MAX_BYTES),
);
}
private ownResource<T extends { close(): Promise<void> }>(
root: string,
resource: T,
): T {
this.ownedRoots.get(root)!.add(resource);
return resource;
}
private async releaseResource(
root: string,
resource: { close(): Promise<void> },
): Promise<void> {
await resource.close();
this.ownedRoots.get(root)?.delete(resource);
}
/** Close every owned handle before removing its root; retain any failure. */
private async discardRoot(root: string): Promise<boolean> {
const lease = this.rootLeases.get(root);
if (lease === undefined) return true;
try {
await lease.release();
this.rootLeases.delete(root);
return true;
} catch {
return false;
}
}
private async cleanupRoot(root: string): Promise<boolean> {
const resources = this.ownedRoots.get(root);
if (resources === undefined) return true;
const attempts = await Promise.allSettled(
[...resources].map((resource) => this.releaseResource(root, resource)),
);
const failures = attempts.flatMap((attempt) =>
attempt.status === "rejected" ? [attempt.reason as unknown] : [],
);
if (failures.length > 0) {
this.cleanupFailures.set(root, failures);
return false;
}
try {
await rm(root, { recursive: true, force: true });
this.ownedRoots.delete(root);
this.cleanupFailures.delete(root);
return true;
} catch (cause) {
this.cleanupFailures.set(root, [cause]);
return false;
}
}
/** Pure parsing; the provider is always available. */
async inspectAvailability(): Promise<ProviderAvailability> {
return {
status: "available",
code: null,
reason: null,
diagnostics: { engine: "static-apk-parsing" },
};
}
private cleanupError(
root: string,
operation: string,
completedObservation?: AnalysisPartialObservation,
): ProviderCleanupError {
const causes = this.cleanupFailures.get(root) ?? [];
const error = new ProviderCleanupError(
FLUTTER_PROVIDER_IDENTITY.id,
[root],
{
reason: causes.map((cause) => errorMessage(cause)).join("; "),
retained_roots: [
{
path: root,
failures: causes.map((cause) => ({
name: cause instanceof Error ? cause.name : "UnknownError",
message: errorMessage(cause),
...(cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string"
? { code: cause.code }
: {}),
})),
},
],
},
{
cause: new AggregateError(causes, "Flutter snapshot cleanup failed"),
operation,
...(completedObservation === undefined ? {} : { completedObservation }),
},
);
const lease = this.rootLeases.get(root);
if (lease !== undefined) new AnalysisCleanupLeaseGroup(error, [lease]);
return error;
}
private withCleanup(
primary: AnalysisError,
cleanup: AnalysisError,
operation: string,
): AnalysisError {
return analysisErrorWithCleanupDependencies(primary, cleanup, operation);
}
/** Stop admission and drain active snapshots before attempting retained cleanup. */
async close(): Promise<void> {
await this.operations.close();
}
private async closeRoots(
roots = [...this.ownedRoots.keys()],
operation = "close_flutter_build",
): Promise<void> {
const failures: AnalysisError[] = [];
for (const root of roots) {
if (!(await this.discardRoot(root)))
failures.push(this.cleanupError(root, operation));
}
if (failures.length === 1) throw failures[0];
if (failures.length > 1)
throw new ProviderCleanupError(
FLUTTER_PROVIDER_IDENTITY.id,
failures.flatMap((failure) => failure.cleanupResources),
{
reason: failures
.map((failure) => failure.diagnostics?.reason ?? failure.message)
.join("; "),
retained_roots: failures.flatMap((failure) => {
const roots = failure.diagnostics?.retained_roots;
return Array.isArray(roots) ? roots : [];
}),
},
{
cause: new AggregateError(failures),
operation,
},
).bindCleanupDependencies(failures);
}
async execute(
request: FlutterRequest,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
try {
return await this.operations.run(() =>
this.executeOwned(request, options),
);
} catch (cause) {
return err(mapOwnedIoFailure(request.operation, cause, null));
}
}
private async executeOwned(
request: FlutterRequest,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
const cancellation = (): AnalysisCancelledError | undefined =>
options?.signal?.aborted === true
? cancelledBy(request.operation, options.signal)
: undefined;
const beforeCleanup = cancellation();
if (beforeCleanup !== undefined) return err(beforeCleanup);
// Only failed roots are safe to retry here: concurrent admitted snapshots
// retain their own live resources until their operations finish.
try {
await this.closeRoots(
[...this.cleanupFailures.keys()],
request.operation,
);
} catch (cause) {
const failure = mapOwnedIoFailure(request.operation, cause, null);
const interrupted = cancellation();
return err(
interrupted === undefined
? failure
: analysisErrorWithCancellation(failure, interrupted),
);
}
const afterCleanup = cancellation();
if (afterCleanup !== undefined) return err(afterCleanup);
const { path } = request.input;
const signal = options?.signal;
let snapshot: OwnedSnapshot | undefined;
let result: Result<AnalysisExecution, AnalysisError>;
try {
snapshot = await this.ownSnapshot(request.operation, path, signal);
const reader = this.readerFor(snapshot);
const libraries = await collectFlutterLibraries(
reader,
request.operation,
path,
signal,
);
result =
request.operation === "inspect_dart_aot"
? await this.inspectDartAot(
path,
request.input.abi,
signal,
snapshot,
reader,
libraries,
dartPoolPolicy(request.input.pool_policy),
)
: await this.identifyFlutterBuild(
path,
signal,
snapshot,
reader,
libraries,
);
} catch (cause) {
result = err(
mapOwnedIoFailure(request.operation, cause, snapshot?.root ?? null),
);
}
const cleanup =
snapshot !== undefined && !(await this.discardRoot(snapshot.root))
? this.cleanupError(
snapshot.root,
request.operation,
result.ok
? createAnalysisExecutionEvidence(
request.operation,
request.input,
result.value,
"observed",
)
: undefined,
)
: undefined;
// Cancellation observed after the awaited snapshot removal still keeps
// the completed facts, composed exactly as the uncancelled Evidence.
if (signal?.aborted === true && result.ok) {
result = err(
cancelledBy(request.operation, signal, {
partialObservation: createAnalysisExecutionEvidence(
request.operation,
request.input,
result.value,
"observed",
),
}),
);
}
if (signal?.aborted === true && !result.ok)
result = err(
analysisErrorWithCancellation(
result.error,
cancelledBy(request.operation, signal),
),
);
if (cleanup !== undefined) {
if (!result.ok)
return err(this.withCleanup(result.error, cleanup, request.operation));
cleanup.retainPartialObservation(
createAnalysisExecutionEvidence(
request.operation,
request.input,
result.value,
"observed",
),
);
return err(cleanup);
}
return result;
}
private async identifyFlutterBuild(
path: string,
signal: AbortSignal | undefined,
snapshot: OwnedSnapshot,
reader: ZipArtifactReader,
flutterEntries: readonly FlutterLibrary[],
): Promise<Result<AnalysisExecution, AnalysisError>> {
const operation = "identify_flutter_build";
for (const { entry } of flutterEntries) {
if (entry.declaredSize !== null && entry.declaredSize > LIBRARY_MAX_BYTES)
return err(
new AnalysisResourceConstraintError(
operation,
"file-size",
`${entry.path} exceeds the library read budget`,
{ max_library_bytes: LIBRARY_MAX_BYTES, entry_path: entry.path },
FLUTTER_ALLOWANCES.libraryRead,
),
);
}
// Preflight: refuse before any I/O when the declared entry sizes
// already exceed the cumulative budget, even though streaming might
// discover smaller actual sizes.
const declaredTotal = flutterEntries.reduce(
(total, { entry }) => total + (entry.declaredSize ?? 0),
0,
);
if (declaredTotal > TOTAL_EXTRACTION_MAX_BYTES)
return err(
new AnalysisResourceConstraintError(
operation,
"file-size",
`declared library sizes total ${String(declaredTotal)} bytes, exceeding the ${String(TOTAL_EXTRACTION_MAX_BYTES)}-byte cumulative budget before any extraction`,
{
max_total_bytes: TOTAL_EXTRACTION_MAX_BYTES,
declared_total: declaredTotal,
},
FLUTTER_ALLOWANCES.cumulativeExtraction,
),
);
const facts = new Map<string, LibraryFacts>();
let extractedTotal = 0;
let libraryIndex = 0;
for (const { entry, abi, kind } of flutterEntries) {
const stream = openEntrySafely(reader, entry, operation, path, signal);
const hash = createHash("sha256");
const snapshotScanner = new SnapshotHashScanner();
const labeledScanner = new LabeledStringScanner();
const engineFile =
kind === "libflutter"
? this.ownResource(
snapshot.root,
new OwnedFileHandle(
await openFile(
join(snapshot.root, `engine-${libraryIndex++}.so`),
"wx+",
),
),
)
: null;
let bytes = 0;
const headerPrefix = Buffer.alloc(ELF_HEADER_MAX_BYTES);
let headerBytes = 0;
for await (const chunk of stream) {
if (signal?.aborted === true)
return err(cancelledBy(operation, signal));
const view = chunk as Buffer;
headerBytes += view.copy(
headerPrefix,
headerBytes,
0,
Math.min(view.length, headerPrefix.length - headerBytes),
);
bytes += view.byteLength;
if (bytes > LIBRARY_MAX_BYTES)
return err(
new AnalysisResourceConstraintError(
operation,
"file-size",
`${entry.path} exceeds the ${String(LIBRARY_MAX_BYTES)}-byte read budget while streaming`,
{
max_library_bytes: LIBRARY_MAX_BYTES,
entry_path: entry.path,
},
FLUTTER_ALLOWANCES.libraryRead,
),
);
hash.update(view);
if (kind === "libapp") snapshotScanner.push(view);
else {
labeledScanner.push(view);
await engineFile!.handle.writeFile(view);
}
// Enforce the cumulative cap inside the chunk loop so refusal
// happens before the remaining bytes are streamed and hashed.
if (extractedTotal + bytes > TOTAL_EXTRACTION_MAX_BYTES)
return err(
new AnalysisResourceConstraintError(
operation,
"file-size",
`cumulative library extraction across ${String(flutterEntries.length)} entries exceeds the ${String(TOTAL_EXTRACTION_MAX_BYTES)}-byte budget`,
{ max_total_bytes: TOTAL_EXTRACTION_MAX_BYTES },
FLUTTER_ALLOWANCES.cumulativeExtraction,
),
);
}
extractedTotal += bytes;
const digest = hash.digest("hex");
const current = facts.get(abi) ?? emptyFacts();
if (kind === "libapp") {
const scan = snapshotScanner.result();
if (scan.capped)
return err(
new AnalysisResourceConstraintError(
operation,
"memory",
"Snapshot hash candidates exceed the retained evidence budget",
{
max_snapshot_hash_candidates: MAX_SNAPSHOT_HASH_CANDIDATES,
entry_path: entry.path,
},
FLUTTER_ALLOWANCES.snapshotHashCandidates,
),
);
facts.set(abi, {
...current,
libapp: {
present: true,
bytes,
sha256: digest,
elfHeaderValid:
readElfHeader(headerPrefix.subarray(0, headerBytes), bytes)
.header !== undefined,
sources: scan.sources,
candidates: scan.candidates,
},
});
} else {
const labeled = labeledScanner.result();
const buildIds = await readElfBuildIds(
engineFile!.handle,
bytes,
signal,
);
await this.releaseResource(snapshot.root, engineFile!);
facts.set(abi, {
...current,
libflutter: {
present: true,
bytes,
sha256: digest,
buildId:
buildIds.failures.length === 0 && buildIds.candidates.length === 1
? buildIds.candidates[0]!
: null,
buildIdCandidates: buildIds.candidates,
buildIdFailures: buildIds.failures.map((failure) => failure.reason),
...labeled,
},
});
}
}
const abis = [...facts.entries()]
.map(([abi, value]) => ({
abi,
libapp: {
present: value.libapp.present,
bytes: value.libapp.bytes,
sha256: value.libapp.sha256,
elf_header_valid: value.libapp.elfHeaderValid,
snapshot_hash_sources: value.libapp.sources,
snapshot_hash_candidates: [...value.libapp.candidates],
snapshot_hash:
value.libapp.candidates.length === 1
? value.libapp.candidates[0]!
: null,
},
libflutter: {
present: value.libflutter.present,
bytes: value.libflutter.bytes,
sha256: value.libflutter.sha256,
build_id: value.libflutter.buildId,
build_id_candidates: [...value.libflutter.buildIdCandidates],
dart_version: value.libflutter.dartVersion,
dart_version_capped: value.libflutter.dartVersionCapped,
toolchain_lines: [...value.libflutter.toolchainLines],
toolchain_capped: value.libflutter.toolchainCapped,
},
}))
.sort((left, right) => compareUnicodeCodePoints(left.abi, right.abi));
const flutterDetected = abis.some((entry) => entry.libapp.present);
const partial =
abis.some(
(entry) =>
(entry.libapp.present &&
(entry.libapp.snapshot_hash === null ||
entry.libapp.snapshot_hash_sources !== 2 ||
entry.libapp.elf_header_valid !== true)) ||
entry.libflutter.toolchain_capped ||
entry.libflutter.dart_version_capped ||
entry.libapp.present !== entry.libflutter.present,
) ||
[...facts.values()].some(
(value) =>
value.libflutter.buildIdFailures.length > 0 ||
value.libflutter.buildIdCandidates.length > 1,
);
return ok(
createAnalysisExecution(
{
target: { path, bytes: snapshot.bytes, sha256: snapshot.sha256 },
flutter_detected: flutterDetected,
abis,
coverage: partial ? "partial" : "complete",
},
FLUTTER_PROVIDER_IDENTITY,
{
subject: { path, format: "apk", sha256: snapshot.sha256 },
locations: [{ kind: "artifact-path", path }],
limitations: [
"The APK is read through an owned read-only snapshot; concurrent changes to the original cannot mix into this observation",
"The snapshot hash identifies a Dart SDK build only against an external mapping dataset; REA performs no lookup",
"Unlabeled Dart version values are identified by their printable-string shape, not a symbol or other source identity; a matching unrelated string may be reported and a null value means no supported pattern was found",
"Engine build IDs come only from ELF-declared PT_NOTE/SHT_NOTE records; conflicting or incompletely examined notes preserve candidates and report partial coverage",
...[...facts].flatMap(([abi, value]) => [
...value.libflutter.buildIdFailures.map(
(reason) => `lib/${abi}/libflutter.so: ${reason}`,
),
...(value.libflutter.buildIdCandidates.length > 1
? [`lib/${abi}/libflutter.so has conflicting GNU build IDs`]
: []),
]),
...abis
.filter((entry) => entry.libflutter.toolchain_capped)
.map(
(entry) =>
`lib/${entry.abi}/libflutter.so has toolchain labels omitted by the complete-label grammar or the 4-line projection`,
),
...abis
.filter((entry) => entry.libflutter.dart_version_capped)
.map(
(entry) =>
`lib/${entry.abi}/libflutter.so has Dart version labels omitted by the complete-label grammar or the single-version projection`,
),
"The snapshot hash sits 20 bytes after each snapshot magic in the AOT payload; findings are observations of that layout",
"ELF header validity checks the supported header layout and declared table extents; identification does not resolve symbols or validate table contents",
...abis
.filter(
(entry) =>
entry.libapp.present &&
entry.libapp.snapshot_hash_sources !== 2,
)
.map(
(entry) =>
`lib/${entry.abi}/libapp.so carries ${String(entry.libapp.snapshot_hash_sources)} observed snapshot header(s); complete coverage of the supported legacy split VM/isolate profile requires two independent sources. Unified and other layouts remain unverified`,
),
...abis
.filter(
(entry) =>
entry.libapp.present &&
entry.libapp.elf_header_valid !== true,
)
.map(
(entry) =>
`lib/${entry.abi}/libapp.so has a truncated, malformed, or unsupported ELF header or table extent; byte-scanned hashes remain observations only`,
),
...(flutterDetected
? []
: [
"No lib/*/libapp.so was found; the target does not carry a Flutter AOT payload",
]),
],
},
),
);
}
private async inspectDartAot(
path: string,
abi: string | undefined,
signal: AbortSignal | undefined,
snapshot: OwnedSnapshot,
reader: ZipArtifactReader,
libraries: readonly FlutterLibrary[],
poolPolicy: DartPoolPolicy,
): Promise<Result<AnalysisExecution, AnalysisError>> {
const candidates = libraries.filter((library) => library.kind === "libapp");
if (candidates.length === 0)
return err(
new AnalysisUnsupportedTargetError(
"inspect_dart_aot",
path,
"No lib/<abi>/libapp.so was found; the target carries no Dart AOT payload",
),
);
const preference = ["arm64-v8a", "x86_64", "x86", "armeabi-v7a"];
const selected =
abi === undefined
? [...candidates].sort(
(left, right) =>
(preference.indexOf(left.abi) + 1 || preference.length + 1) -
(preference.indexOf(right.abi) + 1 || preference.length + 1) ||
compareUnicodeCodePoints(left.abi, right.abi),
)[0]!
: candidates.find((candidate) => candidate.abi === abi);
if (selected === undefined)
return err(
new AnalysisUnsupportedTargetError(
"inspect_dart_aot",
path,
`No libapp.so was found for ABI ${abi ?? "(none)"}; available: ${candidates
.map((candidate) => candidate.abi)
.join(", ")}`,
),
);
const declared = selected.entry.declaredSize ?? LIBRARY_MAX_BYTES + 1;
if (declared > LIBRARY_MAX_BYTES)
return err(
new AnalysisResourceConstraintError(
"inspect_dart_aot",
"file-size",
`lib/${selected.abi}/libapp.so declares ${String(declared)} bytes, exceeding the ${String(LIBRARY_MAX_BYTES)}-byte read budget`,
{ max_library_bytes: LIBRARY_MAX_BYTES },
FLUTTER_ALLOWANCES.libraryRead,
),
);
const imagePath = join(snapshot.root, "libapp.so");
const imageHash = createHash("sha256");
const imageWriter = this.ownResource(
snapshot.root,
new OwnedFileHandle(await openFile(imagePath, "wx")),
);
{
const stream = openEntrySafely(
reader,
selected.entry,
"inspect_dart_aot",
path,
signal,
);
let total = 0;
for await (const chunk of stream) {
if (signal?.aborted === true)
return err(cancelledBy("inspect_dart_aot", signal));
const view = chunk as Buffer;
total += view.byteLength;
if (total > LIBRARY_MAX_BYTES)
return err(
new AnalysisResourceConstraintError(
"inspect_dart_aot",
"file-size",
`lib/${selected.abi}/libapp.so exceeds the ${String(LIBRARY_MAX_BYTES)}-byte read budget while streaming`,
{ max_library_bytes: LIBRARY_MAX_BYTES },
FLUTTER_ALLOWANCES.libraryRead,
),
);
imageHash.update(view);
await imageWriter.handle.writeFile(view);
}
}
await this.releaseResource(snapshot.root, imageWriter);
const imageSha256 = imageHash.digest("hex");
// Allocate exactly the budget-checked size before reading, so the
// buffer cannot exceed the declared library size plus one byte.
const image = Buffer.alloc(declared + 1);
let imageLength = 0;
{
const file = this.ownResource(
snapshot.root,
new OwnedFileHandle(await openFile(imagePath, "r")),
);
while (imageLength < image.length) {
if (signal?.aborted === true)
return err(cancelledBy("inspect_dart_aot", signal));
const result = await file.handle.read(
image,
imageLength,
image.length - imageLength,
null,
);
assertArtifactReadActive(signal);
if (result.bytesRead === 0) break;
imageLength += result.bytesRead;
}
await this.releaseResource(snapshot.root, file);
}
assertArtifactReadActive(signal);
const bounded = image.subarray(0, imageLength);
const symbolNames = [
"_kDartVmSnapshotData",
"_kDartVmSnapshotInstructions",
"_kDartIsolateSnapshotData",
"_kDartIsolateSnapshotInstructions",
];
const sections: {
name: string;
offset: number;
size: number;
magic_valid: boolean;
kind: number | null;
header_length: number | null;
}[] = [];
const dataHeaders: {
name: string;
offset: number;
size: number;
header: ReturnType<typeof readSnapshotHeader>;
}[] = [];
let isolateData: Buffer | null = null;
const inventory = await readElfSymbols(bounded, symbolNames, signal);
for (const symbol of inventory.symbols) {
const name = symbol.name;
const header = name.endsWith("Data")
? readSnapshotHeader(
bounded.subarray(symbol.offset, symbol.offset + symbol.size),
0,
)
: null;
sections.push({
name,
offset: symbol.offset,
size: symbol.size,
magic_valid: header?.magicValid ?? false,
kind: header?.kind ?? null,
header_length: header?.headerLength ?? null,
});
if (header !== null) dataHeaders.push({ ...symbol, header });
if (name === "_kDartIsolateSnapshotData")
isolateData = image.subarray(
symbol.offset,
symbol.offset + symbol.size,
);
}
// Each exported data symbol owns one header at its start. Matching
// records elsewhere in a symbol are not evidence for the other
// symbol's hash. Count a physical header only once for aliased exports.
const observedOffsets = new Set<number>();
let aliasedDataSymbols = false;
const hashes: string[] = [];
for (const section of dataHeaders) {
if (observedOffsets.has(section.offset)) {
aliasedDataSymbols = true;
continue;
}
observedOffsets.add(section.offset);
if (section.header.hash !== null) hashes.push(section.header.hash);
}
const hashScan = {
sources: hashes.length,
candidates: [...new Set(hashes)],
};
const overlappingDataSymbols = dataHeaders.some((section, index) =>
dataHeaders
.slice(0, index)
.some(
(previous) =>
previous.offset < section.offset + section.size &&
section.offset < previous.offset + previous.size,
),
);
if (sections.length === 0) {
// This is a profile diagnostic, not aliases for the split data sources.
// Probe only after the legacy selection fails, leaving its normal path
// and two-source completeness rule unchanged.
const unified = await readElfSymbols(
bounded,
["_kDartSnapshotData", "_kDartSnapshotText"],
signal,
);
if (unified.symbols.length > 0)
return err(
new AnalysisUnsupportedTargetError(
"inspect_dart_aot",
path,
"Observed unified Dart snapshot exports; this reader supports the legacy split VM/isolate profile (Dart 2.14 FullAOT kind 3). The unified profile is unsupported, not missing legacy data",
{
diagnostics: {
supported_profile: "dart-2.14-split-full-aot",
observed_exports: unified.symbols.map(
({ name, offset, size }) => ({ name, offset, size }),
),
abi: selected.abi,
libapp_sha256: imageSha256,
libapp_bytes: imageLength,
},
},
),
);
return err(
new AnalysisUnsupportedTargetError(
"inspect_dart_aot",
path,
`No recognizable legacy split Dart snapshot symbols were found: ${inventory.failures.map((failure) => failure.reason).join("; ")}`,
),
);
}
const pool = await projectStringPool(isolateData, signal, poolPolicy);
const snapshotPartial =
inventory.failures.length > 0 ||
aliasedDataSymbols ||
overlappingDataSymbols ||
sections.length < symbolNames.length ||
dataHeaders.length !== SYMBOL_PAIR_COUNT ||
dataHeaders.some((section) => !section.header.complete) ||
hashScan.candidates.length !== 1 ||
hashScan.sources !== SYMBOL_PAIR_COUNT;
const poolBudgetsReached = new Set<DartPoolBudget>(pool.limitsReached);
if (
pool.packageUriCount > poolPolicy.uri_limit ||
pool.dartUriCount > poolPolicy.uri_limit
)
poolBudgetsReached.add("uri_limit");
if (pool.classLikeTokenCount > poolPolicy.token_limit)
poolBudgetsReached.add("token_limit");
const poolPartial =
isolateData === null ||
pool.collectionCapped ||
pool.packageUriCount > poolPolicy.uri_limit ||
pool.dartUriCount > poolPolicy.uri_limit ||
pool.classLikeTokenCount > poolPolicy.token_limit;
return ok(
createAnalysisExecution(
{
target: { path, bytes: snapshot.bytes, sha256: snapshot.sha256 },
abi: selected.abi,
libapp: {
coverage: snapshotPartial ? "partial" : "complete",
bytes: imageLength,
sha256: imageSha256,
snapshot_hash:
hashScan.candidates.length === 1 ? hashScan.candidates[0]! : null,
snapshot_hash_candidates: [...hashScan.candidates],
snapshot_hash_sources: hashScan.sources,
sections,
},
string_pool: {
policy: { ...poolPolicy },
coverage: poolPartial ? "partial" : "complete",
package_uris: pool.packageUris.slice(0, poolPolicy.uri_limit),
package_uri_count_at_least: pool.packageUriCount,
dart_uris: pool.dartUris.slice(0, poolPolicy.uri_limit),
dart_uri_count_at_least: pool.dartUriCount,
class_like_tokens: pool.classLikeTokens.slice(
0,
poolPolicy.token_limit,
),
class_like_token_count_at_least: pool.classLikeTokenCount,
printable_run_count: pool.printableRunCount,
...(poolBudgetsReached.size === 0
? {}
: {
limits: [...poolBudgetsReached].map((budget) =>
dartPoolBudgetLimit(budget, poolPolicy),
),
}),
},
coverage: snapshotPartial || poolPartial ? "partial" : "complete",
},
FLUTTER_PROVIDER_IDENTITY,
{
subject: { path, format: "apk", sha256: snapshot.sha256 },
locations: [{ kind: "artifact-path", path }],
limitations: [
"The APK is read through an owned read-only snapshot; concurrent changes to the original cannot mix into this observation",
"Snapshot sections are located through the ELF dynamic symbol table; a payload without exported snapshot symbols is refused rather than guessed",
"Snapshot hash sources are the headers at the start of the VM and isolate data symbols; complete decoding supports kind 3 (the Dart 2.14 FullAOT layout), a valid hash and a declared length that fits its symbol, including the four magic bytes; other kind values remain observed with partial coverage",
"String-pool entries are byte-pattern observations from the isolate data section, not deserialized cluster semantics; typed class and function recovery needs an SDK-specific parser",
"class_like_tokens are identifier-shaped runs and include incidental matches",
"URI/token counts are lower bounds for runs matching pool_policy.contains: distinct collection stops at twice each selected projection bound. printable_run_count counts complete printable runs before filtering; overflowed runs are omitted, never fabricated as prefixes",
...inventory.failures.map((failure) => failure.reason),
...(sections.length < symbolNames.length
? [
`Only ${String(sections.length)} of 4 snapshot symbols were present`,
]
: []),
...(aliasedDataSymbols
? [
"Two or more snapshot data symbols share one header offset; its hash counts as one source instead of two agreeing ones",
]
: []),
...(overlappingDataSymbols && !aliasedDataSymbols
? [
"Snapshot data symbol ranges overlap; independent VM/isolate coverage is not established",
]
: []),
...dataHeaders
.filter((section) => !section.header.complete)
.map(
(section) =>
`${section.name} has an incomplete or invalid snapshot header: kind ${String(section.header.kind)} (AOT app requires 3), declared length ${String(section.header.headerLength)} excludes the four magic bytes, symbol size ${String(section.size)}, valid hash ${String(section.header.hash !== null)}`,
),
...pool.limitsReached.map(
(limit) =>
`String-pool admission reached pool_policy.${limit}=${String(poolPolicy[limit])}. Retry with a narrower pool_policy.contains or increase ${limit}; string_pool.limits records the control and no REA restart is required. Counts remain lower bounds and overflowed runs are omitted. APK, library and response limits are unchanged`,
),
...(pool.dartUriCount > poolPolicy.uri_limit
? [
`dart_uris reports ${String(poolPolicy.uri_limit)} of at least ${String(pool.dartUriCount)} distinct URIs; narrow pool_policy.contains or raise pool_policy.uri_limit (recorded in string_pool.limits) on a new call, no restart required`,
]
: []),
...(pool.packageUriCount > poolPolicy.uri_limit
? [
`package_uris reports ${String(poolPolicy.uri_limit)} of at least ${String(pool.packageUriCount)} distinct URIs; narrow pool_policy.contains or raise pool_policy.uri_limit (recorded in string_pool.limits) on a new call, no restart required`,
]
: []),
...(pool.classLikeTokenCount > poolPolicy.token_limit
? [
`class_like_tokens reports ${String(poolPolicy.token_limit)} of at least ${String(pool.classLikeTokenCount)} distinct tokens; narrow pool_policy.contains or raise pool_policy.token_limit (recorded in string_pool.limits) on a new call, no restart required`,
]
: []),
],
},
),
);
}
}
/**
* Categorize printable runs from one snapshot data section. Collection stops
* admitting new distinct entries once each category reaches its projection
* bound times a slack factor, so allocation and sorting stay proportional to
* the response rather than to an adversarial payload; counts still reflect
* how far scanning proceeded before the collection cap tripped.
*/
const projectStringPool = async (
section: Buffer | null,
signal: AbortSignal | undefined,
poolPolicy: DartPoolPolicy,
): Promise<{
packageUris: string[];
packageUriCount: number;
dartUris: string[];
dartUriCount: number;
classLikeTokens: string[];
classLikeTokenCount: number;
printableRunCount: number;
collectionCapped: boolean;
limitsReached: readonly DartPoolBudget[];
}> => {
const packages = new Set<string>();
const darts = new Set<string>();
const tokens = new Set<string>();
let runCount = 0;
const limitsReached = new Set<DartPoolBudget>();
const COLLECTION_SLACK = 2;
// Input bytes bound useful capacity before slack multiplication; large safe
// integer requests never overflow the collection-budget arithmetic.
const packageBudget =
Math.min(poolPolicy.uri_limit, section?.length ?? 0) * COLLECTION_SLACK;
const dartBudget = packageBudget;
const tokenBudget =
Math.min(poolPolicy.token_limit, section?.length ?? 0) * COLLECTION_SLACK;
if (section !== null) {
let run = "";
const consider = (text: string): void => {
if (text.length < 5) return;
runCount += 1;
if (
poolPolicy.contains !== undefined &&
!text.includes(poolPolicy.contains)
)
return;
if (text.startsWith("package:")) {
if (!packages.has(text) && packages.size >= packageBudget)
limitsReached.add("uri_limit");
else packages.add(text);
} else if (text.startsWith("dart:")) {
if (!darts.has(text) && darts.size >= dartBudget)
limitsReached.add("uri_limit");
else darts.add(text);
} else if (IDENTIFIER_PATTERN.test(text)) {
if (text.length > poolPolicy.token_bytes)
limitsReached.add("token_bytes");
else if (!tokens.has(text) && tokens.size >= tokenBudget)
limitsReached.add("token_limit");
else tokens.add(text);
}
};
let overflowed = false;
for (let start = 0; start < section.length; start += 64 * 1024) {
await yieldToEventLoop();
assertArtifactReadActive(signal);
for (const byte of section.subarray(start, start + 64 * 1024)) {
if (byte >= 0x20 && byte < 0x7f) {
// A single unbounded run (an adversarial NUL-free section) never
// materializes: growth stops at the cap and the entire run is
// discarded at its delimiter, since a truncated prefix would be
// fabricated evidence rather than an observation.
if (run.length < poolPolicy.run_bytes)
run += String.fromCharCode(byte);
else {
overflowed = true;
limitsReached.add("run_bytes");
}
} else {
if (!overflowed) consider(run);
overflowed = false;
run = "";
}
}
}
if (!overflowed) consider(run);
}
assertArtifactReadActive(signal);
return {
packageUris: [...packages].sort(),
packageUriCount: packages.size,
dartUris: [...darts].sort(),
dartUriCount: darts.size,
classLikeTokens: [...tokens].sort(),
classLikeTokenCount: tokens.size,
printableRunCount: runCount,
collectionCapped: limitsReached.size > 0,
limitsReached: [...limitsReached],
};
};