Files
reverse-engineering-anything/src/artifacts/MqlProgramArtifactReader.ts
T
morluto a37994b3e8 feat(artifacts): inspect MetaTrader EX4 and EX5 program headers and resources (#16501)
* feat(artifacts): inspect MetaTrader 5 EX5 program headers and resources

Recognize compiled MQL5 programs by their EX5 magic and inventory them
through inspect_artifact and extract_artifact. Report the program type,
compiler build, copyright/link/version property slots, nonzero header
fields of unknown meaning, and the resource table. List the opaque body
and resource payloads as stored byte ranges; nothing is decrypted,
decompressed or decompiled.

Refs #16495

* feat(artifacts): read MetaTrader 4 EX4 programs with the EX5 layout

EX4 (magic EX-) shares the EX5 header, property slots and resource
table, so both containers become one mql-program format with a
container field. The version slot is 64 bytes and the opaque body
starts at 0x2E8 in both containers; the earlier 0x3A8 header length
counted 192 opaque bytes as part of the version slot. EX4 type code 3
is a library; build is reported under a neutral name because its EX4
meaning is not established.

* fix(artifacts): bound repeated MQL resource ranges and let tar outrank printable magics

Resource records may share one payload range, and each occurrence is
hashed and extractable, so the reader now charges every record against
artifact_limits.expanded_bytes, as the DTBO reader does.

A checksum-valid tar header now runs before the recognizers that match a
printable magic at offset 0. A tar whose first member was named EX-...,
GDPC... or UnityFS was claimed as an MQL program, Godot PCK or UnityFS.

Slot text keeps a leading U+FEFF, which is declared content rather than
an encoding mark.

* fix(artifacts): refuse an invalid tar header only after leading-magic formats

Only a checksum-valid tar header outranks the printable leading magics. A
Godot pack can hold ustar at 257 inside its own content without a valid
tar checksum; refusing that header first rejected the valid pack.

* fix(artifacts): compare MetaTrader resource declarations

A resource's name, kind, record index and unpacked size live in the
resource table, outside the stored payload that content comparison
hashes, so a renamed resource compared as unchanged. Compare them as
the resource's declaration, as tar, ar and UnityFS members do.

* fix(artifacts): keep unreadable MetaTrader resource names unknown in comparison
2026-12-03 19:16:36 -05:00

142 lines
4.7 KiB
TypeScript

import { artifactExpansionBudgetBytes } from "../domain/artifactExpansionBudget.js";
import type { MqlProgramMetadata } from "../domain/formatMetadata/mqlProgramMetadata.js";
import {
MQL_PROGRAM_HEADER_BYTES,
MQL_PROGRAM_RESOURCES_LIMIT,
mqlProgramResourceTableRange,
parseMqlProgramHeader,
parseMqlProgramLayout,
type MqlProgramLayout,
} from "../domain/mqlProgram.js";
import { ParseFailureError } from "../domain/parseFailure.js";
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
import {
artifactFixedLimitFailure,
artifactParseFailure,
artifactReaderLimitFailure,
malformedArtifact,
type ArtifactReaderFailure,
} from "../resources/index.js";
import { createExactArtifactRead } from "./ArtifactFileRange.js";
import {
PositionalArtifactReader,
type PositionalArtifactEntries,
type PositionalArtifactEntry,
} from "./PositionalArtifactReader.js";
/** Stored bytes of the body or a resource, whose encoding REA does not decode. */
const OPAQUE_ENTRY =
"Stored bytes as found in the file. REA does not decode, decompress or decrypt them, and their encoding is unknown.";
/**
* MetaTrader 4 (`.ex4`) or MetaTrader 5 (`.ex5`) compiled program: header
* facts, `#property` slots, and the opaque body and resource payloads as
* stored byte ranges. Nothing is decrypted, decompressed or executed.
*/
export class MqlProgramArtifactReader extends PositionalArtifactReader<MqlProgramMetadata> {
override readonly format = "mql-program" as const;
readonly #expandedBytes: number | undefined;
/** `expandedBytes` is `artifact_limits.expanded_bytes`. */
constructor(
path: string,
admitted?: StableRegularFileDescriptor,
expandedBytes?: number,
) {
super(path, "MQL program", admitted);
this.#expandedBytes = expandedBytes;
}
formatMetadata(): MqlProgramMetadata | undefined {
const metadata = this.preparedFormatMetadata;
return metadata === undefined ? undefined : structuredClone(metadata);
}
protected override entryEndedEarly(
entry: PositionalArtifactEntry,
): ArtifactReaderFailure {
return malformedArtifact(
"mql-program",
`MQL program region ended early: ${entry.path}`,
);
}
protected override async prepareEntries(
signal?: AbortSignal,
): Promise<PositionalArtifactEntries<MqlProgramMetadata>> {
const { handle, initial } = await this.verifyCarrier(signal);
const fileSize = initial.size;
const read = createExactArtifactRead(this.format, handle, fileSize, signal);
let layout: MqlProgramLayout;
try {
const header = parseMqlProgramHeader(
await read(0, Math.min(MQL_PROGRAM_HEADER_BYTES, fileSize)),
fileSize,
);
const range = mqlProgramResourceTableRange(header, fileSize);
const table =
range === undefined
? undefined
: await read(range.offset, range.length);
this.assertOpen(signal);
layout = parseMqlProgramLayout(header, table, fileSize);
} catch (cause: unknown) {
if (
cause instanceof ParseFailureError &&
cause.failure.kind === "limit" &&
cause.failure.limit.name === MQL_PROGRAM_RESOURCES_LIMIT
)
throw artifactFixedLimitFailure(
{
name: "The MQL program resource record allowance",
kind: "parser",
limit: cause.failure.limit.maximum,
unit: "records",
},
cause.message,
"capacity",
{ cause },
);
throw artifactParseFailure(cause, signal);
}
// Resource records may share one payload range, but every entry is hashed
// and can be extracted separately, so charge each occurrence.
const expansionBudget =
this.#expandedBytes ?? artifactExpansionBudgetBytes(fileSize);
const declaredBytes = layout.regions.reduce(
(total, region) => total + region.length,
0,
);
if (declaredBytes > expansionBudget)
throw artifactReaderLimitFailure(
"artifact_limits.expanded_bytes",
expansionBudget,
"bytes",
declaredBytes,
"memory",
);
return {
entries: layout.regions.map((region): PositionalArtifactEntry => ({
path: region.path,
kind: "file",
declaredSize: region.length,
compressedSize: null,
executable: false,
encrypted: false,
byteOffset: region.offset,
declaredIntegrity: null,
unpacked: false,
limitations: [OPAQUE_ENTRY],
adapterKey: `mql-program:${region.path}`,
formatMetadata: region.metadata,
})),
coverage: {
status: layout.limitations.length === 0 ? "complete" : "unknown",
limitations: [...layout.limitations],
},
formatMetadata: layout.metadata,
};
}
}