chore: sync current main into the CI baseline repair
Validate the formatting and reconstruction fixture repairs against the latest merged feature and correctness changes. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
@@ -8,6 +8,7 @@ import { CordisExpression, DshCordisYaml } from "./DshCordisYaml.js";
|
||||
export const DSH_ENTRY_ID = "rea-mcp";
|
||||
export const DSH_CLIENT_PACKAGE = "@deepseek-ai/dsh-mcp-client";
|
||||
const LAUNCHER_KEYS = new Set(["serverName", "transport", "command", "args"]);
|
||||
const SELECTOR_KEYS = new Set(["id", "name"]);
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
@@ -295,10 +296,15 @@ export class DshCordisDocument {
|
||||
carried = true;
|
||||
return [this.#entry(desired, invalidated)] as typeof inserted.items;
|
||||
});
|
||||
replacements.set(
|
||||
op.source,
|
||||
inserted.items.length === 0 ? undefined : copy,
|
||||
);
|
||||
if (inserted.items.length === 0) copy.delete("insert");
|
||||
// An emptied operation keeps caller fields unless it would patch REA's row.
|
||||
const kept =
|
||||
inserted.items.length > 0 ||
|
||||
(this.#id(op.map) !== DSH_ENTRY_ID &&
|
||||
copy.items.some(
|
||||
(pair) => !SELECTOR_KEYS.has(this.#yaml.value(pair.key) as string),
|
||||
));
|
||||
replacements.set(op.source, kept ? copy : undefined);
|
||||
}
|
||||
const output = this.#yaml.document.clone();
|
||||
const outputRoot = output.contents;
|
||||
|
||||
@@ -283,7 +283,9 @@ export class BinarySession
|
||||
previous.route.identity.id,
|
||||
);
|
||||
if (!closed.ok) {
|
||||
this.clearSessionRecords();
|
||||
// A failed open retires the provider cache, not the investigation.
|
||||
// Preserve Evidence and Unknown history for export and recovery.
|
||||
this.clearSnapshot();
|
||||
this.#clearRuntimeAvailability();
|
||||
return closed;
|
||||
}
|
||||
|
||||
@@ -199,6 +199,49 @@ const testAnalysis = (
|
||||
});
|
||||
|
||||
describe("native UI action trace", () => {
|
||||
it("retains Hopper targetless call evidence alongside fallback callee routes", async () => {
|
||||
const result = await new EnhancedTools(
|
||||
testAnalysis({
|
||||
procedure_address: () => execution("procedure_address", "0x1000"),
|
||||
procedure_references: (parameters) =>
|
||||
ok(
|
||||
createAnalysisExecution(
|
||||
{
|
||||
reference_kinds_available: false,
|
||||
references: [],
|
||||
unresolved_calls:
|
||||
parameters.procedure === "0x1000"
|
||||
? [{ address: "0x1008", reason: "No static target" }]
|
||||
: [],
|
||||
},
|
||||
{ id: "hopper", name: "Hopper", version: "fixture" },
|
||||
),
|
||||
),
|
||||
}),
|
||||
).execute("trace_native_ui_action", { action: "0x1000" });
|
||||
if (!result.ok) throw result.error;
|
||||
const trace = nativeInvestigationTraceSchema.parse(result.value);
|
||||
expect(trace.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "provider_call",
|
||||
to: "native:function:0x2000",
|
||||
}),
|
||||
);
|
||||
expect(trace.unresolved).toContainEqual(
|
||||
expect.objectContaining({
|
||||
from: "native:function:0x1000",
|
||||
to: null,
|
||||
reason: "No static target",
|
||||
evidence: [
|
||||
expect.objectContaining({
|
||||
description: "Hopper reported an unresolved call: No static target",
|
||||
location: { address: "0x1008", file_offset: null },
|
||||
artifact_sha256: target,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
it("accepts an explicit native seed without an authored UI connection", async () => {
|
||||
const result = await new EnhancedTools(
|
||||
testAnalysis({
|
||||
|
||||
@@ -7,6 +7,59 @@ import { err, ok } from "../../domain/result.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
describe("untyped native call route fallback", () => {
|
||||
it.each([{ callees: [] }, { callees: ["0x2000"] }])(
|
||||
"preserves targetless calls and their provider when fallback callees are $callees",
|
||||
async ({ callees }) => {
|
||||
const calls: string[] = [];
|
||||
const referenceProvider = { ...provider, id: "hopper", name: "Hopper" };
|
||||
const fallbackProvider = { ...provider, id: "fallback" };
|
||||
const signal = new AbortController().signal;
|
||||
const unknown = { address: "0x1008", reason: "No static target" };
|
||||
const result = await readNativeCallRoutes(
|
||||
{
|
||||
execute: async (operation, parameters, options) => {
|
||||
calls.push(operation);
|
||||
expect(parameters.procedure).toBe("0x1000");
|
||||
expect(options).toEqual({ signal, selectorOrigin: "provider" });
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
operation === "procedure_references"
|
||||
? {
|
||||
reference_kinds_available: false,
|
||||
references: [],
|
||||
unresolved_calls: [unknown],
|
||||
}
|
||||
: callees,
|
||||
operation === "procedure_references"
|
||||
? referenceProvider
|
||||
: fallbackProvider,
|
||||
),
|
||||
);
|
||||
},
|
||||
},
|
||||
"0x1000",
|
||||
signal,
|
||||
"provider",
|
||||
);
|
||||
expect(calls).toEqual(["procedure_references", "procedure_callees"]);
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
provider: fallbackProvider,
|
||||
routes: callees.map((address) => ({
|
||||
address,
|
||||
site: "0x1000",
|
||||
relation: "provider_call",
|
||||
resolution: "inferred",
|
||||
})),
|
||||
unknowns: [{ ...unknown, provider: referenceProvider }],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("typed native call routes", () => {
|
||||
it("preserves computed targets, ambiguity and targetless call sites", async () => {
|
||||
const reference = jsonValueSchema.parse(ghidraReferenceEdge());
|
||||
|
||||
@@ -2,12 +2,12 @@ import { z } from "zod";
|
||||
import type {
|
||||
AnalysisOperationPort,
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../AnalysisProvider.js";
|
||||
import {
|
||||
parseRelatedAddresses,
|
||||
referenceKindSchema,
|
||||
} from "../../domain/hopperValues.js";
|
||||
import { err, ok } from "../../domain/result.js";
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
|
||||
const referencesSchema = z.object({
|
||||
@@ -40,15 +40,29 @@ export const readNativeCallRoutes = async (
|
||||
{ procedure, direction: "outgoing" },
|
||||
options,
|
||||
);
|
||||
let unknowns: Array<{
|
||||
address: string;
|
||||
reason: string;
|
||||
provider: ProviderIdentity;
|
||||
}> = [];
|
||||
if (execution.ok) {
|
||||
const parsed = referencesSchema.safeParse(execution.value.result);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
return {
|
||||
ok: false as const,
|
||||
error: new AnalysisOutputError(
|
||||
"procedure_references",
|
||||
"Invalid typed call references",
|
||||
),
|
||||
);
|
||||
unknowns,
|
||||
};
|
||||
// Missing detailed reference flags do not invalidate observed targetless
|
||||
// calls. Keep their producing provider even if another provider supplies
|
||||
// the fallback callee inventory.
|
||||
unknowns = parsed.data.unresolved_calls.map((call) => ({
|
||||
...call,
|
||||
provider: execution.value.provider,
|
||||
}));
|
||||
const references = parsed.data.references;
|
||||
if (
|
||||
parsed.data.reference_kinds_available === true ||
|
||||
@@ -64,45 +78,52 @@ export const readNativeCallRoutes = async (
|
||||
targets.add(call.target_address);
|
||||
countBySite.set(call.source_address, targets);
|
||||
}
|
||||
return ok({
|
||||
provider: execution.value.provider,
|
||||
routes: calls.map((call) => ({
|
||||
address: call.target_procedure?.address ?? call.target_address,
|
||||
site: call.source_address,
|
||||
relation:
|
||||
call.kind.available && (call.kind.computed || call.kind.indirect)
|
||||
? ("indirect_call" as const)
|
||||
: ("direct_call" as const),
|
||||
resolution:
|
||||
(countBySite.get(call.source_address)?.size ?? 0) > 1
|
||||
? ("ambiguous" as const)
|
||||
: call.kind.available &&
|
||||
(call.kind.computed || call.kind.indirect)
|
||||
? ("resolved" as const)
|
||||
: ("observed" as const),
|
||||
})),
|
||||
unknowns: parsed.data.unresolved_calls,
|
||||
});
|
||||
return {
|
||||
ok: true as const,
|
||||
value: {
|
||||
provider: execution.value.provider,
|
||||
routes: calls.map((call) => ({
|
||||
address: call.target_procedure?.address ?? call.target_address,
|
||||
site: call.source_address,
|
||||
relation:
|
||||
call.kind.available && (call.kind.computed || call.kind.indirect)
|
||||
? ("indirect_call" as const)
|
||||
: ("direct_call" as const),
|
||||
resolution:
|
||||
(countBySite.get(call.source_address)?.size ?? 0) > 1
|
||||
? ("ambiguous" as const)
|
||||
: call.kind.available &&
|
||||
(call.kind.computed || call.kind.indirect)
|
||||
? ("resolved" as const)
|
||||
: ("observed" as const),
|
||||
})),
|
||||
unknowns,
|
||||
},
|
||||
};
|
||||
}
|
||||
} else if (execution.error._tag !== "AnalysisCapabilityUnavailableError")
|
||||
return err(execution.error);
|
||||
return { ok: false as const, error: execution.error, unknowns };
|
||||
const callees = await analysis.execute(
|
||||
"procedure_callees",
|
||||
{ procedure },
|
||||
options,
|
||||
);
|
||||
if (!callees.ok) return callees;
|
||||
if (!callees.ok)
|
||||
return { ok: false as const, error: callees.error, unknowns };
|
||||
const parsed = parseRelatedAddresses(callees.value.result, "callees");
|
||||
return parsed.ok
|
||||
? ok({
|
||||
provider: callees.value.provider,
|
||||
routes: parsed.value.map((address) => ({
|
||||
address,
|
||||
site: procedure,
|
||||
relation: "provider_call" as const,
|
||||
resolution: "inferred" as const,
|
||||
})),
|
||||
unknowns: [],
|
||||
})
|
||||
: parsed;
|
||||
? {
|
||||
ok: true as const,
|
||||
value: {
|
||||
provider: callees.value.provider,
|
||||
routes: parsed.value.map((address) => ({
|
||||
address,
|
||||
site: procedure,
|
||||
relation: "provider_call" as const,
|
||||
resolution: "inferred" as const,
|
||||
})),
|
||||
unknowns,
|
||||
},
|
||||
}
|
||||
: { ok: false as const, error: parsed.error, unknowns };
|
||||
};
|
||||
|
||||
@@ -414,9 +414,44 @@ const addDirectCallees = async (input: {
|
||||
"provider",
|
||||
);
|
||||
examined += 1;
|
||||
if (!execution.ok && execution.error._tag === "AnalysisCancelledError")
|
||||
return { error: execution.error };
|
||||
const unknowns = execution.ok
|
||||
? execution.value.unknowns
|
||||
: execution.unknowns;
|
||||
for (const [index, unknown] of unknowns.entries()) {
|
||||
if (edges.size >= input.input.max_edges) {
|
||||
truncated = true;
|
||||
omitted += unknowns.length - index;
|
||||
break;
|
||||
}
|
||||
const id = `unknown-dispatch:${current.address}:${unknown.address}`;
|
||||
edges.set(id, {
|
||||
id,
|
||||
from: current.node.id,
|
||||
to: null,
|
||||
relation: "indirect_call",
|
||||
resolution: "unresolved",
|
||||
reason: unknown.reason,
|
||||
evidence: [
|
||||
{
|
||||
kind: "reference",
|
||||
provider: unknown.provider,
|
||||
description: `${unknown.provider.name} reported an unresolved call: ${unknown.reason}`,
|
||||
location: { address: unknown.address, file_offset: null },
|
||||
artifact_path: null,
|
||||
artifact_sha256: input.targetSha256,
|
||||
},
|
||||
],
|
||||
limitations: [],
|
||||
});
|
||||
}
|
||||
if (!execution.ok) {
|
||||
if (execution.error._tag === "AnalysisCancelledError")
|
||||
return { error: execution.error };
|
||||
if (edges.size >= input.input.max_edges) {
|
||||
truncated = true;
|
||||
omitted += 1;
|
||||
continue;
|
||||
}
|
||||
const id = `unknown-callees:${current.address}`;
|
||||
edges.set(id, {
|
||||
id,
|
||||
@@ -432,32 +467,6 @@ const addDirectCallees = async (input: {
|
||||
});
|
||||
continue;
|
||||
}
|
||||
for (const unknown of execution.value.unknowns) {
|
||||
if (edges.size >= input.input.max_edges) {
|
||||
truncated = true;
|
||||
omitted++;
|
||||
break;
|
||||
}
|
||||
const id = `unknown-dispatch:${current.address}:${unknown.address}`;
|
||||
edges.set(id, {
|
||||
id,
|
||||
from: current.node.id,
|
||||
to: null,
|
||||
relation: "indirect_call",
|
||||
resolution: "unresolved",
|
||||
reason: unknown.reason,
|
||||
evidence: [
|
||||
{
|
||||
kind: "reference",
|
||||
description: unknown.reason,
|
||||
location: { address: unknown.address, file_offset: null },
|
||||
artifact_path: null,
|
||||
artifact_sha256: input.targetSha256,
|
||||
},
|
||||
],
|
||||
limitations: [],
|
||||
});
|
||||
}
|
||||
for (const [index, route] of execution.value.routes.entries()) {
|
||||
const address = route.address;
|
||||
if (edges.size >= input.input.max_edges) {
|
||||
@@ -469,6 +478,7 @@ const addDirectCallees = async (input: {
|
||||
const evidence = [
|
||||
{
|
||||
kind: "reference" as const,
|
||||
provider: execution.value.provider,
|
||||
description: `${execution.value.provider.name} reported ${route.relation} from ${current.address} to ${address}`,
|
||||
location: { address: route.site, file_offset: null },
|
||||
artifact_path: null,
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { orderAsarListing } from "./AsarArtifactReader.js";
|
||||
|
||||
describe("orderAsarListing", () => {
|
||||
it("orders host-spelled listings by their portable archive path", () => {
|
||||
const posix = orderAsarListing(["/a0", "/a", "/a/b"], "/");
|
||||
const windows = orderAsarListing(["\\a0", "\\a", "\\a\\b"], "\\");
|
||||
|
||||
// "/" (0x2F) precedes "0" (0x30); "\" (0x5C) would follow it.
|
||||
expect(posix.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
|
||||
expect(windows.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
|
||||
expect(windows.map(({ listed }) => listed)).toEqual([
|
||||
"\\a",
|
||||
"\\a\\b",
|
||||
"\\a0",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps POSIX backslashes as literal filename characters", () => {
|
||||
expect(orderAsarListing(["/a\\b"], "/")).toEqual([
|
||||
{ listed: "/a\\b", path: "a\\b" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { Readable, Transform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
|
||||
import { listPackage, statFile, uncache } from "@electron/asar";
|
||||
import { getRawHeader, uncache } from "@electron/asar";
|
||||
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
@@ -26,7 +26,11 @@ import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
|
||||
import { admitAsarHeader } from "./AsarHeader.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import {
|
||||
readAsarListing,
|
||||
type AsarListedEntry,
|
||||
type AsarMetadata,
|
||||
} from "./AsarListing.js";
|
||||
|
||||
/**
|
||||
* Official Electron ASAR adapter with range-streamed member reads.
|
||||
@@ -51,7 +55,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
) {}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
let paths: readonly AsarListedPath[];
|
||||
let paths: readonly AsarListedEntry[];
|
||||
try {
|
||||
await this.prepareContainer(undefined, signal);
|
||||
paths = await this.#withSnapshotOperation(async () => {
|
||||
@@ -62,8 +66,9 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
this.#archiveSize = admitted.archiveBytes;
|
||||
this.#headerSize = admitted.headerBytes;
|
||||
abortIfNeeded(signal);
|
||||
const ordered = orderAsarListing(
|
||||
listPackage(snapshotPath, { isPack: false }),
|
||||
const ordered = await readAsarListing(
|
||||
getRawHeader(snapshotPath).header,
|
||||
signal,
|
||||
);
|
||||
const archiveMetadata = await lstat(snapshotPath);
|
||||
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
|
||||
@@ -77,34 +82,25 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(this.path, "inventory", cause);
|
||||
}
|
||||
for (const { listed, path } of paths) {
|
||||
for (const { metadata, path } of paths) {
|
||||
abortIfNeeded(signal);
|
||||
if (path.length === 0) continue;
|
||||
const providerPath = listed.startsWith(sep)
|
||||
? listed.slice(sep.length)
|
||||
: listed;
|
||||
let metadata: ReturnType<typeof statFile>;
|
||||
try {
|
||||
metadata = statFile(this.#snapshotPath(), providerPath, false);
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(this.path, `stat ${path}`, cause);
|
||||
}
|
||||
const providerPath = path.split("/").join(sep);
|
||||
const kind =
|
||||
"files" in metadata
|
||||
metadata.files !== undefined
|
||||
? "directory"
|
||||
: "link" in metadata
|
||||
: metadata.link !== undefined
|
||||
? "symlink"
|
||||
: "file";
|
||||
const entry: ArtifactEntry = {
|
||||
path,
|
||||
kind,
|
||||
declaredSize: "size" in metadata ? metadata.size : null,
|
||||
declaredSize: metadata.size ?? null,
|
||||
compressedSize: null,
|
||||
executable: "executable" in metadata && metadata.executable,
|
||||
executable: metadata.executable === true,
|
||||
encrypted: false,
|
||||
byteOffset: null,
|
||||
declaredSha256:
|
||||
"integrity" in metadata &&
|
||||
metadata.integrity !== undefined &&
|
||||
metadata.integrity.algorithm === "SHA256" &&
|
||||
/^[a-f0-9]{64}$/u.test(metadata.integrity.hash)
|
||||
? metadata.integrity.hash
|
||||
@@ -603,7 +599,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
type AsarFileMetadata = Extract<ReturnType<typeof statFile>, { size: number }>;
|
||||
type AsarFileMetadata = AsarMetadata & { readonly size: number };
|
||||
type AsarEntryState = {
|
||||
readonly metadata: AsarFileMetadata;
|
||||
readonly entry: ArtifactEntry;
|
||||
@@ -652,12 +648,11 @@ const asarUnpackedEntryFailure = (
|
||||
};
|
||||
|
||||
const isAsarFileMetadata = (
|
||||
metadata: ReturnType<typeof statFile>,
|
||||
metadata: AsarMetadata,
|
||||
): metadata is AsarFileMetadata =>
|
||||
"size" in metadata &&
|
||||
typeof metadata.size === "number" &&
|
||||
!("files" in metadata) &&
|
||||
!("link" in metadata);
|
||||
metadata.files === undefined &&
|
||||
metadata.link === undefined;
|
||||
|
||||
const parseArchiveOffset = (value: string): number | undefined => {
|
||||
if (!/^(?:0|[1-9][0-9]*)$/u.test(value)) return undefined;
|
||||
@@ -699,33 +694,6 @@ const waitForOperation = async (
|
||||
});
|
||||
};
|
||||
|
||||
interface AsarListedPath {
|
||||
readonly listed: string;
|
||||
readonly path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pair each host-spelled listing with its portable archive path, ordered by
|
||||
* the portable path so Windows and POSIX hosts agree.
|
||||
*
|
||||
* @electron/asar returns paths assembled with the host path module. Keep that
|
||||
* spelling for its API calls, but expose archive paths with portable
|
||||
* separators. On POSIX, backslashes can be literal filename characters and
|
||||
* must remain untouched.
|
||||
*/
|
||||
export const orderAsarListing = (
|
||||
listed: readonly string[],
|
||||
separator: string = sep,
|
||||
): AsarListedPath[] =>
|
||||
listed
|
||||
.map((entry) => ({ listed: entry, path: toArtifactPath(entry, separator) }))
|
||||
.sort((left, right) => compareUnicodeCodePoints(left.path, right.path));
|
||||
|
||||
const toArtifactPath = (listed: string, separator: string): string => {
|
||||
const portable = separator === "\\" ? listed.replaceAll("\\", "/") : listed;
|
||||
return portable.replace(/^\/+|\/+$/gu, "");
|
||||
};
|
||||
|
||||
const asarFailure = (
|
||||
path: string,
|
||||
operation: string,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** Capacity for expanded paths and listing records, independent of packed bytes. */
|
||||
const MAX_LISTING_BYTES = 64 * 1024 * 1024;
|
||||
const nodeSchema = z.looseObject({
|
||||
files: z
|
||||
.custom<Record<string, unknown>>(
|
||||
(value) =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value),
|
||||
)
|
||||
.optional(),
|
||||
link: z.string().optional(),
|
||||
size: z.number().nonnegative().safe().optional(),
|
||||
offset: z.string().optional(),
|
||||
unpacked: z.boolean().optional(),
|
||||
executable: z.boolean().optional(),
|
||||
integrity: z
|
||||
.looseObject({ algorithm: z.string(), hash: z.string() })
|
||||
.optional(),
|
||||
});
|
||||
export type AsarMetadata = z.infer<typeof nodeSchema>;
|
||||
export interface AsarListedEntry {
|
||||
readonly path: string;
|
||||
readonly metadata: AsarMetadata;
|
||||
}
|
||||
|
||||
function* ownChildren(files: Record<string, unknown>) {
|
||||
for (const name in files)
|
||||
if (Object.hasOwn(files, name)) yield [name, files[name]] as const;
|
||||
}
|
||||
|
||||
/** Decode each node once; admit expanded paths before concatenation and retain no recursive lookup. */
|
||||
export const readAsarListing = async (
|
||||
header: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<AsarListedEntry[]> => {
|
||||
const root = nodeSchema.parse(header);
|
||||
if (root.files === undefined)
|
||||
throw new ArtifactReaderFailure("format", "ASAR root has no files table");
|
||||
const entries: AsarListedEntry[] = [];
|
||||
const pending = [{ parent: "", children: ownChildren(root.files) }];
|
||||
let retainedBytes = 0;
|
||||
let examined = 0;
|
||||
while (pending.length > 0) {
|
||||
if (examined++ % 128 === 0) {
|
||||
await setImmediate();
|
||||
if (signal?.aborted)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"ASAR operation cancelled",
|
||||
);
|
||||
}
|
||||
const frame = pending.at(-1);
|
||||
if (frame === undefined) break;
|
||||
const next = frame.children.next();
|
||||
if (next.done) {
|
||||
pending.pop();
|
||||
continue;
|
||||
}
|
||||
const [name, raw] = next.value;
|
||||
// A header member is one component, not a host path to normalize. POSIX
|
||||
// backslashes remain literal; Windows cannot represent them as components.
|
||||
if (
|
||||
name.length === 0 ||
|
||||
name === "." ||
|
||||
name === ".." ||
|
||||
name.includes("/") ||
|
||||
name.includes("\0") ||
|
||||
(process.platform === "win32" && name.includes("\\"))
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"ASAR header has an unsafe path component",
|
||||
);
|
||||
const units =
|
||||
frame.parent.length + name.length + (frame.parent.length === 0 ? 0 : 1);
|
||||
// UTF-16 storage, plus records and traversal bookkeeping. Charge every
|
||||
// occurrence even when the engine can share a string prefix.
|
||||
retainedBytes += units * 2 + 256;
|
||||
if (retainedBytes > MAX_LISTING_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"ASAR expanded listing exceeds its 64 MiB representation budget",
|
||||
);
|
||||
const path = frame.parent.length === 0 ? name : `${frame.parent}/${name}`;
|
||||
const metadata = nodeSchema.parse(raw);
|
||||
if (
|
||||
metadata.files === undefined &&
|
||||
metadata.link === undefined &&
|
||||
metadata.size === undefined
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"ASAR entry has no directory, link or file metadata",
|
||||
);
|
||||
entries.push({ path, metadata });
|
||||
if (metadata.files !== undefined)
|
||||
pending.push({
|
||||
parent: path,
|
||||
children: ownChildren(metadata.files),
|
||||
});
|
||||
}
|
||||
return entries.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.path, right.path),
|
||||
);
|
||||
};
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
FIELD_RECORD_BUDGET,
|
||||
} from "./parseFieldDiscovery.js";
|
||||
import {
|
||||
BOUNDED_PRODUCER_LIMITS as LIMITS,
|
||||
prlimitArgumentVector,
|
||||
readLinuxResourceLimits,
|
||||
type LinuxResourceLimits,
|
||||
} from "../process/LinuxResourceLimits.js";
|
||||
@@ -60,15 +62,6 @@ export const TSHARK_PROVIDER_IDENTITY = {
|
||||
name: "REA TShark capture adapter",
|
||||
version: "tshark@4",
|
||||
} as const;
|
||||
// Bound the resident input copy and retained text before allocation/collection.
|
||||
const LIMITS = {
|
||||
input_bytes: 32 * 1024 * 1024,
|
||||
output_bytes: 4 * 1024 * 1024,
|
||||
command_timeout_ms: 30_000,
|
||||
address_space_bytes: 1024 * 1024 * 1024,
|
||||
file_bytes: 64 * 1024 * 1024,
|
||||
cpu_seconds: 30,
|
||||
} as const;
|
||||
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
|
||||
|
||||
/** Inspect selected capture files only, retaining cleanup ownership across failures. */
|
||||
@@ -165,14 +158,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
options?.signal,
|
||||
);
|
||||
effectiveLimits = await this.#resources.readLimits(limits);
|
||||
const limitArguments = [
|
||||
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
|
||||
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
|
||||
`--cpu=${effectiveLimits.cpu_seconds}:${effectiveLimits.cpu_seconds}`,
|
||||
"--core=0:0",
|
||||
"--",
|
||||
command,
|
||||
];
|
||||
const limitArguments = prlimitArgumentVector(effectiveLimits, command);
|
||||
phase = "workspace";
|
||||
root = await this.createRuntime();
|
||||
this.#resources.retain(root, undefined);
|
||||
|
||||
@@ -225,7 +225,7 @@ const registerInspectionCommand = (
|
||||
description:
|
||||
"Inspect one artifact and return all available observations and next probes",
|
||||
args: z.object({
|
||||
path: z.string().describe("Application or package path"),
|
||||
path: z.string().min(1).describe("Application or package path"),
|
||||
}),
|
||||
options: z.object({
|
||||
integrityPolicy: z
|
||||
|
||||
@@ -48,7 +48,10 @@ const registerOverviewCommands = (
|
||||
cli.command(CLI_COMMANDS.analyze, {
|
||||
description: "Get an overview of an app",
|
||||
args: z.object({
|
||||
path: z.string().describe("App, program, or analysis database path"),
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("App, program, or analysis database path"),
|
||||
}),
|
||||
options: overviewOptions.extend({
|
||||
integrityPolicy: javascriptApplicationOptions.shape.integrityPolicy,
|
||||
|
||||
@@ -429,7 +429,12 @@ export const addSourceMapDirectives = (
|
||||
end === null
|
||||
)
|
||||
continue;
|
||||
const commentSource = source.slice(start, end);
|
||||
// The parser owns comment boundaries. Exclude only the closing block
|
||||
// delimiter; an asterisk elsewhere remains part of the declared URL.
|
||||
const commentSource = source.slice(
|
||||
start,
|
||||
comment.type === "CommentBlock" ? end - 2 : end,
|
||||
);
|
||||
if (
|
||||
!(commentSource.startsWith("//") || commentSource.startsWith("/*")) ||
|
||||
!(commentSource[2] === "#" || commentSource[2] === "@")
|
||||
@@ -449,9 +454,7 @@ export const addSourceMapDirectives = (
|
||||
const urlOffset = commentSource.slice(equalsStart + 1).search(/\S/u);
|
||||
if (urlOffset === -1) continue;
|
||||
const declaredStart = equalsStart + 1 + urlOffset;
|
||||
const terminator = commentSource
|
||||
.slice(declaredStart)
|
||||
.search(commentSource.startsWith("//") ? /\s/u : /[\s*]/u);
|
||||
const terminator = commentSource.slice(declaredStart).search(/\s/u);
|
||||
const declaredEnd =
|
||||
terminator === -1 ? commentSource.length : declaredStart + terminator;
|
||||
if (declaredEnd === declaredStart) continue;
|
||||
|
||||
@@ -72,10 +72,10 @@ describe("source map directives", () => {
|
||||
it("preserves Unicode whitespace and URL terminator boundaries", () => {
|
||||
const source =
|
||||
"ğ/*@\u00a0sourceMappingURL\u2003=\ufeffapp.js.map* ignored */";
|
||||
const declaredEnd = source.indexOf("* ignored");
|
||||
const declaredEnd = source.indexOf(" ignored");
|
||||
expect(analyzeJavaScriptStaticSource(source).source_map_urls).toEqual([
|
||||
{
|
||||
declared_url: "app.js.map",
|
||||
declared_url: "app.js.map*",
|
||||
location: {
|
||||
start: { line: 1, column: 1 },
|
||||
end: { line: 1, column: declaredEnd },
|
||||
@@ -84,6 +84,29 @@ describe("source map directives", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/*#", "app*part.js.map", " */"],
|
||||
["/*@", "*part.js.map", "*/"],
|
||||
["/*#", "app.js.map*", "*/"],
|
||||
["/*#", "**part.js.map", " */"],
|
||||
["/*#", "app.js.map", "*/"],
|
||||
["//#", "app*part.js.map", ""],
|
||||
])("preserves the URL and range in %s %s%s", (marker, url, suffix) => {
|
||||
const directive = marker + " sourceMappingURL=" + url;
|
||||
const result = analyzeJavaScriptStaticSource(
|
||||
"export const value = 1;\n" + directive + suffix,
|
||||
);
|
||||
expect(result.source_map_urls).toEqual([
|
||||
{
|
||||
declared_url: url,
|
||||
location: {
|
||||
start: { line: 2, column: 0 },
|
||||
end: { line: 2, column: directive.length },
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports nothing when no directive is present", () => {
|
||||
expect(sourceMapUrls("const value = 1;")).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { providerSchema } from "../evidence.js";
|
||||
|
||||
import {
|
||||
compareUnicodeCodePoints,
|
||||
@@ -115,6 +116,7 @@ export const nativeMetadataEvidenceSchema = z.strictObject({
|
||||
"decompiler",
|
||||
]),
|
||||
description: z.string().min(1),
|
||||
provider: providerSchema.optional(),
|
||||
location: nativeMetadataLocationSchema,
|
||||
artifact_path: z.string().min(1).nullable().default(null),
|
||||
artifact_sha256: z
|
||||
|
||||
@@ -143,3 +143,13 @@ export const completeReconstructionCoverageData = () => {
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
/** Complete workspace with its first verifier result and boundary narrowed once. */
|
||||
export const completeReconstructionCoverageFixture = () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
const boundary = workspace.boundaries[0];
|
||||
if (result === undefined || boundary === undefined)
|
||||
throw new Error("Expected complete reconstruction coverage fixture");
|
||||
return { workspace, result, boundary };
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
completeReconstructionCoverageData,
|
||||
completeReconstructionCoverageFixture,
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
reconstructionCoverageEvidenceId,
|
||||
} from "./reconstructionCoverage.fixture.js";
|
||||
@@ -288,11 +289,8 @@ describe("reconstruction coverage verifier selection", () => {
|
||||
|
||||
describe("reconstruction coverage conflicting latest verifier observations", () => {
|
||||
it("keeps conflicting tied assessments unknown regardless of input order", () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
const boundary = workspace.boundaries[0];
|
||||
if (result === undefined || boundary === undefined)
|
||||
throw new Error("Expected complete reconstruction coverage fixture");
|
||||
const { workspace, result, boundary } =
|
||||
completeReconstructionCoverageFixture();
|
||||
const failed = {
|
||||
...result,
|
||||
status: "fail" as const,
|
||||
@@ -338,11 +336,8 @@ describe("reconstruction coverage conflicting latest verifier observations", ()
|
||||
|
||||
describe("reconstruction coverage equivalent latest verifier observations", () => {
|
||||
it("coalesces equivalent equal-instant observations and retains all evidence", () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
const boundary = workspace.boundaries[0];
|
||||
if (result === undefined || boundary === undefined)
|
||||
throw new Error("Expected complete reconstruction coverage fixture");
|
||||
const { workspace, result, boundary } =
|
||||
completeReconstructionCoverageFixture();
|
||||
const first = {
|
||||
...result,
|
||||
observed_at: "2026-07-16T11:00:00.123456789012345678900Z",
|
||||
@@ -388,11 +383,8 @@ describe("reconstruction coverage equivalent latest verifier observations", () =
|
||||
|
||||
describe("reconstruction coverage verifier timestamp selection", () => {
|
||||
it("lets a later unambiguous observation supersede an older tie", () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
const boundary = workspace.boundaries[0];
|
||||
if (result === undefined || boundary === undefined)
|
||||
throw new Error("Expected complete reconstruction coverage fixture");
|
||||
const { workspace, result, boundary } =
|
||||
completeReconstructionCoverageFixture();
|
||||
const failed = { ...result, status: "fail" as const };
|
||||
const latestPass = {
|
||||
...result,
|
||||
@@ -412,50 +404,14 @@ describe("reconstruction coverage verifier timestamp selection", () => {
|
||||
).toMatchObject({ status: "ready", reasons: [] });
|
||||
});
|
||||
|
||||
it("orders offset-bearing verifier timestamps chronologically", () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
const semantic = workspace;
|
||||
const changed = createReconstructionCoverageData({
|
||||
...semantic,
|
||||
verifier_results: [
|
||||
{ ...result, observed_at: "2026-07-16T08:00:00.000Z" },
|
||||
{
|
||||
...result,
|
||||
observed_at: "2026-07-16T04:00:00.000-05:00",
|
||||
status: "fail",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(
|
||||
changed,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "failed",
|
||||
reasons: [expect.objectContaining({ code: "verifier-failed" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the later result when timestamps differ below millisecond precision", () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
/** Evaluate a workspace whose newest verifier observation fails the closure. */
|
||||
const expectNewestObservationFails = (passedAt: string, failedAt: string) => {
|
||||
const { workspace, result } = completeReconstructionCoverageFixture();
|
||||
const changed = createReconstructionCoverageData({
|
||||
...workspace,
|
||||
verifier_results: [
|
||||
{ ...result, observed_at: "2026-07-16T11:00:00.1231Z" },
|
||||
{
|
||||
...result,
|
||||
observed_at: "2026-07-16T11:00:00.1239Z",
|
||||
status: "fail",
|
||||
},
|
||||
{ ...result, observed_at: passedAt },
|
||||
{ ...result, observed_at: failedAt, status: "fail" },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -469,15 +425,26 @@ describe("reconstruction coverage verifier timestamp selection", () => {
|
||||
status: "failed",
|
||||
reasons: [expect.objectContaining({ code: "verifier-failed" })],
|
||||
});
|
||||
};
|
||||
|
||||
it("orders offset-bearing verifier timestamps chronologically", () => {
|
||||
expectNewestObservationFails(
|
||||
"2026-07-16T08:00:00.000Z",
|
||||
"2026-07-16T04:00:00.000-05:00",
|
||||
);
|
||||
});
|
||||
|
||||
it("selects the later result when timestamps differ below millisecond precision", () => {
|
||||
expectNewestObservationFails(
|
||||
"2026-07-16T11:00:00.1231Z",
|
||||
"2026-07-16T11:00:00.1239Z",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconstruction coverage verifier future timestamps", () => {
|
||||
it("treats an observation beyond millisecond-precision now as future", () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
const { workspace, result } = completeReconstructionCoverageFixture();
|
||||
const changed = createReconstructionCoverageData({
|
||||
...workspace,
|
||||
verifier_results: [
|
||||
@@ -505,10 +472,7 @@ describe("reconstruction coverage verifier future timestamps", () => {
|
||||
});
|
||||
|
||||
it("rejects verifier observations from the future", () => {
|
||||
const workspace = completeReconstructionCoverageData();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
const { workspace, result } = completeReconstructionCoverageFixture();
|
||||
const semantic = workspace;
|
||||
const changed = createReconstructionCoverageData({
|
||||
...semantic,
|
||||
|
||||
@@ -35,6 +35,28 @@ const validPng = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
|
||||
/** Screenshot payload as the native helper reports one PNG buffer. */
|
||||
const screenshotOf = (bytes: Buffer) => ({
|
||||
mime_type: "image/png",
|
||||
base64: bytes.toString("base64"),
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
width: bytes.readUInt32BE(16),
|
||||
height: bytes.readUInt32BE(20),
|
||||
});
|
||||
|
||||
/** Observe the fixture snapshot carrying one screenshot payload. */
|
||||
const observeWithScreenshot = (screenshot: Record<string, unknown>) =>
|
||||
observeNativeUi(
|
||||
target,
|
||||
"observe_native_ui",
|
||||
{ ...scope, screenshot: true },
|
||||
{
|
||||
environment: {},
|
||||
invoke: async () => ({ ok: true, result: { ...snapshot, screenshot } }),
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ offset: 8, value: 12 },
|
||||
{ offset: 16, value: 0x8000_0000 },
|
||||
@@ -44,49 +66,16 @@ it.each([
|
||||
async ({ offset, value }) => {
|
||||
const bytes = Buffer.from(validPng);
|
||||
bytes.writeUInt32BE(value, offset);
|
||||
const screenshot = {
|
||||
mime_type: "image/png",
|
||||
base64: bytes.toString("base64"),
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
width: bytes.readUInt32BE(16),
|
||||
height: bytes.readUInt32BE(20),
|
||||
};
|
||||
const result = await observeNativeUi(
|
||||
target,
|
||||
"observe_native_ui",
|
||||
{ ...scope, screenshot: true },
|
||||
{
|
||||
environment: {},
|
||||
invoke: async () => ({
|
||||
ok: true,
|
||||
result: { ...snapshot, screenshot },
|
||||
}),
|
||||
},
|
||||
);
|
||||
const result = await observeWithScreenshot(screenshotOf(bytes));
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
describe("native UI screenshot validation", () => {
|
||||
it("rejects malformed or mismatched screenshot bytes from the helper", async () => {
|
||||
const screenshot = {
|
||||
mime_type: "image/png",
|
||||
base64: validPng.toString("base64"),
|
||||
const result = await observeWithScreenshot({
|
||||
...screenshotOf(validPng),
|
||||
sha256: "0".repeat(64),
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
const result = await observeNativeUi(
|
||||
target,
|
||||
"observe_native_ui",
|
||||
{ ...scope, screenshot: true },
|
||||
{
|
||||
environment: {},
|
||||
invoke: async () => ({
|
||||
ok: true,
|
||||
result: { ...snapshot, screenshot },
|
||||
}),
|
||||
},
|
||||
);
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
});
|
||||
|
||||
@@ -97,26 +86,10 @@ describe("native UI screenshot validation", () => {
|
||||
])(
|
||||
"rejects invalid screenshot field variants from the helper",
|
||||
async (change) => {
|
||||
const screenshot = {
|
||||
mime_type: "image/png",
|
||||
base64: validPng.toString("base64"),
|
||||
sha256: createHash("sha256").update(validPng).digest("hex"),
|
||||
width: 1,
|
||||
height: 1,
|
||||
const result = await observeWithScreenshot({
|
||||
...screenshotOf(validPng),
|
||||
...change,
|
||||
};
|
||||
const result = await observeNativeUi(
|
||||
target,
|
||||
"observe_native_ui",
|
||||
{ ...scope, screenshot: true },
|
||||
{
|
||||
environment: {},
|
||||
invoke: async () => ({
|
||||
ok: true,
|
||||
result: { ...snapshot, screenshot },
|
||||
}),
|
||||
},
|
||||
);
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
@@ -126,49 +99,12 @@ describe("native UI screenshot validation", () => {
|
||||
const type = bytes.subarray(12, 16);
|
||||
type[0] = (type[0] ?? 0) | 0x80;
|
||||
expect(type.toString("ascii")).toBe("IHDR");
|
||||
const screenshot = {
|
||||
mime_type: "image/png",
|
||||
base64: bytes.toString("base64"),
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
const result = await observeNativeUi(
|
||||
target,
|
||||
"observe_native_ui",
|
||||
{ ...scope, screenshot: true },
|
||||
{
|
||||
environment: {},
|
||||
invoke: async () => ({
|
||||
ok: true,
|
||||
result: { ...snapshot, screenshot },
|
||||
}),
|
||||
},
|
||||
);
|
||||
const result = await observeWithScreenshot(screenshotOf(bytes));
|
||||
expect(result.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a self-consistent PNG screenshot from the helper", async () => {
|
||||
const bytes = validPng;
|
||||
const screenshot = {
|
||||
mime_type: "image/png",
|
||||
base64: bytes.toString("base64"),
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
const result = await observeNativeUi(
|
||||
target,
|
||||
"observe_native_ui",
|
||||
{ ...scope, screenshot: true },
|
||||
{
|
||||
environment: {},
|
||||
invoke: async () => ({
|
||||
ok: true,
|
||||
result: { ...snapshot, screenshot },
|
||||
}),
|
||||
},
|
||||
);
|
||||
const result = await observeWithScreenshot(screenshotOf(validPng));
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { clampLinuxResourceLimits } from "./LinuxResourceLimits.js";
|
||||
import {
|
||||
BOUNDED_PRODUCER_LIMITS,
|
||||
clampLinuxResourceLimits,
|
||||
prlimitArgumentVector,
|
||||
} from "./LinuxResourceLimits.js";
|
||||
const configured = {
|
||||
address_space_bytes: 1073741824,
|
||||
file_bytes: 67108864,
|
||||
@@ -41,3 +45,38 @@ it("refuses missing, ambiguous or malformed kernel limits before launch", () =>
|
||||
])
|
||||
expect(() => clampLinuxResourceLimits(configured, value)).toThrow();
|
||||
});
|
||||
it("pins the shared producer budget in one place", () => {
|
||||
expect(BOUNDED_PRODUCER_LIMITS).toEqual({
|
||||
input_bytes: 33554432,
|
||||
output_bytes: 4194304,
|
||||
command_timeout_ms: 30000,
|
||||
address_space_bytes: 1073741824,
|
||||
file_bytes: 67108864,
|
||||
cpu_seconds: 30,
|
||||
});
|
||||
});
|
||||
it("pairs each effective ceiling with itself before the producer argv", () => {
|
||||
expect(
|
||||
prlimitArgumentVector(BOUNDED_PRODUCER_LIMITS, "/bin/producer"),
|
||||
).toEqual([
|
||||
"--as=1073741824:1073741824",
|
||||
"--fsize=67108864:67108864",
|
||||
"--cpu=30:30",
|
||||
"--core=0:0",
|
||||
"--",
|
||||
"/bin/producer",
|
||||
]);
|
||||
expect(
|
||||
prlimitArgumentVector(
|
||||
clampLinuxResourceLimits(BOUNDED_PRODUCER_LIMITS, report("10 20")),
|
||||
"/bin/producer",
|
||||
),
|
||||
).toEqual([
|
||||
"--as=10:10",
|
||||
"--fsize=67108864:67108864",
|
||||
"--cpu=30:30",
|
||||
"--core=0:0",
|
||||
"--",
|
||||
"/bin/producer",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -15,6 +15,29 @@ const rows = {
|
||||
cpu_seconds: "Max cpu time",
|
||||
} as const;
|
||||
|
||||
/** Bound the resident input copy and retained text before allocation/collection. */
|
||||
export const BOUNDED_PRODUCER_LIMITS = {
|
||||
input_bytes: 32 * 1024 * 1024,
|
||||
output_bytes: 4 * 1024 * 1024,
|
||||
command_timeout_ms: 30_000,
|
||||
address_space_bytes: 1024 * 1024 * 1024,
|
||||
file_bytes: 64 * 1024 * 1024,
|
||||
cpu_seconds: 30,
|
||||
} as const;
|
||||
|
||||
/** Pin soft and hard ceilings together, then hand the producer argv to the limiter. */
|
||||
export const prlimitArgumentVector = (
|
||||
limits: LinuxResourceLimits,
|
||||
command: string,
|
||||
): string[] => [
|
||||
`--as=${limits.address_space_bytes}:${limits.address_space_bytes}`,
|
||||
`--fsize=${limits.file_bytes}:${limits.file_bytes}`,
|
||||
`--cpu=${limits.cpu_seconds}:${limits.cpu_seconds}`,
|
||||
"--core=0:0",
|
||||
"--",
|
||||
command,
|
||||
];
|
||||
|
||||
/** Never raise either inherited soft policy or hard ceiling. */
|
||||
export const clampLinuxResourceLimits = (
|
||||
configured: LinuxResourceLimits,
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
parseDecoderDiscovery,
|
||||
} from "./parseDecoderDiscovery.js";
|
||||
import {
|
||||
BOUNDED_PRODUCER_LIMITS as LIMITS,
|
||||
prlimitArgumentVector,
|
||||
readLinuxResourceLimits,
|
||||
type LinuxResourceLimits,
|
||||
} from "../process/LinuxResourceLimits.js";
|
||||
@@ -59,15 +61,6 @@ export const SIGROK_PROVIDER_IDENTITY = {
|
||||
name: "REA sigrok recording adapter",
|
||||
version: "sigrok-cli@0.7.2",
|
||||
} as const;
|
||||
// Bound the resident input copy and retained text before allocation/collection.
|
||||
const LIMITS = {
|
||||
input_bytes: 32 * 1024 * 1024,
|
||||
output_bytes: 4 * 1024 * 1024,
|
||||
command_timeout_ms: 30_000,
|
||||
address_space_bytes: 1024 * 1024 * 1024,
|
||||
file_bytes: 64 * 1024 * 1024,
|
||||
cpu_seconds: 30,
|
||||
} as const;
|
||||
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
|
||||
|
||||
/** Decode selected recordings only, retaining cleanup ownership across failures. */
|
||||
@@ -163,14 +156,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
options?.signal,
|
||||
);
|
||||
effectiveLimits = await this.#resources.readLimits(LIMITS);
|
||||
const limitArguments = [
|
||||
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
|
||||
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
|
||||
`--cpu=${effectiveLimits.cpu_seconds}:${effectiveLimits.cpu_seconds}`,
|
||||
"--core=0:0",
|
||||
"--",
|
||||
command,
|
||||
];
|
||||
const limitArguments = prlimitArgumentVector(effectiveLimits, command);
|
||||
phase = "workspace";
|
||||
root = await this.createRuntime();
|
||||
this.#resources.retain(root, undefined);
|
||||
|
||||
Reference in New Issue
Block a user