Merge remote-tracking branch 'origin/main' into feat/pkg-inventory
# Conflicts: # docs/product-catalog.json # docs/verification/managed-conformance-manifest.json # skills/reverse-engineer-anything/SKILL.md # src/generatedMcpToolCatalog.ts
This commit is contained in:
@@ -32,7 +32,8 @@ export class JadxMcpTransport implements Transport {
|
||||
readonly runId = randomUUID();
|
||||
#spawned: SpawnedOwnedProviderProcess | undefined;
|
||||
#supervisor: ProviderProcessSupervisor | undefined;
|
||||
#buffer = Buffer.alloc(0);
|
||||
#frameBuffer = Buffer.alloc(0);
|
||||
#frameLength = 0;
|
||||
#bytes = 0;
|
||||
#started = false;
|
||||
#closed = false;
|
||||
@@ -61,12 +62,16 @@ export class JadxMcpTransport implements Transport {
|
||||
stdin: "pipe",
|
||||
});
|
||||
this.#spawned = spawned;
|
||||
this.#supervisor = new ProviderProcessSupervisor({
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
|
||||
});
|
||||
this.#supervisor = new ProviderProcessSupervisor(
|
||||
{
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
spawned.cleanup ??
|
||||
(() => cleanupOwnedProcessGroup(spawned.ownership)),
|
||||
},
|
||||
{ captureStdout: false },
|
||||
);
|
||||
if (
|
||||
spawned.process.stdin === undefined ||
|
||||
spawned.process.stdin === null ||
|
||||
@@ -117,6 +122,8 @@ export class JadxMcpTransport implements Transport {
|
||||
|
||||
async #stop(): Promise<void> {
|
||||
this.#closed = true;
|
||||
this.#frameBuffer = Buffer.alloc(0);
|
||||
this.#frameLength = 0;
|
||||
// A cancellation may race acquisition. Join it before inspecting ownership.
|
||||
await this.#starting?.catch(() => undefined);
|
||||
const process = this.#spawned?.process;
|
||||
@@ -161,22 +168,42 @@ export class JadxMcpTransport implements Transport {
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.#buffer = Buffer.concat([this.#buffer, bytes]);
|
||||
try {
|
||||
let newline: number;
|
||||
while ((newline = this.#buffer.indexOf(10)) !== -1) {
|
||||
if (newline > MAX_FRAME_BYTES)
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const newline = bytes.indexOf(10, offset);
|
||||
const end = newline === -1 ? bytes.length : newline;
|
||||
const fragment = bytes.subarray(offset, end);
|
||||
const frameBytes = this.#frameLength + fragment.length;
|
||||
if (frameBytes > MAX_FRAME_BYTES)
|
||||
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
|
||||
const line = this.#buffer.subarray(0, newline).toString("utf8");
|
||||
this.#buffer = this.#buffer.subarray(newline + 1);
|
||||
this.#appendFrame(fragment, frameBytes);
|
||||
if (newline === -1) return;
|
||||
const line = this.#frameBuffer
|
||||
.subarray(0, this.#frameLength)
|
||||
.toString("utf8");
|
||||
this.#frameBuffer = Buffer.alloc(0);
|
||||
this.#frameLength = 0;
|
||||
this.onmessage?.(deserializeMessage(line));
|
||||
offset = newline + 1;
|
||||
}
|
||||
if (this.#buffer.length > MAX_FRAME_BYTES)
|
||||
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
|
||||
} catch (cause) {
|
||||
this.#fail(cause instanceof Error ? cause : new Error(String(cause)));
|
||||
}
|
||||
};
|
||||
#appendFrame(fragment: Buffer, frameBytes: number): void {
|
||||
if (frameBytes > this.#frameBuffer.length) {
|
||||
const capacity = Math.min(
|
||||
MAX_FRAME_BYTES,
|
||||
Math.max(frameBytes, this.#frameBuffer.length * 2, 1),
|
||||
);
|
||||
const grown = Buffer.allocUnsafe(capacity);
|
||||
this.#frameBuffer.copy(grown, 0, 0, this.#frameLength);
|
||||
this.#frameBuffer = grown;
|
||||
}
|
||||
fragment.copy(this.#frameBuffer, this.#frameLength);
|
||||
this.#frameLength = frameBytes;
|
||||
}
|
||||
#fail(error: Error): void {
|
||||
this.#failure ??= error.message;
|
||||
this.onerror?.(error);
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { OfficialToolName } from "../contracts/officialToolContracts.js";
|
||||
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
|
||||
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
|
||||
import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContracts.js";
|
||||
import type { ManagedToolName } from "../contracts/managedToolContracts.js";
|
||||
import type { ManagedToolName } from "../contracts/managed/managedToolContracts.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContrac
|
||||
import {
|
||||
isManagedToolName,
|
||||
type ManagedToolName,
|
||||
} from "../contracts/managedToolContracts.js";
|
||||
} from "../contracts/managed/managedToolContracts.js";
|
||||
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { type AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
installLinuxHopper,
|
||||
linuxHopperLauncherDigestSupported,
|
||||
linuxHopperInstallDisclosure,
|
||||
linuxPackageManagerCommands,
|
||||
linuxSharedLibrariesAvailable,
|
||||
@@ -93,6 +94,20 @@ describe("Linux Hopper host classification", () => {
|
||||
});
|
||||
|
||||
describe("Linux Hopper installation", () => {
|
||||
it.each([
|
||||
[
|
||||
"Debian and Arch",
|
||||
"0294ced141cc373468ee22d8343e7dac41980cb05a937994ca81c9f09afe7ded",
|
||||
],
|
||||
["RPM", "1339f9e58377442b0c6fcb0dfc3cec20d593cc557408521fad9a00dbc6b8da13"],
|
||||
])("accepts the pinned %s launcher build", (_, digest) => {
|
||||
expect(linuxHopperLauncherDigestSupported(digest)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an unverified launcher build", () => {
|
||||
expect(linuxHopperLauncherDigestSupported("0".repeat(64))).toBe(false);
|
||||
});
|
||||
|
||||
it("discloses the exact download, integrity evidence, and privileged command", () => {
|
||||
expect(linuxHopperInstallDisclosure("deb", false)).toEqual({
|
||||
downloadUrl:
|
||||
|
||||
@@ -11,8 +11,10 @@ import { execFileOutput } from "../process/ExecFileOutput.js";
|
||||
const execFileAsync = promisify(execFile);
|
||||
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
|
||||
const MAX_PACKAGE_BYTES = 100_000_000;
|
||||
const SUPPORTED_HOPPER_SHA256 =
|
||||
"0294ced141cc373468ee22d8343e7dac41980cb05a937994ca81c9f09afe7ded";
|
||||
const SUPPORTED_HOPPER_SHA256 = new Set([
|
||||
"0294ced141cc373468ee22d8343e7dac41980cb05a937994ca81c9f09afe7ded",
|
||||
"1339f9e58377442b0c6fcb0dfc3cec20d593cc557408521fad9a00dbc6b8da13",
|
||||
]);
|
||||
interface LinuxHopperRelease {
|
||||
readonly filename: string;
|
||||
readonly file_length: string;
|
||||
@@ -262,7 +264,7 @@ export const linuxHopperBinarySupported = async (
|
||||
try {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex") === SUPPORTED_HOPPER_SHA256;
|
||||
return linuxHopperLauncherDigestSupported(hash.digest("hex"));
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: optional build probing; unreadable means unsupported.
|
||||
void cause;
|
||||
@@ -270,6 +272,10 @@ export const linuxHopperBinarySupported = async (
|
||||
}
|
||||
};
|
||||
|
||||
/** Match a launcher extracted from one of the pinned official Linux packages. */
|
||||
export const linuxHopperLauncherDigestSupported = (digest: string): boolean =>
|
||||
SUPPORTED_HOPPER_SHA256.has(digest);
|
||||
|
||||
/** Interpret ldd output conservatively so a present but broken launcher is unhealthy. */
|
||||
export const linuxSharedLibrariesAvailable = (output: string): boolean =>
|
||||
!/(?:=>\s+not found|error while loading shared libraries)/iu.test(output);
|
||||
|
||||
@@ -52,6 +52,11 @@ export class FakeSetupHost implements SetupHost {
|
||||
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
|
||||
Promise.resolve(this.distribution);
|
||||
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
|
||||
initialSetupState = async (scope?: DoctorScope) => ({
|
||||
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
|
||||
providerEnvironment: await this.providerEnvironment(),
|
||||
doctor: await this.doctor(scope),
|
||||
});
|
||||
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
|
||||
Promise.resolve({
|
||||
...(this.hopper === undefined
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { runSetup } from "./Setup.js";
|
||||
import { FakeSetupHost, options } from "./Setup.fixture.js";
|
||||
|
||||
it("uses the shared initial host snapshot for setup planning", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopperPath = () => {
|
||||
throw new Error("setup snapshot should provide the Hopper path");
|
||||
};
|
||||
host.providerEnvironment = () => {
|
||||
throw new Error("setup snapshot should provide provider settings");
|
||||
};
|
||||
host.initialSetupState = async (scope) => ({
|
||||
hopperPath: "/snapshot/Hopper",
|
||||
providerEnvironment: { HOPPER_LAUNCHER_PATH: "/snapshot/Hopper" },
|
||||
doctor: await host.doctor(scope),
|
||||
});
|
||||
host.clients = [{ name: "codex", configPath: "/codex.json" }];
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(false), dryRun: true, clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.plannedActions.map(({ id }) => id)).toContain(
|
||||
"configure_client:codex",
|
||||
);
|
||||
expect(host.doctorCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("refreshes doctor after approved setup changes", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.doctorHealthy = false;
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.json" }];
|
||||
const configureClient = host.configureClient;
|
||||
host.configureClient = (client, providerEnvironment, command) => {
|
||||
host.doctorHealthy = true;
|
||||
return configureClient(client, providerEnvironment, command);
|
||||
};
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["codex"], installSkill: false },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.doctor.healthy).toBe(true);
|
||||
expect(host.doctorCalls).toBe(2);
|
||||
});
|
||||
@@ -42,8 +42,15 @@ export const runSetup = async (
|
||||
);
|
||||
const unsupported = await hostRemediation(host, false);
|
||||
if (unsupported !== undefined) return fail(unsupported);
|
||||
let hopperPath = await host.hopperPath();
|
||||
let providerEnvironment = await initialProviderEnvironment(host, hopperPath);
|
||||
const initialState = await host.initialSetupState?.(options.readinessScope);
|
||||
let hopperPath =
|
||||
initialState === undefined
|
||||
? await host.hopperPath()
|
||||
: initialState.hopperPath;
|
||||
let providerEnvironment =
|
||||
initialState === undefined
|
||||
? await initialProviderEnvironment(host, hopperPath)
|
||||
: initialState.providerEnvironment;
|
||||
const discovery = await discoverSetupState({
|
||||
host,
|
||||
providerEnvironment,
|
||||
@@ -51,6 +58,9 @@ export const runSetup = async (
|
||||
proposeHopper:
|
||||
options.proposeHopper ?? (confirm !== undefined && !options.structured),
|
||||
doctorScope: options.readinessScope,
|
||||
...(initialState === undefined
|
||||
? {}
|
||||
: { initialDoctor: initialState.doctor }),
|
||||
});
|
||||
clientStates = discovery.clientStates;
|
||||
const clientSelectionAllowed =
|
||||
|
||||
@@ -22,7 +22,12 @@ import {
|
||||
} from "./SetupClientConfiguration.js";
|
||||
import { setupInstallFailure } from "./SetupInstallFailure.js";
|
||||
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
|
||||
import type { SetupHost, SetupProviderEnvironment } from "./SetupTypes.js";
|
||||
import type {
|
||||
SetupHost,
|
||||
SetupInitialState,
|
||||
SetupProviderEnvironment,
|
||||
} from "./SetupTypes.js";
|
||||
import type { DoctorScope } from "./Doctor.js";
|
||||
|
||||
/** Resolve the executable and arguments used in a managed MCP registration. */
|
||||
export const setupRegistrationCommand = (
|
||||
@@ -91,6 +96,25 @@ export const systemSetupHost = (
|
||||
macosVersion: () => doctorHost.macosVersion(),
|
||||
linuxDistribution: readLinuxDistribution,
|
||||
hopperPath: async () => (await runDoctor(undefined, doctorHost)).hopperPath,
|
||||
initialSetupState: async (
|
||||
scope?: DoctorScope,
|
||||
): Promise<SetupInitialState> => {
|
||||
const diagnosis = await runDoctor(undefined, doctorHost, scope);
|
||||
return {
|
||||
...(diagnosis.hopperPath === undefined
|
||||
? {}
|
||||
: { hopperPath: diagnosis.hopperPath }),
|
||||
providerEnvironment: {
|
||||
...providerRegistrationEnvironment(
|
||||
diagnosis.providerInspections ?? [],
|
||||
),
|
||||
...(diagnosis.hopperPath === undefined
|
||||
? {}
|
||||
: { HOPPER_LAUNCHER_PATH: diagnosis.hopperPath }),
|
||||
},
|
||||
doctor: diagnosis,
|
||||
};
|
||||
},
|
||||
providerEnvironment: async () => {
|
||||
const diagnosis = await runDoctor(undefined, doctorHost);
|
||||
return {
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
} from "./SetupTypes.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
import type { DoctorScope } from "./Doctor.js";
|
||||
import type { DoctorReport } from "./Doctor.js";
|
||||
|
||||
/** Read-only setup facts shared by client selection and preflight. */
|
||||
export interface SetupDiscovery {
|
||||
@@ -36,8 +37,10 @@ export const discoverSetupState = async (input: {
|
||||
readonly forceHopperInstall: boolean;
|
||||
readonly proposeHopper: boolean;
|
||||
readonly doctorScope: DoctorScope | undefined;
|
||||
readonly initialDoctor?: DoctorReport;
|
||||
}): Promise<SetupDiscovery> => {
|
||||
const initialDoctor = await input.host.doctor(input.doctorScope);
|
||||
const initialDoctor =
|
||||
input.initialDoctor ?? (await input.host.doctor(input.doctorScope));
|
||||
const linuxHopperRepairNeeded = initialDoctor.checks.some(
|
||||
({ name, ok, detail }) =>
|
||||
!ok &&
|
||||
|
||||
@@ -9,6 +9,13 @@ import type {
|
||||
/** Exact non-secret provider variables propagated into managed registrations. */
|
||||
export type SetupProviderEnvironment = Readonly<Record<string, string>>;
|
||||
|
||||
/** Read-only host facts shared by the initial setup plan. */
|
||||
export interface SetupInitialState {
|
||||
readonly hopperPath?: string;
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly doctor: DoctorReport;
|
||||
}
|
||||
|
||||
/** Result of one backup/write/readback transaction. */
|
||||
export type ClientConfigurationResult =
|
||||
| {
|
||||
@@ -38,6 +45,7 @@ export interface SetupHost {
|
||||
macosVersion(): Promise<string | undefined>;
|
||||
linuxDistribution(): Promise<LinuxDistribution | undefined>;
|
||||
hopperPath(): Promise<string | undefined>;
|
||||
initialSetupState?(scope?: DoctorScope): Promise<SetupInitialState>;
|
||||
installHopper(replaceExisting: boolean): Promise<SetupHopperInstallResult>;
|
||||
providerEnvironment?(): Promise<SetupProviderEnvironment>;
|
||||
detectedClients(): Promise<readonly SetupClient[]>;
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js";
|
||||
import type { JavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticGraph.js";
|
||||
import { javascriptRuntimeReconciliationResultSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { managedApplicationGraphResultSchema } from "../../domain/managedApplicationGraph.js";
|
||||
import { managedApplicationGraphResultSchema } from "../../domain/managed/managedApplicationGraph.js";
|
||||
|
||||
/** Supported immutable source for an application-level graph workflow. */
|
||||
export interface ApplicationGraphEvidenceSource {
|
||||
|
||||
+7
-7
@@ -3,19 +3,19 @@ import { z } from "zod";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { type AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
managedApplicationGraphResultSchema,
|
||||
projectManagedApplicationGraph,
|
||||
projectManagedApplicationGraphInputSchema,
|
||||
type ManagedApplicationGraphResult,
|
||||
type ProjectManagedApplicationGraphInput,
|
||||
} from "../domain/managedApplicationGraph.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
|
||||
} from "../../domain/managed/managedApplicationGraph.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "../InvestigationProviders.js";
|
||||
|
||||
const OPERATION = "project_managed_application_graph" as const;
|
||||
|
||||
+10
-10
@@ -8,22 +8,22 @@ import {
|
||||
managedMemberComparisonResultSchema,
|
||||
parseManagedMemberEvidence,
|
||||
type CompareManagedMembersInput,
|
||||
} from "../domain/managedMemberComparison.js";
|
||||
} from "../../domain/managed/managedMemberComparison.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
|
||||
import { type AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { inspectManagedMembersBytes } from "../dotnet/ManagedMemberInspector.js";
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import { parseBinaryTarget } from "../BinaryTargetResolver.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { inspectManagedMembersBytes } from "../../dotnet/ManagedMemberInspector.js";
|
||||
import {
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
MANAGED_WORKFLOW_PROVIDER,
|
||||
} from "./InvestigationProviders.js";
|
||||
} from "../InvestigationProviders.js";
|
||||
|
||||
/** Compare managed members from input parsed by a trusted adapter. */
|
||||
export const compareManagedMembersEvidenceValidated = (
|
||||
+7
-7
@@ -3,18 +3,18 @@ import { z } from "zod";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { type AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
managedNativeVerificationInputSchema,
|
||||
verifyManagedNativeBoundaries,
|
||||
type ManagedNativeVerificationInput,
|
||||
type ManagedNativeVerificationResult,
|
||||
} from "../domain/managedNativeVerification.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
|
||||
} from "../../domain/managed/managedNativeVerification.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "../InvestigationProviders.js";
|
||||
|
||||
const OPERATION = "verify_managed_native_boundaries" as const;
|
||||
|
||||
+4
-4
@@ -2,13 +2,13 @@ import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../contracts/managedWorkflowExamples.js";
|
||||
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../../contracts/managed/managedWorkflowExamples.js";
|
||||
import {
|
||||
importManagedReconstruction,
|
||||
managedReconstructionImportInputSchema,
|
||||
} from "../domain/managedReconstruction.js";
|
||||
import { managedMemberInspectionSchema } from "../domain/managedArtifact.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
} from "../../domain/managed/managedReconstruction.js";
|
||||
import { managedMemberInspectionSchema } from "../../domain/managed/managedArtifact.js";
|
||||
import { createEvidence } from "../../domain/evidence.js";
|
||||
import { importManagedReconstructionEvidence } from "./ManagedReconstructionService.js";
|
||||
|
||||
const exampleInput = () =>
|
||||
+7
-7
@@ -3,18 +3,18 @@ import { z } from "zod";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { type AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
importManagedReconstruction,
|
||||
managedReconstructionImportInputSchema,
|
||||
type ManagedReconstructionImportInput,
|
||||
type ManagedReconstructionImportResult,
|
||||
} from "../domain/managedReconstruction.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
|
||||
} from "../../domain/managed/managedReconstruction.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "../InvestigationProviders.js";
|
||||
|
||||
const OPERATION = "import_managed_reconstruction" as const;
|
||||
|
||||
@@ -143,14 +143,29 @@ const asarFailure = (
|
||||
path: string,
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure =>
|
||||
cause instanceof ArtifactReaderFailure
|
||||
? cause
|
||||
: new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Malformed or unreadable ASAR during ${operation}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
): ArtifactReaderFailure => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause;
|
||||
if (isFilesystemFailure(cause))
|
||||
return new ArtifactReaderFailure(
|
||||
"io",
|
||||
`Could not ${operation} ASAR at ${path}: ${cause.message}`,
|
||||
{ cause },
|
||||
);
|
||||
return new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Malformed ASAR during ${operation}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const isFilesystemFailure = (
|
||||
cause: unknown,
|
||||
): cause is NodeJS.ErrnoException & Error =>
|
||||
cause instanceof Error &&
|
||||
"errno" in cause &&
|
||||
typeof cause.errno === "number" &&
|
||||
"syscall" in cause &&
|
||||
typeof cause.syscall === "string";
|
||||
|
||||
const isMissingFile = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
|
||||
@@ -85,7 +85,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
);
|
||||
const handle = await open(
|
||||
entry.adapterKey,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
try {
|
||||
const observed = await handle.stat();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { z } from "incur";
|
||||
|
||||
import { compareManagedMemberPaths } from "../application/ManagedMemberComparisonService.js";
|
||||
import { verifyManagedNativeBoundariesEvidence } from "../application/ManagedNativeVerificationService.js";
|
||||
import { importManagedReconstructionEvidence } from "../application/ManagedReconstructionService.js";
|
||||
import { compareManagedMemberPaths } from "../application/managed/ManagedMemberComparisonService.js";
|
||||
import { verifyManagedNativeBoundariesEvidence } from "../application/managed/ManagedNativeVerificationService.js";
|
||||
import { importManagedReconstructionEvidence } from "../application/managed/ManagedReconstructionService.js";
|
||||
import { runProviderAnalysis } from "../application/DirectAnalysis.js";
|
||||
import { parseCliJsonInput } from "../cliJsonInput.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "incur";
|
||||
|
||||
import { projectManagedApplicationGraphEvidence } from "../application/ManagedApplicationGraphService.js";
|
||||
import { projectManagedApplicationGraphEvidence } from "../application/managed/ManagedApplicationGraphService.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "../cliJsonInput.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
|
||||
@@ -8,8 +8,8 @@ import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managed/managedWorkflowToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
|
||||
import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./browserScenarioToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
|
||||
|
||||
+4
-4
@@ -1,9 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { managedOutputSchemas } from "./toolOutputSchemas.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
|
||||
import type { ToolContract } from "../toolContracts.js";
|
||||
import { managedOutputSchemas } from "../toolOutputSchemas.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
|
||||
|
||||
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
|
||||
const managedTargetInputSchema = z.object({
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { createEvidence } from "../../domain/evidence.js";
|
||||
import type {
|
||||
ManagedMemberInspection,
|
||||
ManagedNativeBoundaryInspection,
|
||||
} from "../domain/managedArtifact.js";
|
||||
import type { InspectMacho } from "../domain/nativeInspection.js";
|
||||
} from "../../domain/managed/managedArtifact.js";
|
||||
import type { InspectMacho } from "../../domain/nativeInspection.js";
|
||||
|
||||
const MANAGED_STATIC_EXAMPLE_PROVIDER = {
|
||||
id: "rea-dotnet-static",
|
||||
+6
-6
@@ -1,17 +1,17 @@
|
||||
import { z } from "zod";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import { evidenceSchema } from "../../domain/evidence.js";
|
||||
|
||||
import { managedReconstructionImportInputSchema } from "../domain/managedReconstruction.js";
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { managedWorkflowOutputSchemas } from "./toolOutputSchemas.js";
|
||||
import { managedReconstructionImportInputSchema } from "../../domain/managed/managedReconstruction.js";
|
||||
import type { ToolContract } from "../toolContracts.js";
|
||||
import { managedWorkflowOutputSchemas } from "../toolOutputSchemas.js";
|
||||
import {
|
||||
MANAGED_MEMBER_COMPARISON_EXAMPLE,
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
|
||||
MANAGED_APPLICATION_GRAPH_EXAMPLE,
|
||||
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
|
||||
} from "./managedWorkflowExamples.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
|
||||
|
||||
/** Inputs for comparing two managed observations carried inline. */
|
||||
export const compareManagedMembersReferenceInputSchema = z
|
||||
@@ -80,7 +80,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
session(
|
||||
"capture_process_scenario",
|
||||
"Run one caller-selected command under a PTY and return process capture Evidence with residual unknowns. A command name resolves through the inherited PATH; the working directory defaults to the caller's current directory; host environment variables are inherited with scenario overrides. Filesystem snapshots are opt-in through filesystem_observation_paths. The target runs with the current user's permissions; this is not a security sandbox.",
|
||||
"Run one caller-selected command under a PTY and return process capture Evidence with residual unknowns. A command name resolves through the inherited PATH; the working directory defaults to the caller's current directory; host environment variables are inherited with scenario overrides. Environment keys cannot contain '=' or NUL, and REA_PROCESS_RUN_ID is reserved for process ownership. Filesystem snapshots are opt-in through filesystem_observation_paths. The target runs with the current user's permissions; this is not a security sandbox.",
|
||||
processScenarioSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -5,10 +5,10 @@ import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
|
||||
import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
|
||||
import { TOOL_CONTRACTS } from "./toolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
|
||||
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managed/managedWorkflowToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
|
||||
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managed/managedWorkflowToolContracts.js";
|
||||
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
|
||||
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascript/javascriptRuntimeObservationToolContracts.js";
|
||||
|
||||
@@ -37,11 +37,11 @@ import {
|
||||
managedArtifactInspectionSchema,
|
||||
managedMemberInspectionSchema,
|
||||
managedNativeBoundaryInspectionSchema,
|
||||
} from "../domain/managedArtifact.js";
|
||||
import { managedMemberComparisonResultSchema } from "../domain/managedMemberComparison.js";
|
||||
import { managedNativeVerificationResultSchema } from "../domain/managedNativeVerification.js";
|
||||
import { managedReconstructionImportResultSchema } from "../domain/managedReconstruction.js";
|
||||
import { managedApplicationGraphResultSchema } from "../domain/managedApplicationGraph.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import { managedMemberComparisonResultSchema } from "../domain/managed/managedMemberComparison.js";
|
||||
import { managedNativeVerificationResultSchema } from "../domain/managed/managedNativeVerification.js";
|
||||
import { managedReconstructionImportResultSchema } from "../domain/managed/managedReconstruction.js";
|
||||
import { managedApplicationGraphResultSchema } from "../domain/managed/managedApplicationGraph.js";
|
||||
import { artifactComparisonResultSchema } from "../domain/artifactComparison.js";
|
||||
import { functionComparisonResultSchema } from "../domain/functionComparison.js";
|
||||
import { bundleComparisonResultSchema } from "../domain/bundleComparison.js";
|
||||
|
||||
@@ -7,12 +7,12 @@ import {
|
||||
MANAGED_APPLICATION_GRAPH_EXAMPLE,
|
||||
MANAGED_MEMBER_COMPARISON_EXAMPLE,
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
|
||||
} from "./managedWorkflowExamples.js";
|
||||
} from "./managed/managedWorkflowExamples.js";
|
||||
import {
|
||||
compareManagedMembersReferenceInputSchema,
|
||||
managedApplicationGraphReferenceInputSchema,
|
||||
managedNativeVerificationReferenceInputSchema,
|
||||
} from "./managedWorkflowToolContracts.js";
|
||||
} from "./managed/managedWorkflowToolContracts.js";
|
||||
|
||||
describe("workflow input contracts", () => {
|
||||
it("rejects application Evidence ID references and duplicate inline records", () => {
|
||||
|
||||
@@ -309,6 +309,29 @@ describe("Apple bundle layouts and containers", () => {
|
||||
expect(
|
||||
result.bundles.find(({ path }) => path === framework)?.info_plist_path,
|
||||
).toBeNull();
|
||||
// Files beside the only real version are not versions.
|
||||
const withFiles = project(
|
||||
inventoryEvidence("zip", "Fixture.zip", [
|
||||
macho("Fixture.app/Contents/MacOS/Fixture"),
|
||||
{ path: `${framework}/Versions/A/Resources/Info.plist` },
|
||||
{ path: `${framework}/Versions/.DS_Store` },
|
||||
{ path: `${framework}/Versions/Current`, kind: "symlink" },
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
withFiles.bundles.find(({ path }) => path === framework)?.info_plist_path,
|
||||
).toBe(`${framework}/Versions/A/Resources/Info.plist`);
|
||||
// Only A has a plist, but Versions/Current may select B.
|
||||
const onlyA = project(
|
||||
inventoryEvidence("zip", "Fixture.zip", [
|
||||
macho("Fixture.app/Contents/MacOS/Fixture"),
|
||||
{ path: `${framework}/Versions/A/Resources/Info.plist` },
|
||||
macho(`${framework}/Versions/B/Core`),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
onlyA.bundles.find(({ path }) => path === framework)?.info_plist_path,
|
||||
).toBeNull();
|
||||
expect(result.limitations).toContainEqual(
|
||||
expect.stringContaining("Versions/Current selects is unknown"),
|
||||
);
|
||||
@@ -438,3 +461,37 @@ describe("macOS application scope", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Apple application bridge candidates", () => {
|
||||
it("pairs scripts and native code only within one application root", () => {
|
||||
const result = project(
|
||||
inventoryEvidence("zip", "Suite.zip", [
|
||||
macho("First.app/Contents/MacOS/First"),
|
||||
{
|
||||
path: "First.app/Contents/Resources/first.js",
|
||||
format: "javascript-bundle",
|
||||
},
|
||||
macho("Second.app/Contents/MacOS/Second"),
|
||||
{
|
||||
path: "Second.app/Contents/Resources/second.js",
|
||||
format: "javascript-bundle",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(result.application_roots).toEqual(["First.app", "Second.app"]);
|
||||
expect(
|
||||
result.bridge_candidates.map(
|
||||
({ source_path: source, native_path: target }) => [source, target],
|
||||
),
|
||||
).toEqual([
|
||||
[
|
||||
"First.app/Contents/Resources/first.js",
|
||||
"First.app/Contents/MacOS/First",
|
||||
],
|
||||
[
|
||||
"Second.app/Contents/Resources/second.js",
|
||||
"Second.app/Contents/MacOS/Second",
|
||||
],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -149,6 +149,7 @@ export const projectAppleApplication = (
|
||||
...classified.executables,
|
||||
...classified.native_libraries,
|
||||
]),
|
||||
roots,
|
||||
);
|
||||
const uninventoriedImage =
|
||||
rootFormat === "dmg" && inventory.occurrences.length === 1;
|
||||
@@ -305,18 +306,27 @@ const identifyRuntimeFamilies = (all: readonly Component[]) => {
|
||||
return [...families].sort(compare);
|
||||
};
|
||||
|
||||
/** Pair scripts and native code only within the same application root. */
|
||||
const identifyBridgeCandidates = (
|
||||
scripts: readonly Component[],
|
||||
native: readonly Component[],
|
||||
) => ({
|
||||
candidates: scripts.flatMap((script) =>
|
||||
native.map((item) => ({
|
||||
source_path: script.path,
|
||||
native_path: item.path,
|
||||
basis: bridgeBasis(item.path),
|
||||
})),
|
||||
),
|
||||
});
|
||||
roots: readonly string[],
|
||||
) => {
|
||||
const owner = (path: string): string | null =>
|
||||
roots.find((root) => isWithin(path, root)) ?? null;
|
||||
return {
|
||||
candidates: scripts.flatMap((script) => {
|
||||
const root = owner(script.path);
|
||||
return native
|
||||
.filter(({ path }) => owner(path) === root)
|
||||
.map((item) => ({
|
||||
source_path: script.path,
|
||||
native_path: item.path,
|
||||
basis: bridgeBasis(item.path),
|
||||
}));
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const bridgeBasis = (
|
||||
path: string,
|
||||
@@ -360,7 +370,7 @@ const projectionLimitations = (facts: {
|
||||
layout === "versioned-framework" && plist === null,
|
||||
)
|
||||
? [
|
||||
"A versioned framework has zero or several Versions/*/Resources/Info.plist files; the one Versions/Current selects is unknown because symlink targets are not inventoried.",
|
||||
"A versioned framework has several version directories or no Versions/*/Resources/Info.plist; the Info.plist that Versions/Current selects is unknown because symlink targets are not inventoried.",
|
||||
]
|
||||
: []),
|
||||
...(facts.symlinks
|
||||
|
||||
@@ -141,14 +141,18 @@ export const detectBundles = (
|
||||
interface Tree {
|
||||
readonly children: ReadonlyMap<string, ReadonlySet<string>>;
|
||||
readonly files: ReadonlyMap<string, Component>;
|
||||
/** Paths observed as directories, or implied by a deeper path. */
|
||||
readonly directories: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
const indexTree = (entries: readonly Entry[]): Tree => {
|
||||
const children = new Map<string, Set<string>>();
|
||||
const files = new Map<string, Component>();
|
||||
const directories = new Set<string>();
|
||||
for (const { path, kind, component } of entries) {
|
||||
if (isSidecar(path)) continue;
|
||||
if (kind === "file" && component !== undefined) files.set(path, component);
|
||||
if (kind === "directory") directories.add(path);
|
||||
const segments = path.split("/");
|
||||
let parent = "";
|
||||
for (const segment of segments) {
|
||||
@@ -156,9 +160,10 @@ const indexTree = (entries: readonly Entry[]): Tree => {
|
||||
names.add(segment);
|
||||
children.set(parent, names);
|
||||
parent = joinPath(parent, segment);
|
||||
if (parent !== path) directories.add(parent);
|
||||
}
|
||||
}
|
||||
return { children, files };
|
||||
return { children, files, directories };
|
||||
};
|
||||
|
||||
const joinPath = (directory: string, name: string): string =>
|
||||
@@ -223,9 +228,12 @@ const contentDirectories = (
|
||||
if (layout === "macos-deep") return [joinPath(directory, "Contents")];
|
||||
if (layout === "shallow") return [directory];
|
||||
const versions = joinPath(directory, "Versions");
|
||||
// Only real version directories count: Current is a symlink, and files
|
||||
// such as .DS_Store are not versions.
|
||||
return [...(tree.children.get(versions) ?? [])]
|
||||
.filter((version) => version !== "Current")
|
||||
.map((version) => joinPath(versions, version))
|
||||
.filter((version) => tree.directories.has(version))
|
||||
.sort(compare);
|
||||
};
|
||||
|
||||
@@ -234,7 +242,11 @@ const infoPlistPath = (
|
||||
layout: Bundle["layout"],
|
||||
tree: Tree,
|
||||
): string | null => {
|
||||
const candidates = contentDirectories(bundle, layout, tree)
|
||||
const directories = contentDirectories(bundle, layout, tree);
|
||||
// With several real versions, Versions/Current (a symlink outside the
|
||||
// inventory) decides which plist applies, so the plist stays unknown.
|
||||
if (directories.length !== 1) return null;
|
||||
const candidates = directories
|
||||
.map((directory) =>
|
||||
joinPath(
|
||||
directory,
|
||||
|
||||
@@ -119,14 +119,30 @@ const addExport = (output: Set<string>, name: string): void => {
|
||||
};
|
||||
|
||||
const memberPath = (node: t.Node | null | undefined): string => {
|
||||
if (node === undefined || node === null) return "";
|
||||
if (t.isIdentifier(node) || t.isPrivateName(node))
|
||||
return t.isIdentifier(node) ? node.name : "";
|
||||
if (t.isThisExpression(node)) return "this";
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const object = t.isNode(node.object) ? memberPath(node.object) : "";
|
||||
const property = propertyName(node.property);
|
||||
return object === "" ? property : `${object}.${property}`;
|
||||
const properties: string[] = [];
|
||||
let current = node;
|
||||
while (
|
||||
current !== undefined &&
|
||||
current !== null &&
|
||||
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
|
||||
) {
|
||||
properties.push(propertyName(current.property));
|
||||
current = t.isNode(current.object) ? current.object : undefined;
|
||||
}
|
||||
return "";
|
||||
|
||||
const root =
|
||||
current !== undefined && t.isIdentifier(current)
|
||||
? current.name
|
||||
: current !== undefined && t.isThisExpression(current)
|
||||
? "this"
|
||||
: "";
|
||||
if (properties.length === 0) return root;
|
||||
|
||||
properties.reverse();
|
||||
const path = root === "" ? [] : [root];
|
||||
for (const property of properties) {
|
||||
if (path.length === 0 && property === "") continue;
|
||||
path.push(property);
|
||||
}
|
||||
return path.join(".");
|
||||
};
|
||||
|
||||
@@ -192,6 +192,51 @@ describe("JavaScript semantic analysis: calls 2", () => {
|
||||
).not.toBe(left.functionFingerprints[0]?.components.literalSetSha256);
|
||||
});
|
||||
|
||||
it("keeps fingerprint relations ordered and effects scoped to their owner", () => {
|
||||
const ordered = analyzeJavaScriptSemantics(`
|
||||
function first() {}
|
||||
function second(one, two) {}
|
||||
function ordered() { first(); second(1, 2); }
|
||||
function timerOwner() { setTimeout(work, 10); }
|
||||
function networkOwner() { fetch('/data'); }
|
||||
function noEffects() { return 1; }
|
||||
`);
|
||||
const reversed = analyzeJavaScriptSemantics(`
|
||||
function first() {}
|
||||
function second(one, two) {}
|
||||
function ordered() { second(1, 2); first(); }
|
||||
function timerOwner() { setTimeout(work, 10); }
|
||||
function networkOwner() { fetch('/data'); }
|
||||
function noEffects() { return 1; }
|
||||
`);
|
||||
const fingerprint = (ir: typeof ordered, name: string) =>
|
||||
ir.functionFingerprints.find((value) =>
|
||||
ir.callables.some(
|
||||
(callable) =>
|
||||
callable.callableId === value.callableId && callable.name === name,
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
fingerprint(ordered, "ordered")?.components.relationShapeSha256,
|
||||
).not.toBe(
|
||||
fingerprint(reversed, "ordered")?.components.relationShapeSha256,
|
||||
);
|
||||
expect(fingerprint(ordered, "timerOwner")?.components.effects).toContain(
|
||||
"timer",
|
||||
);
|
||||
expect(fingerprint(ordered, "networkOwner")?.components.effects).toContain(
|
||||
"network",
|
||||
);
|
||||
expect(fingerprint(ordered, "noEffects")?.components.effects).toEqual([]);
|
||||
expect(
|
||||
fingerprint(ordered, "timerOwner")?.components.effects,
|
||||
).not.toContain("network");
|
||||
expect(
|
||||
fingerprint(ordered, "networkOwner")?.components.effects,
|
||||
).not.toContain("timer");
|
||||
});
|
||||
|
||||
it("retains ambiguous local callees and explicit dynamic frontiers", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function left(value) { return value; }
|
||||
|
||||
@@ -149,6 +149,31 @@ describe("JavaScript semantic analysis: dataflow 1", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic call result flows", () => {
|
||||
it("links only directly assigned scalar call results", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function run() {
|
||||
const direct = produce();
|
||||
const { field } = unpack();
|
||||
const nested = outer(inner());
|
||||
return direct;
|
||||
}
|
||||
`);
|
||||
const bindingNames = new Map(
|
||||
ir.bindings.map(({ bindingId, name }) => [bindingId, name]),
|
||||
);
|
||||
|
||||
expect(
|
||||
ir.callResultFlows.map(({ bindingId }) => bindingNames.get(bindingId)),
|
||||
).toEqual(["direct", "nested"]);
|
||||
expect(ir.callSites).toHaveLength(4);
|
||||
expect(ir.callResultFlows.map(({ callSiteId }) => callSiteId)).toEqual([
|
||||
ir.callSites[0]?.callSiteId,
|
||||
ir.callSites[2]?.callSiteId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic analysis: read-modify-write", () => {
|
||||
it.each(["+= 1", "++", "--", "||= 1", "&&= 1", "??= 1"])(
|
||||
"retains the property read in a read-modify-write operation: %s",
|
||||
|
||||
@@ -183,9 +183,7 @@ const collectCallResultFlow = (
|
||||
context.ancestors,
|
||||
context.state,
|
||||
).filter(({ projectionPath }) => projectionPath.length === 0)) {
|
||||
const binding = [...context.state.bindingsById.values()].find(
|
||||
({ bindingId }) => bindingId === assigned.bindingId,
|
||||
);
|
||||
const binding = context.state.bindingsById.get(assigned.bindingId);
|
||||
if (binding === undefined) continue;
|
||||
const identifierRange = range(assigned.identifier);
|
||||
const definition = binding.definitions.find(
|
||||
|
||||
@@ -50,30 +50,36 @@ export const collectJavaScriptSemanticFingerprints = (
|
||||
resourceOperations,
|
||||
parserPartial,
|
||||
} = input;
|
||||
const callSitesByCaller = groupByOwner(
|
||||
calls.callSites,
|
||||
({ callerCallableId }) => callerCallableId,
|
||||
);
|
||||
const captureCountByCallable = countByOwner(
|
||||
calls.closureCaptures,
|
||||
({ callableId }) => callableId,
|
||||
);
|
||||
const promiseEffectsByOwner = groupByOwner(promises, ownerId);
|
||||
const eventEffectsByOwner = groupByOwner(events, ownerId);
|
||||
const timerEffectsByOwner = groupByOwner(timers, ownerId);
|
||||
const childProcessEffectsByOwner = groupByOwner(
|
||||
[...childProcessSpawns, ...childProcessInteractions],
|
||||
ownerId,
|
||||
);
|
||||
const networkEffectsByOwner = groupByOwner(requestOperations, ownerId);
|
||||
const resourceEffectsByOwner = groupByOwner(resourceOperations, ownerId);
|
||||
return callables.flatMap((callable) => {
|
||||
if (callable.kind === "class") return [];
|
||||
const node = state.callableNodesById.get(callable.callableId);
|
||||
if (node === undefined) return [];
|
||||
const syntax = fingerprintSyntax(node, callable.callableId);
|
||||
const promiseEffects = promises.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const eventEffects = events.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const timerEffects = timers.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const childProcessEffects = [
|
||||
...childProcessSpawns,
|
||||
...childProcessInteractions,
|
||||
].filter(({ ownerCallableId }) => ownerCallableId === callable.callableId);
|
||||
const networkEffects = requestOperations.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const resourceEffects = resourceOperations.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const promiseEffects = promiseEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const eventEffects = eventEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const timerEffects = timerEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const childProcessEffects =
|
||||
childProcessEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const networkEffects = networkEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const resourceEffects =
|
||||
resourceEffectsByOwner.get(callable.callableId) ?? [];
|
||||
return [
|
||||
{
|
||||
callableId: callable.callableId,
|
||||
@@ -86,7 +92,12 @@ export const collectJavaScriptSemanticFingerprints = (
|
||||
normalizedAstSha256: digest(syntax.normalizedTokens),
|
||||
controlFlowSha256: digest(syntax.controlFlowTokens),
|
||||
relationShapeSha256: digest(
|
||||
relationShape(callable, calls, promiseEffects),
|
||||
relationShape(
|
||||
callable,
|
||||
callSitesByCaller.get(callable.callableId) ?? [],
|
||||
captureCountByCallable.get(callable.callableId) ?? 0,
|
||||
promiseEffects,
|
||||
),
|
||||
),
|
||||
literalSetSha256: digest(
|
||||
[...new Set(syntax.literals)].sort(compareCodePoints),
|
||||
@@ -114,6 +125,36 @@ export const collectJavaScriptSemanticFingerprints = (
|
||||
});
|
||||
};
|
||||
|
||||
const ownerId = <T extends { readonly ownerCallableId: string | null }>(
|
||||
value: T,
|
||||
): string | null => value.ownerCallableId;
|
||||
|
||||
const groupByOwner = <T, K extends string | null>(
|
||||
values: readonly T[],
|
||||
getOwner: (value: T) => K,
|
||||
): Map<K, T[]> => {
|
||||
const grouped = new Map<K, T[]>();
|
||||
for (const value of values) {
|
||||
const owner = getOwner(value);
|
||||
const ownedValues = grouped.get(owner);
|
||||
if (ownedValues === undefined) grouped.set(owner, [value]);
|
||||
else ownedValues.push(value);
|
||||
}
|
||||
return grouped;
|
||||
};
|
||||
|
||||
const countByOwner = <T, K extends string | null>(
|
||||
values: readonly T[],
|
||||
getOwner: (value: T) => K,
|
||||
): Map<K, number> => {
|
||||
const counts = new Map<K, number>();
|
||||
for (const value of values) {
|
||||
const owner = getOwner(value);
|
||||
counts.set(owner, (counts.get(owner) ?? 0) + 1);
|
||||
}
|
||||
return counts;
|
||||
};
|
||||
|
||||
interface FingerprintSyntax {
|
||||
readonly normalizedTokens: readonly string[];
|
||||
readonly controlFlowTokens: readonly string[];
|
||||
@@ -229,21 +270,16 @@ const semanticLiteral = (node: t.Node): string | null => {
|
||||
|
||||
const relationShape = (
|
||||
callable: JavaScriptSemanticCallable,
|
||||
calls: JavaScriptSemanticCallAnalysis,
|
||||
callSites: JavaScriptSemanticCallAnalysis["callSites"],
|
||||
captureCount: number,
|
||||
promises: readonly JavaScriptSemanticPromiseOperation[],
|
||||
): string[] => [
|
||||
`returns:${String(callable.returnSites.length)}:${callable.returnCoverage.status}`,
|
||||
...calls.callSites
|
||||
.filter(({ callerCallableId }) => callerCallableId === callable.callableId)
|
||||
.map(
|
||||
({ kind, resolution, arguments: args, calleeCallableIds }) =>
|
||||
`call:${kind}:${resolution}:${String(args.length)}:${String(calleeCallableIds.length)}`,
|
||||
),
|
||||
`captures:${String(
|
||||
calls.closureCaptures.filter(
|
||||
({ callableId }) => callableId === callable.callableId,
|
||||
).length,
|
||||
)}`,
|
||||
...callSites.map(
|
||||
({ kind, resolution, arguments: args, calleeCallableIds }) =>
|
||||
`call:${kind}:${resolution}:${String(args.length)}:${String(calleeCallableIds.length)}`,
|
||||
),
|
||||
`captures:${String(captureCount)}`,
|
||||
...promises.map(
|
||||
({ kind, method, ownership, sourceResolution }) =>
|
||||
`promise:${kind}:${method}:${ownership}:${sourceResolution}`,
|
||||
|
||||
@@ -51,3 +51,16 @@ it("preserves source-tree enter/exit order and detached ancestor snapshots", ()
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips sparse child slots without disturbing sibling visit order", () => {
|
||||
const parsed = parseJavaScriptSource("const values = [first, , second];");
|
||||
if (parsed === null)
|
||||
throw new TypeError("Expected a parsed JavaScript fixture");
|
||||
const identifiers: string[] = [];
|
||||
traverseJavaScriptAst(parsed.program, {
|
||||
enter: (node) => {
|
||||
if (t.isIdentifier(node)) identifiers.push(node.name);
|
||||
},
|
||||
});
|
||||
expect(identifiers).toEqual(["values", "first", "second"]);
|
||||
});
|
||||
|
||||
@@ -51,11 +51,19 @@ interface TraversalFrame {
|
||||
}
|
||||
|
||||
const childNodes = (node: t.Node): t.Node[] => {
|
||||
const keys: readonly string[] = t.VISITOR_KEYS[node.type] ?? [];
|
||||
return keys.flatMap((key) => {
|
||||
const keys = t.VISITOR_KEYS[node.type];
|
||||
if (keys === undefined) return [];
|
||||
const children: t.Node[] = [];
|
||||
for (const key of keys) {
|
||||
const value: unknown = Reflect.get(node, key);
|
||||
if (t.isNode(value)) return [value];
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter((item): item is t.Node => t.isNode(item));
|
||||
});
|
||||
if (t.isNode(value)) {
|
||||
children.push(value);
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(value)) continue;
|
||||
for (const item of value) {
|
||||
if (t.isNode(item)) children.push(item);
|
||||
}
|
||||
}
|
||||
return children;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { collectJavaScriptExports } from "./javascriptAstFingerprint.js";
|
||||
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
|
||||
|
||||
const memberChain = ".next".repeat(12_000);
|
||||
|
||||
it("collects a 12,000-member CommonJS export path without recursion", () => {
|
||||
const file = parseJavaScriptSource(`exports${memberChain}.last = 1;`);
|
||||
if (file === null) throw new Error("Expected valid JavaScript");
|
||||
expect(collectJavaScriptExports(file).values).toEqual([
|
||||
`${"next.".repeat(12_000)}last`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves empty, dynamic, this, and private member path behavior", () => {
|
||||
const file = parseJavaScriptSource(`
|
||||
exports[""].value = 1;
|
||||
exports[""] = 0;
|
||||
exports[key].value = 2;
|
||||
this.exports.ignored = 3;
|
||||
class Example { #private = 0; read() { this.#private = 1; } }
|
||||
`);
|
||||
if (file === null) throw new Error("Expected valid JavaScript");
|
||||
expect(collectJavaScriptExports(file).values).toEqual([
|
||||
"",
|
||||
".value",
|
||||
"key.value",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps left-first and outer-member-first bundler runtime matches", () => {
|
||||
const source = `
|
||||
(globalThis.webpackChunkLeft || globalThis.webpackChunkRight).push([[1], { 1: function() {} }]);
|
||||
globalThis.webpackChunkOuter.webpackChunkInner.push([[2], { 2: function() {} }]);
|
||||
`;
|
||||
const analysis = analyzeJavaScriptStaticSource(source);
|
||||
expect(
|
||||
analysis.bundler_registrations.find(({ chunk_keys }) =>
|
||||
chunk_keys.includes("1"),
|
||||
)?.runtime,
|
||||
).toBe("webpackChunkLeft");
|
||||
expect(
|
||||
analysis.bundler_registrations.find(({ chunk_keys }) =>
|
||||
chunk_keys.includes("2"),
|
||||
)?.runtime,
|
||||
).toBe("webpackChunkInner");
|
||||
});
|
||||
|
||||
it("analyzes a 12,000-member bundler runtime chain without recursion", () => {
|
||||
const source = `globalThis.webpackChunkApp${memberChain}.push([[1], { 1: function(module) { module.exports.ok = 42; } }]);`;
|
||||
const analysis = analyzeJavaScriptStaticSource(source);
|
||||
expect(analysis.parse_status).toBe("complete");
|
||||
expect(analysis.parse_error_count).toBe(0);
|
||||
expect(analysis.bundler_registrations).toHaveLength(1);
|
||||
expect(analysis.bundler_registrations[0]).toMatchObject({
|
||||
bundler: "webpack",
|
||||
runtime: "webpackChunkApp",
|
||||
chunk_keys: ["1"],
|
||||
modules: [expect.objectContaining({ exports: ["ok"] })],
|
||||
});
|
||||
});
|
||||
@@ -73,19 +73,38 @@ export const chunkRuntime = (call: t.CallExpression): string | undefined => {
|
||||
};
|
||||
|
||||
const findChunkRuntime = (node: t.Node): string | undefined => {
|
||||
if (t.isIdentifier(node) && /(?:webpack|rspack)Chunk/iu.test(node.name))
|
||||
return node.name;
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const property = semanticStaticPropertyName(node.property, node.computed);
|
||||
if (/(?:webpack|rspack)Chunk/iu.test(property)) return property;
|
||||
return t.isNode(node.object) ? findChunkRuntime(node.object) : undefined;
|
||||
const pending: t.Node[] = [node];
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) continue;
|
||||
if (
|
||||
t.isIdentifier(current) &&
|
||||
/(?:webpack|rspack)Chunk/iu.test(current.name)
|
||||
)
|
||||
return current.name;
|
||||
if (
|
||||
t.isMemberExpression(current) ||
|
||||
t.isOptionalMemberExpression(current)
|
||||
) {
|
||||
const property = semanticStaticPropertyName(
|
||||
current.property,
|
||||
current.computed,
|
||||
);
|
||||
if (/(?:webpack|rspack)Chunk/iu.test(property)) return property;
|
||||
if (t.isNode(current.object)) pending.push(current.object);
|
||||
continue;
|
||||
}
|
||||
if (t.isAssignmentExpression(current)) {
|
||||
pending.push(current.right, current.left);
|
||||
continue;
|
||||
}
|
||||
if (t.isLogicalExpression(current) || t.isBinaryExpression(current)) {
|
||||
pending.push(current.right, current.left);
|
||||
continue;
|
||||
}
|
||||
if (t.isParenthesizedExpression(current) || t.isTSAsExpression(current))
|
||||
pending.push(current.expression);
|
||||
}
|
||||
if (t.isAssignmentExpression(node))
|
||||
return findChunkRuntime(node.left) ?? findChunkRuntime(node.right);
|
||||
if (t.isLogicalExpression(node) || t.isBinaryExpression(node))
|
||||
return findChunkRuntime(node.left) ?? findChunkRuntime(node.right);
|
||||
if (t.isParenthesizedExpression(node) || t.isTSAsExpression(node))
|
||||
return findChunkRuntime(node.expression);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
|
||||
+5
-5
@@ -3,13 +3,13 @@ import { createHash } from "node:crypto";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js";
|
||||
import { evidenceSchema, parseEvidence, type Evidence } from "../evidence.js";
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
javascriptApplicationGraphSchema,
|
||||
type ApplicationEdge,
|
||||
type ApplicationNode,
|
||||
} from "./javascript/javascriptApplicationGraph.js";
|
||||
} from "../javascript/javascriptApplicationGraph.js";
|
||||
import {
|
||||
managedArtifactInspectionSchema,
|
||||
managedMemberInspectionSchema,
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
type ManagedMemberInspection,
|
||||
type ManagedNativeBoundaryInspection,
|
||||
} from "./managedArtifact.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import type { JsonValue } from "../jsonValue.js";
|
||||
import {
|
||||
assessManagedGraphOmissions,
|
||||
managedGraphEvidenceCoverage,
|
||||
@@ -30,8 +30,8 @@ import {
|
||||
addBoundaryNodes,
|
||||
addMemberNodes,
|
||||
} from "./managedApplicationGraphNodes.js";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { prefixedDigestSchema } from "../digests.js";
|
||||
|
||||
const evidenceIdSchema = prefixedDigestSchema("ev");
|
||||
const textSchema = z.string().min(1);
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { ApplicationGraphEvidence } from "./javascript/javascriptApplicationGraph.js";
|
||||
import type { ApplicationGraphEvidence } from "../javascript/javascriptApplicationGraph.js";
|
||||
import type {
|
||||
ManagedArtifactInspection,
|
||||
ManagedMemberInspection,
|
||||
+1
-1
@@ -4,7 +4,7 @@ import {
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationGraphEvidence,
|
||||
type ApplicationNode,
|
||||
} from "./javascript/javascriptApplicationGraph.js";
|
||||
} from "../javascript/javascriptApplicationGraph.js";
|
||||
import { managedSourceCoverage } from "./managedApplicationGraphCoverage.js";
|
||||
import {
|
||||
type ManagedMemberInspection,
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { digestSchema } from "../digests.js";
|
||||
|
||||
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
|
||||
const offsetSchema = z.number().int().min(0);
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { emptyArraySchema } from "./emptyArraySchema.js";
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
import { emptyArraySchema } from "../emptyArraySchema.js";
|
||||
import { evidenceSchema } from "../evidence.js";
|
||||
import {
|
||||
cliMetadataGuidSchema,
|
||||
type ManagedMemberInspection,
|
||||
@@ -18,8 +18,8 @@ import {
|
||||
buildMethodItems,
|
||||
} from "./managedMemberComparisonItems.js";
|
||||
import { keyMembers, sha256 } from "./managedMemberComparisonMatch.js";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { prefixedDigestSchema } from "../digests.js";
|
||||
|
||||
const evidenceIdSchema = prefixedDigestSchema("ev");
|
||||
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
|
||||
+2
-2
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { parseEvidence } from "./evidence.js";
|
||||
import { parseEvidence } from "../evidence.js";
|
||||
import {
|
||||
managedMemberInspectionSchema,
|
||||
type ManagedMemberInspection,
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
ManagedMemberComparisonResult,
|
||||
ManagedMemberComparisonSide,
|
||||
} from "./managedMemberComparison.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import type { JsonValue } from "../jsonValue.js";
|
||||
|
||||
export const sha256 = (value: JsonValue): string => {
|
||||
const serialized = canonicalize(value);
|
||||
+2
-2
@@ -2,12 +2,12 @@ import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { parseEvidence } from "./evidence.js";
|
||||
import { parseEvidence } from "../evidence.js";
|
||||
import {
|
||||
managedNativeBoundaryInspectionSchema,
|
||||
type ManagedNativeBoundaryInspection,
|
||||
} from "./managedArtifact.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import type { JsonValue } from "../jsonValue.js";
|
||||
import {
|
||||
managedNativeVerificationResultSchema,
|
||||
type ManagedNativeVerificationInput,
|
||||
+4
-4
@@ -3,11 +3,11 @@ import { basename } from "node:path";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { parseEvidence } from "./evidence.js";
|
||||
import { functionDossierSchema } from "./hopperValues.js";
|
||||
import { inspectMachoSchema } from "./nativeInspection.js";
|
||||
import { parseEvidence } from "../evidence.js";
|
||||
import { functionDossierSchema } from "../hopperValues.js";
|
||||
import { inspectMachoSchema } from "../nativeInspection.js";
|
||||
import type { ManagedNativeBoundaryInspection } from "./managedArtifact.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import type { JsonValue } from "../jsonValue.js";
|
||||
import {
|
||||
pinvokeVerificationSchema,
|
||||
type ManagedNativeVerificationInput,
|
||||
+4
-4
@@ -1,10 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { emptyArraySchema } from "./emptyArraySchema.js";
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
import { emptyArraySchema } from "../emptyArraySchema.js";
|
||||
import { evidenceSchema } from "../evidence.js";
|
||||
import { cliMetadataGuidSchema } from "./managedArtifact.js";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { prefixedDigestSchema } from "../digests.js";
|
||||
|
||||
const evidenceIdSchema = prefixedDigestSchema("ev");
|
||||
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidence } from "../evidence.js";
|
||||
import { managedReconstructionImportInputSchema } from "./managedReconstruction.js";
|
||||
|
||||
describe("managed reconstruction import input", () => {
|
||||
@@ -3,15 +3,15 @@ import { createHash } from "node:crypto";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceSchema, parseEvidence } from "./evidence.js";
|
||||
import { evidenceSchema, parseEvidence } from "../evidence.js";
|
||||
import {
|
||||
cliMetadataGuidSchema,
|
||||
managedMemberInspectionSchema,
|
||||
type ManagedMemberInspection,
|
||||
} from "./managedArtifact.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import type { JsonValue } from "../jsonValue.js";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { prefixedDigestSchema } from "../digests.js";
|
||||
|
||||
const evidenceIdSchema = prefixedDigestSchema("ev");
|
||||
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
|
||||
@@ -166,6 +166,7 @@ describe("Interface Builder dispatch joins", () => {
|
||||
const joined = joinInterfaceBuilderDispatch(ui.graph, {
|
||||
objc_classes: [],
|
||||
objc_protocols: [],
|
||||
objc_categories: [],
|
||||
swift_decls: [],
|
||||
objc_ivars: [],
|
||||
objc_protocol_records: [],
|
||||
@@ -227,6 +228,7 @@ describe("Interface Builder dispatch joins", () => {
|
||||
const metadata = {
|
||||
objc_classes: [],
|
||||
objc_protocols: [],
|
||||
objc_categories: [],
|
||||
swift_decls: [],
|
||||
objc_ivars: [],
|
||||
objc_protocol_records: [],
|
||||
@@ -304,6 +306,7 @@ describe("placeholder dispatch joins", () => {
|
||||
const joined = joinInterfaceBuilderDispatch(ui.graph, {
|
||||
objc_classes: [],
|
||||
objc_protocols: [],
|
||||
objc_categories: [],
|
||||
swift_decls: [],
|
||||
objc_ivars: [],
|
||||
objc_protocol_records: [],
|
||||
|
||||
@@ -156,6 +156,8 @@ export const objcDispatchImplementationSchema = z.strictObject({
|
||||
selector: z.string().min(1),
|
||||
method_type: z.enum(["instance", "class"]),
|
||||
implementation_address: z.string().nullable(),
|
||||
/** Category that adds this method, when it is not defined by the class itself. */
|
||||
category: z.string().nullable().optional(),
|
||||
location: nativeMetadataLocationSchema,
|
||||
decode: nativeMetadataDecodeSchema,
|
||||
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
|
||||
@@ -164,6 +166,21 @@ export type ObjcDispatchImplementation = z.infer<
|
||||
typeof objcDispatchImplementationSchema
|
||||
>;
|
||||
|
||||
/** Objective-C category: methods, protocols and properties added to a class. */
|
||||
export const objcCategorySchema = z.strictObject({
|
||||
name: z.string().min(1),
|
||||
/** Extended class; external classes come from the category's bind symbol. */
|
||||
class_name: z.string().min(1).nullable(),
|
||||
class_source: z.enum(["local", "external", "unresolved"]),
|
||||
instance_methods: z.array(z.string()),
|
||||
class_methods: z.array(z.string()),
|
||||
protocols: z.array(z.string()),
|
||||
properties: z.array(objcPropertySchema),
|
||||
location: nativeMetadataLocationSchema,
|
||||
decode: nativeMetadataDecodeSchema,
|
||||
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
|
||||
});
|
||||
|
||||
/** Swift protocol conformance and its associated witness-table location. */
|
||||
export const swiftConformanceSchema = z.strictObject({
|
||||
type_name: z.string().min(1),
|
||||
@@ -279,6 +296,7 @@ export type DbSaveResult = z.infer<typeof dbSaveResultSchema>;
|
||||
export const objcSwiftMetadataSchema = z.strictObject({
|
||||
objc_classes: z.array(objcClassSchema).default([]),
|
||||
objc_protocols: z.array(objcProtocolSchema).default([]),
|
||||
objc_categories: z.array(objcCategorySchema).default([]),
|
||||
swift_decls: z.array(swiftDeclSchema).default([]),
|
||||
objc_ivars: z.array(objcIvarSchema).default([]),
|
||||
objc_protocol_records: z.array(objcProtocolRecordSchema).default([]),
|
||||
|
||||
@@ -28,13 +28,37 @@ describe("direct process scenarios", () => {
|
||||
});
|
||||
|
||||
it("rejects malformed environment names and adapter-reserved identity", () => {
|
||||
for (const name of ["", "KEY=VALUE", "KEY\0VALUE", "REA_PROCESS_RUN_ID"])
|
||||
expect(
|
||||
processScenarioSchema.safeParse({
|
||||
executable: "node",
|
||||
environment: { [name]: "value" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
for (const name of ["", "KEY=VALUE", "KEY\0VALUE", "REA_PROCESS_RUN_ID"]) {
|
||||
const result = processScenarioSchema.safeParse({
|
||||
executable: "node",
|
||||
environment: { [name]: "value" },
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (name === "" && !result.success) {
|
||||
const invalidKey = result.error.issues[0];
|
||||
expect(invalidKey?.code).toBe("invalid_key");
|
||||
if (invalidKey?.code === "invalid_key") {
|
||||
expect(invalidKey.issues[0]?.message).toBe(
|
||||
"Environment names must not be empty",
|
||||
);
|
||||
}
|
||||
}
|
||||
if (name === "REA_PROCESS_RUN_ID" && !result.success) {
|
||||
const invalidKey = result.error.issues[0];
|
||||
expect(invalidKey?.code).toBe("invalid_key");
|
||||
if (invalidKey?.code === "invalid_key") {
|
||||
expect(invalidKey.issues[0]?.message).toBe(
|
||||
"REA_PROCESS_RUN_ID is reserved by the process adapter",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(
|
||||
processScenarioSchema.safeParse({
|
||||
executable: "node",
|
||||
environment: { "REA_PROCESS_RUN_ID\n": "caller-value" },
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps bounded capture controls and ordered scheduled interaction", () => {
|
||||
|
||||
@@ -4,10 +4,16 @@ import { z } from "zod";
|
||||
|
||||
const positiveBudget = z.number().int().safe().positive();
|
||||
const timedEventBase = { at_ms: z.number().int().safe().nonnegative() };
|
||||
const reservedRunIdEnvironmentName = "REA_PROCESS_RUN_ID";
|
||||
const environmentName = z
|
||||
.string()
|
||||
.regex(/^[^=\0]+$/u, "Environment names cannot contain '=' or NUL");
|
||||
const reservedEnvironment = new Set(["REA_PROCESS_RUN_ID"]);
|
||||
.min(1, "Environment names must not be empty")
|
||||
.regex(/^(?!REA_PROCESS_RUN_ID(?![\s\S]))[^=\0]+$/u, {
|
||||
error: (issue) =>
|
||||
issue.input === reservedRunIdEnvironmentName
|
||||
? `${reservedRunIdEnvironmentName} is reserved by the process adapter`
|
||||
: "Environment names cannot contain '=' or NUL",
|
||||
});
|
||||
export const normalizationSchema = z.object({
|
||||
paths: z.boolean(),
|
||||
pids: z.boolean(),
|
||||
@@ -170,16 +176,6 @@ export const processScenarioSchema = z
|
||||
});
|
||||
}
|
||||
}
|
||||
const explicit = new Set(Object.keys(scenario.environment));
|
||||
for (const name of explicit) {
|
||||
if (reservedEnvironment.has(name)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `${name} is reserved by the process adapter`,
|
||||
path: ["environment", name],
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const event of scenario.events) {
|
||||
if (event.at_ms > scenario.timeout_ms) {
|
||||
context.addIssue({
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
managedArtifactInspectionSchema,
|
||||
type ManagedArtifactInspection,
|
||||
type ManagedParseIssue,
|
||||
} from "../domain/managedArtifact.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
readManagedPeLayout,
|
||||
type ManagedCliHeader,
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
managedMemberInspectionSchema,
|
||||
type ManagedMemberInspection,
|
||||
type ManagedParseIssue,
|
||||
} from "../domain/managedArtifact.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
readManagedPeLayout,
|
||||
type ManagedPeLayout,
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
managedFailure,
|
||||
ManagedReaderFailure,
|
||||
} from "./ManagedReaderFailure.js";
|
||||
import type { ManagedMemberInspection } from "../domain/managedArtifact.js";
|
||||
import type { ManagedMemberInspection } from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
type ManagedMetadataLayout,
|
||||
type MetadataTableLayout,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
ManagedArtifactInspection,
|
||||
ManagedParseIssue,
|
||||
} from "../domain/managedArtifact.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
METADATA_TABLE_NAMES,
|
||||
type ManagedMetadataLayout,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
ManagedArtifactInspection,
|
||||
ManagedParseIssue,
|
||||
} from "../domain/managedArtifact.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
metadataRowOffset,
|
||||
type ManagedMetadataLayout,
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
managedNativeBoundaryInspectionSchema,
|
||||
type ManagedNativeBoundaryInspection,
|
||||
type ManagedParseIssue,
|
||||
} from "../domain/managedArtifact.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import { type ManagedMetadataLayout } from "./ManagedMetadataLayout.js";
|
||||
import {
|
||||
metadataRowCursor,
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
managedNativeBoundaryInspectionSchema,
|
||||
type ManagedNativeBoundaryInspection,
|
||||
type ManagedParseIssue,
|
||||
} from "../domain/managedArtifact.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
readManagedMetadataInventory,
|
||||
type ManagedResourceDirectory,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ManagedParseIssue } from "../domain/managedArtifact.js";
|
||||
import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
managedFailure,
|
||||
ManagedReaderFailure,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ManagedParseIssue } from "../domain/managedArtifact.js";
|
||||
import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";
|
||||
|
||||
/** Bounded format failure retained as caller-visible managed coverage. */
|
||||
export class ManagedReaderFailure extends Error {
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
managedMemberInputSchema,
|
||||
managedNativeBoundaryInputSchema,
|
||||
type ManagedToolName,
|
||||
} from "../contracts/managedToolContracts.js";
|
||||
} from "../contracts/managed/managedToolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
@@ -35,7 +35,7 @@ import type {
|
||||
ManagedArtifactInspection,
|
||||
ManagedMemberInspection,
|
||||
ManagedNativeBoundaryInspection,
|
||||
} from "../domain/managedArtifact.js";
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
|
||||
@@ -6,7 +6,7 @@ import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.j
|
||||
import {
|
||||
MANAGED_TOOL_CONTRACTS,
|
||||
type ManagedToolName,
|
||||
} from "../contracts/managedToolContracts.js";
|
||||
} from "../contracts/managed/managedToolContracts.js";
|
||||
|
||||
/** Identity of execution-free managed metadata observations. */
|
||||
export const MANAGED_STATIC_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze(
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -312,6 +312,36 @@ describe("headless IDA lifecycle boundaries", () => {
|
||||
});
|
||||
|
||||
describe("headless IDA session ownership and cleanup", () => {
|
||||
it("shares an in-flight close across concurrent cleanup callers", async () => {
|
||||
const { producer, client } = await fixture("headless");
|
||||
expect((await client.execute("health", {})).ok).toBe(true);
|
||||
|
||||
let release: (() => void) | undefined;
|
||||
let notify: (() => void) | undefined;
|
||||
const closeStarted = new Promise<void>((resolve) => {
|
||||
notify = resolve;
|
||||
});
|
||||
producer.beforeCall = async (name) => {
|
||||
if (name !== "idb_close") return;
|
||||
notify?.();
|
||||
await new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
};
|
||||
|
||||
const first = client.closeWithOutcome();
|
||||
await closeStarted;
|
||||
const second = client.closeWithOutcome();
|
||||
release?.();
|
||||
const results = await Promise.all([first, second]);
|
||||
|
||||
expect(results.every((result) => result.ok)).toBe(true);
|
||||
expect(
|
||||
producer.calls.filter(({ name }) => name === "idb_close"),
|
||||
).toHaveLength(1);
|
||||
expect(producer.closes).toBe(1);
|
||||
});
|
||||
|
||||
it("retains the workspace after an unconfirmed open, even when inventory is empty, and never retries startup implicitly", async () => {
|
||||
const { producer, client, root } = await fixture("headless");
|
||||
producer.beforeCall = async (name) => {
|
||||
|
||||
@@ -95,6 +95,7 @@ export class IdaSessionClient implements AnalysisClient {
|
||||
#startup: Promise<void> | undefined;
|
||||
#closed = false;
|
||||
#closing = false;
|
||||
#closePromise: Promise<Result<null, AnalysisError>> | undefined;
|
||||
#workspace: IdaWorkspace | undefined;
|
||||
#database: string | undefined;
|
||||
#openAttempted = false;
|
||||
@@ -385,6 +386,16 @@ export class IdaSessionClient implements AnalysisClient {
|
||||
}
|
||||
|
||||
async closeWithOutcome(): Promise<Result<null, AnalysisError>> {
|
||||
if (this.#closePromise !== undefined) return this.#closePromise;
|
||||
const closing = this.#closeOnce();
|
||||
const shared = closing.finally(() => {
|
||||
if (this.#closePromise === shared) this.#closePromise = undefined;
|
||||
});
|
||||
this.#closePromise = shared;
|
||||
return shared;
|
||||
}
|
||||
|
||||
async #closeOnce(): Promise<Result<null, AnalysisError>> {
|
||||
this.#closing = true;
|
||||
await this.#tail;
|
||||
if (this.#closed) return ok(null);
|
||||
|
||||
@@ -151,6 +151,9 @@ describe("source-map layout admission", () => {
|
||||
expect(() => trace({ ...leaf, mappings })).toThrow();
|
||||
},
|
||||
);
|
||||
it("validates regular-map source indexes after reusing its decoded rows", () => {
|
||||
expect(() => trace({ ...leaf, mappings: "ACAA" })).toThrow(/index/u);
|
||||
});
|
||||
it("rejects huge indexed offsets before upstream row allocation", () => {
|
||||
expect(() =>
|
||||
trace({
|
||||
|
||||
@@ -81,10 +81,12 @@ const decodeValidatedMap = (
|
||||
inspected: ReturnType<typeof inspectSourceMap>,
|
||||
url: string,
|
||||
) => {
|
||||
let regularRows: ReturnType<typeof decodedMappings> | undefined;
|
||||
for (const leaf of inspected.leaves) {
|
||||
const decoded = decodedMappings(
|
||||
new TraceMap(JSON.stringify(leaf.map), url),
|
||||
);
|
||||
if (inspected.format === "regular") regularRows = decoded;
|
||||
for (const [line, row] of decoded.entries())
|
||||
for (const segment of row) {
|
||||
if (
|
||||
@@ -112,7 +114,7 @@ const decodeValidatedMap = (
|
||||
}
|
||||
}
|
||||
const map = new AnyMap(inspected.jsonText, url);
|
||||
const rows = decodedMappings(map);
|
||||
const rows = regularRows ?? decodedMappings(map);
|
||||
for (const row of rows)
|
||||
for (const segment of row) {
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { ObjcSwiftMetadata } from "../domain/objcSwiftMetadata.js";
|
||||
import type { PointerFixups } from "./AppleMachoFixups.js";
|
||||
|
||||
const describeFixups = (fixups: PointerFixups): string => {
|
||||
if (fixups.kind === "chained")
|
||||
return `chained fixups: ${fixups.formats.join(", ") || "no fixup segments"}`;
|
||||
return fixups.kind === "dyld-info"
|
||||
? "LC_DYLD_INFO bind opcodes"
|
||||
: "no fixup load commands";
|
||||
};
|
||||
|
||||
/** Append the per-facet coverage of one Apple dispatch metadata decode. */
|
||||
export const pushDispatchCoverage = (input: {
|
||||
readonly result: ObjcSwiftMetadata;
|
||||
readonly failures: readonly string[];
|
||||
readonly examined: number;
|
||||
readonly categoriesExamined: number;
|
||||
readonly truncated: boolean;
|
||||
readonly fixups: PointerFixups;
|
||||
}): void => {
|
||||
const { result, failures, examined, categoriesExamined, truncated, fixups } =
|
||||
input;
|
||||
result.coverage.push({
|
||||
facet: "objc_class_method_ivar_metadata",
|
||||
status: failures.length > 0 || truncated ? "partial" : "complete",
|
||||
reason:
|
||||
[...failures, ...(truncated ? ["max_records_reached"] : [])].join("; ") ||
|
||||
null,
|
||||
examined,
|
||||
decoded: result.objc_classes.length,
|
||||
});
|
||||
result.coverage.push({
|
||||
facet: "binary_relative_pointers",
|
||||
status:
|
||||
truncated ||
|
||||
result.relative_pointers.some((item) => item.decode.status !== "decoded")
|
||||
? "partial"
|
||||
: "complete",
|
||||
reason: truncated
|
||||
? "max_records_reached"
|
||||
: result.relative_pointers.some(
|
||||
(item) => item.decode.status !== "decoded",
|
||||
)
|
||||
? "relative_pointer_targets_unresolved"
|
||||
: null,
|
||||
examined: result.relative_pointers.length,
|
||||
decoded: result.relative_pointers.filter(
|
||||
(item) => item.decode.status === "decoded",
|
||||
).length,
|
||||
});
|
||||
const categoryFailures = failures.filter((failure) =>
|
||||
/^(?:Properties of|Category at)/u.test(failure),
|
||||
);
|
||||
result.coverage.push({
|
||||
facet: "objc_properties_categories",
|
||||
status:
|
||||
categoryFailures.length > 0 ||
|
||||
result.objc_categories.some(({ decode }) => decode.status !== "decoded")
|
||||
? "partial"
|
||||
: "complete",
|
||||
reason: categoryFailures.join("; ") || null,
|
||||
examined: categoriesExamined,
|
||||
decoded: result.objc_categories.filter(
|
||||
({ decode }) => decode.status === "decoded",
|
||||
).length,
|
||||
});
|
||||
result.coverage.push({
|
||||
facet: "pointer_fixups",
|
||||
status: fixups.failures.length > 0 ? "partial" : "complete",
|
||||
reason: [describeFixups(fixups), ...fixups.failures].join("; "),
|
||||
examined: 0,
|
||||
decoded: 0,
|
||||
});
|
||||
result.coverage.push({
|
||||
facet: "swift_generic_resilient_witnesses_overrides_async_coroutines",
|
||||
status: "unsupported",
|
||||
reason:
|
||||
"This reader admits simple Swift conformance/static witness records and non-generic, non-resilient class vtables; generic/resilient tables and other Swift metadata families are not decoded",
|
||||
examined: 0,
|
||||
decoded: 0,
|
||||
});
|
||||
};
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
|
||||
import { pushDispatchCoverage } from "./AppleDispatchCoverage.js";
|
||||
import { parsePointerFixups } from "./AppleMachoFixups.js";
|
||||
import { parseMachoLayout } from "./AppleMachoSelection.js";
|
||||
import { decodeObjcDispatchFacets } from "./AppleObjcDispatchFacets.js";
|
||||
import {
|
||||
@@ -25,10 +27,26 @@ export const decodeAppleDispatchMetadata = (
|
||||
provenance: { path: string; sha256: string },
|
||||
architecture = "arm64",
|
||||
): ObjcSwiftMetadata => {
|
||||
const { segments, sections, offset } = parseMachoLayout(bytes, architecture);
|
||||
const layout = parseMachoLayout(bytes, architecture);
|
||||
const { segments, sections, offset } = layout;
|
||||
const fixups = parsePointerFixups(
|
||||
bytes,
|
||||
layout.fixups,
|
||||
segments,
|
||||
layout.baseAddress,
|
||||
);
|
||||
const u32 = (address: bigint) => bytes.readUInt32LE(offset(address, 4));
|
||||
const pointer = (address: bigint) =>
|
||||
bytes.readBigUInt64LE(offset(address, 8));
|
||||
const decodePointer = (address: bigint) =>
|
||||
fixups.decode(address, bytes.readBigUInt64LE(offset(address, 8)));
|
||||
/** Rebased target of a pointer; a bind to another image reads as 0. */
|
||||
const pointer = (address: bigint) => {
|
||||
const decodedPointer = decodePointer(address);
|
||||
return decodedPointer.kind === "rebase" ? decodedPointer.target : 0n;
|
||||
};
|
||||
const bound = (address: bigint) => {
|
||||
const decodedPointer = decodePointer(address);
|
||||
return decodedPointer.kind === "bind" ? decodedPointer : undefined;
|
||||
};
|
||||
const location = (address: bigint) => ({
|
||||
address: `0x${address.toString(16)}`,
|
||||
file_offset: offset(address),
|
||||
@@ -73,13 +91,15 @@ export const decodeAppleDispatchMetadata = (
|
||||
const readers = {
|
||||
u32,
|
||||
i32: (address: bigint) => bytes.readInt32LE(offset(address, 4)),
|
||||
u64: (address: bigint) => bytes.readBigUInt64LE(offset(address, 8)),
|
||||
pointer,
|
||||
bound,
|
||||
string,
|
||||
location,
|
||||
evidence,
|
||||
offset,
|
||||
};
|
||||
const { failures, examined } = decodeObjcDispatchFacets({
|
||||
const { failures, examined, categoriesExamined } = decodeObjcDispatchFacets({
|
||||
bytes,
|
||||
sections,
|
||||
segments,
|
||||
@@ -130,47 +150,14 @@ export const decodeAppleDispatchMetadata = (
|
||||
),
|
||||
},
|
||||
});
|
||||
result.coverage.push({
|
||||
facet: "objc_class_method_ivar_metadata",
|
||||
status: failures.length > 0 || budget.truncated ? "partial" : "complete",
|
||||
reason:
|
||||
[...failures, ...(budget.truncated ? ["max_records_reached"] : [])].join(
|
||||
"; ",
|
||||
) || null,
|
||||
pushDispatchCoverage({
|
||||
result,
|
||||
failures,
|
||||
examined,
|
||||
decoded: result.objc_classes.length,
|
||||
categoriesExamined,
|
||||
truncated: budget.truncated,
|
||||
fixups,
|
||||
});
|
||||
result.coverage.push({
|
||||
facet: "binary_relative_pointers",
|
||||
status:
|
||||
budget.truncated ||
|
||||
result.relative_pointers.some((item) => item.decode.status !== "decoded")
|
||||
? "partial"
|
||||
: "complete",
|
||||
reason: budget.truncated
|
||||
? "max_records_reached"
|
||||
: result.relative_pointers.some(
|
||||
(item) => item.decode.status !== "decoded",
|
||||
)
|
||||
? "relative_pointer_targets_unresolved"
|
||||
: null,
|
||||
examined: result.relative_pointers.length,
|
||||
decoded: result.relative_pointers.filter(
|
||||
(item) => item.decode.status === "decoded",
|
||||
).length,
|
||||
});
|
||||
for (const facet of [
|
||||
"objc_properties_categories",
|
||||
"swift_generic_resilient_witnesses_overrides_async_coroutines",
|
||||
])
|
||||
result.coverage.push({
|
||||
facet,
|
||||
status: "unsupported",
|
||||
reason:
|
||||
"This reader admits validated 64-bit Objective-C class/ivar/method lists and simple Swift conformance/static witness records; chained fixups, generic/resilient tables and other metadata families are not decoded",
|
||||
examined: 0,
|
||||
decoded: 0,
|
||||
});
|
||||
return objcSwiftMetadataSchema.parse(result);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
decodeChainedPointer,
|
||||
parsePointerFixups,
|
||||
} from "./AppleMachoFixups.js";
|
||||
import { parsePropertyAttributes } from "./AppleObjcProperties.js";
|
||||
import type { Segment } from "./AppleMachoSelection.js";
|
||||
|
||||
const BASE = 0x100000000n;
|
||||
const IMPORTS = [
|
||||
{
|
||||
symbol: "_OBJC_CLASS_$_NSObject",
|
||||
library: "/usr/lib/libobjc.A.dylib",
|
||||
weak: false,
|
||||
addend: 0n,
|
||||
},
|
||||
{
|
||||
symbol: "_free",
|
||||
library: "/usr/lib/libSystem.B.dylib",
|
||||
weak: true,
|
||||
addend: 4n,
|
||||
},
|
||||
];
|
||||
|
||||
const field = (value: bigint, from: number): bigint => value << BigInt(from);
|
||||
|
||||
describe("chained pointer decoding", () => {
|
||||
it("decodes DYLD_CHAINED_PTR_64 and _64_OFFSET rebases and binds", () => {
|
||||
const rebase = 0x4000n | field(0x80n, 36) | field(3n, 51);
|
||||
expect(decodeChainedPointer(BASE + 0x4000n, 2, BASE, IMPORTS)).toEqual({
|
||||
kind: "rebase",
|
||||
target: BASE + 0x4000n,
|
||||
});
|
||||
expect(decodeChainedPointer(rebase, 6, BASE, IMPORTS)).toEqual({
|
||||
kind: "rebase",
|
||||
target: (0x80n << 56n) + BASE + 0x4000n,
|
||||
});
|
||||
const bind = 1n | field(2n, 24) | field(1n, 63);
|
||||
expect(decodeChainedPointer(bind, 6, BASE, IMPORTS)).toEqual({
|
||||
kind: "bind",
|
||||
symbol: "_free",
|
||||
library: "/usr/lib/libSystem.B.dylib",
|
||||
weak: true,
|
||||
addend: 6n,
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes arm64e plain, authenticated and 24-bit binds", () => {
|
||||
expect(decodeChainedPointer(0x8000n, 9, BASE, IMPORTS)).toEqual({
|
||||
kind: "rebase",
|
||||
target: BASE + 0x8000n,
|
||||
});
|
||||
expect(decodeChainedPointer(BASE + 0x8000n, 1, BASE, IMPORTS)).toEqual({
|
||||
kind: "rebase",
|
||||
target: BASE + 0x8000n,
|
||||
});
|
||||
const authRebase = 0x8000n | field(0x1234n, 32) | field(1n, 63);
|
||||
expect(decodeChainedPointer(authRebase, 1, BASE, IMPORTS)).toEqual({
|
||||
kind: "rebase",
|
||||
target: BASE + 0x8000n,
|
||||
});
|
||||
const authBind = 0n | field(1n, 62) | field(1n, 63);
|
||||
expect(decodeChainedPointer(authBind, 9, BASE, IMPORTS)).toMatchObject({
|
||||
kind: "bind",
|
||||
symbol: "_OBJC_CLASS_$_NSObject",
|
||||
addend: 0n,
|
||||
});
|
||||
const bind24 = 1n | field(0x7ffffn, 32) | field(1n, 62);
|
||||
expect(decodeChainedPointer(bind24, 12, BASE, IMPORTS)).toMatchObject({
|
||||
kind: "bind",
|
||||
symbol: "_free",
|
||||
addend: 3n,
|
||||
});
|
||||
expect(() =>
|
||||
decodeChainedPointer(field(1n, 62) | 9n, 9, BASE, IMPORTS),
|
||||
).toThrow("Chained bind ordinal 9 has no import");
|
||||
expect(() => decodeChainedPointer(1n, 3, BASE, IMPORTS)).toThrow(
|
||||
"Unsupported chained pointer format 3",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/** Build `LC_DYLD_CHAINED_FIXUPS` data with one fixup segment and the given imports. */
|
||||
const chainedData = (format: 1 | 2 | 3): Buffer => {
|
||||
const symbols = Buffer.from("\0_OBJC_CLASS_$_NSObject\0_free\0");
|
||||
const importSize = format === 3 ? 16 : format === 2 ? 8 : 4;
|
||||
const imports = Buffer.alloc(importSize * 2);
|
||||
const entry = (
|
||||
index: number,
|
||||
{
|
||||
ordinal,
|
||||
weak,
|
||||
nameOffset,
|
||||
addend,
|
||||
}: {
|
||||
ordinal: number;
|
||||
weak: boolean;
|
||||
nameOffset: number;
|
||||
addend: number;
|
||||
},
|
||||
) => {
|
||||
const at = index * importSize;
|
||||
if (format === 3) {
|
||||
imports.writeBigUInt64LE(
|
||||
BigInt(ordinal & 0xffff) |
|
||||
(BigInt(weak ? 1 : 0) << 16n) |
|
||||
(BigInt(nameOffset) << 32n),
|
||||
at,
|
||||
);
|
||||
imports.writeBigInt64LE(BigInt(addend), at + 8);
|
||||
} else {
|
||||
imports.writeUInt32LE(
|
||||
((nameOffset << 9) | ((weak ? 1 : 0) << 8) | (ordinal & 0xff)) >>> 0,
|
||||
at,
|
||||
);
|
||||
if (format === 2) imports.writeInt32LE(addend, at + 4);
|
||||
}
|
||||
};
|
||||
entry(0, { ordinal: 1, weak: false, nameOffset: 1, addend: 0 });
|
||||
entry(1, { ordinal: 2, weak: true, nameOffset: 24, addend: 7 });
|
||||
// starts_in_image: two segments, only the second has fixups.
|
||||
const starts = Buffer.alloc(12 + 24);
|
||||
starts.writeUInt32LE(2, 0);
|
||||
starts.writeUInt32LE(0, 4);
|
||||
starts.writeUInt32LE(12, 8);
|
||||
starts.writeUInt32LE(24, 12);
|
||||
starts.writeUInt16LE(0x4000, 16);
|
||||
starts.writeUInt16LE(6, 18);
|
||||
const header = Buffer.alloc(28);
|
||||
header.writeUInt32LE(0, 0);
|
||||
header.writeUInt32LE(28, 4);
|
||||
header.writeUInt32LE(28 + starts.length, 8);
|
||||
header.writeUInt32LE(28 + starts.length + imports.length, 12);
|
||||
header.writeUInt32LE(2, 16);
|
||||
header.writeUInt32LE(format, 20);
|
||||
header.writeUInt32LE(0, 24);
|
||||
return Buffer.concat([header, starts, imports, symbols]);
|
||||
};
|
||||
|
||||
const SEGMENTS: Segment[] = [
|
||||
{ address: BASE, size: 0x4000n, offset: 0, executable: true },
|
||||
{ address: BASE + 0x4000n, size: 0x4000n, offset: 0x4000, executable: false },
|
||||
];
|
||||
|
||||
describe("pointer fixup tables", () => {
|
||||
for (const format of [1, 2, 3] as const)
|
||||
it(`reads chained import format ${format}`, () => {
|
||||
const data = chainedData(format);
|
||||
const fixups = parsePointerFixups(
|
||||
data,
|
||||
{
|
||||
chained: { offset: 0, size: data.length },
|
||||
binds: [],
|
||||
dylibs: ["/usr/lib/libobjc.A.dylib", "/usr/lib/libSystem.B.dylib"],
|
||||
},
|
||||
SEGMENTS,
|
||||
BASE,
|
||||
);
|
||||
expect(fixups).toMatchObject({
|
||||
kind: "chained",
|
||||
formats: ["DYLD_CHAINED_PTR_64_OFFSET"],
|
||||
});
|
||||
expect(fixups.decode(BASE + 0x4008n, 1n | field(1n, 63))).toMatchObject({
|
||||
kind: "bind",
|
||||
symbol: "_free",
|
||||
library: "/usr/lib/libSystem.B.dylib",
|
||||
weak: true,
|
||||
addend: format === 1 ? 0n : 7n,
|
||||
});
|
||||
// Pointers outside fixup segments are stored plainly.
|
||||
expect(fixups.decode(BASE + 0x10n, 0x1234n)).toEqual({
|
||||
kind: "rebase",
|
||||
target: 0x1234n,
|
||||
});
|
||||
});
|
||||
|
||||
it("interprets legacy bind, weak-bind and lazy-bind opcodes", () => {
|
||||
const opcodes = Buffer.from([
|
||||
0x11, // SET_DYLIB_ORDINAL_IMM 1
|
||||
0x40,
|
||||
...Buffer.from("_OBJC_CLASS_$_NSObject\0"),
|
||||
0x51, // SET_TYPE_IMM pointer
|
||||
0x71,
|
||||
0x08, // SET_SEGMENT_AND_OFFSET segment 1 + 8
|
||||
0x90, // DO_BIND
|
||||
0xc0,
|
||||
0x02,
|
||||
0x08, // DO_BIND_ULEB_TIMES_SKIPPING_ULEB 2 times, skip 8
|
||||
0x00,
|
||||
]);
|
||||
const lazy = Buffer.from([
|
||||
0x71,
|
||||
0x30,
|
||||
0x12,
|
||||
0x40,
|
||||
...Buffer.from("_free\0"),
|
||||
0x90,
|
||||
0x00,
|
||||
0x71,
|
||||
0x38,
|
||||
0x12,
|
||||
0x40,
|
||||
...Buffer.from("_malloc\0"),
|
||||
0x90,
|
||||
0x00,
|
||||
]);
|
||||
const data = Buffer.concat([opcodes, lazy]);
|
||||
const fixups = parsePointerFixups(
|
||||
data,
|
||||
{
|
||||
chained: null,
|
||||
binds: [
|
||||
{ offset: 0, size: opcodes.length, stream: "bind" },
|
||||
{ offset: opcodes.length, size: lazy.length, stream: "lazy" },
|
||||
],
|
||||
dylibs: ["/usr/lib/libobjc.A.dylib", "/usr/lib/libSystem.B.dylib"],
|
||||
},
|
||||
SEGMENTS,
|
||||
BASE,
|
||||
);
|
||||
expect(fixups.kind).toBe("dyld-info");
|
||||
expect(fixups.failures).toEqual([]);
|
||||
for (const offset of [0x08n, 0x10n, 0x20n])
|
||||
expect(fixups.decode(BASE + 0x4000n + offset, 0n)).toMatchObject({
|
||||
kind: "bind",
|
||||
symbol: "_OBJC_CLASS_$_NSObject",
|
||||
library: "/usr/lib/libobjc.A.dylib",
|
||||
});
|
||||
expect(fixups.decode(BASE + 0x4038n, 0n)).toMatchObject({
|
||||
symbol: "_malloc",
|
||||
library: "/usr/lib/libSystem.B.dylib",
|
||||
});
|
||||
expect(fixups.decode(BASE + 0x4018n, 0x99n)).toEqual({
|
||||
kind: "rebase",
|
||||
target: 0x99n,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Objective-C property attributes", () => {
|
||||
it("parses type, ownership, accessors and quoted class names", () => {
|
||||
expect(
|
||||
parsePropertyAttributes(
|
||||
"title",
|
||||
'T@"NSString<NSCopying, NSSecureCoding>",C,N,GcustomTitle,V_title',
|
||||
),
|
||||
).toEqual({
|
||||
name: "title",
|
||||
type_encoding: '@"NSString<NSCopying, NSSecureCoding>"',
|
||||
attributes: [
|
||||
expect.objectContaining({
|
||||
name: "T",
|
||||
value: '@"NSString<NSCopying, NSSecureCoding>"',
|
||||
}),
|
||||
expect.objectContaining({ name: "C", is_copy: true }),
|
||||
expect.objectContaining({ name: "N" }),
|
||||
expect.objectContaining({ name: "G", value: "customTitle" }),
|
||||
expect.objectContaining({ name: "V", value: "_title" }),
|
||||
],
|
||||
is_readonly: false,
|
||||
getter: "customTitle",
|
||||
setter: null,
|
||||
});
|
||||
expect(parsePropertyAttributes("count", "Tq,R,N")).toMatchObject({
|
||||
type_encoding: "q",
|
||||
is_readonly: true,
|
||||
});
|
||||
expect(
|
||||
parsePropertyAttributes("delegate", "T@,W,N,V_delegate").attributes[1],
|
||||
).toMatchObject({
|
||||
is_weak: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,414 @@
|
||||
import type { Segment } from "./AppleMachoSelection.js";
|
||||
|
||||
/** Where a Mach-O stores pointer fixups, from its load commands. */
|
||||
export interface FixupCommands {
|
||||
/** Absolute file range of `LC_DYLD_CHAINED_FIXUPS` data. */
|
||||
readonly chained: { readonly offset: number; readonly size: number } | null;
|
||||
/** Absolute file ranges of `LC_DYLD_INFO(_ONLY)` bind streams. */
|
||||
readonly binds: readonly {
|
||||
readonly offset: number;
|
||||
readonly size: number;
|
||||
readonly stream: "bind" | "weak" | "lazy";
|
||||
}[];
|
||||
/** Install names of dependent dylibs, in library-ordinal order. */
|
||||
readonly dylibs: readonly string[];
|
||||
}
|
||||
|
||||
/** One decoded pointer: a rebase to an in-image address or a bind to a symbol. */
|
||||
export type DecodedPointer =
|
||||
| { readonly kind: "rebase"; readonly target: bigint }
|
||||
| {
|
||||
readonly kind: "bind";
|
||||
readonly symbol: string;
|
||||
readonly library: string | null;
|
||||
readonly weak: boolean;
|
||||
readonly addend: bigint;
|
||||
};
|
||||
|
||||
/** Pointer decoding for one Mach-O slice. */
|
||||
export interface PointerFixups {
|
||||
readonly kind: "chained" | "dyld-info" | "none";
|
||||
/** Chained pointer formats in use, such as `DYLD_CHAINED_PTR_64_OFFSET`. */
|
||||
readonly formats: readonly string[];
|
||||
readonly failures: readonly string[];
|
||||
/** Decode the pointer stored at `address` whose raw 64-bit value is `raw`. */
|
||||
decode(address: bigint, raw: bigint): DecodedPointer;
|
||||
}
|
||||
|
||||
const POINTER_FORMATS: Readonly<Record<number, string>> = {
|
||||
1: "DYLD_CHAINED_PTR_ARM64E",
|
||||
2: "DYLD_CHAINED_PTR_64",
|
||||
6: "DYLD_CHAINED_PTR_64_OFFSET",
|
||||
9: "DYLD_CHAINED_PTR_ARM64E_USERLAND",
|
||||
12: "DYLD_CHAINED_PTR_ARM64E_USERLAND24",
|
||||
};
|
||||
|
||||
const bits = (value: bigint, from: number, width: number): bigint =>
|
||||
(value >> BigInt(from)) & ((1n << BigInt(width)) - 1n);
|
||||
|
||||
const signed = (value: bigint, width: number): bigint =>
|
||||
value >= 1n << BigInt(width - 1) ? value - (1n << BigInt(width)) : value;
|
||||
|
||||
interface Import {
|
||||
readonly symbol: string;
|
||||
readonly library: string | null;
|
||||
readonly weak: boolean;
|
||||
readonly addend: bigint;
|
||||
}
|
||||
|
||||
/** Library ordinal to install name; 0 and negative ordinals are special lookups. */
|
||||
const libraryName = (
|
||||
ordinal: number,
|
||||
dylibs: readonly string[],
|
||||
): string | null => {
|
||||
if (ordinal > 0) return dylibs[ordinal - 1] ?? null;
|
||||
return null;
|
||||
};
|
||||
|
||||
const cString = (bytes: Buffer, offset: number, end: number): string => {
|
||||
const stop = bytes.indexOf(0, offset);
|
||||
if (offset < 0 || offset >= end || stop < 0 || stop >= end)
|
||||
throw new RangeError("Fixup symbol name is outside the symbol pool");
|
||||
return bytes.toString("utf8", offset, stop);
|
||||
};
|
||||
|
||||
const readImports = (
|
||||
data: {
|
||||
readonly bytes: Buffer;
|
||||
readonly base: number;
|
||||
readonly end: number;
|
||||
readonly dylibs: readonly string[];
|
||||
},
|
||||
header: {
|
||||
readonly offset: number;
|
||||
readonly count: number;
|
||||
readonly format: number;
|
||||
readonly symbols: number;
|
||||
},
|
||||
): Import[] => {
|
||||
const { bytes, base, end, dylibs } = data;
|
||||
const size = header.format === 3 ? 16 : header.format === 2 ? 8 : 4;
|
||||
if (header.format < 1 || header.format > 3)
|
||||
throw new RangeError(`Unsupported chained import format ${header.format}`);
|
||||
if (base + header.offset + header.count * size > end)
|
||||
throw new RangeError("Chained import table exceeds the fixup data");
|
||||
return Array.from({ length: header.count }, (_, index) => {
|
||||
const at = base + header.offset + index * size;
|
||||
if (header.format === 3) {
|
||||
const word = bytes.readBigUInt64LE(at);
|
||||
const ordinal = Number(signed(bits(word, 0, 16), 16));
|
||||
return {
|
||||
symbol: cString(
|
||||
bytes,
|
||||
base + header.symbols + Number(bits(word, 32, 32)),
|
||||
end,
|
||||
),
|
||||
library: libraryName(ordinal, dylibs),
|
||||
weak: bits(word, 16, 1) === 1n,
|
||||
addend: bytes.readBigInt64LE(at + 8),
|
||||
};
|
||||
}
|
||||
const word = bytes.readUInt32LE(at);
|
||||
const ordinal = Number(signed(BigInt(word & 0xff), 8));
|
||||
return {
|
||||
symbol: cString(bytes, base + header.symbols + (word >>> 9), end),
|
||||
library: libraryName(ordinal, dylibs),
|
||||
weak: ((word >>> 8) & 1) === 1,
|
||||
addend: header.format === 2 ? BigInt(bytes.readInt32LE(at + 4)) : 0n,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
/** Decode one raw chained pointer for its segment's pointer format. */
|
||||
export const decodeChainedPointer = (
|
||||
raw: bigint,
|
||||
format: number,
|
||||
baseAddress: bigint,
|
||||
imports: readonly Import[],
|
||||
): DecodedPointer => {
|
||||
const bind = (ordinal: bigint, addend: bigint): DecodedPointer => {
|
||||
const target = imports[Number(ordinal)];
|
||||
if (target === undefined)
|
||||
throw new RangeError(`Chained bind ordinal ${ordinal} has no import`);
|
||||
return { kind: "bind", ...target, addend: target.addend + addend };
|
||||
};
|
||||
if (format === 2 || format === 6) {
|
||||
if (bits(raw, 63, 1) === 1n)
|
||||
return bind(bits(raw, 0, 24), bits(raw, 24, 8));
|
||||
const target = bits(raw, 0, 36) | (bits(raw, 36, 8) << 56n);
|
||||
return {
|
||||
kind: "rebase",
|
||||
target: format === 6 ? target + baseAddress : target,
|
||||
};
|
||||
}
|
||||
if (format === 1 || format === 9 || format === 12) {
|
||||
const auth = bits(raw, 63, 1) === 1n;
|
||||
if (bits(raw, 62, 1) === 1n)
|
||||
return bind(
|
||||
bits(raw, 0, format === 12 ? 24 : 16),
|
||||
auth ? 0n : signed(bits(raw, 32, 19), 19),
|
||||
);
|
||||
if (auth) return { kind: "rebase", target: bits(raw, 0, 32) + baseAddress };
|
||||
const target = bits(raw, 0, 43) | (bits(raw, 43, 8) << 56n);
|
||||
return {
|
||||
kind: "rebase",
|
||||
target: format === 1 ? target : target + baseAddress,
|
||||
};
|
||||
}
|
||||
throw new RangeError(`Unsupported chained pointer format ${format}`);
|
||||
};
|
||||
|
||||
/** The slice bytes and load-command facts that fixup decoding reads. */
|
||||
interface FixupImage {
|
||||
readonly bytes: Buffer;
|
||||
readonly segments: readonly Segment[];
|
||||
readonly dylibs: readonly string[];
|
||||
readonly baseAddress: bigint;
|
||||
}
|
||||
|
||||
const chainedFixups = (
|
||||
image: FixupImage,
|
||||
range: { readonly offset: number; readonly size: number },
|
||||
): PointerFixups => {
|
||||
const { bytes, segments, dylibs, baseAddress } = image;
|
||||
const base = range.offset;
|
||||
const end = range.offset + range.size;
|
||||
if (range.size < 28 || end > bytes.length)
|
||||
throw new RangeError("Chained fixup header exceeds the target");
|
||||
const startsOffset = bytes.readUInt32LE(base + 4);
|
||||
const imports = readImports(
|
||||
{ bytes, base, end, dylibs },
|
||||
{
|
||||
offset: bytes.readUInt32LE(base + 8),
|
||||
symbols: bytes.readUInt32LE(base + 12),
|
||||
count: bytes.readUInt32LE(base + 16),
|
||||
format: bytes.readUInt32LE(base + 20),
|
||||
},
|
||||
);
|
||||
if (bytes.readUInt32LE(base + 24) !== 0)
|
||||
throw new RangeError(
|
||||
"Compressed chained-fixup symbol names are not supported",
|
||||
);
|
||||
const starts = base + startsOffset;
|
||||
const segmentCount = bytes.readUInt32LE(starts);
|
||||
const ranges: {
|
||||
readonly from: bigint;
|
||||
readonly to: bigint;
|
||||
readonly format: number;
|
||||
}[] = [];
|
||||
for (let index = 0; index < segmentCount; index++) {
|
||||
const infoOffset = bytes.readUInt32LE(starts + 4 + index * 4);
|
||||
if (infoOffset === 0) continue;
|
||||
const segment = segments[index];
|
||||
if (segment === undefined || starts + infoOffset + 22 > end)
|
||||
throw new RangeError("Chained fixup segment table is out of range");
|
||||
ranges.push({
|
||||
from: segment.address,
|
||||
to: segment.address + segment.size,
|
||||
format: bytes.readUInt16LE(starts + infoOffset + 6),
|
||||
});
|
||||
}
|
||||
const formats = [
|
||||
...new Set(
|
||||
ranges.map(({ format }) => POINTER_FORMATS[format] ?? `format-${format}`),
|
||||
),
|
||||
];
|
||||
return {
|
||||
kind: "chained",
|
||||
formats,
|
||||
failures: [],
|
||||
decode(address, raw) {
|
||||
const segment = ranges.find(
|
||||
({ from, to }) => address >= from && address < to,
|
||||
);
|
||||
// Pointers outside fixup segments, such as in __TEXT, are stored plainly.
|
||||
if (segment === undefined) return { kind: "rebase", target: raw };
|
||||
if (raw === 0n) return { kind: "rebase", target: 0n };
|
||||
return decodeChainedPointer(raw, segment.format, baseAddress, imports);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const uleb = (bytes: Buffer, cursor: { at: number }, end: number): bigint => {
|
||||
let value = 0n;
|
||||
let shift = 0n;
|
||||
for (;;) {
|
||||
if (cursor.at >= end) throw new RangeError("Truncated bind opcode operand");
|
||||
const byte = bytes[cursor.at++] ?? 0;
|
||||
value |= BigInt(byte & 0x7f) << shift;
|
||||
shift += 7n;
|
||||
if ((byte & 0x80) === 0) return value;
|
||||
if (shift > 63n) throw new RangeError("Oversized bind opcode operand");
|
||||
}
|
||||
};
|
||||
|
||||
const sleb = (bytes: Buffer, cursor: { at: number }, end: number): bigint => {
|
||||
let value = 0n;
|
||||
let shift = 0n;
|
||||
let byte = 0;
|
||||
do {
|
||||
if (cursor.at >= end) throw new RangeError("Truncated bind opcode operand");
|
||||
byte = bytes[cursor.at++] ?? 0;
|
||||
value |= BigInt(byte & 0x7f) << shift;
|
||||
shift += 7n;
|
||||
} while ((byte & 0x80) !== 0 && shift <= 63n);
|
||||
return (byte & 0x40) !== 0 ? value - (1n << shift) : value;
|
||||
};
|
||||
|
||||
/** Registers of the `LC_DYLD_INFO` bind state machine. */
|
||||
interface BindState {
|
||||
ordinal: number;
|
||||
symbol: string;
|
||||
weak: boolean;
|
||||
addend: bigint;
|
||||
address: bigint;
|
||||
}
|
||||
|
||||
/** Apply a bind opcode that sets a register; false when the opcode is not one. */
|
||||
const setBindRegister = (
|
||||
image: FixupImage,
|
||||
stream: { readonly cursor: { at: number }; readonly end: number },
|
||||
state: BindState,
|
||||
byte: number,
|
||||
): boolean => {
|
||||
const { bytes } = image;
|
||||
const { cursor, end } = stream;
|
||||
const immediate = byte & 0x0f;
|
||||
switch (byte & 0xf0) {
|
||||
case 0x10:
|
||||
state.ordinal = immediate;
|
||||
return true;
|
||||
case 0x20:
|
||||
state.ordinal = Number(uleb(bytes, cursor, end));
|
||||
return true;
|
||||
case 0x30:
|
||||
state.ordinal = immediate === 0 ? 0 : immediate - 16;
|
||||
return true;
|
||||
case 0x40: {
|
||||
const stop = bytes.indexOf(0, cursor.at);
|
||||
if (stop < 0 || stop >= end)
|
||||
throw new RangeError("Unterminated bind symbol");
|
||||
state.symbol = bytes.toString("utf8", cursor.at, stop);
|
||||
state.weak = (immediate & 0x1) !== 0;
|
||||
cursor.at = stop + 1;
|
||||
return true;
|
||||
}
|
||||
case 0x50:
|
||||
return true;
|
||||
case 0x60:
|
||||
state.addend = sleb(bytes, cursor, end);
|
||||
return true;
|
||||
case 0x70: {
|
||||
const segment = image.segments[immediate];
|
||||
if (segment === undefined)
|
||||
throw new RangeError("Bind segment index is out of range");
|
||||
state.address = segment.address + uleb(bytes, cursor, end);
|
||||
return true;
|
||||
}
|
||||
case 0x80:
|
||||
// ULEB deltas wrap at 64 bits to encode negative steps.
|
||||
state.address =
|
||||
(state.address + uleb(bytes, cursor, end)) & 0xffffffffffffffffn;
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** Interpret one `LC_DYLD_INFO` bind opcode stream into address -> import. */
|
||||
const readBindStream = (
|
||||
image: FixupImage,
|
||||
range: FixupCommands["binds"][number],
|
||||
binds: Map<bigint, Import>,
|
||||
): void => {
|
||||
const { bytes } = image;
|
||||
const end = range.offset + range.size;
|
||||
if (end > bytes.length)
|
||||
throw new RangeError("Bind opcodes exceed the target");
|
||||
const cursor = { at: range.offset };
|
||||
const state: BindState = {
|
||||
ordinal: 0,
|
||||
symbol: "",
|
||||
weak: false,
|
||||
addend: 0n,
|
||||
address: 0n,
|
||||
};
|
||||
const bind = (skip: bigint): void => {
|
||||
binds.set(state.address, {
|
||||
symbol: state.symbol,
|
||||
library:
|
||||
range.stream === "weak"
|
||||
? null
|
||||
: libraryName(state.ordinal, image.dylibs),
|
||||
weak: state.weak,
|
||||
addend: state.addend,
|
||||
});
|
||||
state.address += 8n + skip;
|
||||
};
|
||||
while (cursor.at < end) {
|
||||
const byte = bytes[cursor.at++] ?? 0;
|
||||
if (setBindRegister(image, { cursor, end }, state, byte)) continue;
|
||||
switch (byte & 0xf0) {
|
||||
case 0x00:
|
||||
// DONE separates lazy-bind entries; other streams end here.
|
||||
if (range.stream !== "lazy") return;
|
||||
break;
|
||||
case 0x90:
|
||||
bind(0n);
|
||||
break;
|
||||
case 0xa0:
|
||||
bind(uleb(bytes, cursor, end));
|
||||
break;
|
||||
case 0xb0:
|
||||
bind(BigInt(byte & 0x0f) * 8n);
|
||||
break;
|
||||
case 0xc0: {
|
||||
const count = uleb(bytes, cursor, end);
|
||||
const skip = uleb(bytes, cursor, end);
|
||||
for (let index = 0n; index < count; index++) bind(skip);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new RangeError(`Unsupported bind opcode 0x${byte.toString(16)}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Build pointer decoding for one slice from its fixup load commands. */
|
||||
export const parsePointerFixups = (
|
||||
bytes: Buffer,
|
||||
commands: FixupCommands,
|
||||
segments: readonly Segment[],
|
||||
baseAddress: bigint,
|
||||
): PointerFixups => {
|
||||
const image = { bytes, segments, dylibs: commands.dylibs, baseAddress };
|
||||
if (commands.chained !== null) return chainedFixups(image, commands.chained);
|
||||
if (commands.binds.length === 0)
|
||||
return {
|
||||
kind: "none",
|
||||
formats: [],
|
||||
failures: [],
|
||||
decode: (_address, raw) => ({ kind: "rebase", target: raw }),
|
||||
};
|
||||
const binds = new Map<bigint, Import>();
|
||||
const failures: string[] = [];
|
||||
for (const stream of commands.binds)
|
||||
try {
|
||||
readBindStream(image, stream, binds);
|
||||
} catch (cause: unknown) {
|
||||
failures.push(
|
||||
`${stream.stream} bind opcodes: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
kind: "dyld-info",
|
||||
formats: [],
|
||||
failures,
|
||||
decode(address, raw) {
|
||||
const bound = binds.get(address);
|
||||
return bound === undefined
|
||||
? { kind: "rebase", target: raw }
|
||||
: { kind: "bind", ...bound };
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { FixupCommands } from "./AppleMachoFixups.js";
|
||||
|
||||
/** One mapped Mach-O segment with file-backed VA range. */
|
||||
export interface Segment {
|
||||
address: bigint;
|
||||
@@ -23,6 +25,10 @@ export interface MachoSlice {
|
||||
export interface MachoLayout {
|
||||
segments: Segment[];
|
||||
sections: Section[];
|
||||
/** Fixup load commands and dependent dylibs of the selected slice. */
|
||||
fixups: FixupCommands;
|
||||
/** VM address of the segment that maps file offset 0 (the preferred load address). */
|
||||
baseAddress: bigint;
|
||||
/** Map a virtual address range onto a file offset within the selected slice. */
|
||||
offset(address: bigint, size?: number): number;
|
||||
}
|
||||
@@ -112,48 +118,31 @@ export const parseMachoLayout = (
|
||||
const commandEnd = slice + 32 + bytes.readUInt32LE(slice + 20);
|
||||
if (commands > 4096 || commandEnd > sliceEnd)
|
||||
throw new RangeError("Malformed Mach-O command bounds");
|
||||
const segments: Segment[] = [];
|
||||
const sections: Section[] = [];
|
||||
const state: LayoutState = {
|
||||
slice,
|
||||
sliceEnd,
|
||||
segments: [],
|
||||
sections: [],
|
||||
dylibs: [],
|
||||
binds: [],
|
||||
chained: null,
|
||||
baseAddress: undefined,
|
||||
};
|
||||
let cursor = slice + 32;
|
||||
for (let index = 0; index < commands; index++) {
|
||||
if (cursor + 8 > commandEnd) throw new RangeError("Truncated load command");
|
||||
const kind = bytes.readUInt32LE(cursor),
|
||||
size = bytes.readUInt32LE(cursor + 4);
|
||||
if (size < 8 || cursor + size > commandEnd)
|
||||
const command = {
|
||||
cursor,
|
||||
kind: bytes.readUInt32LE(cursor),
|
||||
size: bytes.readUInt32LE(cursor + 4),
|
||||
};
|
||||
if (command.size < 8 || cursor + command.size > commandEnd)
|
||||
throw new RangeError("Invalid load command size");
|
||||
if (kind === 0x19) {
|
||||
if (size < 72) throw new RangeError("Truncated segment command");
|
||||
const address = bytes.readBigUInt64LE(cursor + 24),
|
||||
fileSize = bytes.readBigUInt64LE(cursor + 48),
|
||||
fileOffset = bytes.readBigUInt64LE(cursor + 40);
|
||||
if (fileOffset + fileSize > BigInt(sliceEnd - slice))
|
||||
throw new RangeError("Segment file range exceeds target bytes");
|
||||
segments.push({
|
||||
address,
|
||||
size: fileSize,
|
||||
offset: slice + Number(fileOffset),
|
||||
executable: (bytes.readUInt32LE(cursor + 60) & 4) !== 0,
|
||||
});
|
||||
const count = bytes.readUInt32LE(cursor + 64);
|
||||
if (72 + count * 80 > size)
|
||||
throw new RangeError("Truncated section table");
|
||||
for (let section = 0; section < count; section++) {
|
||||
const position = cursor + 72 + section * 80;
|
||||
const sectionSize = bytes.readBigUInt64LE(position + 40);
|
||||
if (sectionSize > BigInt(Number.MAX_SAFE_INTEGER))
|
||||
throw new RangeError("Section size exceeds exact numeric range");
|
||||
sections.push({
|
||||
name: bytes
|
||||
.subarray(position, position + 16)
|
||||
.toString("ascii")
|
||||
.replace(/\0.*$/u, ""),
|
||||
address: bytes.readBigUInt64LE(position + 32),
|
||||
size: Number(sectionSize),
|
||||
});
|
||||
}
|
||||
}
|
||||
cursor += size;
|
||||
if (command.kind === 0x19) collectSegment(bytes, command, state);
|
||||
else collectFixupCommand(bytes, command, state);
|
||||
cursor += command.size;
|
||||
}
|
||||
const { segments, sections, chained, binds, dylibs } = state;
|
||||
const offset = (address: bigint, size = 1): number => {
|
||||
const matches = segments.filter(
|
||||
(segment) =>
|
||||
@@ -168,5 +157,109 @@ export const parseMachoLayout = (
|
||||
if (segment === undefined) throw new RangeError("Missing metadata segment");
|
||||
return segment.offset + Number(address - segment.address);
|
||||
};
|
||||
return { segments, sections, offset };
|
||||
return {
|
||||
segments,
|
||||
sections,
|
||||
offset,
|
||||
fixups: { chained, binds, dylibs },
|
||||
baseAddress: state.baseAddress ?? 0n,
|
||||
};
|
||||
};
|
||||
|
||||
/** Load commands and fixup ranges collected while walking one slice. */
|
||||
interface LayoutState {
|
||||
readonly slice: number;
|
||||
readonly sliceEnd: number;
|
||||
readonly segments: Segment[];
|
||||
readonly sections: Section[];
|
||||
readonly dylibs: string[];
|
||||
readonly binds: FixupCommands["binds"][number][];
|
||||
chained: FixupCommands["chained"];
|
||||
baseAddress: bigint | undefined;
|
||||
}
|
||||
|
||||
/** One load command header inside the selected slice. */
|
||||
interface LoadCommand {
|
||||
readonly cursor: number;
|
||||
readonly kind: number;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
/** Record an `LC_SEGMENT_64` and its section table. */
|
||||
const collectSegment = (
|
||||
bytes: Buffer,
|
||||
{ cursor, size }: LoadCommand,
|
||||
state: LayoutState,
|
||||
): void => {
|
||||
if (size < 72) throw new RangeError("Truncated segment command");
|
||||
const address = bytes.readBigUInt64LE(cursor + 24),
|
||||
fileSize = bytes.readBigUInt64LE(cursor + 48),
|
||||
fileOffset = bytes.readBigUInt64LE(cursor + 40);
|
||||
if (fileOffset + fileSize > BigInt(state.sliceEnd - state.slice))
|
||||
throw new RangeError("Segment file range exceeds target bytes");
|
||||
state.segments.push({
|
||||
address,
|
||||
size: fileSize,
|
||||
offset: state.slice + Number(fileOffset),
|
||||
executable: (bytes.readUInt32LE(cursor + 60) & 4) !== 0,
|
||||
});
|
||||
if (fileOffset === 0n && fileSize > 0n) state.baseAddress ??= address;
|
||||
const count = bytes.readUInt32LE(cursor + 64);
|
||||
if (72 + count * 80 > size) throw new RangeError("Truncated section table");
|
||||
for (let section = 0; section < count; section++) {
|
||||
const position = cursor + 72 + section * 80;
|
||||
const sectionSize = bytes.readBigUInt64LE(position + 40);
|
||||
if (sectionSize > BigInt(Number.MAX_SAFE_INTEGER))
|
||||
throw new RangeError("Section size exceeds exact numeric range");
|
||||
state.sections.push({
|
||||
name: bytes
|
||||
.subarray(position, position + 16)
|
||||
.toString("ascii")
|
||||
.replace(/\0.*$/u, ""),
|
||||
address: bytes.readBigUInt64LE(position + 32),
|
||||
size: Number(sectionSize),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const LC_DYLD_INFO = 0x22;
|
||||
const LC_DYLD_INFO_ONLY = 0x80000022;
|
||||
const LC_DYLD_CHAINED_FIXUPS = 0x80000034;
|
||||
const DYLIB_COMMANDS: readonly number[] = [
|
||||
0xc, 0x80000018, 0x8000001f, 0x20, 0x80000023,
|
||||
];
|
||||
|
||||
/** Record fixup data ranges and dylib install names from one load command. */
|
||||
const collectFixupCommand = (
|
||||
bytes: Buffer,
|
||||
{ cursor, kind, size }: LoadCommand,
|
||||
state: LayoutState,
|
||||
): void => {
|
||||
const range = (at: number): { offset: number; size: number } => {
|
||||
const offset = state.slice + bytes.readUInt32LE(at);
|
||||
const length = bytes.readUInt32LE(at + 4);
|
||||
if (offset + length > state.sliceEnd)
|
||||
throw new RangeError("Fixup data exceeds the Mach-O slice");
|
||||
return { offset, size: length };
|
||||
};
|
||||
if (kind === LC_DYLD_CHAINED_FIXUPS && size >= 16)
|
||||
state.chained = range(cursor + 8);
|
||||
else if ((kind === LC_DYLD_INFO || kind === LC_DYLD_INFO_ONLY) && size >= 48)
|
||||
for (const [at, stream] of [
|
||||
[cursor + 16, "bind"],
|
||||
[cursor + 24, "weak"],
|
||||
[cursor + 32, "lazy"],
|
||||
] as const) {
|
||||
const bound = range(at);
|
||||
if (bound.size > 0) state.binds.push({ ...bound, stream });
|
||||
}
|
||||
else if (DYLIB_COMMANDS.includes(kind) && size >= 24) {
|
||||
const nameOffset = bytes.readUInt32LE(cursor + 8);
|
||||
const end = bytes.indexOf(0, cursor + nameOffset);
|
||||
state.dylibs.push(
|
||||
nameOffset >= size || end < 0 || end > cursor + size
|
||||
? ""
|
||||
: bytes.toString("utf8", cursor + nameOffset, end),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { ObjcSwiftMetadata } from "../domain/objcSwiftMetadata.js";
|
||||
import type { Section } from "./AppleMachoSelection.js";
|
||||
import type { ObjcDispatchReaders } from "./AppleObjcDispatchFacets.js";
|
||||
import { readObjcPropertiesOf } from "./AppleObjcProperties.js";
|
||||
|
||||
const CLASS_SYMBOL = /^_OBJC_(?:META)?CLASS_\$_(.+)$/u;
|
||||
|
||||
/** External class name from a bound `_OBJC_CLASS_$_Name` symbol. */
|
||||
export const boundClassName = (
|
||||
read: Pick<ObjcDispatchReaders, "bound">,
|
||||
field: bigint,
|
||||
): string | undefined => {
|
||||
const bound = read.bound(field);
|
||||
return bound === undefined ? undefined : CLASS_SYMBOL.exec(bound.symbol)?.[1];
|
||||
};
|
||||
|
||||
/**
|
||||
* Decode `__objc_catlist` `category_t` records:
|
||||
* name, cls, instanceMethods, classMethods, protocols, instanceProperties.
|
||||
*/
|
||||
export const decodeObjcCategories = (input: {
|
||||
readonly sections: readonly Section[];
|
||||
readonly read: ObjcDispatchReaders;
|
||||
readonly result: ObjcSwiftMetadata;
|
||||
readonly failures: string[];
|
||||
readonly admit: () => boolean;
|
||||
/** Decode a method list into implementations attributed to the category. */
|
||||
readonly methods: (
|
||||
list: bigint,
|
||||
className: string,
|
||||
methodType: "instance" | "class",
|
||||
category: string,
|
||||
) => string[];
|
||||
readonly protocols: (list: bigint) => string[];
|
||||
/** Name of a class defined in this image, from its class_ro_t. */
|
||||
readonly localClassName: (address: bigint) => string;
|
||||
}): number => {
|
||||
const { read, result, failures } = input;
|
||||
let examined = 0;
|
||||
for (const section of input.sections.filter(
|
||||
({ name }) => name === "__objc_catlist",
|
||||
)) {
|
||||
if (section.size % 8 !== 0)
|
||||
throw new RangeError("Misaligned Objective-C category list");
|
||||
for (let index = 0; index < section.size / 8; index++) {
|
||||
if (!input.admit()) break;
|
||||
examined++;
|
||||
const field = section.address + BigInt(index * 8);
|
||||
try {
|
||||
const category = read.pointer(field);
|
||||
const name = read.string(read.pointer(category));
|
||||
const external = boundClassName(read, category + 8n);
|
||||
const local = read.pointer(category + 8n);
|
||||
const className =
|
||||
external ?? (local === 0n ? null : input.localClassName(local));
|
||||
const owner = className ?? `(${name})`;
|
||||
result.objc_categories.push({
|
||||
name,
|
||||
class_name: className,
|
||||
class_source:
|
||||
external !== undefined
|
||||
? "external"
|
||||
: className === null
|
||||
? "unresolved"
|
||||
: "local",
|
||||
instance_methods: input.methods(
|
||||
read.pointer(category + 16n),
|
||||
owner,
|
||||
"instance",
|
||||
name,
|
||||
),
|
||||
class_methods: input.methods(
|
||||
read.pointer(category + 24n),
|
||||
owner,
|
||||
"class",
|
||||
name,
|
||||
),
|
||||
protocols: input.protocols(read.pointer(category + 32n)),
|
||||
properties: readObjcPropertiesOf(read, read.pointer(category + 40n), {
|
||||
owner: `category ${name}`,
|
||||
admit: input.admit,
|
||||
failures,
|
||||
}),
|
||||
location: read.location(category),
|
||||
decode:
|
||||
className === null
|
||||
? { status: "partial", reason: "category_class_unresolved" }
|
||||
: { status: "decoded", reason: null },
|
||||
evidence: read.evidence(category, "Objective-C category_t record"),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
failures.push(
|
||||
`Category at ${`0x${field.toString(16)}`}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return examined;
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { ObjcSwiftMetadata } from "../domain/objcSwiftMetadata.js";
|
||||
import type { Segment, Section } from "./AppleMachoSelection.js";
|
||||
import { boundClassName, decodeObjcCategories } from "./AppleObjcCategories.js";
|
||||
import { readObjcPropertiesOf } from "./AppleObjcProperties.js";
|
||||
import { createObjcProtocolReader } from "./AppleObjcProtocols.js";
|
||||
import type {
|
||||
BinaryMetadataEvidence,
|
||||
@@ -10,8 +12,14 @@ import type {
|
||||
/** Byte readers shared by Objective-C class/method/ivar decode facets. */
|
||||
export interface ObjcDispatchReaders {
|
||||
u32(address: bigint): number;
|
||||
/** Plain 64-bit data, never a fixup. */
|
||||
u64(address: bigint): bigint;
|
||||
i32(address: bigint): number;
|
||||
pointer(address: bigint): bigint;
|
||||
/** The symbol a pointer at `address` is bound to, when it is a bind fixup. */
|
||||
bound(
|
||||
address: bigint,
|
||||
): { readonly symbol: string; readonly library: string | null } | undefined;
|
||||
string(address: bigint): string;
|
||||
location(address: bigint): ResolvedMetadataLocation;
|
||||
evidence(address: bigint, description: string): BinaryMetadataEvidence;
|
||||
@@ -21,6 +29,36 @@ export interface ObjcDispatchReaders {
|
||||
const hex = (value: bigint) => `0x${value.toString(16)}`;
|
||||
const decoded = { status: "decoded" as const, reason: null };
|
||||
|
||||
/** Name of a class defined in this image, from its class_ro_t. */
|
||||
const localClassName = (read: ObjcDispatchReaders, address: bigint): string =>
|
||||
read.string(read.pointer((read.pointer(address + 32n) & ~7n) + 24n));
|
||||
|
||||
/**
|
||||
* Resolve a class's superclass: a bind to `_OBJC_CLASS_$_Name` names a class
|
||||
* in another image; otherwise the pointer is a class_t in this image.
|
||||
*/
|
||||
const resolveSuperclass = (
|
||||
read: ObjcDispatchReaders,
|
||||
address: bigint,
|
||||
className: string,
|
||||
failures: string[],
|
||||
): { name: string | null; address: string | null } => {
|
||||
const external = boundClassName(read, address + 8n);
|
||||
if (external !== undefined) return { name: external, address: null };
|
||||
const superclass = read.pointer(address + 8n);
|
||||
if (superclass === 0n) return { name: null, address: null };
|
||||
try {
|
||||
return { name: localClassName(read, superclass), address: hex(superclass) };
|
||||
} catch (cause: unknown) {
|
||||
// Superclass resolution failure is recorded; the cause adds no identity.
|
||||
void cause;
|
||||
failures.push(
|
||||
`Superclass pointer ${hex(superclass)} of ${className} requires unsupported binding/fixup resolution`,
|
||||
);
|
||||
return { name: null, address: hex(superclass) };
|
||||
}
|
||||
};
|
||||
|
||||
/** Decode Objective-C protocol lists, classlists, methods, and ivars into `result`. */
|
||||
export const decodeObjcDispatchFacets = (input: {
|
||||
bytes: Buffer;
|
||||
@@ -29,7 +67,7 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
readers: ObjcDispatchReaders;
|
||||
budget: DispatchRecordBudget;
|
||||
result: ObjcSwiftMetadata;
|
||||
}): { failures: string[]; examined: number } => {
|
||||
}): { failures: string[]; examined: number; categoriesExamined: number } => {
|
||||
const { bytes, sections, segments, readers: read, budget, result } = input;
|
||||
const failures: string[] = [];
|
||||
let examined = 0;
|
||||
@@ -37,8 +75,10 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
list: bigint,
|
||||
className: string,
|
||||
methodType: "instance" | "class",
|
||||
) => {
|
||||
if (list === 0n) return;
|
||||
category?: string,
|
||||
): string[] => {
|
||||
const selectors: string[] = [];
|
||||
if (list === 0n) return selectors;
|
||||
const flags = read.u32(list),
|
||||
count = read.u32(list + 4n),
|
||||
relative = (flags & 0x80000000) !== 0;
|
||||
@@ -103,10 +143,13 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
// best-effort cleanup: external/chained pointers remain unresolved.
|
||||
void cause;
|
||||
}
|
||||
const selector = read.string(selectorAddress);
|
||||
selectors.push(selector);
|
||||
result.objc_dispatch_implementations.push({
|
||||
class_name: className,
|
||||
selector: read.string(selectorAddress),
|
||||
selector,
|
||||
method_type: methodType,
|
||||
...(category === undefined ? {} : { category }),
|
||||
implementation_address: implementationLocation?.address ?? null,
|
||||
location: read.location(entry),
|
||||
decode:
|
||||
@@ -124,6 +167,7 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
),
|
||||
});
|
||||
}
|
||||
return selectors;
|
||||
};
|
||||
const protocolReader = createObjcProtocolReader({
|
||||
readers: {
|
||||
@@ -134,6 +178,7 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
evidence: read.evidence,
|
||||
admit: () => budget.admit(),
|
||||
i32: read.i32,
|
||||
u64: read.u64,
|
||||
},
|
||||
result,
|
||||
failures,
|
||||
@@ -157,23 +202,9 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
visited.add(hex(address));
|
||||
const ro = read.pointer(address + 32n) & ~7n;
|
||||
const name = read.string(read.pointer(ro + 24n));
|
||||
const superclass = read.pointer(address + 8n);
|
||||
const root = (read.u32(ro) & 2) !== 0;
|
||||
let superclassName: string | null = null;
|
||||
if (superclass !== 0n) {
|
||||
try {
|
||||
superclassName = read.string(
|
||||
read.pointer((read.pointer(superclass + 32n) & ~7n) + 24n),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
// Superclass resolution failure is recorded; the cause adds no identity.
|
||||
void cause;
|
||||
failures.push(
|
||||
`Superclass pointer ${hex(superclass)} of ${name} requires unsupported binding/fixup resolution`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (superclass === 0n && !root)
|
||||
const superclass = resolveSuperclass(read, address, name, failures);
|
||||
if (superclass.name === null && superclass.address === null && !root)
|
||||
failures.push(
|
||||
`Superclass of ${name} requires external binding resolution`,
|
||||
);
|
||||
@@ -220,7 +251,7 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
methods(read.pointer(ro + 32n), name, meta ? "class" : "instance");
|
||||
result.objc_classes.push({
|
||||
name,
|
||||
super_class: superclassName,
|
||||
super_class: superclass.name,
|
||||
is_meta_class: meta,
|
||||
is_root_class: root,
|
||||
methods: result.objc_dispatch_implementations
|
||||
@@ -241,15 +272,19 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
is_required: false,
|
||||
is_optional: false,
|
||||
})),
|
||||
properties: [],
|
||||
properties: readObjcPropertiesOf(read, read.pointer(ro + 64n), {
|
||||
owner: name,
|
||||
admit: () => budget.admit(),
|
||||
failures,
|
||||
}),
|
||||
protocols: protocolReader.list(read.pointer(ro + 40n)),
|
||||
ivar_count: ivarCount,
|
||||
instance_size: read.u32(ro + 8n),
|
||||
location: read.location(address),
|
||||
superclass_address: superclass === 0n ? null : hex(superclass),
|
||||
superclass_address: superclass.address,
|
||||
metaclass_address: meta ? null : hex(read.pointer(address)),
|
||||
decode:
|
||||
superclassName === null && !root
|
||||
superclass.name === null && !root
|
||||
? { status: "partial", reason: "superclass_binding_unresolved" }
|
||||
: decoded,
|
||||
evidence: read.evidence(
|
||||
@@ -288,5 +323,15 @@ export const decodeObjcDispatchFacets = (input: {
|
||||
}
|
||||
}
|
||||
}
|
||||
return { failures, examined };
|
||||
const categoriesExamined = decodeObjcCategories({
|
||||
sections,
|
||||
read,
|
||||
result,
|
||||
failures,
|
||||
admit: () => budget.admit(),
|
||||
methods,
|
||||
protocols: (list) => protocolReader.list(list),
|
||||
localClassName: (address) => localClassName(read, address),
|
||||
});
|
||||
return { failures, examined, categoriesExamined };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { objcPropertySchema } from "../domain/objcSwiftMetadata.js";
|
||||
|
||||
type ObjcProperty = z.infer<typeof objcPropertySchema>;
|
||||
|
||||
/** Byte readers needed to decode an Objective-C `property_list_t`. */
|
||||
export interface ObjcPropertyReaders {
|
||||
u32(address: bigint): number;
|
||||
pointer(address: bigint): bigint;
|
||||
string(address: bigint): string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an `@property` attribute string such as `T@"NSString",C,N,V_name`.
|
||||
* Each comma-separated token is one attribute; `T` is the type encoding.
|
||||
*/
|
||||
export const parsePropertyAttributes = (
|
||||
name: string,
|
||||
attributes: string,
|
||||
): ObjcProperty => {
|
||||
const tokens = attributes.length === 0 ? [] : splitAttributes(attributes);
|
||||
const value = (code: string): string | null =>
|
||||
tokens.find((token) => token.startsWith(code))?.slice(1) ?? null;
|
||||
return {
|
||||
name,
|
||||
type_encoding: value("T"),
|
||||
attributes: tokens.map((token) => ({
|
||||
name: token.slice(0, 1),
|
||||
value: token.slice(1),
|
||||
is_weak: token === "W",
|
||||
is_atomic: false,
|
||||
is_copy: token === "C",
|
||||
is_strong: token === "&",
|
||||
})),
|
||||
is_readonly: tokens.includes("R"),
|
||||
getter: value("G"),
|
||||
setter: value("S"),
|
||||
};
|
||||
};
|
||||
|
||||
/** Split on commas that are outside a quoted class name in the type encoding. */
|
||||
const splitAttributes = (attributes: string): string[] => {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let quoted = false;
|
||||
for (const character of attributes) {
|
||||
if (character === '"') quoted = !quoted;
|
||||
if (character === "," && !quoted) {
|
||||
tokens.push(current);
|
||||
current = "";
|
||||
} else current += character;
|
||||
}
|
||||
tokens.push(current);
|
||||
return tokens.filter((token) => token.length > 0);
|
||||
};
|
||||
|
||||
/** Decode `property_list_t { entsize_and_flags, count, property_t[] }`. */
|
||||
export const readObjcPropertyList = (
|
||||
read: ObjcPropertyReaders,
|
||||
list: bigint,
|
||||
admit: () => boolean,
|
||||
): ObjcProperty[] => {
|
||||
if (list === 0n) return [];
|
||||
const entrySize = read.u32(list) & ~3;
|
||||
const count = read.u32(list + 4n);
|
||||
if (entrySize !== 16)
|
||||
throw new TypeError(
|
||||
`Unsupported Objective-C property entry size ${entrySize}`,
|
||||
);
|
||||
const properties: ObjcProperty[] = [];
|
||||
for (let index = 0; index < count; index++) {
|
||||
if (!admit()) break;
|
||||
const entry = list + 8n + BigInt(index * entrySize);
|
||||
properties.push(
|
||||
parsePropertyAttributes(
|
||||
read.string(read.pointer(entry)),
|
||||
read.string(read.pointer(entry + 8n)),
|
||||
),
|
||||
);
|
||||
}
|
||||
return properties;
|
||||
};
|
||||
|
||||
/** Decode a property list, recording a failure for `owner` instead of throwing. */
|
||||
export const readObjcPropertiesOf = (
|
||||
read: ObjcPropertyReaders,
|
||||
list: bigint,
|
||||
context: {
|
||||
readonly owner: string;
|
||||
readonly admit: () => boolean;
|
||||
readonly failures: string[];
|
||||
},
|
||||
): ObjcProperty[] => {
|
||||
try {
|
||||
return readObjcPropertyList(read, list, context.admit);
|
||||
} catch (cause: unknown) {
|
||||
context.failures.push(
|
||||
`Properties of ${context.owner}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -6,7 +6,12 @@ export const createObjcProtocolReader = (input: {
|
||||
readers: Pick<
|
||||
SwiftMetadataReaders,
|
||||
"u32" | "string" | "location" | "evidence" | "admit"
|
||||
> & { pointer(address: bigint): bigint; i32(address: bigint): number };
|
||||
> & {
|
||||
pointer(address: bigint): bigint;
|
||||
/** Plain 64-bit data, never a fixup. */
|
||||
u64(address: bigint): bigint;
|
||||
i32(address: bigint): number;
|
||||
};
|
||||
result: ObjcSwiftMetadata;
|
||||
failures: string[];
|
||||
}) => {
|
||||
@@ -15,7 +20,8 @@ export const createObjcProtocolReader = (input: {
|
||||
const name = (address: bigint) => read.string(read.pointer(address + 8n));
|
||||
const list = (address: bigint): string[] => {
|
||||
if (address === 0n) return [];
|
||||
const count = read.pointer(address);
|
||||
// `count` is plain uintptr_t data, not a pointer fixup.
|
||||
const count = read.u64(address);
|
||||
if (count > 20000n)
|
||||
throw new RangeError("Protocol list exceeds 20000 entries");
|
||||
const names: string[] = [];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { mkdtemp, rm, symlink } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -14,6 +14,13 @@ export const createNativeUiHelperRuntime = () => {
|
||||
if (executable === undefined) {
|
||||
root = await mkdtemp(join(tmpdir(), "rea-native-ui-"));
|
||||
const output = join(root, "observer");
|
||||
const main = join(root, "main.swift");
|
||||
await symlink(
|
||||
fileURLToPath(
|
||||
new URL("../../bridge/native/ReaNativeUI.swift", import.meta.url),
|
||||
),
|
||||
main,
|
||||
);
|
||||
await execFileOutput(
|
||||
"/usr/bin/xcrun",
|
||||
[
|
||||
@@ -21,8 +28,12 @@ export const createNativeUiHelperRuntime = () => {
|
||||
"-module-cache-path",
|
||||
join(root, "modules"),
|
||||
fileURLToPath(
|
||||
new URL("../../bridge/native/ReaNativeUI.swift", import.meta.url),
|
||||
new URL(
|
||||
"../../bridge/native/NativeUIChildren.swift",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
main,
|
||||
"-o",
|
||||
output,
|
||||
],
|
||||
|
||||
@@ -99,6 +99,8 @@ export type ProviderProcessDiagnostic =
|
||||
|
||||
/** Options for process lifecycle diagnostics. */
|
||||
export interface ProviderProcessSupervisorOptions {
|
||||
/** Retain stdout for diagnostics; disable when it carries a parsed protocol. Defaults to true. */
|
||||
readonly captureStdout?: boolean;
|
||||
readonly onDiagnostic?: (event: ProviderProcessDiagnostic) => void;
|
||||
}
|
||||
|
||||
@@ -235,7 +237,8 @@ export class ProviderProcessSupervisor {
|
||||
options: ProviderProcessSupervisorOptions = {},
|
||||
) {
|
||||
this.#options = options;
|
||||
this.#attach(launch.process.stdout, "stdout");
|
||||
if (options.captureStdout !== false)
|
||||
this.#attach(launch.process.stdout, "stdout");
|
||||
this.#attach(launch.process.stderr, "stderr");
|
||||
launch.process.once("exit", this.#onExit);
|
||||
launch.process.once("close", this.#onClose);
|
||||
|
||||
@@ -3,14 +3,14 @@ import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/binary/BinarySession.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "../contracts/managedToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "../contracts/managed/managedToolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { registerEvidenceTools } from "./registerEvidenceTools.js";
|
||||
import { runManagedProviderExecution } from "../application/DirectAnalysis.js";
|
||||
import { isManagedToolName } from "../contracts/managedToolContracts.js";
|
||||
import { isManagedToolName } from "../contracts/managed/managedToolContracts.js";
|
||||
|
||||
/** Register execution-free managed PE/CLI inspection. */
|
||||
export const registerManagedTools = (
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { compareManagedMembersEvidenceValidated } from "../../application/ManagedMemberComparisonService.js";
|
||||
import { managedMemberComparisonResultSchema } from "../../domain/managedMemberComparison.js";
|
||||
import { compareManagedMembersEvidenceValidated } from "../../application/managed/ManagedMemberComparisonService.js";
|
||||
import { managedMemberComparisonResultSchema } from "../../domain/managed/managedMemberComparison.js";
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../contracts/managedWorkflowToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../contracts/managed/managedWorkflowToolContracts.js";
|
||||
|
||||
/** Locate one managed workflow tool contract by exact name. */
|
||||
export function managedWorkflowContract(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { importManagedReconstructionEvidenceValidated } from "../../application/ManagedReconstructionService.js";
|
||||
import { importManagedReconstructionEvidenceValidated } from "../../application/managed/ManagedReconstructionService.js";
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { projectManagedApplicationGraphEvidence } from "../../application/ManagedApplicationGraphService.js";
|
||||
import { projectManagedApplicationGraphEvidence } from "../../application/managed/ManagedApplicationGraphService.js";
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { verifyManagedNativeBoundariesEvidence } from "../../application/ManagedNativeVerificationService.js";
|
||||
import { managedNativeVerificationResultSchema } from "../../domain/managedNativeVerification.js";
|
||||
import { verifyManagedNativeBoundariesEvidence } from "../../application/managed/ManagedNativeVerificationService.js";
|
||||
import { managedNativeVerificationResultSchema } from "../../domain/managed/managedNativeVerification.js";
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
|
||||
Reference in New Issue
Block a user