mirror of
https://github.com/morluto/rea.git
synced 2026-11-25 21:59:09 +00:00
* refactor(process): share executable lookup with provider commands Process capture owned the only spawn-equivalent PATH lookup, wrapped in scenario-specific errors. Move the lookup into src/process as a result type, so a provider command can resolve an executable once, hash it and then run that same file. Process capture maps the result to its existing errors unchanged. * feat(rizin): record which tool and version answered execute_rizin_command execute_rizin_command recorded version null and labelled any executable selected by REA_RIZIN_COMMAND as Rizin, although radare2 also accepts REA's argument list. Before the first command for each executable digest, resolve the selected executable through PATH, hash it, run it with -v and read its banner; the command then runs the same file. The Evidence provider records the tool name and version, and the parameters record the resolved executable path, its SHA-256 and the banner line. A tool other than Rizin still runs, with a limitation; a failed, timed out or unrecognized probe leaves the version unknown. Each digest's reading, including a failure, is reused for the life of the process, and concurrent first calls share one probe within the caller's command_timeout_ms budget. A caller that stops waiting cancels the probe only when no other caller needs it. A probe whose process cleanup is incomplete stays retained for retry. * fix(rizin): probe per call and reuse only completed probes Sharing an in-flight version probe between callers let a joining call outlive its own command_timeout_ms and inherit another caller's cancellation, and the cache was keyed by digest alone, so byte-identical launchers in different directories shared one reading. Remove the sharing: each call runs its own probe under its own deadline and cancellation. Reuse only completed probes (a banner, a non-zero exit or a timeout), keyed by the resolved launch path and its SHA-256. The executable lookup now honours the call's deadline and cancellation, so a stalled PATH entry cannot hang a call or close(). A failed probe records its exit status and bounded stdout and stderr in provider_version_probe, and a cancelled probe keeps its captured output on the error. * fix(rizin): never let a later probe failure replace a successful reading Concurrent first calls can each probe the same launch path and digest. When one probe printed a banner and another later timed out or exited non-zero, the failure overwrote the cached reading, so every later call reported an unknown version for the life of the server. Route the cache write through one rule: a failure never replaces a successful reading, and a success replaces an earlier failure. Each call still reports its own probe's outcome. * docs(rizin): state what the executable digest and version observe The guide said the command "runs the same file" as the version probe. REA runs the same resolved path; the recorded SHA-256, tool and version describe the file there when REA checked it. Say so, with the limit the guide already states for artifact digests: they cannot prove the exact bytes executed if the file changes before the launch. * test(rizin): pin the banner a real Rizin 0.9.1 printed Homebrew's Rizin 0.9.1 prints `rizin 0.9.1 @ darwin-arm-64, package: 0.9.1_2 (Homebrew)`, with a package suffix after the platform. The identity test now uses that banner, so a parser that expects the line to end at the platform fails; the other tests keep the plain form. The test name and the probe comment now say REA runs the path it hashed and reuses a completed probe per launch path and digest, as the guide says sincec73a0be9c. * fix(rizin): replace the service's lookup and execution together Tests that injected a fake runner still resolved `rizin` through the host PATH. With Rizin installed, the version probe took the fake runner's first canned result, and three tests in reverseEngineering.test.ts failed. CI has no Rizin, so they passed there. The service now takes one `processes` option: the executable lookup with either a runner or the owned-process primitive. It replaces `run` and `runOwned`, so a fake runner cannot be paired with the host lookup. Omitting it keeps the host lookup and owned execution. The lookup no longer reads the service's `stat` seam. The test service pairs a fake runner with a lookup that finds nothing unless the test passes one; the identity tests pass the real lookup explicitly. A new test puts an executable `rizin` first on PATH with a fake runner and checks that each command gets its canned result, and that the options type rejects a runner without its lookup. * fix(rizin): end the call when hashing the executable reaches the deadline When hashing the resolved executable reached command_timeout_ms, digestFile rejected with ETIMEDOUT and the service recorded an unknown identity, then launched the caller's command with a fresh deadline. A caller-selected, possibly side-effecting command ran after its preflight deadline had passed. The hash deadline now returns AnalysisTimeoutError with phase executable_digest, as the lookup's deadline already did, and the timeout guidance names executable identification among the phases. A test stalls the executable's stat past a 50 ms deadline and checks that nothing runs. * fix(rizin): bound kept version probes and keep only complete readings The probe cache kept one entry per launch path and digest and never evicted one, and a kept banner could be as long as the 16 MiB capture. It now keeps the latest completed probe per launch path with the digest it read; a new digest replaces it, and a later failure still never replaces a successful reading of the same digest. The service reads the banner (the first stdout line, trimmed), keeps at most 2,048 characters of it and records provider_version_banner_truncated; the provider's parser now reads that bounded banner, so everything a probe keeps is bounded. A -v output that was not valid UTF-8 was parsed anyway, so replacement characters could become provider.version. It now leaves the version unknown, with a limitation saying the output is not valid UTF-8. An owned probe whose output was not fully collected was labelled failed when it carried a numeric exit status, and cached. A collection failure is now checked first: the probe is unfinished, is not kept, and its diagnostics report no exit status. Tests cover a digest change replacing the kept probe, a capped banner, undecodable output and a collection failure that is probed again. * fix(rizin): keep only probe outcomes that describe the executable A timed-out version probe was kept for its launch path and digest, so a later call with a longer command_timeout_ms reused it without probing: its Evidence said the probe reached the command deadline, and the version stayed unknown until the executable changed. A timeout is a fact about one call's deadline, not about the file. Each probe outcome now carries its scope in its type: a reading, a failed exit and undecodable output describe the executable and are kept; a timeout and unfinished output describe the call and are not. The cache accepts only executable-scoped outcomes, so the call site no longer filters. Both runners report a deadline as ETIMEDOUT, which the probe checks before any signal, so a stopped probe is always timed-out. A test times out a probe through the owned runner's deadline failure, then checks that a call with a longer deadline probes again and reads the version. * fix(rizin): flag invalid UTF-8 in version-probe diagnostics When -v exited nonzero or timed out with output that was not valid UTF-8, provider_version_probe kept the decoded text, replacement characters included, with no flag. Undecodable output's stderr had the same gap. The failure capture (execFileOutputFailure) now reads the runner's stdoutInvalidUtf8 and stderrInvalidUtf8, as it already reads collectionFailure. The probe diagnostics record them for every outcome that keeps output, as stdout_invalid_utf8 and stderr_invalid_utf8, following gdb Evidence's stderr_invalid_utf8. The command path takes its flags from the same capture instead of reading the owned failure directly. The guide names the two fields. Tests cover failed and timed-out probes with invalid stdout or stderr, undecodable output on both streams, and a failed command whose stdout is not valid UTF-8, which pins the command path's flags to the capture. * fix(rizin): mark the provider as assumed when no banner identifies it When the -v banner did not match, identifyRizinTool returned Rizin's identity with no limitation, so Evidence named Rizin although nothing identified the tool; the limitation qualified only the version and formats. Failed, timed-out and undecodable probes, and an executable that could not be located or read, named Rizin the same way. The Evidence provider schema requires a name, so the tool cannot be recorded as unknown. The parser now returns no identification for a banner it does not recognise. Wherever no banner identified the tool, the service keeps the configured identity, sets provider_identity to "assumed" and adds the probe's assumed-identity limitation, which the Rizin probe owns; an identified tool gets provider_identity "banner". The guide and the tool description say so. Tests cover an empty first line and a Usage: banner; two composition tests now count the added limitation. * fix(rizin): keep invalid UTF-8 flags in typed errors' captured output A cancelled or cleanup-incomplete version probe carried captured output from execFileFailureCapturedOutput, which dropped the runner's invalid-UTF-8 flags, so its replacement characters looked like provider output. The command path's own captured output had the same gap when cancellation ended a run or a failure was captured. AnalysisCapturedOutput gains stdout_invalid_utf8 and stderr_invalid_utf8, set to true only when the runner reported invalid UTF-8, as command observations mark output_invalid_utf8. The shared projection fills them through capturedInvalidUtf8, and the command path's two captured outputs use the same helper, so every consumer of a runner's failure report keeps them. The guide mentions the markers. Tests cover a cancelled and a cleanup-incomplete probe, and a command cancelled during and after its run, each with invalid UTF-8 output. * fix(rizin): probe the executable before every command A launcher such as a version-manager shim keeps its path and SHA-256 while the tool it delegates to changes, so a reading kept for that path and digest could name a tool the command no longer runs. A shim's delegate cannot be observed, so no kept reading can be checked for freshness. Every call now probes in its own environment and under its own deadline before the command, and nothing is reused. The cache, its keep and replace rules and the outcome scopes that existed only for it are removed; without a cache, an unfinished probe is reported as failed, and its diagnostics still give no exit status when output was not fully collected. The per-call digest stays in Evidence. The guide and the tool description say each call probes. On this Mac (Homebrew rizin 0.9.1) a probe costs about 180 ms through REA's owned-process runner, of which rizin -v itself takes about 15 ms warm: the price of identifying the answering tool on every call. A test runs a launcher whose bytes stay the same while the tool it runs changes, and checks that each call reports the tool that answered. Tests that only covered the cache are removed; the rest now expect a probe per call. * test(rizin): restore the per-caller probe deadline testdd06ad27cremoved the cache-only tests with a script that also removed "runs each caller's probe under its own deadline and cancellation", which covers per-call probing: two concurrent calls each probe under their own deadline and signal, and cancelling one stops only its probe. Restore it without the reuse check that only the cache needed. * fix(rizin): read the working directory only when the lookup needs it The service passed process.cwd() to the executable lookup on every call. If the server's working directory had been removed, process.cwd() threw ENOENT before the lookup looked at an absolute REA_RIZIN_COMMAND, and executeRizinCommand rejected instead of returning its Result. lookupExecutable now takes a function for the working directory and reads it only for a relative command or PATH entry, or on Windows, where an absolute path can still depend on the working directory's drive. A failed read is a typed no-working-directory status, which the service records as an executable it could not locate, so the call still resolves to a Result. Process capture, whose working directory is already resolved, maps it to its working-directory input error. Tests make process.cwd() throw ENOENT: an absolute command and target identify and run without reading it, and a relative command or PATH entry gets a Result with an assumed identity. * fix(rizin): cut probe banners and diagnostics between code points The banner and a failed probe's two diagnostic streams were cut at 2,048 UTF-16 code units, so a cut could leave a lone surrogate. REA already owns this cut: boundedUtf8Text keeps text within a UTF-8 byte budget without splitting a code point, as other providers' probes use it. The banner and both streams now go through it with a 2,048-byte budget, and provider_version_banner_truncated and output_truncated come from its truncated flag. The guide states the limits in UTF-8 bytes. Tests cut an astral banner and astral diagnostic streams at the boundary; an ASCII banner keeps its 2,048 bytes. * fix(rizin): keep diagnostics for a banner that identifies no tool When -v exited 0 but its banner identified nothing, Evidence recorded only provider_version_banner: the probe's exit status, stderr and later stdout lines were dropped, although the guide promises provider_version_probe for any probe without a usable banner, and that is when the assumed identity needs explaining. Such a probe is now its own unrecognized outcome. It keeps the banner and versionProbeDiagnostics(0, output), like the other unusable outcomes, and Evidence records both; a recognized banner remains read. Tests cover an empty first line with an explanatory stderr and a Usage: banner followed by more lines. * fix(rizin): identify nothing from a banner cut at its byte limit identify ran on the banner even when boundedUtf8Text had cut it, so a version token running past the 2,048-byte cut was published as an exact provider.version. A real banner is about 40 characters, so one guard is enough: a cut banner identifies nothing. It becomes the unrecognized outcome, with the probe's diagnostics and the assumed identity; no separate token parser is added. The guide says so. A test cuts a first line inside its version token; the banner-cap test now expects no version from a cut banner. * fix(rizin): accept only the -v banner Rizin and radare2 print The banner pattern ^(\S+) (\d\S*) read any first line with a digit token as an identity, so `Warning: 123 …` became tool "Warning:", version 123. identifyRizinTool now accepts only the first-line form Rizin and radare2 print: a plain tool token, a version, any build tokens, then `@ <os>-<arch>-<bits>` and an optional `, <package>` suffix. The real banners on this Mac fix the form: Rizin 0.9.1 (Homebrew) prints `rizin 0.9.1 @ darwin-arm-64, package: 0.9.1_2 (Homebrew)`, and radare2 6.1.8 prints `radare2 6.1.8 +0 abi:110 @ darwin-arm_64`. Anything else is unrecognized, with the assumed identity and the probe's diagnostics; a well-formed radare2 banner keeps its non-Rizin limitation. The guide gives the form. Tests cover `Warning: 123 …`, a status line before the banner, a banner without the @ suffix, and the real Rizin and radare2 banners. Two fixtures that printed `@ test` as the platform now print a real form. * fix(rizin): keep the probe's identification when the command fails to start After a successful -v probe, a command that failed to start, such as an oversized command the host refused with E2BIG, returned its typed error without the tool, version, path, SHA-256 or banner the probe had observed: only Evidence carried the identification, and these failures build none. The identification now records whether a probe ran. When one did, the launch failure keeps `provider` and the provider_* parameters in its diagnostics; the Evidence limitations, which describe command output, stay out. A probe that is cancelled or whose cleanup is incomplete keeps the executable path and SHA-256 it ran from. An executable that was not located or could not be read adds nothing, since nothing about it was observed. A real-process MCP test probes a fake rizin, then fails the launch with a real E2BIG (a 2 MiB command) and with ENOENT (the probe removes the executable after a banner that identifies no tool). The probe cancellation test checks the path and SHA-256. The guide says where the facts appear. * test(rizin): move tool-identity cases to boundary and process-global projects The tool-identity cases run the real executable lookup and file digest, which crosses the production filesystem boundary, so they move from the shared-worker composition project to tests/boundary/filesystem. The two cases that replace process.cwd move to tests/process-global, whose isolated forks keep that process-global state from leaking into other files. The fixture, fake runner and probe count they share move to tests/support/rizinToolIdentity.ts. * fix(process): resolve each PATH entry only when the lookup reaches it Candidate construction resolved every PATH entry up front, so a relative entry after the match (PATH=/opt/rizin/bin:.) read the working directory before the absolute entry was checked. With that directory removed, the lookup reported no-working-directory and skipped hashing and probing, while the bare command still ran from /opt/rizin/bin with an assumed identity. Each entry now resolves when the search reaches it. * fix(rizin): run the found executable when it cannot be read for hashing When the lookup found an executable that the hash could not read, such as a native binary with mode 0111, identification fell back to the bare command name. The command then searched PATH again instead of running the file the lookup selected, so another executable could answer, and Evidence lost the path that was observed. The fallback now keeps the found path for the launch and as provider_executable_path, without a SHA-256 or probe. The flag that keeps these facts on a launch failure is renamed from probed to observed, since it now also covers a lookup whose hash failed. * fix(rizin): leave the version unknown when probe stderr is not valid UTF-8 An exit-0 probe with a valid stdout banner and malformed stderr was accepted as a banner, and the read outcome dropped the probe's diagnostics, so Evidence published the version while losing stderr and its stderr_invalid_utf8 marker. The documentation says output that is not valid UTF-8 leaves the version unknown; the probe now checks both streams before reading a banner. * fix(process): report no exit status for output that was not fully collected execFileFailureCapturedOutput published a failed run's numeric exit code even when its output was not fully collected. The command path and the version probe's diagnostics already report null for that status, so a probe that lost output and whose cleanup also failed carried conflicting completion facts: null in provider_version_probe, a number in the error's captured_output. The shared projection now owns the rule, which also applies it to the ADB, Ghidra launcher, Doctor, Apple asset catalog and Darwin process-token failures that use it. * fix(rizin): bound the version banner as printed before trimming it The probe trimmed the first line before applying its 2,048-byte budget, so a line with more than 2,048 bytes of leading whitespace before a valid banner lost that prefix unrecorded and was identified, with provider_version_banner_truncated false, although the documented budget covers the banner line. The budget and the recorded banner now cover the line as printed; only identification reads a trimmed copy. * fix(process): continue the PATH search past an unreadable relative entry With the working directory removed and PATH starting with "." or an empty entry, the lookup stopped at that entry with no-working-directory. A spawned search finds nothing under a removed directory and moves on, so the command still ran a later match by its bare name, while Evidence reported an assumed identity without path, digest or version. The lookup now skips such an entry and reports the unread working directory only when no later entry matches; an explicit relative command still reports it at once. * fix(rizin): keep the found executable path when hashing it ends the call When the hash of a PATH-selected executable reached the deadline or was cancelled, the typed error kept only its phase. The call returns no Evidence then, so the caller lost the provider_executable_path the lookup had observed and could not tell which PATH location stalled, although a cancelled probe and a failed hash keep that path. Both errors now carry it in details.diagnostics beside the phase. * fix(rizin): keep the PATH candidate a stalled lookup was checking When the stat or access of a PATH candidate reached command_timeout_ms or was cancelled, the lookup reported only that it was interrupted, so the typed error carried phase executable_lookup and nothing else. The caller could not tell which PATH location stalled, as on a slow network mount. The interrupted lookup now returns the candidate it was checking, and both errors carry it as executable_lookup_candidate. * fix(rizin): state that the executable digest precedes both launches REA hashes the selected executable before the -v probe and the command run, so a file replaced in between gives a SHA-256 of the old file beside the identity and output of the new one. The documentation said so, but inline Evidence did not. Evidence that records provider_executable_sha256, identified or assumed, now carries a limitation saying the digest was read before both launches and does not prove the bytes that ran. * fix(process): check an unreadable relative PATH entry as written12244b7a3skipped a relative PATH entry whose working directory could not be read, assuming nothing under a removed directory is reachable. The kernel still resolves `..` from a removed directory, so with PATH=../bin:/usr/bin a spawned search runs ../bin/rizin while the lookup selected /usr/bin/rizin, and the service probed and ran that other tool. Such an entry is now checked as written, against the process's working directory: an entry without the executable lets the search continue, and a match there ends the lookup with no-working-directory, so the launch by name follows PATH order. * test(rizin): join the hash-interruption call before teardown The hash-interruption test waited for its gate with a bounded wait and only released the gate and aborted the caller in finally, so a failed wait left the call running past teardown. It now waits through awaitAcknowledgement, keeps the call in pending, and in finally releases the gate, aborts, joins the call and closes the service, as the stalled-lookup test does. * fix(rizin): keep the selected executable when the command fails to start When the command failed to start after identification, for example with E2BIG, the error kept the provider, the resolved path, the digest and the banner, but not the executable the caller selected. Evidence records it as provider_executable, and only the ENOENT launch branch carried it as command; an E2BIG resource constraint carries just argument_bytes, so a bare alias or configured path was lost. The retained diagnostics now include provider_executable beside the lookup, hash and probe facts. * fix(rizin): keep the selected executable on every error before Evidence7a003942akept provider_executable only on a launch failure after identification. The lookup's, the hash's and the probe's errors also end the call before Evidence exists, as does a launch failure without identification facts, and none of them kept the executable the caller selected, so a bare alias or relative spelling was lost. The service now adds provider_executable to an identification error where it returns, and to every launch failure, with the observed facts only when there are some. inspect_with_objdump's launch failures keep it too. * fix(rizin): mark a version probe whose completion is unknown When the owned runner reported a collection failure with completed cleanup and the partial streams fit the 2,048-byte cut, the probe's diagnostics showed output_truncated false and no completeness field; only the nulled exit code hinted that bytes were missing. The probe's diagnostics now carry completion_status with the command's own rule: unknown when output was not fully collected or the probe was killed, signalled or left no exit code, and complete otherwise. * fix(process): end the PATH search at errors a spawned search stops at The lookup moved past every PATH candidate whose stat failed. A spawned search moves past only a missing file, a non-directory and a denied directory; at any other error, such as a symlink loop (ELOOP), it stops and the launch fails. With PATH=<loop>:/usr/bin, the lookup selected /usr/bin/rizin and the service hashed, probed and ran it, although a launch by name fails. The search now ends there, reporting the error in checked, so the launch by name fails as a spawned search would. A non-executable file earlier on PATH still lets the search continue. * fix(process): end the PATH search at execute-check errors a spawn stops atc1d66e52fclassified only stat failures: the execute check still moved past any error, so an EIO from a failing network-backed PATH entry let the lookup select a later executable that a launch by name would not reach. Both checks now use one rule, searchMovesPast: a spawned search moves past ENOENT, ENOTDIR and EACCES and stops at any other error. The execute check is injectable beside stat, so the EIO case is tested. * fix(rizin): state that the version banner, too, precedes the commanda2fc5a11fqualified only the executable's SHA-256 as a pre-launch observation. The -v banner, and so the recorded tool and version, is also read before the command runs, so a package update in between attributes the command's output to the old version. The limitation, renamed EXECUTABLE_OBSERVATION_TIMING, now says the SHA-256 and any -v banner were read before the command launched and do not prove the bytes or the version that ran; the documentation says so too. * fix(process): skip PATH entries a spawned search cannot holdc1d66e52fended the search at any error a spawned search does not move past, including ENAMETOOLONG. But glibc's execvp on Linux and libuv's own search on macOS skip a PATH entry of at least PATH_MAX bytes (4,096 and 1,024) before trying it, so with a 5,000-byte entry first, a launch by name ran /usr/bin/true while the lookup reported it missing, and capture_process_scenario rejected a command that worked. Such entries are now skipped before they are checked; a shorter entry with an over-long component still stops the search with ENAMETOOLONG, as a launch by name does. On Linux the search also moves past ESTALE, ENODEV and ETIMEDOUT, as glibc's execvp does. * test(rizin): check the timing limitation through its constant only The regex added in85eb3b6c0froze the limitation's wording, which docs/testing.md rules out: guidance delivery is checked against the owning constant, beside independent assertions for the facts. The test keeps the EXECUTABLE_OBSERVATION_TIMING delivery check and its provider, path, digest and banner assertions; a harmless rewording now passes. * fix(process): skip long PATH entries only where the host's limit is known3e32a4422used a 1,024-byte limit on every host other than Linux, so on Android (Termux), where execvp has a 4,096-byte buffer, a valid 1,500-byte PATH entry was skipped and a later rizin ran. The length skip now applies only on Linux (4,096 bytes, glibc and musl) and macOS (1,024 bytes, libuv); elsewhere an over-long entry stops the lookup, and the launch by name lets the host's own search decide. By the same rule, the lookup no longer moves past ESTALE, ENODEV and ETIMEDOUT on Linux: glibc does but musl does not, so the lookup stops there too, leaving the tool unidentified rather than possibly wrong. * fix(rizin): keep a probe's timeout when its cleanup is also incomplete When the -v probe reached command_timeout_ms and stopping it left cleanup incomplete, the incomplete-cleanup branch ran first and returned an AnalysisOutputError, so the error said only that cleanup remained and lost the timeout and its remediation, even after a cleanup retry. The command path keeps the AnalysisTimeoutError and attaches the cleanup; the probe now does the same, so the timeout stays the failure, the call still ends, and the owner is retained until it stops. * fix(rizin): keep the target's path and digest on errors before Evidence The lookup, hash and probe errors, and launch failures, end the call before Evidence exists, after the target was already resolved and hashed, but kept only the selected executable and provider facts. The caller could not bind the failed attempt to the artifact it submitted. Every such error now also keeps artifact_path and artifact_sha256 for a call with a target, beside provider_executable. * test(rizin): expect the long PATH entry skip only on Linux and macOS The long-entry case required a skip on every POSIX host, but the length skip applies only on Linux and macOS; on Android and other hosts the lookup stops with ENAMETOOLONG instead, so the test failed there although the lookup behaved as intended. It now expects the skip on Linux and macOS and the stop elsewhere. * fix(rizin): defer an unstartable file to the host and bound stalled I/O The lookup took an executable regular file as the match, but a spawned PATH search also moves past a file that fails to start with ENOENT, such as a script whose interpreter is missing. Pinning the probe and the command to that file failed calls that the host would run. When the version probe does not start, the command now runs as selected, with the version unknown, and a limitation names the file. A lookup that stops waiting for a stalled stat or access leaves the call running, and later lookups of the same path now share it instead of starting another, so retries no longer add calls on an unresponsive mount. digestFile ends at its deadline or on cancellation even while the file's open is pending; a destroyed stream reports its error only after that open returns. A lookup the host refuses to inspect runs the resolved path and keeps it as provider_executable_path, also when the launch fails. Process capture verifies the file it launches, so it still rejects a scenario where native searches disagree; its docs now say so. * docs(rizin): say the lookup stops where any native search stops The lookup stops at every error other than a missing file, a non-directory or a denied directory, because at least one native search stops there; musl's stops at each of them. At a symbolic link loop or an I/O error the searches agree, so "do not agree" was wrong there. The process-capture docs and resolveExecutable's comment now state the same rule. * fix(rizin): bound stalled hash opens and defer EACCES launches The interruptible hash let each timed-out retry start another open on a stalled mount, outside the eight-operation cap. A later hash of the same path now waits, within its own deadline and cancellation, for an earlier open that has not returned, and hashes share a stalled stat through the helper lookups use, now src/process/SharedFileCall.ts. A probe launch that fails with EACCES, as for a script whose interpreter is not executable, is one a native PATH search moves past, like ENOENT, so the command now runs as selected. The shared-check test bounds its gate wait and joins its started checks in teardown. * test(rizin): return stalled opens and join their streams in finally The open-gate test returned its stalled open only after its assertions passed, and the deadline and cancellation test never returned its open, so a failed assertion, or every run, left a stream waiting on a pending open. docs/testing.md asks for held work to be released and joined in finally. A shared helper now holds each stalled open; both tests return it, destroy the stream and wait a bounded time for its close in finally, so a failed assertion is still reported as itself. * refactor(rizin): own the version-probe types in the domain layer RizinCommand.ts imported ProviderToolIdentification and ProviderVersionProbe from the application port, so the Rizin provider depended on the application layer; the architecture has Rizin depend on the domain only. Move both neutral types into src/domain/reverseEngineering.ts beside the command inputs. The port, the service and the Rizin adapter import them from there. * fix(rizin): hold a hashed path until its stream closes A hash released its path when the file's open returned. A read that a stalled mount then held kept its libuv worker after the digest timed out, while the next hash of the same path opened the file again, so repeated hashes could start stalled reads without bound. Keep each stream registered until it closes: a file stream closes only after its pending open or read returns, so a later hash of the path waits for it, and stalled opens and reads stay bounded by the paths. * fix(rizin): make hashes wait only for streams an earlier hash gave up13515107akept every hash's stream registered until it closed, so a hash waited for every earlier hash of the same path, healthy ones included, and concurrent calls on one target could spend their deadline waiting and time out before they launched. Register a stream only when its hash gives up while its open or a read is pending, and keep it until it closes. Later hashes of that path wait for those streams, so abandoned I/O stays bounded by the paths, while hashes that have not given up no longer wait for each other. * fix(rizin): keep an explicitly selected path the lookup does not accept An explicitly selected command that resolved to a file without execute permission ended the lookup as missing, with its absolute path only in the checked strings. The command then ran by its relative name, and the launch failure lost provider_executable_path. A missing lookup now reports the path an explicit selection names, and the service runs that path and keeps it, as it does for a path the host refuses to inspect. Process capture ignores the field and still rejects such a file as an invalid selection. * fix(rizin): keep an explicit path's facts when its probe does not start When the version probe of an explicitly selected path failed to start, as a script with a missing interpreter does, the command ran the selection as written and kept nothing the lookup and hash observed, so its launch failure lost the resolved path and SHA-256. An explicit selection has no later PATH candidate for the host to try. The lookup now marks a found explicit path with selectedPath, and the service runs that path and keeps its observations, while a PATH match still runs by name for the host's search to decide. * fix(rizin): launch a selection the lookup did not accept as spelled73554211blaunched the absolute path an explicit selection names whenever the lookup did not accept it. A relative selection that fits the host's path limit can have an absolute spelling that does not, so a command that launched before failed with ENAMETOOLONG. Launch the selection as the caller spelled it again, and keep the resolved path in Evidence and launch failures as provider_executable_path. A path the host refused to inspect still launches as resolved. * test(rizin): release and join the concurrent hashes in their test The concurrent-hash test left both hashes running when its wait for the second open failed, so their later rejections could hide that failure. Wait with awaitAcknowledgement, settle both hashes together, and destroy the streams and join the hashes in finally. * fix(rizin): let the host's search decide after ESTALE or ENODEV probes When the version probe of the file the lookup found failed to start with ESTALE or ENODEV, the service recorded a failed probe and ran that file again, although glibc's PATH search moves past such a file and musl's stops there. Treat both like the errors every search moves past: the command runs by name and the host's search decides, as the lookup does where native searches differ. ETIMEDOUT stays the probe's deadline, which both runners report with that code. * fix(rizin): keep a call's place until its abandoned file streams close A call that ended at its deadline while a hash's stream was stalled on an unresponsive mount freed its place among the eight concurrent operations, though the stream's read or close still held a libuv worker, so calls on different files could pile up stalled file work without bound. A successful hash also completed at its stream's end, before a close that could stall. A hash now completes when its stream closes, so a stalled close reaches the deadline as a stalled read does, and each stream a hash gives up on is reported to the service, which keeps the call's place until those streams close. The capacity error counts such calls as operations_awaiting_file_close. * test(rizin): keep disk reads and prose out of two tests The admission test for abandoned file streams called the real digestFile once its files closed, reading the disk in a composition test; its fake now returns a fixed digest. Two assertions matched the not-started limitation's whole phrase; they now check that a limitation names the skipped file and its launch error, so rewording the limitation does not fail them. * fix(rizin): give file work that a call gives up on one owner A lookup or hash that reached its deadline while a stalled mount held a stat or access check gave the call's place among the eight concurrent operations back, although that check still held a libuv worker. Streams were already held, through a separate map, a callback threaded through three layers and a second set in the service, while stat and access checks were shared through a third, module-level map. FileWork now owns all of it. Each call runs its stat, access and stream steps through a scope of the service's FileWork under one deadline. A step the deadline or cancellation interrupts is left with the scope that started it, later work on that path waits for it instead of starting more, and the service keeps the call's place until what it left has returned. A call that only waited for another call's work leaves nothing and keeps no place. The capacity error counts held calls as operations_awaiting_file_work. digestFile takes its bounds as one object, like lookupExecutable. SharedFileCall, the stream map, the onAbandoned callback and the per-step deadline helpers are removed, and the two edge-case tests that probed the gap between the old stat and stream listeners now check the single deadline instead. * fix(rizin): let a call that stops waiting for left file work detach A call waiting for file work left behind on its path raced a Promise.all over that work against its deadline. When the deadline won, the reactions stayed attached to the stalled work's promises, so retries on a stalled path kept about 2 KiB each until the mount answered: 207 MiB over 100,000 interrupted waits. Each waiting call now adds a wake function to the path's left work and removes it when it stops waiting, and the last left step on the path wakes the waiters that remain. The same measurement retains 2.5 MiB, and 4.5 MiB over 400,000 waits. * fix(rizin): keep where a stopped PATH lookup stopped When the lookup of a bare command stopped at a candidate whose error at least one native search stops at, such as ELOOP, EIO or ESTALE, the command ran by name, but Evidence and launch failures said only that the executable could not be located. The candidate and its code existed only as display text in the lookup's checked list. The lookup now returns them as stoppedAt, and the service names them in the limitation and keeps them as executable_lookup_candidate and executable_lookup_code. * fix(rizin): report held file work when the service closes close() aborted active calls, awaited their results and retried process cleanup, then resolved, although a call that had returned could still hold a stat, access or stream step that an unresponsive mount had not answered. Waiting for that work could hang shutdown on a mount that never answers, so close now fails instead with a cleanup error that names file_system_work and counts the calls holding it (operations_awaiting_file_work), and a later close checks again, as it does for retained provider processes. * fix(rizin): keep stalled file work out of closead4a22b32made close() fail while a call still held file work that a stuck mount had not returned. That error could not clear once the work returned, it hid behind a process-cleanup failure, and the CLI replaced the command's own error and Evidence with it. Close cannot release that work anyway: it cannot be cancelled, joining it would hang shutdown on a mount that never answers, and the runtime keeps the process alive until it returns. close() again aborts active calls, awaits them and retries process cleanup; the call keeps its slot until its file work returns. * fix(rizin): bound stalled file work by the thread pool Each stalled stat, access or stream step holds a thread of libuv's pool, which Node sizes at 4, while the eight-call cap allowed eight on distinct paths. Four would stall every other file, DNS and compression call in the process. The pool belongs to the process, so FileWork now has one process-wide owner, HOST_FILE_WORK, with a budget of 2 held steps. Past it a new step starts nothing: the service reports a retryable capacity error with file_steps_held and max_held_file_steps, and the lookup returns saturated, which capture reports too. A step on a path that already has stalled work waits and takes no thread. The service takes its owner as an option, and test services get their own. * fix(cli): exit after a command while a stalled file step is held A pending system call keeps Node's event loop alive, so a CLI command that timed out on a stalled mount wrote its result and then stayed running until the mount answered, which may be never. The launcher now asks the CLI runtime whether the process holds stalled file work and, once the result is delivered and stdout has drained, exits explicitly. Runs that hold no stalled work end as before. * fix(rizin): reserve the file-step budget before a step starts The budget counted only steps already left behind, so calls that stalled together all started while it read zero, and eight concurrent stats could exhaust the pool. A step now reserves the budget before it starts and releases it when the underlying work settles. A step waits within its deadline while running steps fill the budget, and is refused once left-behind steps fill it. The budget is half of libuv's pool as UV_THREADPOOL_SIZE sizes it, with at least one step, instead of a fixed 2. A refused target preflight also keeps its path as artifact_path. * fix(rizin): keep unbounded file work out of the shared budget Process capture's executable lookup has no deadline, so a stalled check would stay running forever, fill the shared budget and make healthy captures wait without end. A lookup or hash that is given no owner now joins no budget, so capture behaves as it does on main, and only the service, whose calls have deadlines, shares the process-wide owner. Tests that count steps fix their budget instead of inheriting the host's UV_THREADPOOL_SIZE, and the concurrent-step tests use bounded waits and release their work in finally. * Revert "fix(cli): exit after a command while a stalled file step is held" This reverts commit4a4bb74bc. It did not work: process.exit() also hangs while a pool thread is stuck in a system call, because Node joins the pool at exit. Its test passed only because the simulated stall held no thread. The docs now state the limit: a CLI command prints its result and then stays alive until the mount answers. A real exit path needs a process-wide design and goes to the maintainer proposal. * fix(rizin): keep a found file that did not start as a candidate When the file a bare command's lookup found did not start, the command ran by name, and a failed launch then lost that file's path, digest and launch error. Evidence and launch failures now keep them as executable_lookup_candidate, executable_lookup_candidate_sha256 and executable_lookup_code, without claiming that the candidate ran. * fix(rizin): keep why a post-run digest or lookup gave no answer A post-run hash that the file-step budget refused was reported as an artifact that could not be read. Evidence now keeps the command output with artifact_digest_after_refused and a limitation saying the artifact was not read. A lookup that needed an unreadable working directory also lost that outcome when the launch by name failed; it now keeps it as executable_lookup_outcome and executable_lookup_code. * test(rizin): compare the post-run limitation through its owner The refused post-run digest test froze one explanatory phrase and banned another. It now keeps the structured refusal facts and checks that the unreadable-artifact limitation, an exported constant, is absent. * fix(rizin): keep preparation failures' output and cleanup Ownership preparation throws its own failure, or an interruption wraps it, and runOwnedCommandOutput recognized neither. The compiler output was lost and a retained helper could not be retried, for the version probe and for the command. Normalize both shapes at that boundary, so preparation is a launch failure that carries its output, and its cleanup reaches retryCleanup through the same stop contract. * refactor(rizin): drop the shared file-work pool from tool identity A maintainer asked to separate the shared FileWork pool from this PR until the lifetime design in #8860 settles. The pool kept a call's place while file work it gave up on was running, made later work on that path wait for it, reserved half of libuv's pool as a budget of stalled steps, and refused new steps with a capacity error once that budget was held. The lookup and hash now run each stat, access and stream step under one deadline and cancellation listener (FileDeadline). A step the call stops waiting for keeps running until its mount answers, untracked, as main's stat already did. The call returns and gives back its place. The saturated lookup outcome, FileWorkSaturatedError, the operations_awaiting_file_work count and artifact_digest_after_refused are removed, with the tests that covered them. New tests check that a call gives back its place at its deadline, and that a hash ends at its deadline on a stalled open, read or close while a later hash of the path starts its own read. The pool is kept on the fork branch rizin-filework-pool. * fix(rizin): keep the PATH candidate a launch by name is denied When a bare REA_RIZIN_COMMAND finds only a file without execute permission or a candidate under an unsearchable directory, the lookup records it only as display text, and the by-name launch then fails with EACCES. The capability error kept neither selectedPath nor stoppedAt, so it lost the file whose permissions need repair. The lookup now reports the first PATH candidate it moved past with EACCES as deniedAt, and the service keeps it as executable_lookup_denied_candidate in Evidence and launch failures, with a limitation naming it. * fix(rizin): keep a non-regular PATH candidate a launch by name is denied A launch by name also fails with EACCES when the only PATH match is a directory or another non-regular file, which execve refuses; the lookup kept that candidate only as checked display text. deniedAt now covers it and carries its reason, permission or not-regular-file, which the service keeps as executable_lookup_denied_reason beside the candidate and names in its limitation. * fix(process): mark invalid UTF-8 where execFileBytes decodes a failure execFileOutputFailure projects stdoutInvalidUtf8 and stderrInvalidUtf8, but execFileBytes decoded a failed command's buffers without setting them, so direct runner callers such as adb reported replacement characters without the stdout_invalid_utf8 and stderr_invalid_utf8 markers. The failure now validates each buffer when it decodes it, on both the execFile and owned-spawn routes, and execFileOutput's result marks invalid streams the same way, as the owned process runner does. * test(process): expect the invalid UTF-8 marker on compiler failures The Darwin token reader's compiler capture now reports stderr_invalid_utf8 for a replaced byte, and the decoding tests get their own block under the 150-line function limit. * fix(reverse): report a post-run digest deadline with its recovery A post-run hash that reached command_timeout_ms, for example at a close a stalled mount holds, fell into the empty catch and was reported as an unreadable artifact. It now adds a limitation naming the deadline (ETIMEDOUT) and how to raise command_timeout_ms, and the command's Evidence is kept. The deadline-raising sentence is shared with the timeout error. * refactor(rizin): retain version-probe preparation through main's inspection owner main's #10113 owns ownership-preparation failures for the command: it maps them to analysis errors and retains their cleanup in the service's inspection scope. This branch had its own copy in runOwnedCommandOutput (630610d30), so a retained helper now had two owners, and the copy no longer typechecked against the inspection-failure union. The runner returns to main's version. Main's two inline mappings become one ownershipPreparationError, which the command and the version probe share: a preparation that fails or stops during the probe ends the call as it would for the command, and its cleanup joins the same scope, so retryCleanup closes the helper once. A deadline that interrupts Darwin preparation keeps the compiler output, as a failed preparation does. The preparation tests read the primary error under the cleanup wrapper; main's two new collection-failure tests use this branch's processes option. reverseProviderLaunchErrors.test.ts returns to main's version: the retry assertions this branch added there expected a cleanup failure with no owner to be retried by polling its state, which main's owner does not retain; the error still reports the cleanup as incomplete. * refactor(rizin): parse an ownership preparation failure once before mapping it to an error * test(rizin): expect PATH entries on search candidates and the launched path in launch failures * refactor(process): take the host platform of an executable lookup from its caller * test(rizin): register the renamed Rizin cancellation test for lifecycle coverage The cancellation test now covers the command and the version probe as "waits for a Rizin process cancelled during its %s to exit before returning", so the lifecycle coverage registry names that title. * test(rizin): assert the facts a post-run digest deadline names, not its wording The limitation must name the setting that stopped the hash, its value and the error code; the recovery sentence belongs to nativeDeadlineRecovery, whose wording may change. * fix(rizin): keep host capacity during version-probe preparation retryable When the ownership helper's compiler could not start for EAGAIN, EMFILE, ENFILE or ENOMEM, the version probe mapped the failure to a non-retryable ownership-preparation error with setup remediation, while the command path classifies the same condition as a retryable resource constraint. Run the shared preparationHostCapacityFailure owner first in the probe, as the command does, and test each of the four codes. * test(rizin): create the abandoned-stat fixture with createTestTempDirectory The fixture root came from mkdtemp before the try block, so a setup failure skipped its removal. createTestTempDirectory registers the cleanup when it creates the root. * test(rizin): align tool identity assertions with normalized_result and clean up lookup --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
178 lines
6.3 KiB
TypeScript
178 lines
6.3 KiB
TypeScript
import { delimiter, dirname, relative } from "node:path";
|
|
|
|
import { expect, it, vi } from "vitest";
|
|
|
|
import { lookupExecutable } from "../../src/process/ExecutableLookup.js";
|
|
import { TestReverseEngineeringService } from "../support/reverseEngineeringService.js";
|
|
import {
|
|
rizinExecutableFixture,
|
|
versionProbeCount,
|
|
versionProbeRunner,
|
|
} from "../support/rizinToolIdentity.js";
|
|
|
|
// The selected executable is a POSIX mode-0755 file; Windows resolves
|
|
// REA_RIZIN_COMMAND separately and is not covered here.
|
|
const posix = it.skipIf(process.platform === "win32");
|
|
|
|
/** As when the server's working directory has been removed. */
|
|
const unreadableWorkingDirectory = () =>
|
|
vi.spyOn(process, "cwd").mockImplementation(() => {
|
|
throw Object.assign(new Error("uv_cwd"), { code: "ENOENT" });
|
|
});
|
|
|
|
posix(
|
|
"identifies and runs an absolute command and target without reading the working directory",
|
|
async () => {
|
|
const { executable, path } = await rizinExecutableFixture();
|
|
const run = versionProbeRunner(() => "rizin 0.9.1 @ linux-x86-64");
|
|
const service = new TestReverseEngineeringService({
|
|
run,
|
|
lookup: lookupExecutable,
|
|
// A relative PATH entry is not searched for an explicit command.
|
|
environment: { REA_RIZIN_COMMAND: executable, PATH: "bin" },
|
|
});
|
|
const cwd = unreadableWorkingDirectory();
|
|
try {
|
|
const result = await service.executeRizinCommand({ path, command: "iI" });
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.provider.version).toBe("0.9.1");
|
|
expect(result.value.parameters).toMatchObject({
|
|
provider_executable_path: executable,
|
|
provider_identity: "banner",
|
|
});
|
|
expect(cwd).not.toHaveBeenCalled();
|
|
} finally {
|
|
cwd.mockRestore();
|
|
}
|
|
},
|
|
);
|
|
|
|
posix(
|
|
"keeps why the lookup needed the working directory when the launch by name fails",
|
|
async () => {
|
|
const { executable, path } = await rizinExecutableFixture();
|
|
const reachable = relative(process.cwd(), dirname(executable));
|
|
const run = vi.fn(async (): Promise<never> => {
|
|
throw Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" });
|
|
});
|
|
const service = new TestReverseEngineeringService({
|
|
run,
|
|
lookup: lookupExecutable,
|
|
environment: { REA_RIZIN_COMMAND: "rizin", PATH: reachable },
|
|
});
|
|
const cwd = unreadableWorkingDirectory();
|
|
try {
|
|
const result = await service.executeRizinCommand({ path, command: "iI" });
|
|
if (result.ok) throw new Error("Expected the launch to fail");
|
|
expect(result.error.diagnostics).toMatchObject({
|
|
provider_executable: "rizin",
|
|
executable_lookup_outcome: "no-working-directory",
|
|
executable_lookup_code: "ENOENT",
|
|
});
|
|
} finally {
|
|
cwd.mockRestore();
|
|
}
|
|
},
|
|
);
|
|
|
|
posix.each([
|
|
["before", false],
|
|
["after", true],
|
|
] as const)(
|
|
"identifies a PATH match %s a relative entry whose working directory cannot be read",
|
|
async (_order, relativeFirst) => {
|
|
const { executable, path } = await rizinExecutableFixture();
|
|
const run = versionProbeRunner(() => "rizin 0.9.1 @ linux-x86-64");
|
|
const service = new TestReverseEngineeringService({
|
|
run,
|
|
lookup: lookupExecutable,
|
|
environment: {
|
|
REA_RIZIN_COMMAND: "rizin",
|
|
PATH: relativeFirst
|
|
? `.${delimiter}${dirname(executable)}`
|
|
: `${dirname(executable)}${delimiter}.`,
|
|
},
|
|
});
|
|
const cwd = unreadableWorkingDirectory();
|
|
try {
|
|
const result = await service.executeRizinCommand({ path, command: "iI" });
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.provider.version).toBe("0.9.1");
|
|
expect(result.value.parameters).toMatchObject({
|
|
provider_executable_path: executable,
|
|
provider_identity: "banner",
|
|
});
|
|
// A relative entry before the match is reached and skipped.
|
|
expect(cwd).toHaveBeenCalledTimes(relativeFirst ? 1 : 0);
|
|
} finally {
|
|
cwd.mockRestore();
|
|
}
|
|
},
|
|
);
|
|
|
|
posix(
|
|
"runs the command by name, unidentified, when a relative PATH entry before the match still reaches an executable",
|
|
async () => {
|
|
const { executable, path } = await rizinExecutableFixture();
|
|
const earlier = await rizinExecutableFixture();
|
|
const run = versionProbeRunner(() => "rizin 0.9.1 @ linux-x86-64");
|
|
const service = new TestReverseEngineeringService({
|
|
run,
|
|
lookup: lookupExecutable,
|
|
environment: {
|
|
REA_RIZIN_COMMAND: "rizin",
|
|
// Relative to the working directory, as `../bin` is.
|
|
PATH: `${relative(process.cwd(), dirname(earlier.executable))}${delimiter}${dirname(executable)}`,
|
|
},
|
|
});
|
|
const cwd = unreadableWorkingDirectory();
|
|
try {
|
|
const result = await service.executeRizinCommand({ path, command: "iI" });
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.parameters.provider_identity).toBe("assumed");
|
|
expect(result.value.parameters).not.toHaveProperty(
|
|
"provider_executable_path",
|
|
);
|
|
// The later match is not selected: the launch by name follows PATH.
|
|
expect(run.mock.calls.map(([command]) => command)).toEqual(["rizin"]);
|
|
expect(versionProbeCount(run)).toBe(0);
|
|
} finally {
|
|
cwd.mockRestore();
|
|
}
|
|
},
|
|
);
|
|
|
|
posix.each([
|
|
["a relative command", { REA_RIZIN_COMMAND: "bin/rizin" }],
|
|
["a relative PATH entry", { REA_RIZIN_COMMAND: "rizin", PATH: "bin" }],
|
|
] as const)(
|
|
"returns a result when %s needs a working directory that cannot be read",
|
|
async (_case, environment) => {
|
|
const { path } = await rizinExecutableFixture();
|
|
const run = versionProbeRunner(() => "rizin 0.9.1 @ linux-x86-64");
|
|
const service = new TestReverseEngineeringService({
|
|
run,
|
|
lookup: lookupExecutable,
|
|
environment,
|
|
});
|
|
const cwd = unreadableWorkingDirectory();
|
|
try {
|
|
const result = await service.executeRizinCommand({ path, command: "iI" });
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.provider).toEqual({
|
|
id: "rizin",
|
|
name: "Rizin",
|
|
version: null,
|
|
});
|
|
expect(result.value.parameters.provider_identity).toBe("assumed");
|
|
expect(result.value.parameters).not.toHaveProperty(
|
|
"provider_executable_path",
|
|
);
|
|
expect(versionProbeCount(run)).toBe(0);
|
|
expect(cwd).toHaveBeenCalled();
|
|
} finally {
|
|
cwd.mockRestore();
|
|
}
|
|
},
|
|
);
|