fix(javascript): integrate current main stability fixes
Include the merged Hopper reconnect-listener readiness fix so local and CI validation use the same current main recovery boundary. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Kaoru0822
commit
b60248c462
@@ -66,7 +66,7 @@ export const analysisErrorRemediationAction = (
|
||||
if (error instanceof HopperRemoteError)
|
||||
return error.diagnosticType === "invalid_request"
|
||||
? "Correct the reported address, document, or arguments and retry."
|
||||
: "Review the Hopper diagnostic details; correct the request or retry if the failure was transient.";
|
||||
: "Review the Hopper diagnostic details and correct the request or target; run `rea doctor` if the provider itself is failing. Repeating the unchanged request is not expected to succeed.";
|
||||
if (error instanceof EvidenceReferenceError)
|
||||
return "Use an exact Evidence reference retained by this session, supply the complete inline Evidence, re-run its producer, or import its Evidence bundle. close_binary clears retained records.";
|
||||
if (
|
||||
@@ -282,7 +282,7 @@ const hopperProcessMessage = (error: HopperProcessError): string => {
|
||||
|
||||
const standardErrorMessage = (tag: AnalysisErrorTag): string | undefined => {
|
||||
if (UNREADABLE_OUTPUT_TAGS.has(tag))
|
||||
return "Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.";
|
||||
return "Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.";
|
||||
if (UNSUPPORTED_PROVIDER_TAGS.has(tag))
|
||||
return "This analysis is unavailable for the current target. Choose another analysis or target.";
|
||||
if (CANCELLED_TAGS.has(tag))
|
||||
@@ -290,7 +290,7 @@ const standardErrorMessage = (tag: AnalysisErrorTag): string | undefined => {
|
||||
if (TIMEOUT_TAGS.has(tag))
|
||||
return "Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.";
|
||||
if (ADAPTER_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not complete. Retry once; if it continues, run `rea doctor`.";
|
||||
return "Analysis could not complete. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.";
|
||||
if (START_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not start or stopped unexpectedly. Run `rea doctor`, then try again.";
|
||||
return undefined;
|
||||
|
||||
@@ -384,6 +384,38 @@ describe("analysis error projection: provider failures", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis error projection: retry guidance", () => {
|
||||
it.each([
|
||||
[
|
||||
"unreadable output",
|
||||
new AnalysisOutputError("inspect_firmware_regions", "report missing"),
|
||||
"unreadable_output",
|
||||
],
|
||||
[
|
||||
"adapter failure",
|
||||
new ProviderAdapterError("firmware", "inspect_firmware_regions"),
|
||||
"execution_failure",
|
||||
],
|
||||
[
|
||||
"Hopper remote failure",
|
||||
new HopperRemoteError(7, "Hopper analysis failed", {
|
||||
diagnosticType: "bridge_exception",
|
||||
operation: "trace_feature",
|
||||
}),
|
||||
"execution_failure",
|
||||
],
|
||||
])(
|
||||
"does not recommend an unchanged retry for non-retryable %s",
|
||||
(_name, error, code) => {
|
||||
const projected = projectAnalysisError(error);
|
||||
|
||||
expect(projected).toMatchObject({ code, retryable: false });
|
||||
for (const text of [projected.message, projected.remediation.action])
|
||||
expect(text).not.toMatch(/\bretry\b/iu);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("analysis error projection: caller contract", () => {
|
||||
it("preserves the reported output constraint without exposing its internal cause", () => {
|
||||
const projected = projectAnalysisError(
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
snapshotBinding,
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotTarget,
|
||||
snapshotMatchesTarget,
|
||||
} from "./analysisSnapshot.js";
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
} from "./analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import type { BinaryTarget } from "./binaryTargetTypes.js";
|
||||
|
||||
const snapshotWithHistoricalEvidence = () => {
|
||||
const target = snapshotTarget(ANALYSIS_SNAPSHOT_TARGET);
|
||||
@@ -68,6 +70,54 @@ const snapshotWithHistoricalEvidence = () => {
|
||||
};
|
||||
|
||||
describe("analysis snapshot contract", () => {
|
||||
it("partitions raw snapshots and query identities by the canonical entry", () => {
|
||||
const target: BinaryTarget = {
|
||||
path: "/fixture/image.bin",
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x08000000",
|
||||
};
|
||||
const snapshot = snapshotTarget(target);
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const changed = {
|
||||
...target,
|
||||
entryPoint: "0x9000000",
|
||||
entryPointSource: "0x09000000",
|
||||
};
|
||||
expect(
|
||||
snapshotMatchesTarget(snapshot, {
|
||||
...target,
|
||||
entryPointSource: "0x8000000",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(snapshotMatchesTarget(snapshot, changed)).toBe(false);
|
||||
expect(analysisQueryId(snapshot, binding, "list_procedures", {})).not.toBe(
|
||||
analysisQueryId(snapshotTarget(changed), binding, "list_procedures", {}),
|
||||
);
|
||||
const parsed = analysisSnapshotSchema.parse({
|
||||
target: snapshot,
|
||||
binding,
|
||||
entries: [],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
});
|
||||
expect(parsed.target).toHaveProperty("entry_point", target.entryPoint);
|
||||
const { entry_point: _entry, ...legacy } = {
|
||||
...snapshot,
|
||||
entry_point: target.entryPoint,
|
||||
};
|
||||
expect(
|
||||
analysisSnapshotSchema.safeParse({ ...parsed, target: legacy }).success,
|
||||
).toBe(false);
|
||||
expect(snapshotTarget(ANALYSIS_SNAPSHOT_TARGET)).not.toHaveProperty(
|
||||
"entry_point",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves DOS MZ target and subject formats with the x86 family", () => {
|
||||
const target = {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
@@ -113,6 +163,37 @@ describe("analysis snapshot contract", () => {
|
||||
expect(parsed.evidence_bundle.records[0]?.subject?.format).toBe("dos-mz");
|
||||
});
|
||||
|
||||
it("rejects a snapshot subject path containing NUL", () => {
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const entry = {
|
||||
query_id: `query_${"0".repeat(64)}`,
|
||||
operation: "analyze_function",
|
||||
parameters: {},
|
||||
execution: {
|
||||
result: null,
|
||||
raw_result: null,
|
||||
provider: binding.provider,
|
||||
limitations: [],
|
||||
locations: [],
|
||||
subject: {
|
||||
path: "a\u0000b",
|
||||
sha256: "a".repeat(64),
|
||||
format: "elf" as const,
|
||||
architecture: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(
|
||||
analysisSnapshotSchema.safeParse({
|
||||
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
|
||||
binding,
|
||||
entries: [entry],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts snapshots with more than ten thousand analysis entries", () => {
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const entry = {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
compareUnicodeCodePoints,
|
||||
compositeKey,
|
||||
} from "./unicodeCodePointOrder.js";
|
||||
import { localPathStringSchema } from "./localPath.js";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
@@ -39,6 +40,7 @@ import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
|
||||
import { freezeJsonSnapshot } from "./immutableJson.js";
|
||||
import { rawBinaryEntryPointSchema } from "./rawBinary.js";
|
||||
|
||||
const architectureSchema = z.enum(BINARY_ARCHITECTURES);
|
||||
const formatSchema = z.enum([
|
||||
@@ -48,6 +50,7 @@ const formatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
@@ -65,7 +68,7 @@ const formatSchema = z.enum([
|
||||
]);
|
||||
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
|
||||
const subjectSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
path: localPathStringSchema,
|
||||
sha256: digestSchema,
|
||||
format: z.enum([
|
||||
...formatSchema.options,
|
||||
@@ -79,12 +82,22 @@ const subjectSchema = z.object({
|
||||
]),
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
const targetSchema = z.object({
|
||||
const targetIdentitySchema = z.object({
|
||||
sha256: digestSchema,
|
||||
kind: kindSchema,
|
||||
format: formatSchema,
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
const targetSchema = z.discriminatedUnion("format", [
|
||||
targetIdentitySchema.extend({
|
||||
format: z.enum(
|
||||
formatSchema.options.filter((format) => format !== "raw-binary"),
|
||||
),
|
||||
}),
|
||||
targetIdentitySchema.extend({
|
||||
format: z.literal("raw-binary"),
|
||||
entry_point: rawBinaryEntryPointSchema,
|
||||
}),
|
||||
]);
|
||||
const bindingSchema = z
|
||||
.object({
|
||||
provider: committedProviderSchema,
|
||||
@@ -310,12 +323,16 @@ const canonicalJson = (value: unknown): string => {
|
||||
/** Project a binary into the path-free identity used for cache invalidation. */
|
||||
export const snapshotTarget = (
|
||||
target: BinaryTarget,
|
||||
): AnalysisSnapshotTarget => ({
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
});
|
||||
): AnalysisSnapshotTarget => {
|
||||
const identity = {
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
architecture: target.architecture ?? null,
|
||||
};
|
||||
return target.format === "raw-binary"
|
||||
? { ...identity, format: target.format, entry_point: target.entryPoint }
|
||||
: { ...identity, format: target.format };
|
||||
};
|
||||
|
||||
/** Build the immutable provider/profile binding used by a cached snapshot. */
|
||||
export const snapshotBinding = (
|
||||
@@ -334,7 +351,10 @@ export const snapshotMatchesTarget = (
|
||||
snapshot.sha256 === target.sha256 &&
|
||||
snapshot.kind === target.kind &&
|
||||
snapshot.format === target.format &&
|
||||
snapshot.architecture === (target.architecture ?? null);
|
||||
snapshot.architecture === (target.architecture ?? null) &&
|
||||
(snapshot.format !== "raw-binary" ||
|
||||
(target.format === "raw-binary" &&
|
||||
snapshot.entry_point === target.entryPoint));
|
||||
|
||||
/** Compare a snapshot binding with the selected concrete analysis profile. */
|
||||
export const snapshotMatchesProfile = (
|
||||
|
||||
@@ -50,6 +50,7 @@ const artifactFormatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
|
||||
@@ -78,6 +78,13 @@ export type BinaryTarget =
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "raw-binary";
|
||||
readonly entryPoint: string;
|
||||
readonly entryPointSource: string;
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "pe";
|
||||
/** Provider-neutral PE image role observed from COFF characteristics. */
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Headerless DOS COM interpretation explicitly selected by the caller. */
|
||||
export const executableFormatHintSchema = z.literal("dos-com");
|
||||
/** Headerless executable interpretation explicitly selected by the caller. */
|
||||
export const executableFormatHintSchema = z.enum(["dos-com", "raw-binary"]);
|
||||
/** Explicit executable interpretation for formats with no identifying header. */
|
||||
export type ExecutableFormatHint = z.infer<typeof executableFormatHintSchema>;
|
||||
|
||||
|
||||
@@ -291,6 +291,22 @@ describe("analysis evidence identity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a subject local path containing NUL while admitting an empty path", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
expect(evidence.subject).not.toBeNull();
|
||||
const withPath = (path: string) => ({
|
||||
...evidence,
|
||||
subject: { ...evidence.subject, local_path: path },
|
||||
});
|
||||
expect(evidenceSchema.safeParse(withPath("/tmp/fixture")).success).toBe(true);
|
||||
expect(evidenceSchema.safeParse(withPath("")).success).toBe(true);
|
||||
expect(evidenceSchema.safeParse(withPath("a\u0000b")).success).toBe(false);
|
||||
});
|
||||
|
||||
it("binds an explicit unknown-subject reason into the semantic Evidence identity", () => {
|
||||
const reason = "Caller excluded the observed digest.";
|
||||
const observation = { operation: "health", parameters: {}, result: true };
|
||||
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
import { digestCanonicalValue } from "./canonicalDigest.js";
|
||||
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
|
||||
import { nulFreeStringSchema } from "./localPath.js";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
@@ -43,6 +44,7 @@ const subjectSchema = z.object({
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
@@ -65,7 +67,7 @@ const subjectSchema = z.object({
|
||||
"entitlements",
|
||||
]),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
local_path: z.string(),
|
||||
local_path: nulFreeStringSchema,
|
||||
});
|
||||
/** Source location attached to an evidence observation. */
|
||||
/** Source-location schema shared by evidence-bearing persistence formats. */
|
||||
|
||||
@@ -2,7 +2,9 @@ import { isAbsolute, relative, sep } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Preserve selected filesystem names while rejecting OS-invalid NUL bytes.
|
||||
* Reject OS-invalid NUL bytes in a local filesystem name. This is not a path
|
||||
* shape check: an empty or relative value is admitted here and narrowed by the
|
||||
* callers that need a nonempty or absolute path.
|
||||
*
|
||||
* The pattern spells NUL as `\x00` rather than `\u0000`. Both accept exactly the
|
||||
* same strings. The hex form also avoids the short `\0` spelling rejected by
|
||||
@@ -10,11 +12,13 @@ import { z } from "zod";
|
||||
* one advertised pattern cannot compile. See `offsetDateTimeSchema` for the
|
||||
* same hex-escape convention.
|
||||
*/
|
||||
export const localPathStringSchema = z
|
||||
export const nulFreeStringSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.regex(/^[^\x00]*$/u, "Local filesystem paths cannot contain NUL");
|
||||
|
||||
/** A selected local filesystem path: nonempty and free of NUL bytes. */
|
||||
export const localPathStringSchema = nulFreeStringSchema.min(1);
|
||||
|
||||
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
|
||||
export const isPathWithinRoot = (root: string, path: string): boolean => {
|
||||
const value = relative(root, path);
|
||||
|
||||
@@ -84,7 +84,7 @@ export const nativeLoadImageCheckSchema = z.strictObject({
|
||||
});
|
||||
|
||||
/** Read-only native image verification; verified applies only to declared coverage. */
|
||||
export const nativeLoadImageSchema = z.discriminatedUnion("status", [
|
||||
export const nativeLoadImageSchema = z.union([
|
||||
z.strictObject({
|
||||
status: z.literal("unsupported"),
|
||||
reason: z.string().min(1),
|
||||
@@ -108,6 +108,23 @@ export const nativeLoadImageSchema = z.discriminatedUnion("status", [
|
||||
checks: z.array(nativeLoadImageCheckSchema),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.enum(["verified", "mismatch"]),
|
||||
format: z.literal("raw-binary"),
|
||||
target_sha256: digest,
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
|
||||
language_id: z.string().min(1),
|
||||
compiler_spec_id: z.string().min(1),
|
||||
base_address: address,
|
||||
file_bytes: integer.min(1),
|
||||
entry: z.strictObject({
|
||||
address: address,
|
||||
file_offset: z.literal(0),
|
||||
}),
|
||||
observations: nativeLoadImageObservationSchema,
|
||||
checks: z.array(nativeLoadImageCheckSchema),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Provider-neutral native load-image result. */
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { executableFormatHintSchema } from "./dosCom.js";
|
||||
import {
|
||||
admitRawBinary,
|
||||
parseRawBinaryEntryPoint,
|
||||
rawBinarySelectionError,
|
||||
validateRawBinaryLength,
|
||||
} from "./rawBinary.js";
|
||||
|
||||
describe("headerless format hints", () => {
|
||||
it("admits dos-com and raw-binary names only", () => {
|
||||
expect(executableFormatHintSchema.safeParse("dos-com").success).toBe(true);
|
||||
expect(executableFormatHintSchema.safeParse("raw-binary").success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(executableFormatHintSchema.safeParse("raw").success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("raw-binary entry addresses", () => {
|
||||
it("canonicalizes equivalent hex spellings without dropping the source", () => {
|
||||
const parsed = parseRawBinaryEntryPoint("0x08000000");
|
||||
expect(parsed).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
source: "0x08000000",
|
||||
canonical: "0x8000000",
|
||||
value: 0x8000000n,
|
||||
},
|
||||
});
|
||||
});
|
||||
it.each(["8000000", "0x", "0xgg", "0X8000000", ""])(
|
||||
"rejects malformed entry %s",
|
||||
(value) => {
|
||||
expect(parseRawBinaryEntryPoint(value).ok).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("raw-binary admission", () => {
|
||||
it("admits a little-endian ARM image mapped at the caller entry", () => {
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
fileBytes: 4,
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x8000000",
|
||||
},
|
||||
});
|
||||
});
|
||||
it("rejects an empty file", () => {
|
||||
expect(validateRawBinaryLength(0).ok).toBe(false);
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "x86",
|
||||
entryPoint: "0x1000",
|
||||
fileBytes: 0,
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects a 32-bit mapping that exceeds the architecture width", () => {
|
||||
const result = admitRawBinary({
|
||||
architecture: "arm",
|
||||
entryPoint: "0xfffffffc",
|
||||
fileBytes: 8,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected overflow rejection");
|
||||
expect(result.error).toContain("arm address width");
|
||||
});
|
||||
it("allows a 64-bit mapping that would overflow 32-bit ARM", () => {
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "arm64",
|
||||
entryPoint: "0xfffffffc",
|
||||
fileBytes: 8,
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
});
|
||||
it.each(["arm", "arm64"])(
|
||||
"rejects unaligned %s entries before provider selection",
|
||||
(architecture) => {
|
||||
for (const entryPoint of ["0x8000001", "0x8000002", "0x8000003"]) {
|
||||
expect(
|
||||
admitRawBinary({ architecture, entryPoint, fileBytes: 4 }),
|
||||
).toEqual({
|
||||
ok: false,
|
||||
error: `raw-binary ${architecture} entry_point ${entryPoint} must be 4-byte aligned`,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
it.each(["x86", "x86_64"])(
|
||||
"admits byte-aligned %s entries",
|
||||
(architecture) => {
|
||||
const admitted = admitRawBinary({
|
||||
architecture,
|
||||
entryPoint: "0x1001",
|
||||
fileBytes: 1,
|
||||
});
|
||||
if (!admitted.ok) throw new Error(admitted.error);
|
||||
expect(admitted.value.entryPoint).toBe("0x1001");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("raw-binary selection pairing", () => {
|
||||
it("requires architecture and entry with format=raw-binary", () => {
|
||||
expect(rawBinarySelectionError({ format: "raw-binary" })).toBe(
|
||||
"format=raw-binary requires architecture and entry_point",
|
||||
);
|
||||
expect(
|
||||
rawBinarySelectionError({
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it("rejects architecture or entry without format=raw-binary", () => {
|
||||
expect(
|
||||
rawBinarySelectionError({ architecture: "arm", entryPoint: "0x1" }),
|
||||
).toBe("architecture and entry_point apply only with format=raw-binary");
|
||||
expect(
|
||||
rawBinarySelectionError({ format: "dos-com", architecture: "x86" }),
|
||||
).toBe("architecture and entry_point apply only with format=raw-binary");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
|
||||
import type { ExecutableFormatHint } from "./dosCom.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Caller-visible CPU families admitted for headerless raw binaries. */
|
||||
export const BINARY_ARCHITECTURES = [
|
||||
"x86",
|
||||
"x86_64",
|
||||
"arm",
|
||||
"arm64",
|
||||
] as const satisfies readonly BinaryArchitecture[];
|
||||
|
||||
/** Provider-neutral CPU family for a caller-supplied raw-binary load. */
|
||||
export const binaryArchitectureSchema = z.enum(BINARY_ARCHITECTURES);
|
||||
|
||||
const RAW_BINARY_ENTRY_POINT = /^0x[0-9A-Fa-f]{1,16}$/u;
|
||||
|
||||
/** Hexadecimal load and entry address; file offset 0 is mapped here. */
|
||||
export const rawBinaryEntryPointSchema = z
|
||||
.string()
|
||||
.regex(RAW_BINARY_ENTRY_POINT, {
|
||||
message: "entry_point must be a hexadecimal address of the form 0x…",
|
||||
});
|
||||
|
||||
/** Canonicalized caller-supplied raw-binary entry with the original spelling. */
|
||||
export interface CanonicalRawBinaryEntry {
|
||||
readonly source: string;
|
||||
readonly canonical: string;
|
||||
readonly value: bigint;
|
||||
}
|
||||
|
||||
/** Parse a caller-supplied hex entry while preserving the source spelling. */
|
||||
export const parseRawBinaryEntryPoint = (
|
||||
value: string,
|
||||
): Result<CanonicalRawBinaryEntry, string> => {
|
||||
if (!RAW_BINARY_ENTRY_POINT.test(value))
|
||||
return err("entry_point must be a hexadecimal address of the form 0x…");
|
||||
const parsed = BigInt(value);
|
||||
return ok({
|
||||
source: value,
|
||||
canonical: `0x${parsed.toString(16)}`,
|
||||
value: parsed,
|
||||
});
|
||||
};
|
||||
|
||||
/** Reject empty or non-integral file extents for a headerless image. */
|
||||
export const validateRawBinaryLength = (
|
||||
length: number,
|
||||
): Result<null, string> =>
|
||||
Number.isSafeInteger(length) && length >= 1
|
||||
? ok(null)
|
||||
: err("raw-binary requires at least one file byte");
|
||||
|
||||
/** Admitted headerless load identity used by target resolution and profiles. */
|
||||
export interface RawBinaryAdmission {
|
||||
readonly architecture: Exclude<BinaryArchitecture, "mips">;
|
||||
readonly entryPoint: string;
|
||||
readonly entryPointSource: string;
|
||||
}
|
||||
|
||||
const addressWidth = (architecture: BinaryArchitecture): bigint =>
|
||||
architecture === "x86" || architecture === "arm"
|
||||
? 0xffffffffn
|
||||
: 0xffffffffffffffffn;
|
||||
|
||||
/** Validate architecture, entry, and that the mapped image fits the CPU width. */
|
||||
export const admitRawBinary = (input: {
|
||||
readonly architecture: unknown;
|
||||
readonly entryPoint: unknown;
|
||||
readonly fileBytes: number;
|
||||
}): Result<RawBinaryAdmission, string> => {
|
||||
const architecture = binaryArchitectureSchema.safeParse(input.architecture);
|
||||
if (!architecture.success)
|
||||
return err(
|
||||
"raw-binary format requires architecture (x86, x86_64, arm, or arm64)",
|
||||
);
|
||||
if (typeof input.entryPoint !== "string")
|
||||
return err(
|
||||
"raw-binary format requires entry_point as a hexadecimal address of the form 0x…",
|
||||
);
|
||||
const entry = parseRawBinaryEntryPoint(input.entryPoint);
|
||||
if (!entry.ok) return entry;
|
||||
if (
|
||||
(architecture.data === "arm" || architecture.data === "arm64") &&
|
||||
entry.value.value % 4n !== 0n
|
||||
)
|
||||
return err(
|
||||
`raw-binary ${architecture.data} entry_point ${entry.value.canonical} must be 4-byte aligned`,
|
||||
);
|
||||
const length = validateRawBinaryLength(input.fileBytes);
|
||||
if (!length.ok) return length;
|
||||
const last = entry.value.value + BigInt(input.fileBytes) - 1n;
|
||||
const max = addressWidth(architecture.data);
|
||||
if (entry.value.value > max || last > max)
|
||||
return err(
|
||||
`raw-binary mapping from ${entry.value.canonical} must fit in the ${architecture.data} address width`,
|
||||
);
|
||||
return ok({
|
||||
architecture: architecture.data,
|
||||
entryPoint: entry.value.canonical,
|
||||
entryPointSource: entry.value.source,
|
||||
});
|
||||
};
|
||||
|
||||
/** Describe the format/architecture/entry pairing without performing I/O. */
|
||||
export const rawBinarySelectionError = (input: {
|
||||
readonly format?: ExecutableFormatHint;
|
||||
readonly architecture?: unknown;
|
||||
readonly entryPoint?: unknown;
|
||||
}): string | undefined => {
|
||||
const hasArchitecture = input.architecture !== undefined;
|
||||
const hasEntry = input.entryPoint !== undefined;
|
||||
if (input.format === "raw-binary") {
|
||||
if (!hasArchitecture || !hasEntry)
|
||||
return "format=raw-binary requires architecture and entry_point";
|
||||
return undefined;
|
||||
}
|
||||
if (hasArchitecture || hasEntry)
|
||||
return "architecture and entry_point apply only with format=raw-binary";
|
||||
return undefined;
|
||||
};
|
||||
Reference in New Issue
Block a user