Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(nativeaot): preserve COPY bytes when hydration output grows (#6254)

Kaoru082214877a069bc7
diff --git a/src/domain/native/nativeAotPe.hydration.test.ts b/src/domain/native/nativeAotPe.hydration.test.ts
new file mode 100644
index 000000000..68668bb68
--- /dev/null
+++ b/src/domain/native/nativeAotPe.hydration.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from "vitest";
+import {
+ NATIVE_AOT_MAX_REPORT_BYTES,
+ parseNativeAotPe,
+} from "./nativeAotPe.js";
+import {
+ NATIVE_AOT_HYDRATION_BASE,
+ NATIVE_AOT_HYDRATION_CAPACITY,
+ type NativeAotHydrationCommand,
+ nativeAotPeDigest,
+ nativeAotPeHydrationFixture,
+} from "../../../tests/fixtures/nativeaotPe.js";
+
+/** The parser's first output allocation; larger streams must grow it. */
+const INITIAL_OUTPUT = 64 * 1024;
+const TARGET = 0x140001010n;
+const fill = (length: number, value = 0xa5): Buffer =>
+ Buffer.alloc(length, value);
+
+const hydrate = (commands: readonly NativeAotHydrationCommand[]) => {
+ const { bytes, expected } = nativeAotPeHydrationFixture(commands);
+ const digest = nativeAotPeDigest(bytes);
+ const { summary } = parseNativeAotPe(
+ bytes,
+ digest,
+ NATIVE_AOT_MAX_REPORT_BYTES,
+ );
+ // The overlay is parser-owned; the captured snapshot must stay unchanged.
+ expect(nativeAotPeDigest(bytes)).toBe(digest);
+ return { summary, expected };
+};
+
+describe("NativeAOT DEHYDRATED_DATA hydration output", () => {
+ it.each<[string, NativeAotHydrationCommand[]]>([
+ ["COPY ending at the initial capacity", [{ copy: fill(INITIAL_OUTPUT) }]],
+ ["COPY that grows the output", [{ copy: fill(INITIAL_OUTPUT + 1) }]],
+ [
+ "COPY that grows retained output",
+ [{ copy: fill(32768) }, { copy: fill(32769, 0xa6) }],
+ ],
+ [
+ "COPYs that grow the output twice",
+ [
+ { copy: fill(INITIAL_OUTPUT + 1) },
+ { copy: fill(INITIAL_OUTPUT + 1, 0xa6) },
+ ],
+ ],
+ [
+ "empty COPYs around growth",
+ [
+ { copy: Buffer.alloc(0) },
+ { copy: fill(INITIAL_OUTPUT + 1) },
+ { copy: Buffer.alloc(0) },
+ { copy: fill(3, 0xa6) },
+ ],
+ ],
+ [
+ "zero fill that grows the output",
+ [
+ { copy: fill(INITIAL_OUTPUT - 1) },
+ { zero: 10 },
+ { copy: fill(5, 0xa6) },
+ ],
+ ],
+ [
+ "relative fixup straddling growth",
+ [
+ { copy: fill(INITIAL_OUTPUT - 2) },
+ { fixupRel: TARGET },
+ { copy: fill(3, 0xa6) },
+ ],
+ ],
+ [
+ "pointer fixup straddling growth",
+ [
+ { copy: fill(INITIAL_OUTPUT - 4) },
+ { fixupPtr: TARGET },
+ { copy: fill(3, 0xa6) },
+ ],
+ ],
+ [
+ "inline relative pointers straddling growth",
+ [
+ { copy: fill(INITIAL_OUTPUT - 6) },
+ { inlineRel: [TARGET, TARGET + 8n, TARGET + 16n] },
+ { copy: fill(3, 0xa6) },
+ ],
+ ],
+ [
+ "inline pointers straddling growth",
+ [
+ { copy: fill(INITIAL_OUTPUT - 12) },
+ { inlinePtr: [TARGET, TARGET + 8n, TARGET + 16n] },
+ { copy: fill(3, 0xa6) },
+ ],
+ ],
+ [
+ "output growing to exactly the mapped section end",
+ [
+ { copy: fill(NATIVE_AOT_HYDRATION_CAPACITY - 9) },
+ { fixupPtr: TARGET },
+ { zero: 1 },
+ ],
+ ],
+ ])("preserves every byte for %s", (_case, commands) => {
+ const { summary, expected } = hydrate(commands);
+ expect(summary.status).toBe("complete");
+ expect(summary.diagnostics).toEqual([]);
+ expect(summary.derived_overlay).toEqual({
+ address: `0x${NATIVE_AOT_HYDRATION_BASE.toString(16)}`,
+ size_bytes: expected.length,
+ sha256: nativeAotPeDigest(expected),
+ });
+ });
+
+ it.each<[string, NativeAotHydrationCommand[], string]>([
+ [
+ "COPY past the mapped section",
+ [{ copy: fill(NATIVE_AOT_HYDRATION_CAPACITY + 1) }],
+ "Hydrated metadata exceeds its mapped PE section",
+ ],
+ [
+ "pointer fixup past the mapped section after growth",
+ [{ copy: fill(NATIVE_AOT_HYDRATION_CAPACITY - 4) }, { fixupPtr: TARGET }],
+ "Hydrated metadata exceeds its mapped PE section",
+ ],
+ [
+ "COPY payload past DEHYDRATED_DATA after growth",
+ [
+ { copy: fill(INITIAL_OUTPUT + 1) },
+ { raw: Buffer.from([4 << 3, 1, 2]) },
+ ],
+ "DEHYDRATED_DATA COPY leaves its section",
+ ],
+ [
+ "fixup index outside captured sections after growth",
+ [
+ { copy: fill(INITIAL_OUTPUT + 1) },
+ { raw: Buffer.from([(31 << 3) | 3, 0xff, 0xff, 0xff]) },
+ ],
+ "DEHYDRATED_DATA fixup leaves captured PE sections",
+ ],
+ ])("reports %s as partial without an overlay", (_case, commands, reason) => {
+ const { summary } = hydrate(commands);
+ expect(summary.status).toBe("partial");
+ expect(summary.derived_overlay).toBeNull();
+ expect(summary.diagnostics.join("\n")).toContain(reason);
+ });
+});
diff --git a/src/domain/native/nativeAotPe.ts b/src/domain/native/nativeAotPe.ts
index 90f539943..8706bee8e 100644
--- a/src/domain/native/nativeAotPe.ts
+++ b/src/domain/native/nativeAotPe.ts
@@ -862,7 +862,12 @@ const hydrate = (
parserBudgetExhausted("working-memory");
let outputLength = 0;
let cursor = 4;
- const ensureOutput = (length: number): number => {
+ /** Reserve the next output bytes and return a view of the retained buffer.
+ * Writers must use only this view: growth replaces `output`, so a reference
+ * taken before reserving would write into the superseded buffer. Every byte
+ * of the view must be written because growth leaves new capacity
+ * uninitialized. */
+ const reserveOutput = (length: number): Buffer => {
if (
!Number.isSafeInteger(length) ||
length < 0 ||
@@ -890,29 +895,26 @@ const hydrate = (
output = expanded;
}
outputLength = required;
- return start;
+ return output.subarray(start, required);
};
const append = (chunk: Buffer): void => {
if (!budget.consumeWork(chunk.length)) parserBudgetExhausted("work");
- chunk.copy(output, ensureOutput(chunk.length));
+ chunk.copy(reserveOutput(chunk.length));
};
const appendZero = (length: number): void => {
if (!budget.consumeWork(length)) parserBudgetExhausted("work");
- const start = ensureOutput(length);
- output.fill(0, start, outputLength);
+ reserveOutput(length).fill(0);
};
const appendRel = (target: bigint): void => {
if (!budget.consumeWork(4)) parserBudgetExhausted("work");
const delta = target - (base + BigInt(outputLength));
if (delta < -0x80000000n || delta > 0x7fffffffn)
throw new Error("Hydrated relative pointer does not fit int32");
- const offset = ensureOutput(4);
- output.writeInt32LE(Number(delta), offset);
+ reserveOutput(4).writeInt32LE(Number(delta), 0);
};
const appendPtr = (target: bigint): void => {
if (!budget.consumeWork(8)) parserBudgetExhausted("work");
- const offset = ensureOutput(8);
- output.writeBigUInt64LE(target, offset);
+ reserveOutput(8).writeBigUInt64LE(target, 0);
};
const readFixup = (index: number): bigint => {
const fixupLocation = dehydrated.end + BigInt(index * 4);
diff --git a/tests/fixtures/nativeaotPe.ts b/tests/fixtures/nativeaotPe.ts
index 09c712ec6..99df5754b 100644
--- a/tests/fixtures/nativeaotPe.ts
+++ b/tests/fixtures/nativeaotPe.ts
@@ -128,3 +128,119 @@ export const nativeAotPeVirtualSectionFixture = (
if (position === "before-data") data.copy(bytes, table + 80);
return bytes;
};
+
+/** One authored RTR9.1 hydration command; fixup targets are absolute addresses. */
+export type NativeAotHydrationCommand =
+ | { readonly copy: Buffer }
+ | { readonly zero: number }
+ | { readonly fixupRel: bigint }
+ | { readonly fixupPtr: bigint }
+ | { readonly inlineRel: readonly bigint[] }
+ | { readonly inlinePtr: readonly bigint[] }
+ /** Stream bytes emitted verbatim for malformed-input cases; no output. */
+ | { readonly raw: Buffer };
+
+/** Overlay address and capacity of {@link nativeAotPeHydrationFixture}. */
+export const NATIVE_AOT_HYDRATION_BASE = address(0x40000);
+export const NATIVE_AOT_HYDRATION_CAPACITY = 0x22000;
+
+const hydrationHeader = (command: number, payload: number): Buffer => {
+ if (payload <= 28) return Buffer.from([(payload << 3) | command]);
+ const extra = payload - 28;
+ const width = extra < 0x100 ? 1 : extra < 0x10000 ? 2 : 3;
+ const bytes = Buffer.alloc(1 + width, ((28 + width) << 3) | command);
+ bytes.writeUIntLE(extra, 1, width);
+ return bytes;
+};
+
+/**
+ * Expand .rdata so DEHYDRATED_DATA at RVA 0x3000 can carry an authored command
+ * stream whose overlay at RVA 0x40000 may grow to the end of the section.
+ * Returns the bytes the RTR9.1 writer semantics say hydration must produce.
+ */
+export const nativeAotPeHydrationFixture = (
+ commands: readonly NativeAotHydrationCommand[],
+): { readonly bytes: Buffer; readonly expected: Buffer } => {
+ const bytes = Buffer.alloc(0x60600);
+ nativeAotPeFixture().copy(bytes);
+ const data = 0x98 + 0xf0 + 40;
+ bytes.writeUInt32LE(0x60000, data + 8);
+ bytes.writeUInt32LE(0x60000, data + 16);
+ bytes.writeUInt32LE(0x62000, 0x98 + 56);
+ const start = 0x3000;
+ const fileOffset = (rva: number): number => 0x600 + rva - 0x2000;
+ const stream: Buffer[] = [Buffer.alloc(4)];
+ let streamLength = 4;
+ const emit = (...chunks: Buffer[]): void => {
+ for (const chunk of chunks) {
+ stream.push(chunk);
+ streamLength += chunk.length;
+ }
+ };
+ const fixups: bigint[] = [];
+ const expected: Buffer[] = [];
+ let produced = 0;
+ const relative = (target: bigint): Buffer => {
+ const value = Buffer.alloc(4);
+ value.writeInt32LE(
+ Number(target - (NATIVE_AOT_HYDRATION_BASE + BigInt(produced))),
+ );
+ produced += 4;
+ return value;
+ };
+ const pointer = (target: bigint): Buffer => {
+ const value = Buffer.alloc(8);
+ value.writeBigUInt64LE(target);
+ produced += 8;
+ return value;
+ };
+ const inline = (targets: readonly bigint[]): void => {
+ for (const target of targets) {
+ const value = Buffer.alloc(4);
+ value.writeInt32LE(Number(target - address(start + streamLength)));
+ emit(value);
+ }
+ };
+ for (const command of commands) {
+ if ("copy" in command) {
+ emit(hydrationHeader(0, command.copy.length), command.copy);
+ expected.push(command.copy);
+ produced += command.copy.length;
+ } else if ("zero" in command) {
+ emit(hydrationHeader(1, command.zero));
+ expected.push(Buffer.alloc(command.zero));
+ produced += command.zero;
+ } else if ("fixupRel" in command) {
+ emit(hydrationHeader(2, fixups.push(command.fixupRel) - 1));
+ expected.push(relative(command.fixupRel));
+ } else if ("fixupPtr" in command) {
+ emit(hydrationHeader(3, fixups.push(command.fixupPtr) - 1));
+ expected.push(pointer(command.fixupPtr));
+ } else if ("inlineRel" in command) {
+ emit(hydrationHeader(4, command.inlineRel.length));
+ inline(command.inlineRel);
+ expected.push(...command.inlineRel.map(relative));
+ } else if ("raw" in command) {
+ emit(command.raw);
+ } else {
+ emit(hydrationHeader(5, command.inlinePtr.length));
+ inline(command.inlinePtr);
+ expected.push(...command.inlinePtr.map(pointer));
+ }
+ }
+ const end = start + streamLength;
+ if (end + fixups.length * 4 > 0x40000)
+ throw new Error("Hydration fixture stream overlaps its overlay");
+ Buffer.concat(stream).copy(bytes, fileOffset(start));
+ bytes.writeInt32LE(0x40000 - start, fileOffset(start));
+ fixups.forEach((target, index) => {
+ const location = end + index * 4;
+ bytes.writeInt32LE(
+ Number(target - address(location)),
+ fileOffset(location),
+ );
+ });
+ bytes.writeBigUInt64LE(address(start), 0x618);
+ bytes.writeBigUInt64LE(address(end), 0x620);
+ return { bytes, expected: Buffer.concat(expected) };
+};