Files
reverse-engineering-anything/tests/boundary/providers/desktopStateHeap.test.ts
T
Aniket Rawatandmorluto dd1bb43db3 feat(elf): decode FDO packaging and dlopen note metadata (#7237)
* feat(elf): decode FDO packaging and dlopen note metadata

Name FDO notes within their owner's namespace: type 0xcafe1a7e is
fdo_packaging_metadata and 0x407c0c0a is fdo_dlopen_metadata. One
elfNoteTypeName(owner, type) replaces the GNU-only gnuNoteTypeName.

Each entry gains an fdo field next to gnu. metadata holds the descriptor's
JSON object (packaging) or array (dlopen) when it is NUL-terminated UTF-8
JSON followed only by NUL padding; otherwise metadata is null and issue
names the broken rule, without failing the inspection. Each descriptor
range is decoded once and its retained JSON text is charged to the shared
note text budget per repeated entry. A limitation marks the metadata as a
producer declaration.

Fixes #7235

* fix(elf): key FDO note decoding by note type

The FDO decode cache was keyed by descriptor range only, but the note
type selects the required JSON shape. Overlapping PT_NOTE and SHT_NOTE
tables can give one descriptor range a packaging note and a dlopen note,
and the second reused the first note's verdict. Include the type name in
the key.

Refs #7235

* fix(elf): bound FDO note decoding before parsing JSON

The FDO decoder charged only descriptor source bytes before JSON.parse,
but a dense JSON value such as [{},{},...] decodes to about 50 times its
source size in heap before the service and Evidence copy it again. A
16 MiB descriptor took about 790 MiB of heap; one near the default
64 MiB file budget could exhaust the Node heap. Leave descriptors above
64 KiB undecoded with an issue naming the limit; real FDO notes are a
few hundred bytes.

Refs #7235

* fix(elf): share one FDO decode allowance across the report

The 64 KiB FDO decode bound applied to each descriptor, so raising
max_entries to 256 admitted 256 distinct dense 64 KiB notes: a 16 MiB
file added about 700 MiB of heap before Evidence copied it again.
Charge each distinct descriptor's size to one 64 KiB allowance per
report; a range repeated by another table reuses its decode, and notes
past the allowance keep their entry with an issue.

Refs #7235

* test(desktop): exercise the shared JSON depth guard in the heap suite

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-19 06:01:39 +00:00

167 lines
6.1 KiB
TypeScript

import { execFileSync } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const ROOT = join(import.meta.dirname, "../../..");
/** What a script using one export of a domain module prints, run in a 32 MiB V8 old space. */
const inSmallHeap = async (module: string, name: string, body: string) => {
const folder = await createTestTempDirectory("desktop-state-heap-");
const script = join(folder, "run.mjs");
const url = pathToFileURL(join(ROOT, "src/domain", module)).href;
await writeFile(
script,
`import { ${name} } from ${JSON.stringify(url)};\n${body}`,
);
const output = execFileSync(
process.execPath,
[
"--max-old-space-size=32",
"--max-semi-space-size=1",
"--import",
"tsx",
script,
],
{ cwd: ROOT, encoding: "utf8", timeout: 120_000 },
);
return JSON.parse(output) as unknown;
};
it(
"checks JSON depth with one iterator per level, so a wide array fits a small heap",
{ tags: ["long-running"] },
async () => {
// Queuing a pair per member needed more than 64 MiB here; one iterator per level runs in 18 MiB.
const depths = await inSmallHeap(
"jsonValue.ts",
"jsonValueExceedsDepth",
`const wide = new Array(800_000).fill(null);
let nested = [];
for (let level = 0; level < 501; level += 1) nested = [nested];
console.log(JSON.stringify({
wide: jsonValueExceedsDepth(wide, 500),
edge: jsonValueExceedsDepth(nested, 501),
over: jsonValueExceedsDepth(nested, 500),
}));
`,
);
expect(depths).toEqual({ wide: false, edge: false, over: true });
},
);
it(
"pairs elements with a long tag and many attributes in a small heap, spelling a selector only once chosen",
{ tags: ["long-running"] },
async () => {
// Spelling the tag into a selector per attribute needed more than 140 MiB here.
const pairing = await inSmallHeap(
"desktop/memberPairing.ts",
"pairMembers",
`const tag = "t".repeat(40_000);
const element = (id) => {
const attributes = { id };
for (let index = 0; index < 2000; index += 1) attributes["a" + index] = String(index);
return { name: tag, attributes, children: [] };
};
const members = [element("1"), element("2")];
const { newer, older } = pairMembers(members, members, undefined, "xml");
console.log(JSON.stringify({ keys: newer.keys.map((key) => key.replace(tag, "T")), partners: newer.partners, same: older.keys.every((key, index) => key === newer.keys[index]) }));
`,
);
expect(pairing).toEqual({
keys: ["[name=T][@id=1]", "[name=T][@id=2]"],
partners: [0, 1],
same: true,
});
},
);
it(
"refuses JSON over the parsed-view limit in a small heap, telling it apart from text without building it",
{ tags: ["long-running"] },
async () => {
// Parsing the entry to detect its format needed more than 80 MiB here.
const entries = await inSmallHeap(
"desktop/zipView.ts",
"zipEntry",
`const read = (name, text) => {
const bytes = new TextEncoder().encode(text);
const entry = zipEntry({ name, size: bytes.length, compressedSize: bytes.length, method: 0, encrypted: false }, bytes);
return [entry.format, entry.view_error ?? entry.view.line_count];
};
console.log(JSON.stringify([
read("objects.json", "[{}" + ",{}".repeat(1_400_000) + "]"),
read("objects.txt", "[{}" + ",{}".repeat(1_400_000) + "}"),
]));
`,
);
expect(entries).toEqual([
["json", "larger than the 4 MiB limit for JSON and key file views"],
["text", 1],
]);
},
);
it(
"scrubs UTF-16 XML and JSON seeds of a million elements in a small heap, telling their format without building them",
{ tags: ["long-running"] },
async () => {
// Building the XML document to choose the scrubber needed more than 768 MiB here, and parsing the JSON more than 64 MiB; the syntax checks and copying only changes run in 24 MiB.
const outcomes = await inSmallHeap(
"desktop/seedScrub.ts",
"scrubSeed",
`const scrub = (home, text, tail, clean) => {
const seed = Buffer.from("\\uFEFF" + text + tail, "utf16le");
const scrubbed = scrubSeed(seed, { home, format: "binary" }, { home: "/home/ada", hostname: "e81232be457d", user: "ada" });
const expected = Buffer.concat([seed.subarray(0, -2 * tail.length), Buffer.from(clean, "utf16le")]);
return { exact: scrubbed.bytes?.equals(expected), holdsIdentity: scrubbed.holdsIdentity };
};
console.log(JSON.stringify([
scrub(".config/wide.xml", "<?xml version=\\"1.0\\" encoding=\\"UTF-16\\"?>\\n<r>" + "<e/>".repeat(1_000_000), "<m>ada@e81232be457d</m></r>", "<m>user@localhost</m></r>"),
scrub(".config/wide.json", "[{}" + ",{}".repeat(1_000_000), ',"ada@e81232be457d"]', ',"user@localhost"]'),
]));
`,
);
expect(outcomes).toEqual([
{ exact: true, holdsIdentity: false },
{ exact: true, holdsIdentity: false },
]);
},
);
it(
"compares objects of selector keys with arrays in a small heap, however many field sets or spellings they use",
{ tags: ["long-running"] },
async () => {
// An index per field set or spelling needed more than 48 MiB for either comparison here.
const removed = await inSmallHeap(
"desktop/stateChanges.ts",
"diffStateViews",
`const fields = ["f0", "f1", "f2", "f3", "f4", "f5", "f6"];
const members = Array.from({ length: 5000 }, (_, i) => Object.fromEntries(fields.map((f) => [f, f + "-" + i])));
const combinations = {};
for (let mask = 1; mask < 128; mask += 1)
combinations[fields.filter((_, bit) => mask & (1 << bit)).map((f) => "[" + f + "=" + f + "-0]").join("")] = mask;
const named = Array.from({ length: 800 }, (_, i) => ({ name: "n" + i }));
const repeated = {};
for (let count = 1; count <= 160; count += 1) repeated["[name=n0]".repeat(count)] = count;
console.log(JSON.stringify([
diffStateViews("json", { items: combinations }, { items: members }),
diffStateViews("json", { items: repeated }, { items: named }),
].map((difference) => difference.removed_count)));
`,
);
expect(removed).toEqual([0, 0]);
},
);