/** * Write a verified plan into a copy of the executable's bytes. The expected original bytes * are checked again right before each write, so a plan made against other bytes is refused * instead of landing half applied. The input is never modified. */ import { VerifyError } from './errors.ts'; import type { PlannedWrite } from './plan.ts'; export function applyWrites(data: Uint8Array, writes: readonly PlannedWrite[]): Uint8Array { const patched = Uint8Array.from(data); for (const write of [...writes].sort((left, right) => left.fileOffset - right.fileOffset)) { const end = write.fileOffset + write.payload.length; const actual = Buffer.from(patched.subarray(write.fileOffset, end)); if (!actual.equals(write.expectOriginal)) { throw new VerifyError(`${write.patchId}: bytes at file offset 0x${write.fileOffset.toString(16)} are ${actual.toString('hex')}, ` + `expected ${Buffer.from(write.expectOriginal).toString('hex')}; nothing was written`); } patched.set(write.payload, write.fileOffset); } return patched; }