Compare commits

..
8 changed files with 107 additions and 155 deletions

No files matched your search

@@ -175,6 +175,27 @@ describe("ESP flash layout inventory", () => {
});
});
it("inventories a zero-byte partition without reporting missing bytes", async () => {
const dump = espFlashDump({
bootloader: { at: 0, bytes: BOOTLOADER },
table: partitionTable([
...TWO_OTA_PARTITIONS,
{ label: "empty", type: 1, subtype: 0x82, offset: 0xa000, size: 0 },
]),
});
const snapshot = await scanCanonicalArtifactInventory(await writeDump(dump));
expect(snapshot.coverage.status).toBe("complete");
expect(
snapshot.occurrences.find(
({ logical_path }) => logical_path === "partitions/empty.bin",
),
).toMatchObject({
declared_size: 0,
limitations: ["partitions/empty.bin declares zero bytes."],
format_metadata: { flash_address: 0xa000, size: 0 },
});
});
describe("ESP flash layout coverage and selection", () => {
it("keeps usable partitions beside a truncated and a missing one", async () => {
const cut = DUMP.subarray(0, 0x2_8000);
+9 -7
View File
@@ -272,15 +272,17 @@ const regionEntry = (
declaredIntegrity: null,
unpacked: false,
limitations:
region.available === 0
? [
`${region.path} lies outside the dump: the file holds none of its ${String(region.length)} bytes.`,
]
: region.available < region.length
region.availability === "empty"
? [`${region.path} declares zero bytes.`]
: region.availability === "missing"
? [
`${region.path} is truncated: the dump holds ${String(region.available)} of its ${String(region.length)} bytes.`,
`${region.path} lies outside the dump: the file holds none of its ${String(region.length)} bytes.`,
]
: [],
: region.availability === "truncated"
? [
`${region.path} is truncated: the dump holds ${String(region.available)} of its ${String(region.length)} bytes.`,
]
: [],
adapterKey: `esp-flash-image:${region.path}`,
...(region.partition === undefined
? {}
@@ -20,11 +20,6 @@ it("reads a Python 3.9 reference-flagged PYZ table", () => {
]);
});
it("reads marshal one-byte string tags as Latin-1", () => {
for (const hex of ["6101000000e9", "4101000000e9", "7a01e9", "5a01e9"])
expect(readMarshalSubset(bytes(hex))).toEqual({ ok: true, value: "é" });
});
it("decodes CPython marshal Unicode with surrogatepass", () => {
expect(
readMarshalSubset(
+8 -2
View File
@@ -168,8 +168,14 @@ const readAsciiBytes = (
): Result<string, PyInstallerFailure> => {
const bytes = readBytes(cursor, length);
if (!bytes.ok) return bytes;
// These tags use CPython's one-byte Unicode constructor, not an ASCII check.
return ok(bytes.value.toString("latin1"));
if (bytes.value.some((byte) => byte > 0x7f))
return err(
pyInstallerFailure(
"format",
"PYZ marshal ASCII string contains a non-ASCII byte",
),
);
return ok(bytes.value.toString("ascii"));
};
const readUtf8 = (
+20 -4
View File
@@ -38,6 +38,8 @@ export interface EspFlashRegion {
readonly fileOffset: number;
/** Bytes of the region the file holds, from `fileOffset`. */
readonly available: number;
/** An empty declaration has no bytes to be missing from the dump. */
readonly availability: "empty" | "missing" | "truncated" | "complete";
readonly partition: EspPartition | undefined;
}
@@ -117,12 +119,21 @@ const partitionPaths = (
const region = (
input: EspFlashPlanInput,
fields: Omit<EspFlashRegion, "fileOffset" | "available">,
fields: Omit<EspFlashRegion, "fileOffset" | "available" | "availability">,
): EspFlashRegion => {
const fileOffset = fields.flashAddress - input.origin.value;
const start = Math.max(0, fileOffset);
const end = Math.min(input.fileSize, fileOffset + fields.length);
return { ...fields, fileOffset, available: Math.max(0, end - start) };
const available = Math.max(0, end - start);
const availability =
fields.length === 0
? "empty"
: available === 0
? "missing"
: available < fields.length
? "truncated"
: "complete";
return { ...fields, fileOffset, available, availability };
};
const rangeText = (address: number, length: number): string =>
@@ -211,11 +222,15 @@ export const planEspFlashLayout = (input: EspFlashPlanInput): EspFlashPlan => {
limitations.push(
`Partition ${name} at ${offsetText(part.offset)} begins before the dump's first byte at flash ${offsetText(input.origin.value)}; it is not read.`,
);
else if (placed.available === 0)
else if (placed.availability === "empty")
limitations.push(
`Partition ${name} at ${offsetText(part.offset)} declares zero bytes.`,
);
else if (placed.availability === "missing")
limitations.push(
`Partition ${name} at ${rangeText(part.offset, part.size)} lies outside the dump, which ends at flash ${offsetText(input.origin.value + input.fileSize)}.`,
);
else if (placed.available < part.size)
else if (placed.availability === "truncated")
limitations.push(
`Partition ${name} at ${rangeText(part.offset, part.size)} is truncated: the dump holds ${String(placed.available)} of its ${String(part.size)} bytes.`,
);
@@ -268,6 +283,7 @@ const overlaps = (regions: readonly EspFlashRegion[]): string[] => {
// The region reaching furthest so far, so a long one shows every overlap.
let furthest: EspFlashRegion | undefined;
for (const current of ordered) {
if (current.availability === "empty") continue;
if (
furthest !== undefined &&
current.flashAddress < regionEnd(furthest) &&
+32
View File
@@ -179,6 +179,38 @@ describe("ESP flash layout plans", () => {
});
describe("ESP flash layout overlaps", () => {
it.each([
["inside another partition", 0xa000],
["at the end of the dump", 0x4_0000],
])(
"retains a zero-byte partition %s as an empty declaration",
(_, offset) => {
const plan = planEspFlashLayout(
input({
table: table([
{
label: "data",
type: 1,
subtype: 2,
offset: 0x9000,
size: 0x4000,
},
{ label: "empty", type: 1, subtype: 0x82, offset, size: 0 },
]),
}),
);
expect(plan.regions.at(-1)).toMatchObject({
path: "partitions/empty.bin",
fileOffset: offset,
length: 0,
available: 0,
});
expect(plan.limitations).toEqual([
`Partition empty at 0x${offset.toString(16)} declares zero bytes.`,
]);
},
);
it("reports every region inside a longer one", () => {
const plan = planEspFlashLayout(
input({
-54
View File
@@ -407,30 +407,6 @@ it("charges long digits to the string budget and keeps large previews bounded",
);
});
it("reads marshal one-byte string tags as Latin-1 with Unicode identity", () => {
for (const tag of [0x61, 0x41, 0x7a, 0x5a]) {
const encoded = Buffer.concat([
Buffer.from([tag]),
tag === 0x61 || tag === 0x41 ? u32(1) : Buffer.from([1]),
Buffer.from([0xe9]),
]);
const sameUnicode = marshalUnicode(Buffer.from("é", "utf8"));
const set = Buffer.concat([
Buffer.from([0x3c]),
u32(2),
encoded,
sameUnicode,
]);
const report = root(parse(withConsts([encoded, set])));
expect(report.consts[0]).toMatchObject({
kind: "str",
value: "é",
bytes: 1,
});
expect(report.consts[1]).toEqual({ kind: "set", length: 1 });
}
});
it("decodes marshal strings with CPython surrogatepass rules", () => {
const report = parse(
withConsts([marshalUnicode(Buffer.from("efbbbf73eda080efbbbf", "hex"))]),
@@ -1558,36 +1534,6 @@ it("hashes a long TYPE_REF tuple chain without recursing", () => {
expect(pythonPycSchema.safeParse(report).success).toBe(true);
});
it("hashes shallow TYPE_REF code chains without using the JavaScript stack", () => {
const links = 3000;
const codes = Array.from({ length: links }, (_, index) =>
marshalCode("py311", {
flagged: true,
name: "f",
consts: index === 0 ? [Buffer.from([0x4e])] : [marshalRef(index - 1)],
}),
);
const bytes = Buffer.concat([
pythonPycHeader(3531),
marshalCode("py311", {
constsObject: Buffer.concat([
Buffer.from([0x28]),
u32(links + 1),
...codes,
Buffer.from([0x3c]),
u32(1),
marshalRef(links - 1),
]),
}),
]);
const report = parseWith(bytes, { max_objects: 65_536 });
expect(root(report).consts.at(-1)).toEqual({ kind: "set", length: 1 });
expect(report.coverage).toMatchObject({
status: "complete",
code_objects: links + 1,
});
});
it("rejects code CPython treats as corrupt instead of complete coverage", () => {
const file = (
layout: "py37" | "py38" | "py311",
+17 -83
View File
@@ -332,7 +332,7 @@ class MarshalReader {
readonly #codeKeys = new WeakMap<CodeNode, string>();
readonly #codeIdentities = new WeakMap<CodeNode, number>();
readonly #codeEquality = new WeakMap<CodeNode, CodeEquality>();
/** Completed Python hashability checks per code object. */
/** Python hashability per code object. False while that check is in progress. */
readonly #codeHashable = new WeakMap<CodeNode, boolean>();
/** Tuples whose items are still being read; CPython cannot hash them yet. */
readonly #readingTuples = new WeakSet<MarshalValue>();
@@ -436,19 +436,13 @@ class MarshalReader {
};
case TYPE_INTERNED:
case TYPE_UNICODE:
return this.string(
this.nonNegativeInt32("Marshal string length"),
"utf8",
);
return this.utf8(this.nonNegativeInt32("Marshal string length"), false);
case TYPE_ASCII:
case TYPE_ASCII_INTERNED:
return this.string(
this.nonNegativeInt32("Marshal string length"),
"latin1",
);
return this.utf8(this.nonNegativeInt32("Marshal string length"), true);
case TYPE_SHORT_ASCII:
case TYPE_SHORT_ASCII_INTERNED:
return this.string(this.u8(), "latin1");
return this.utf8(this.u8(), true);
case TYPE_TUPLE:
return this.sequenceValue(
"tuple",
@@ -1315,70 +1309,13 @@ class MarshalReader {
#isCodeHashable(node: CodeNode): boolean {
const known = this.#codeHashable.get(node);
if (known !== undefined) return known;
const frames: { value: MarshalValue; finish: boolean }[] = [
{ value: { kind: "code", value: node }, finish: false },
];
const gray = new Set<MarshalValue | CodeNode>();
const complete = new Set<MarshalValue>();
const reject = (): false => {
this.#codeHashable.set(node, false);
return false;
};
while (frames.length > 0) {
this.#takeKeyStep();
const frame = frames.pop()!;
const value = frame.value;
const identity = value.kind === "code" ? value.value : value;
if (frame.finish) {
gray.delete(identity);
if (value.kind === "code") {
const material =
this.#codeEquality.get(value.value) ??
malformed("Code object is missing equality material.");
// Child code checks are now complete, so the existing tuple key
// walker preserves its equality and expansion budgets without recursion.
const hashable =
this.#equalityKey(material.constsTuple, "hash") !== null;
this.#codeHashable.set(value.value, hashable);
if (!hashable) return reject();
} else complete.add(value);
continue;
}
if (value.kind === "code") {
const cached = this.#codeHashable.get(value.value);
if (cached === false) return reject();
if (cached === true) continue;
} else {
const cached = this.#keyCache.get(value);
if (cached === null) return reject();
if (cached !== undefined || complete.has(value)) continue;
}
if (
gray.has(identity) ||
this.#readingTuples.has(value) ||
value.kind === "list" ||
value.kind === "set" ||
value.kind === "dict" ||
value.kind === "null"
)
return reject();
const children =
value.kind === "code"
? [
(
this.#codeEquality.get(value.value) ??
malformed("Code object is missing equality material.")
).constsTuple,
]
: value.kind === "tuple" || value.kind === "frozenset"
? value.items
: [];
gray.add(identity);
frames.push({ value, finish: true });
for (let index = children.length - 1; index >= 0; index -= 1)
frames.push({ value: children[index]!, finish: false });
}
return true;
this.#codeHashable.set(node, false);
const material =
this.#codeEquality.get(node) ??
malformed("Code object is missing equality material.");
const hashable = this.#equalityKey(material.constsTuple, "hash") !== null;
this.#codeHashable.set(node, hashable);
return hashable;
}
#codeIdentity(node: CodeNode): number {
@@ -1555,20 +1492,17 @@ class MarshalReader {
);
}
string(length: number, encoding: "latin1" | "utf8"): MarshalValue {
utf8(length: number, ascii: boolean): MarshalValue {
const bytes = this.blob(length);
if (encoding === "latin1") {
// CPython reads the ASCII-tagged forms as one-byte Unicode, even when
// high bytes appear. Identity must agree with the UTF-8 string form.
const value = bytes.toString("latin1");
if (ascii) {
if (bytes.some((byte) => byte > 0x7f))
malformed("Marshal ASCII string contains a non-ASCII byte.");
return {
kind: "str",
value,
value: bytes.toString("latin1"),
previewEnd: Math.min(length, PYTHON_PYC_CONST_PREVIEW_LIMIT),
bytes: length,
raw: bytes.some((byte) => byte > 0x7f)
? Buffer.from(value, "utf8")
: bytes,
raw: bytes,
};
}
const decoded = decodeMarshalUtf8(bytes, PYTHON_PYC_CONST_PREVIEW_LIMIT);