Files
WT-Offline/packages/exepatch/src/plan.ts
T

169 lines
7.4 KiB
TypeScript

/**
* Work out every write first; nothing is written here.
*
* Per patch: choose the variant that fits (variants.ts); for it, find the site, require exactly
* one match, check the bytes there against the expected original, and fill the holes of the
* bytes to write from the site's captures. A patch failing any of these gets a reason instead
* of a write, and so does every patch that depends on it, so a game update yields a list of
* unavailable patches and the features they cover rather than a broken executable.
*/
import { formatBytePattern, formatBytes, patternMatches } from './byte-pattern.ts';
import type { PatchDefinition, PatchVariant } from './definition.ts';
import { DefinitionError, PatchError, VerifyError } from './errors.ts';
import { resolvePayload } from './fixups.ts';
import type { PeImage } from './pe-image.ts';
import { findSite, hex } from './site.ts';
import { chooseVariant } from './variants.ts';
export interface PlannedWrite {
readonly patchId: string;
/** written_for of the variant that applies. */
readonly variant: string;
readonly rva: number;
readonly fileOffset: number;
readonly payload: Uint8Array;
/** The bytes found at the site when planning; writing requires they are still there. */
readonly original: Uint8Array;
}
export interface PatchFailure {
readonly patchId: string;
readonly features: readonly string[];
readonly reason: string;
}
export interface PatchPlan {
readonly writes: readonly PlannedWrite[];
readonly failures: readonly PatchFailure[];
}
export function planPatches(image: PeImage, definitions: readonly PatchDefinition[]): PatchPlan {
const planned = new Map<string, PlannedWrite>();
const failed = new Map<string, string>();
for (const definition of definitions) {
try {
const chosen = chooseVariant(definition.variants, (variant) => planVariant(image, variant));
planned.set(definition.id, { patchId: definition.id, variant: chosen.variant.writtenFor, ...chosen.value });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
failed.set(definition.id, error.message);
}
}
propagateFailures(definitions, failed);
const writes = definitions.filter((item) => !failed.has(item.id)).map((item) => planned.get(item.id)!);
rejectOverlaps(writes);
const failures = definitions.filter((item) => failed.has(item.id))
.map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! }));
return { writes, failures };
}
/**
* Plan additive patches (such as declarative mod exe patches) on top of locked core writes.
* Any patch that fails to locate/verify, depends on a failed patch, overlaps a protected core
* write, or overlaps an earlier accepted additive write is recorded in `failures` rather than
* throwing, so core offline isolation patches are never overwritten or broken.
*/
export function planAdditionalPatches(
image: PeImage,
definitions: readonly PatchDefinition[],
protectedWrites: readonly PlannedWrite[],
): PatchPlan {
const planned = new Map<string, PlannedWrite>();
const failed = new Map<string, string>();
for (const definition of definitions) {
try {
const chosen = chooseVariant(definition.variants, (variant) => planVariant(image, variant));
planned.set(definition.id, { patchId: definition.id, variant: chosen.variant.writtenFor, ...chosen.value });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
failed.set(definition.id, error.message);
}
}
propagateFailures(definitions, failed);
const accepted: PlannedWrite[] = [];
for (const definition of definitions) {
if (failed.has(definition.id)) continue;
const candidate = planned.get(definition.id)!;
const coreConflict = findOverlappingWrite(candidate, protectedWrites);
if (coreConflict) {
failed.set(definition.id, `overlaps protected core patch "${coreConflict.patchId}" at ${hex(candidate.rva)}`);
continue;
}
const earlierConflict = findOverlappingWrite(candidate, accepted);
if (earlierConflict) {
failed.set(definition.id, `overlaps earlier patch "${earlierConflict.patchId}" at ${hex(candidate.rva)}`);
continue;
}
accepted.push(candidate);
}
// Re-propagate if an overlap rejection broke a downstream dependency.
const beforeSecondPass = failed.size;
propagateFailures(definitions, failed);
const writes = failed.size === beforeSecondPass
? accepted
: accepted.filter((write) => !failed.has(write.patchId));
const failures = definitions.filter((item) => failed.has(item.id))
.map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! }));
return { writes, failures };
}
function findOverlappingWrite(candidate: PlannedWrite, existing: readonly PlannedWrite[]): PlannedWrite | undefined {
const cStart = candidate.fileOffset;
const cEnd = cStart + candidate.payload.length;
return existing.find((write) => {
const wStart = write.fileOffset;
const wEnd = wStart + write.payload.length;
return cStart < wEnd && wStart < cEnd;
});
}
export function describePlan(plan: PatchPlan): string {
const lines = [`${plan.writes.length} patch(es) ready, ${plan.failures.length} unavailable`];
for (const write of plan.writes) lines.push(` ready ${write.patchId} at ${hex(write.rva)} (variant ${write.variant})`);
for (const failure of plan.failures) lines.push(` FAILED ${failure.patchId}: ${failure.reason}`);
const features = [...new Set(plan.failures.flatMap((failure) => failure.features))].sort();
if (plan.failures.length) lines.push(` features affected: ${features.join(', ') || 'none recorded'}`);
return lines.join('\n');
}
type VariantWrite = Omit<PlannedWrite, 'patchId' | 'variant'>;
function planVariant(image: PeImage, variant: PatchVariant): VariantWrite {
const site = findSite(image, variant.locate);
const { edit } = variant;
const rva = site.rva + edit.offset;
const original = Uint8Array.from(image.read(rva, edit.expectOriginal.bytes.length));
if (!patternMatches(edit.expectOriginal, original)) {
throw new VerifyError(`bytes at ${hex(rva)} are ${formatBytes(original)}, expected ${formatBytePattern(edit.expectOriginal)} (different game build, or already patched)`);
}
return { rva, fileOffset: image.fileOffset(rva), payload: resolvePayload(edit.payload, edit.fixups, rva, site.captures), original };
}
/** A patch whose prerequisite is unavailable cannot be applied either. */
function propagateFailures(definitions: readonly PatchDefinition[], failed: Map<string, string>): void {
for (let changed = true; changed;) {
changed = false;
for (const definition of definitions) {
if (failed.has(definition.id)) continue;
const blocking = definition.requires.filter((id) => failed.has(id));
if (blocking.length) {
failed.set(definition.id, `depends on unavailable patch(es): ${blocking.join(', ')}`);
changed = true;
}
}
}
}
function rejectOverlaps(writes: readonly PlannedWrite[]): void {
const sorted = [...writes].sort((left, right) => left.fileOffset - right.fileOffset);
for (let index = 1; index < sorted.length; index++) {
const earlier = sorted[index - 1]!;
const later = sorted[index]!;
if (later.fileOffset < earlier.fileOffset + earlier.payload.length) {
throw new DefinitionError(`${earlier.patchId} and ${later.patchId} write overlapping bytes at ${hex(earlier.rva)} and ${hex(later.rva)}`);
}
}
}