Files
reverse-engineering-anything/src/domain/mqlProgram.test.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

276 lines
8.6 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { mqlProgram } from "./mqlProgram.fixture.js";
import {
MQL_PROGRAM_HEADER_BYTES,
MQL_PROGRAM_MAX_RESOURCES,
MQL_PROGRAM_RESOURCES_LIMIT,
hasMqlProgramMagic,
mqlProgramResourceTableRange,
parseMqlProgramHeader,
parseMqlProgramLayout,
} from "./mqlProgram.js";
import { ParseFailureError } from "./parseFailure.js";
const layoutOf = (bytes: Buffer) => {
const header = parseMqlProgramHeader(
bytes.subarray(0, MQL_PROGRAM_HEADER_BYTES),
bytes.length,
);
const range = mqlProgramResourceTableRange(header, bytes.length);
return parseMqlProgramLayout(
header,
range === undefined
? undefined
: bytes.subarray(range.offset, range.offset + range.length),
bytes.length,
);
};
const failureOf = (run: () => unknown) => {
try {
run();
} catch (cause) {
if (cause instanceof ParseFailureError) return cause.failure;
throw cause;
}
throw new Error("expected a parse failure");
};
describe("MetaTrader program header", () => {
it("reads the EX5 program type, build and property slots", () => {
const { metadata, regions, limitations } = layoutOf(
mqlProgram({ programType: 4, build: 3802, version: "5.50" }),
);
expect(metadata).toMatchObject({
kind: "mql-program",
container: "ex5",
program_type: "indicator",
program_type_code: 4,
build: 3802,
properties: {
copyright: {
offset: 0xa8,
state: "declared",
text: "Copyright 2026, Example",
},
link: {
offset: 0x1a8,
state: "declared",
text: "https://example.test",
},
version: { offset: 0x2a8, state: "declared", text: "5.50" },
},
body: { offset: MQL_PROGRAM_HEADER_BYTES, length: 17 },
resource_count: 0,
resource_section: null,
});
expect(metadata.unknown_header_fields).toEqual([
{ offset: 0x04, width: 2, value: 113 },
{ offset: 0x08, width: 4, value: 0x400 },
{ offset: 0x0e, width: 2, value: 1 },
{ offset: 0x10, width: 4, value: 1252 },
]);
expect(regions.map((region) => region.path)).toEqual(["body.stored"]);
expect(limitations).toEqual([]);
});
it("reads an EX4 library, which EX5 does not name", () => {
const ex4 = layoutOf(
mqlProgram({ container: "ex4", programType: 3, version: "" }),
);
expect(ex4.metadata).toMatchObject({
container: "ex4",
program_type: "library",
program_type_code: 3,
build: 2421,
properties: { version: { offset: 0x2a8, state: "empty", text: null } },
body: { offset: 0x2e8, length: 17 },
});
expect(ex4.metadata.unknown_header_fields[0]).toEqual({
offset: 0x04,
width: 2,
value: 112,
});
expect(layoutOf(mqlProgram({ programType: 3 })).metadata.program_type).toBe(
"unknown",
);
});
it("stops the version slot at its 64 bytes, before the opaque body", () => {
const bytes = mqlProgram({
version: "9".repeat(32),
body: Buffer.from("xy"),
});
const { metadata } = layoutOf(bytes);
expect(metadata.properties.version.text).toBe("9".repeat(32));
expect(metadata.body).toEqual({ offset: 0x2e8, length: 2 });
});
it("keeps a leading U+FEFF in property text and resource names", () => {
const { metadata, regions } = layoutOf(
mqlProgram({
link: "\ufeffhttps://example.test",
resources: [{ name: "\ufeffres\\a.bmp", payload: Buffer.from("x") }],
}),
);
expect(metadata.properties.link.text).toBe("\ufeffhttps://example.test");
expect(regions[1]?.metadata.name).toBe("\ufeffres\\a.bmp");
});
it("keeps an unknown program type code and empty or ill-formed slots", () => {
const bytes = mqlProgram({ programType: 7, copyright: "" });
// A lone high surrogate in the link slot.
bytes.writeUInt16LE(0xd800, 0x1a8);
bytes.writeUInt16LE(0x0041, 0x1aa);
const { metadata } = layoutOf(bytes);
expect(metadata.program_type).toBe("unknown");
expect(metadata.program_type_code).toBe(7);
expect(metadata.properties.copyright).toEqual({
offset: 0xa8,
state: "empty",
text: null,
});
expect(metadata.properties.link).toEqual({
offset: 0x1a8,
state: "malformed",
text: null,
});
});
it("recognizes only the EX- and EX5 magics", () => {
expect(hasMqlProgramMagic(mqlProgram())).toBe(true);
expect(hasMqlProgramMagic(mqlProgram({ container: "ex4" }))).toBe(true);
expect(hasMqlProgramMagic(Buffer.from("EX4\u0002"))).toBe(false);
expect(
failureOf(() => parseMqlProgramHeader(Buffer.from("MZ"), 2)),
).toMatchObject({ kind: "unrecognized", field: "magic" });
});
it("refuses a header shorter than its fixed size", () => {
const bytes = mqlProgram().subarray(0, 0x100);
expect(
failureOf(() => parseMqlProgramHeader(bytes, bytes.length)),
).toMatchObject({
kind: "truncated",
extent: {
availableBytes: 0x100,
requiredBytes: MQL_PROGRAM_HEADER_BYTES,
},
});
});
});
describe("MetaTrader program resources", () => {
const resources = [
{
name: "res\\Close.bmp",
payload: Buffer.from("close"),
unpackedSize: 1078,
},
{ name: "Textures\\checker.bmp", payload: Buffer.alloc(20, 7) },
];
it("lists each resource payload as a stored range after the table", () => {
const bytes = mqlProgram({ resources });
const { metadata, regions, limitations } = layoutOf(bytes);
const tableOffset = MQL_PROGRAM_HEADER_BYTES + 17;
expect(metadata.resource_count).toBe(2);
expect(metadata.body).toEqual({
offset: MQL_PROGRAM_HEADER_BYTES,
length: 17,
});
expect(metadata.resource_section).toEqual({
offset: tableOffset,
length: bytes.length - tableOffset,
});
const payloadStart = tableOffset + 2 * 0x9c;
expect(regions.slice(1)).toEqual([
{
path: "resources/0000.stored",
offset: payloadStart,
length: 5,
metadata: {
kind: "mql-program-entry",
role: "resource",
table_index: 0,
name: "res\\Close.bmp",
resource_kind: 2,
record_index: 1,
unpacked_size: 1078,
},
},
expect.objectContaining({
path: "resources/0001.stored",
offset: payloadStart + 16,
length: 20,
}),
]);
expect(
bytes.subarray(payloadStart, payloadStart + 5).toString("latin1"),
).toBe("close");
expect(limitations).toEqual([]);
});
it("omits a payload that ends past the file and reports it", () => {
const bytes = mqlProgram({ resources });
const tableOffset = bytes.readUInt32LE(0x18);
bytes.writeUInt32LE(0xffff, tableOffset + 0x9c + 0x08);
const { regions, limitations } = layoutOf(bytes);
expect(regions.map((region) => region.path)).toEqual([
"body.stored",
"resources/0000.stored",
]);
expect(limitations).toEqual([
expect.stringContaining("record 1 payload of 65535 bytes"),
]);
});
it("refuses a resource table that is inconsistent with the file", () => {
const bytes = mqlProgram({ resources });
const header = (patch: (copy: Buffer) => void) => {
const copy = Buffer.from(bytes);
patch(copy);
return () =>
mqlProgramResourceTableRange(
parseMqlProgramHeader(copy, copy.length),
copy.length,
);
};
expect(
failureOf(header((copy) => copy.writeUInt32LE(0x10, 0x18))),
).toMatchObject({ kind: "malformed", field: "resource_table_offset" });
expect(
failureOf(header((copy) => copy.writeUInt32LE(9, 0x14))),
).toMatchObject({ kind: "truncated", field: "resource_table" });
expect(
failureOf(header((copy) => copy.writeUInt32LE(1, 0x1c))),
).toMatchObject({ kind: "malformed", field: "resource_section_bytes" });
expect(
failureOf(
header((copy) =>
copy.writeUInt32LE(MQL_PROGRAM_MAX_RESOURCES + 1, 0x14),
),
),
).toMatchObject({
kind: "limit",
limit: {
name: MQL_PROGRAM_RESOURCES_LIMIT,
maximum: MQL_PROGRAM_MAX_RESOURCES,
required: MQL_PROGRAM_MAX_RESOURCES + 1,
},
});
});
it("reports a stray table offset without resources as a limitation", () => {
const bytes = mqlProgram();
bytes.writeUInt32LE(0x400, 0x18);
const { metadata, limitations } = layoutOf(bytes);
expect(metadata.resource_section).toBeNull();
expect(metadata.body.length).toBe(bytes.length - MQL_PROGRAM_HEADER_BYTES);
expect(limitations).toEqual([
expect.stringContaining("declares no resources"),
]);
});
});