Files
reverse-engineering-anything/src/dotnet/ManagedStaticProvider.ts
T
morluto 5f718ce30e refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)
* refactor(kernel): give error-to-message text one owner in a new src/kernel layer

* fix(kernel): keep the regex worker's own error text inside its isolated source

* refactor(kernel): exclude copies that run in another realm from the error-message guard by name

The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them.

* refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552)

Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560)

byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out.

Refs #11548

* refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562)

sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted.

Refs #11548

* refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563)

All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567)

All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
2026-11-16 07:05:30 +08:00

298 lines
9.6 KiB
TypeScript

import {
createAnalysisExecution,
type AnalysisClient,
type AnalysisOperation,
type AnalysisProvider,
type CapabilityDescriptor,
type ExecutionOptions,
type ProviderIdentity,
} from "../ports/AnalysisProvider.js";
import { invariantViolation } from "../domain/internalInvariant.js";
import {
ArtifactReaderFailure,
ArtifactResourceScope,
} from "../resources/index.js";
import { managedStaticCapabilities } from "./ManagedStaticProviderMetadata.js";
import { MANAGED_STATIC_PROVIDER } from "../domain/investigationProviders.js";
import {
MANAGED_TOOL_CONTRACTS,
managedMembersInputSchema,
managedTargetInputSchema,
type ManagedToolName,
} from "../contracts/managed/managedToolContracts.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
cancelledBy,
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type {
ManagedArtifactInspection,
ManagedMemberInspection,
ManagedNativeBoundaryInspection,
} from "../domain/managed/managedArtifact.js";
import { err, ok, type Result } from "../domain/result.js";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { managedInspectionInputFailure } from "../domain/managed/managedReaderFailure.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import type { z } from "zod";
import {
hashManagedSource,
managedCleanupError,
readManagedSnapshot,
verifyManagedSourceIdentity,
} from "./ManagedSnapshot.js";
import { errorMessage } from "../kernel/errorMessage.js";
/** Execution-free managed PE/CLI auxiliary provider. */
export class ManagedStaticProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[] =
managedStaticCapabilities();
identity(): ProviderIdentity {
return MANAGED_STATIC_PROVIDER;
}
capabilities(): readonly CapabilityDescriptor[] {
return this.#capabilities;
}
createClient(target: BinaryTarget): AnalysisClient {
return new ManagedStaticClient(target);
}
}
class ManagedStaticClient implements AnalysisClient {
#snapshotBytes: Buffer | undefined;
readonly #resources = new ArtifactResourceScope();
constructor(private readonly target: BinaryTarget) {}
async execute(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
if (operation === "health")
return ok(createAnalysisExecution(null, MANAGED_STATIC_PROVIDER));
if (!isManagedOperation(operation))
return err(
new AnalysisCapabilityUnavailableError(
MANAGED_STATIC_PROVIDER.id,
operation,
"Operation is not implemented by the managed static provider.",
),
);
// A non-PE target is outside this operation's formats, not a missing
// provider capability; the unimplemented-operation refusal above is.
if (this.target.format !== "pe")
return err(
new AnalysisUnsupportedTargetError(
operation,
this.target.path,
`Managed static triage requires a PE target; observed ${this.target.format}.`,
),
);
try {
const input =
operation === "inspect_managed_members"
? managedMembersInputSchema.safeParse(parameters)
: managedTargetInputSchema.safeParse(parameters);
if (!input.success)
return err(
analysisInputErrorFromIssues(
operation,
input.error.issues,
parameters,
),
);
const snapshotOptions = {
expectedSha256: this.target.sha256,
signal: options?.signal,
resources: this.#resources,
...(input.data.max_snapshot_bytes === undefined
? {}
: { maxBytes: input.data.max_snapshot_bytes }),
};
if (options?.signal?.aborted === true)
return err(cancelledBy(operation, options.signal));
const snapshot = this.#snapshotBytes;
const observed =
snapshot === undefined
? await readManagedSnapshot(
this.target.path,
operation,
snapshotOptions,
)
: await hashManagedSource(
this.target.path,
operation,
snapshotOptions,
);
const admitted = verifyManagedSourceIdentity(
this.target,
observed,
operation,
);
if (!admitted.ok) return admitted;
const bytes = snapshot ?? observed.bytes;
if (bytes === undefined)
throw invariantViolation("Managed snapshot bytes are unavailable");
this.#snapshotBytes = bytes;
const result = inspectManagedOperation(
operation,
input.data,
bytes,
this.target,
);
return ok(
createAnalysisExecution(result, MANAGED_STATIC_PROVIDER, {
rawResult: null,
limitations: result.limitations,
subject: this.target,
locations: managedLocations(result),
}),
);
} catch (cause: unknown) {
if (isCleanupFailure(cause))
return err(this.#cleanupError(operation, cause));
if (cause instanceof AnalysisError) return err(cause);
if (options?.signal?.aborted === true)
return err(cancelledBy(operation, options.signal));
const inputFailure = managedInspectionInputFailure(
operation,
this.target.path,
cause,
);
if (inputFailure !== undefined) return err(inputFailure);
return err(
new ProviderAdapterError(MANAGED_STATIC_PROVIDER.id, operation, {
cause,
}),
);
}
}
async close(): Promise<Result<null, AnalysisError>> {
this.#snapshotBytes = undefined;
try {
await this.#resources.close();
return ok(null);
} catch (cause: unknown) {
return err(this.#cleanupError("close", cause));
}
}
#cleanupError(operation: string, cause: unknown): ProviderCleanupError {
const failure = managedCleanupError(cause, this.target.path, operation);
if (failure instanceof ProviderCleanupError) return failure;
const cleanup =
cause instanceof ArtifactReaderFailure ? cause.cleanup : undefined;
return new ProviderCleanupError(
MANAGED_STATIC_PROVIDER.id,
cleanup?.resources ?? [this.target.path],
{
reason: cleanup?.reason ?? errorMessage(cause),
},
{ cause, operation },
);
}
}
const isCleanupFailure = (cause: unknown): boolean =>
cause instanceof RegularFileCleanupFailure ||
(cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined);
const isManagedOperation = (
operation: AnalysisOperation,
): operation is ManagedToolName =>
MANAGED_TOOL_CONTRACTS.some(({ name }) => name === operation);
const inspectManagedOperation = (
operation: ManagedToolName,
parameters: Omit<z.output<typeof managedMembersInputSchema>, "detail">,
bytes: Buffer,
target: BinaryTarget,
):
| ManagedArtifactInspection
| ManagedMemberInspection
| ManagedNativeBoundaryInspection => {
if (operation === "inspect_managed_members") {
const { type_names: typeNames } = parameters;
return inspectManagedMembersBytes(bytes, target, {
...(typeNames === undefined ? {} : { typeNames }),
...(parameters.max_metadata_representation_bytes === undefined
? {}
: {
maxRepresentationBytes:
parameters.max_metadata_representation_bytes,
}),
});
}
if (operation === "inspect_managed_artifact") {
return inspectManagedArtifactBytes(
bytes,
target,
parameters.max_metadata_representation_bytes,
);
}
return inspectManagedNativeBoundariesBytes(
bytes,
target,
parameters.max_metadata_representation_bytes,
);
};
const managedLocations = (
result:
| ManagedArtifactInspection
| ManagedMemberInspection
| ManagedNativeBoundaryInspection,
): readonly EvidenceLocation[] => {
if ("pe" in result) {
if (result.pe.cli === null) return [{ kind: "file-offset", offset: 0 }];
return [
{
kind: "file-offset-range",
start: result.pe.cli.header_offset,
end: result.pe.cli.header_offset + result.pe.cli.header_size,
},
...[result.module, result.assembly]
.filter((value) => value !== null)
.map((value) => ({
kind: "file-offset" as const,
offset: value.row_offset,
})),
];
}
if ("methods" in result)
return [
...(result.module === null
? [{ kind: "file-offset" as const, offset: 0 }]
: [{ kind: "file-offset" as const, offset: result.module.row_offset }]),
...result.methods
.filter((method) => method.body.file_offset !== null)
.map((method) => ({
kind: "file-offset" as const,
offset: method.body.file_offset ?? 0,
})),
];
return [
...(result.module === null
? [{ kind: "file-offset" as const, offset: 0 }]
: [{ kind: "file-offset" as const, offset: result.module.row_offset }]),
...result.pinvoke_imports.map((mapping) => ({
kind: "file-offset" as const,
offset: mapping.row_offset,
})),
];
};