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
This commit is contained in:
morluto authored and GitHub committed 2026-12-03 19:16:36 -05:00
1 parent a59694d492
commit a37994b3e8
29 files changed
+1422 -7

No files matched your search

@@ -1219,6 +1219,17 @@ checked. LZFSE (`bvx2`, `bvx1`, `bvxn`, `bvx-`) and `complzss` payloads stay com
such as `BNCN` are listed and their values stay redacted. See
[Image4 containers](https://github.com/morluto/rea/blob/main/docs/guides/apple/image4-containers.md).
MetaTrader compiled programs (`.ex4` magic `EX-`, `.ex5` magic `EX5`) use
`inspect_artifact` and `extract_artifact` (`mql-program`). Root metadata
reports `container`, `program_type`, `build`, the `copyright`, `link` and
`version` property slots, the opaque `body` range and the resource section;
unknown header values stay raw. `body.stored` and `resources/NNNN.stored` are
stored bytes: nothing is decrypted, decompressed or decompiled, and
`#property description` and other source facts are not readable. When asked to
recover MQL source, report these header facts and say the body is not decoded.
See
[MetaTrader compiled programs](https://github.com/morluto/rea/blob/main/docs/guides/artifacts/mql-programs.md).
MCUboot firmware images (`0x96f3b83d` at offset 0; legacy `0x96f3b83c` v1 is
refused) use `inspect_artifact` and `extract_artifact` (`mcuboot`). Root
metadata records `load_address`, `header_size`, `protected_tlv_size`,
@@ -1219,6 +1219,17 @@ checked. LZFSE (`bvx2`, `bvx1`, `bvxn`, `bvx-`) and `complzss` payloads stay com
such as `BNCN` are listed and their values stay redacted. See
[Image4 containers](https://github.com/morluto/rea/blob/main/docs/guides/apple/image4-containers.md).
MetaTrader compiled programs (`.ex4` magic `EX-`, `.ex5` magic `EX5`) use
`inspect_artifact` and `extract_artifact` (`mql-program`). Root metadata
reports `container`, `program_type`, `build`, the `copyright`, `link` and
`version` property slots, the opaque `body` range and the resource section;
unknown header values stay raw. `body.stored` and `resources/NNNN.stored` are
stored bytes: nothing is decrypted, decompressed or decompiled, and
`#property description` and other source facts are not readable. When asked to
recover MQL source, report these header facts and say the body is not decoded.
See
[MetaTrader compiled programs](https://github.com/morluto/rea/blob/main/docs/guides/artifacts/mql-programs.md).
MCUboot firmware images (`0x96f3b83d` at offset 0; legacy `0x96f3b83c` v1 is
refused) use `inspect_artifact` and `extract_artifact` (`mcuboot`). Root
metadata records `load_address`, `header_size`, `protected_tlv_size`,
+5
View File
@@ -479,6 +479,11 @@ export const documentationSections = [
source: "guides/artifacts/ar-archives.md",
route: "/ar-archives",
},
{
text: "MetaTrader compiled programs (EX4 and EX5)",
source: "guides/artifacts/mql-programs.md",
route: "/mql-programs",
},
guideAtRoute("WeChat mini-program wxapkg archives", "/wxapkg"),
guideAtRoute("macOS flat installer packages", "/macos-pkg"),
{
+1
View File
@@ -160,6 +160,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages.
- [ISO 9660 disc images](guides/firmware/iso9660-images.md)
- [tar and gzip-compressed tar archives](tar-archives.md)
- [Unix ar archives](guides/artifacts/ar-archives.md)
- [MetaTrader compiled programs (EX4 and EX5)](guides/artifacts/mql-programs.md)
- [Nintendo Switch NSO and NRO executables](guides/firmware/switch-executables.md)
- [GPU asset headers: DDS, GLB, KTX and KTX2](gpu-asset-headers.md)
- [Media asset headers: Ogg Opus, RIFF/XMA2, Bink 2 and Vulkan pipeline cache](media-asset-headers.md)
+10
View File
@@ -574,6 +574,16 @@ rea extract-artifact ./kernelcache.im4p --json
See [Image4 containers](../guides/apple/image4-containers.md) for IM4P, IM4M
and IMG4 facts, keybag reporting, and what is not decrypted.
Inventory a MetaTrader 4 or 5 compiled program and extract its stored ranges:
```sh
rea inspect-artifact ./Expert.ex5 --json
rea extract-artifact ./Indicator.ex4 --json
```
See [MetaTrader compiled programs](../guides/artifacts/mql-programs.md) for
header facts, properties, resources and what is not decoded.
Inventory and extract an MCUboot (`0x96f3b83d`) firmware image:
```sh
+90
View File
@@ -0,0 +1,90 @@
# MetaTrader compiled programs (EX4 and EX5)
`inspect-artifact` and `extract-artifact` recognize a MetaTrader 4 compiled
MQL4 program (`.ex4`, magic `EX-`) and a MetaTrader 5 compiled MQL5 program
(`.ex5`, magic `EX5`), under any file name. Both share one header and resource
table layout and report format `mql-program`.
REA reads the plaintext header and resource table offline. It reports the
program type, the build value, the `copyright`, `link` and `version`
properties, and where the code body and embedded resources are stored. It
does not decrypt, decompress, disassemble or decompile the body or the
resources, and it does not run the program.
```sh
rea inspect-artifact ./Expert.ex5 --json
rea extract-artifact ./Indicator.ex4 --json
```
MetaQuotes does not publish this layout. REA's reading was established from 28
`.ex4` programs (build value 2421) and 170 `.ex5` programs (builds 3802, 3808
and 6275), with the matching `.mq4` and `.mq5` sources. Fields whose meaning is
not established are reported raw rather than named.
## Program facts
Root `format_metadata` has kind `mql-program`:
| Field | Meaning |
| ----------------------- | ----------------------------------------------------------------------------------------------------------- |
| `container` | `ex4` or `ex5`, from the magic |
| `program_type` | From the type byte at offset 3; see below. An unobserved code is `unknown` |
| `program_type_code` | The type byte as stored |
| `build` | The u16 at offset 0x06 |
| `properties` | `copyright`, `link` and `version` slots, each with its `offset`, `state` and `text` |
| `body` | `offset` and `length` of the opaque span from 0x2E8 to the resource table, or to the end of the file |
| `resource_count` | Declared resource records |
| `resource_section` | `offset` and `length` of the resource table and payloads, or null without resources |
| `unknown_header_fields` | Nonzero header values of unknown meaning, with their `offset`, `width` and `value`; omitted fields are zero |
Type codes 1, 2 and 4 are `script`, `expert` and `indicator` in both
containers. Code 3 is `library` in EX4; no EX5 library was examined, so code 3
in EX5 is `unknown`.
For EX5, `build` matched the build of the MetaTrader 5 terminal that compiled
the samples. For EX4 it was 2421 while the MetaTrader 4 terminal reported build
1476, so its meaning there is not established.
`copyright` and `link` are 256-byte UTF-16LE slots at 0xA8 and 0x1A8;
`version` is a 64-byte slot at 0x2A8. A slot's `state` is `declared`, `empty`
when the program did not declare it, or `malformed` when the slot is not
well-formed UTF-16LE; `text` is null unless the state is `declared`. The header
blocks at 0x20 to 0x2F and 0x78 to 0xA7 are opaque and are not reported.
`#property description`, inputs, function names and other source facts are not
in the readable header. Recovering them would require decrypting the body,
which REA does not do.
## Stored ranges
Inventory lists the body as `body.stored` and each resource payload as
`resources/NNNN.stored`, in table order. Each entry carries kind
`mql-program-entry` metadata:
| Field | Meaning |
| --------------- | ---------------------------------------------------------------------------------------- |
| `role` | `body` or `resource` |
| `table_index` | Position in the resource table; null for the body |
| `name` | Resource name as declared, such as `res\Close.bmp`; null for the body or when ill-formed |
| `resource_kind` | Record field 0x0C; 2 for every bitmap observed |
| `record_index` | Record field 0x10; its ordering is unknown |
| `unpacked_size` | Declared size before the stored encoding |
`compare-artifacts` compares each resource's `name`, `resource_kind`,
`record_index` and `unpacked_size`, which the resource table declares outside
the stored payload, so a changed declaration is reported even when the payload
bytes match. The body declares nothing beyond its bytes.
`extract-artifact` writes the stored bytes unchanged. A resource payload is not
the original file: its stored size is smaller than `unpacked_size` and its
encoding is unknown, so it is named `.stored` rather than after the resource.
## Failures and limitations
A file shorter than the 0x2E8-byte header, or a resource table that starts
inside the header, ends past the file, or whose declared section does not end
at the end of the file, is refused with its offset and field. A payload range
that ends past the file is omitted and reported as a limitation, and coverage
becomes `unknown`. A program declaring more than 65,536 resources is refused at
the fixed MQL program resource record allowance; see
[analysis settings, limits, and recovery](../../reference/limits-and-recovery.md).
+10 -2
View File
@@ -645,6 +645,13 @@ Image4 property allowance is 256 properties. The Image4 string allowance is
string counts as one element and is not loaded to measure it. See
[Image4 containers](../guides/apple/image4-containers.md).
MetaTrader EX4 and EX5 inventory refuses a program declaring more than 65,536
resources at the MQL program resource record allowance, before the resource
table is read.
Each record becomes an inventory row, and real programs embed tens. This
release has no runtime override. See
[MetaTrader compiled programs](../guides/artifacts/mql-programs.md).
## Typed refusals
A producer that refuses a request types the refusal instead of leaving
@@ -873,8 +880,9 @@ SEA, PCK, ISO 9660, Deno, wxapkg, tar, macOS flat `.pkg` (including
allowances, plus `Distribution`/`PackageInfo` metadata decoding and scaled
metadata record and XML-node allowances), Android sparse image and Android DTBO
readers (every DTBO row is charged, including rows that share one payload),
FIT readers (every image is charged, including images linked to one range by
`image-data`), NSO
MetaTrader EX4 and EX5 readers (every resource record is charged, including
records that share one payload), FIT readers (every image is charged, including
images linked to one range by `image-data`), NSO
segment decompression, bFLT gzip decompression (which is also capped at a
fixed 128 MiB in-memory inflation ceiling), and the zlib body of
[Flash SWF files](../guides/artifacts/swf-artifacts.md), including repeated
+2 -2
View File
@@ -2223,8 +2223,8 @@ when both are omitted, storage is not compared.
(`pyinstaller-entry`), Node SEA members (`node-sea-entry`),
UBI volumes (`ubi-volume`), ESP image segments (`esp-image-segment`), DfuSe elements (`dfuse-element`),
ESP flash partitions (`esp-flash-partition`), Nintendo DS ROM members
(`nds-entry`), FIT images (`fit-image`), SWF binary data (`swf-binary-data`), Unix ar members (`ar-entry`)
and tar members (`tar-entry`)<!-- END:compare-artifacts:compared-format-metadata-kinds -->;
(`nds-entry`), FIT images (`fit-image`), SWF binary data (`swf-binary-data`), Unix ar members (`ar-entry`),
MetaTrader program resources (`mql-program-entry`) and tar members (`tar-entry`)<!-- END:compare-artifacts:compared-format-metadata-kinds -->;
each format's guide names the compared fields. A changed declaration is a
metadata change, including when content is unavailable. A declaration that
only one side records, or that the other side records as another kind, is
+1
View File
@@ -20,6 +20,7 @@ The table lists what REA returns for each target and which tools or host it requ
| Media asset headers | Ogg Opus, RIFF/XMA2, Bink 2 and Vulkan pipeline-cache header facts and declared regions; payloads not decoded | Built-in static header parsing; [media asset headers](../media-asset-headers.md) |
| Nintendo DS ROMs | Cartridge header, ARM9/ARM7 load facts, overlay tables and FNT/FAT file ranges; nothing decrypted | Built-in static header and table parsing; [Nintendo DS ROMs](../guides/firmware/nds-roms.md) |
| Image4 containers | IM4P type, compression and keybag presence; IM4M properties and digests; stored payload bytes | Built-in static DER parsing; nothing decrypted; [Image4 containers](../guides/apple/image4-containers.md) |
| MetaTrader programs | EX4/EX5 program type, build, copyright/link/version properties, resource table; body and resources as stored | Built-in static header parsing; nothing decrypted; [EX4 and EX5 programs](../guides/artifacts/mql-programs.md) |
| Nintendo 64 ROMs | Cartridge header, CIC/IPL3 variant, CRC pair and big-endian program.z64; nothing executed | Built-in static header parsing; [Nintendo 64 ROMs](../guides/firmware/n64-roms.md) |
| Sega Mega Drive ROMs | Vector table, header fields, declared and computed checksum, ROM and RAM ranges; SMD dumps de-interleaved | Built-in static header parsing; [Sega Mega Drive ROMs](../guides/firmware/mega-drive-roms.md) |
| Rust binaries | Embedded cargo-auditable crate names, versions, sources and dependency edges | Built-in static ELF/PE/thin or universal Mach-O/WebAssembly module inspection; [Rust binaries](../rust-binaries.md) |
+3
View File
@@ -167,6 +167,9 @@ const PATH_SCOPES = {
"src/artifacts/Image4ArtifactReader*.ts",
"src/domain/apple/image4*.ts",
"docs/guides/apple/image4-containers.md",
"src/artifacts/MqlProgramArtifactReader*.ts",
"src/domain/mqlProgram*.ts",
"docs/guides/artifacts/mql-programs.md",
"src/artifacts/MegaDriveRomArtifactReader*.ts",
"src/domain/megaDriveRom*.ts",
"src/artifacts/N64RomArtifactReader*.ts",
@@ -133,6 +133,12 @@
"reason": "Bounds one IA5, UTF8 or PrintableString retained as text."
}
},
"src/artifacts/MqlProgramArtifactReader.ts": {
"\"The MQL program resource record allowance\"": {
"class": "representation",
"reason": "Bounds retained resource inventory rows before the 156-byte-per-record table is read. Real programs embed tens of resources."
}
},
"src/artifacts/MegaDriveRomArtifactReader.ts": {
"\"The Mega Drive ROM byte ceiling\"": {
"class": "format",
@@ -147,6 +147,7 @@ const TARGETS: TargetFixtures = {
iso9660: { ...archive, format: "iso9660" },
"qualcomm-mbn": { ...archive, format: "qualcomm-mbn" },
"apple-img4": { ...archive, format: "apple-img4" },
"mql-program": { ...archive, format: "mql-program" },
"android-ota-payload": { ...archive, format: "android-ota-payload" },
"android-vbmeta": { ...archive, format: "android-vbmeta" },
"android-sparse-image": { ...archive, format: "android-sparse-image" },
@@ -0,0 +1,133 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { extractArtifact } from "./extraction/ArtifactExtraction.js";
import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js";
import { mqlProgram } from "../domain/mqlProgram.fixture.js";
import {
createTestTempDirectory,
createTestTempFile,
} from "../../tests/fixtures/temporaryDirectory.js";
import { scanCanonicalArtifactInventory } from "../../tests/fixtures/artifactInventory.js";
import { collectEntries } from "../../tests/fixtures/artifactEntries.js";
import { MqlProgramArtifactReader } from "./MqlProgramArtifactReader.js";
import { MQL_PROGRAM_RESOURCE_RECORD_BYTES } from "../domain/mqlProgram.js";
it("inventories an EX5 program and extracts its stored ranges unchanged", async () => {
const body = Buffer.from("opaque-code-body");
const payload = Buffer.from("stored-bitmap");
const path = await createTestTempFile(
"rea-ex5-",
"Expert.ex5",
mqlProgram({ body, resources: [{ name: "res\\Close.bmp", payload }] }),
);
const snapshot = await scanCanonicalArtifactInventory(path);
expect(snapshot.manifest.root_format).toBe("mql-program");
expect(snapshot.coverage).toMatchObject({ status: "complete" });
expect(
snapshot.occurrences.find((row) => row.logical_path === ".")
?.format_metadata,
).toMatchObject({
kind: "mql-program",
program_type: "expert",
build: 6275,
resource_count: 1,
});
expect(
snapshot.occurrences.find(
(row) => row.logical_path === "resources/0000.stored",
),
).toMatchObject({
format_metadata: {
kind: "mql-program-entry",
role: "resource",
name: "res\\Close.bmp",
},
});
const directory = await createTestTempDirectory("rea-ex5-extract-");
const resourceScope = new ArtifactResourceScope();
try {
const extracted = await extractArtifact({
inputPath: path,
inputFormat: "mql-program",
outputRoot: join(directory, "out"),
environment: process.env,
integrityPolicy: "fail",
resourceScope,
});
const stored = (path: string) =>
readFile(join(extracted.output_root, path));
expect((await stored("body.stored")).equals(body)).toBe(true);
expect((await stored("resources/0000.stored")).equals(payload)).toBe(true);
} finally {
await resourceScope.close();
}
});
it("inventories an EX4 library with its container and program type", async () => {
const path = await createTestTempFile(
"rea-ex4-",
"stdlib.ex4",
mqlProgram({ container: "ex4", programType: 3 }),
);
const snapshot = await scanCanonicalArtifactInventory(path);
expect(snapshot.manifest.root_format).toBe("mql-program");
expect(
snapshot.occurrences.find((row) => row.logical_path === ".")
?.format_metadata,
).toMatchObject({
kind: "mql-program",
container: "ex4",
program_type: "library",
body: { offset: 0x2e8 },
});
});
it("refuses a truncated header with the format and extent", async () => {
const path = await createTestTempFile(
"rea-ex5-",
"Short.ex5",
mqlProgram().subarray(0, 0x80),
);
await expect(scanCanonicalArtifactInventory(path)).rejects.toMatchObject({
reason: "truncated",
});
});
it("charges every resource record that shares one payload against expanded_bytes", async () => {
// Three records name the first 16-byte payload; with the 17-byte body the
// entries declare 65 readable bytes although the file stores fewer.
const bytes = mqlProgram({
resources: ["a", "b", "c"].map((name) => ({
name,
payload: Buffer.alloc(16, name),
})),
});
const table = bytes.readUInt32LE(0x18);
for (const record of [1, 2])
bytes.writeUInt32LE(0, table + record * MQL_PROGRAM_RESOURCE_RECORD_BYTES);
const path = await createTestTempFile("rea-ex5-", "Shared.ex5", bytes);
const admitted = new MqlProgramArtifactReader(path, undefined, 65);
try {
expect(await collectEntries(admitted)).toHaveLength(4);
} finally {
await admitted.close();
}
const refused = new MqlProgramArtifactReader(path, undefined, 64);
try {
await expect(collectEntries(refused)).rejects.toMatchObject({
reason: "limit",
readerLimit: {
parameter: "artifact_limits.expanded_bytes",
effective_value: 64,
required_value: 65,
},
});
} finally {
await refused.close();
}
});
+141
View File
@@ -0,0 +1,141 @@
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,
};
}
}
+12
View File
@@ -51,6 +51,7 @@ import { N64RomArtifactReader } from "./N64RomArtifactReader.js";
import { NdsRomArtifactReader } from "./NdsRomArtifactReader.js";
import { Iso9660ArtifactReader } from "./Iso9660ArtifactReader.js";
import { Image4ArtifactReader } from "./Image4ArtifactReader.js";
import { MqlProgramArtifactReader } from "./MqlProgramArtifactReader.js";
import { QualcommMbnArtifactReader } from "./QualcommMbnArtifactReader.js";
import { HexRecordArtifactReader } from "./HexRecordArtifactReader.js";
import { MachOSliceArtifactReader } from "./MachOSliceArtifactReader.js";
@@ -749,6 +750,17 @@ const NON_ZIP_FORMATS = {
createReader: (path, options) =>
new Image4ArtifactReader(path, sourceOf(options)),
}),
"mql-program": container("mql-program", {
...EXTRACTABLE_ROLE_CONTAINER,
readerLimitation:
"MetaTrader EX4 and EX5 inventory reports the container, program type, build value, the copyright, link and version properties, and the resource table. The code body and resource payloads are listed as stored byte ranges; REA does not decrypt, decompress, disassemble or decompile them. #property description and other source facts are not in the readable header.",
createReader: (path, options) =>
new MqlProgramArtifactReader(
path,
sourceOf(options),
options.readerLimits?.expanded_bytes,
),
}),
mcuboot: container("mcuboot", {
roleContainer: true,
retainClassifiedSource: true,
@@ -419,6 +419,7 @@ export const projectArtifactInventoryView = (
inventory.manifest.root_format === "n64-rom" ||
inventory.manifest.root_format === "qualcomm-mbn" ||
inventory.manifest.root_format === "apple-img4" ||
inventory.manifest.root_format === "mql-program" ||
inventory.manifest.root_format === "android-ota-payload" ||
inventory.manifest.root_format === "android-vbmeta" ||
inventory.manifest.root_format === "android-dtbo" ||
+70
View File
@@ -636,6 +636,76 @@ const recordObservation = (
return commit(inventory);
};
it("compares MetaTrader resource declarations with identical payload bytes", () => {
const resource = {
kind: "mql-program-entry",
role: "resource",
table_index: 0,
name: "res\\Close.bmp",
resource_kind: 2,
record_index: 0,
unpacked_size: 1080,
} as const satisfies FormatMetadata;
const content = { content: "1" };
const left = recordObservation(resource, content);
for (const changed of [
{ name: "res\\Open.bmp" },
{ resource_kind: 3 },
{ record_index: 1 },
{ unpacked_size: 2048 },
])
expect(
compareArtifacts(
left,
recordObservation({ ...resource, ...changed }, content),
),
JSON.stringify(changed),
).toMatchObject({
status: "changed",
changes: [{ classification: "changed", dimensions: ["metadata"] }],
});
// The table position is layout, not a declaration.
expect(
compareArtifacts(
left,
recordObservation({ ...resource, table_index: 5 }, content),
),
).toMatchObject({ status: "unchanged" });
});
it("keeps an unreadable MetaTrader resource name unknown", () => {
const resource = {
kind: "mql-program-entry",
role: "resource",
table_index: 0,
name: "res\\Close.bmp",
resource_kind: 2,
record_index: 0,
unpacked_size: 1080,
} as const satisfies FormatMetadata;
const content = { content: "1" };
const result = compareArtifacts(
recordObservation({ ...resource, name: null }, content),
recordObservation(resource, content),
);
expect(result).toMatchObject({
status: "unknown",
changes: [{ classification: "unknown", dimensions: ["availability"] }],
});
// Facts that remain readable still compare.
expect(
compareArtifacts(
recordObservation({ ...resource, name: null }, content),
recordObservation({ ...resource, resource_kind: 3 }, content),
).changes,
).toEqual(
expect.arrayContaining([
expect.objectContaining({ classification: "changed" }),
]),
);
});
it("compares NDS CPU entry addresses with identical member content", () => {
const arm9 = {
kind: "nds-entry",
+22
View File
@@ -95,6 +95,10 @@ import {
swfBinaryDataMetadataSchema,
swfMetadataSchema,
} from "./formatMetadata/swfMetadata.js";
import {
mqlProgramEntryMetadataSchema,
mqlProgramMetadataSchema,
} from "./formatMetadata/mqlProgramMetadata.js";
import { ndsEntryMetadataSchema, ndsMetadataSchema } from "./ndsRom.js";
export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [
@@ -153,6 +157,8 @@ export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [
swfBinaryDataMetadataSchema,
image4EntryMetadataSchema,
image4MetadataSchema,
mqlProgramMetadataSchema,
mqlProgramEntryMetadataSchema,
mcubootMetadataSchema,
mcubootEntryMetadataSchema,
qualcommMbnMetadataSchema,
@@ -472,6 +478,22 @@ const declarationsByKind: {
"Its header and hash-segment facts come from the image's own bytes, which content comparison covers. Signatures are located, not verified.",
"apple-img4":
"Its fields come from the container's own DER, which content comparison covers. Keybag values are not recorded.",
"mql-program":
"Its fields come from the program's own header and resource table, which content comparison covers.",
/**
* A resource's record fields live in the resource table, outside the stored
* payload that content comparison hashes. Role and table index are layout;
* the body declares nothing. A resource whose name is not well-formed UTF-16LE
* has no readable name, which is unknown rather than a declared value.
*/
"mql-program-entry": {
unreadable: ({ role, name }) =>
role === "resource" && name === null ? ["name"] : [],
declaration: ({ role, name, resource_kind, record_index, unpacked_size }) =>
role === "body"
? undefined
: { name, resource_kind, record_index, unpacked_size },
},
"apple-img4-entry":
"Role, encryption and compression restate the entry path and the root facts; decoded is always false.",
/**
@@ -1,6 +1,7 @@
import { expect, it } from "vitest";
import { im4p } from "./apple/image4.fixture.js";
import { mqlProgram } from "./mqlProgram.fixture.js";
import {
ESP32C3_APP_SEGMENTS,
@@ -9,6 +10,7 @@ import {
} from "../../tests/fixtures/espImage.js";
import { androidSuperFixture } from "../../tests/fixtures/androidSuperImage.js";
import { buildFv } from "../../tests/fixtures/uefiImage.js";
import { buildGodotPck } from "../../tests/fixtures/godotPck.js";
import { DEB_AR_HEADER_BYTES, DEB_AR_MAGIC } from "./deb/debPackage.js";
import {
recognizeArtifactFormat,
@@ -534,6 +536,49 @@ it("recognizes an Image4 IM4P container", () => {
).toMatchObject({ state: "recognized", format: "apple-img4" });
});
it.each(["ex4", "ex5"] as const)(
"recognizes a MetaTrader %s program",
(container) => {
expect(recognize(mqlProgram({ container }))).toMatchObject({
state: "recognized",
format: "mql-program",
});
},
);
it("keeps a Godot pack whose content holds ustar at 257 without a valid tar header", () => {
const pack = buildGodotPck(2, [
{ path: "a".repeat(153) + "ustar", data: Buffer.alloc(1024) },
]);
expect(pack.subarray(257, 263).toString("latin1")).toBe("ustar\0");
expect(recognize(pack)).toMatchObject({
state: "recognized",
format: "godot-pck",
});
});
it.each(["EX-report.txt", "EX5notes.txt", "GDPC.txt", "UnityFS"])(
"recognizes a tar whose first member name %s spells another format's magic",
(name) => {
const block = Buffer.alloc(512);
block.write(name, 0, "latin1");
block.write("0000644\0", 100, "latin1");
block.write("0000000\0", 108, "latin1");
block.write("0000000\0", 116, "latin1");
block.write("00000000000\0", 124, "latin1");
block.write("00000000000\0", 136, "latin1");
block.write("0", 156, "latin1");
block.write("ustar\0" + "00", 257, "latin1");
block.fill(0x20, 148, 156);
let sum = 0;
for (const byte of block) sum += byte;
block.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, "latin1");
expect(recognize(Buffer.concat([block, Buffer.alloc(1024)]))).toMatchObject(
{ state: "recognized", format: "tar" },
);
},
);
it("recognizes the descriptor signature at sector 16 or asks for it", () => {
const { bytes } = buildIso9660Image();
expect(
+12 -3
View File
@@ -32,6 +32,7 @@ import { claimsExecutableHeader } from "./binaryTarget.js";
import { hasQualcommMbnHeader } from "./qualcommMbnImage.js";
import { hasUImageMagic } from "./uimageFormat.js";
import { hasBfltMagic } from "./bfltExecutable.js";
import { hasMqlProgramMagic } from "./mqlProgram.js";
import { hasNroMagic, hasNsoMagic } from "./switchExecutable.js";
import { hasUnityFsHeader } from "./unityfsFormat.js";
import { hasMftFileRecordHeader } from "./windows/ntfsMft.js";
@@ -114,6 +115,7 @@ export type RecognizedArtifactFormat = Extract<
| "mcuboot"
| "qualcomm-mbn"
| "apple-img4"
| "mql-program"
| "ntfs-mft"
| "systemd-journal"
| "auditd-log"
@@ -251,6 +253,13 @@ export const ARTIFACT_FORMAT_RECOGNIZERS: readonly ArtifactFormatRecognizer[] =
},
whenClaimed("n64-rom", n64RomRecognition),
when("zip", hasZipSignature),
// A valid ustar or GNU header, or a gzip member whose first block is one.
// Its magic and checksum outrank the printable magics below, which a tar's
// first member name can spell, such as `GDPC`, `UnityFS` or `EX-`.
({ prefix }) =>
recognizeTarPrefix(prefix) === undefined
? undefined
: { state: "recognized", format: "tar" },
when("godot-pck", hasGodotPckHeader),
when("unityfs", hasUnityFsHeader),
when(
@@ -258,10 +267,10 @@ export const ARTIFACT_FORMAT_RECOGNIZERS: readonly ArtifactFormatRecognizer[] =
(prefix) => hasWxapkgEncryptedMagic(prefix) || hasWxapkgHeader(prefix),
),
when("apple-img4", hasImage4Prefix),
// A ustar or GNU header, or a gzip member whose first block is one.
when("mql-program", hasMqlProgramMagic),
// An invalid tar header is refused only after those magics: their own
// content can hold `ustar` at 257 without a valid tar checksum.
({ prefix }) => {
if (recognizeTarPrefix(prefix) !== undefined)
return { state: "recognized", format: "tar" };
const reason = tarHeaderRefusal(prefix);
return reason === undefined
? undefined
+2
View File
@@ -131,6 +131,7 @@ export const ARTIFACT_FORMAT_IDS = [
"mcuboot",
"qualcomm-mbn",
"apple-img4",
"mql-program",
"ntfs-mft",
"systemd-journal",
"auditd-log",
@@ -193,6 +194,7 @@ const artifactContentFormatSchema = artifactFormatSchema.extract([
"mcuboot",
"qualcomm-mbn",
"apple-img4",
"mql-program",
"ntfs-mft",
"systemd-journal",
"auditd-log",
@@ -0,0 +1,66 @@
import { z } from "zod";
import { byteRange, offset, uint16, uint32, uint8 } from "./primitives.js";
/**
* One fixed UTF-16LE `#property` slot. `empty` means the program did not
* declare it; `malformed` means the slot is not well-formed UTF-16.
*/
const mqlPropertySlotSchema = z.strictObject({
offset,
state: z.enum(["declared", "empty", "malformed"]),
text: z.string().max(128).nullable(),
});
/** A header field whose meaning is not established, preserved as stored. */
const mqlUnknownHeaderFieldSchema = z.strictObject({
offset,
width: z.union([z.literal(2), z.literal(4)]),
value: uint32,
});
/**
* MetaTrader compiled program (`.ex4` or `.ex5`) header facts. The body after
* the header and the resource payloads are opaque and are never decoded.
*/
export const mqlProgramMetadataSchema = z.strictObject({
kind: z.literal("mql-program"),
/** `ex4` (magic `EX-`, MetaTrader 4) or `ex5` (magic `EX5`, MetaTrader 5). */
container: z.enum(["ex4", "ex5"]),
/** Byte 3, named only where observed; anything else is `unknown`. */
program_type: z.enum(["script", "expert", "library", "indicator", "unknown"]),
program_type_code: uint8,
/** The u16 at 0x06; for EX5 it matched the MetaTrader 5 terminal build. */
build: uint16,
properties: z.strictObject({
copyright: mqlPropertySlotSchema,
link: mqlPropertySlotSchema,
version: mqlPropertySlotSchema,
}),
/** The opaque span between the header and the resource table or end of file. */
body: byteRange,
resource_count: uint32,
/** The resource table and payloads; null when the program has no resources. */
resource_section: byteRange.nullable(),
/** Nonzero header fields of unknown meaning; omitted fields are zero. */
unknown_header_fields: z.array(mqlUnknownHeaderFieldSchema),
});
export type MqlProgramMetadata = z.infer<typeof mqlProgramMetadataSchema>;
/** One stored region: the opaque code body or one resource payload. */
export const mqlProgramEntryMetadataSchema = z.strictObject({
kind: z.literal("mql-program-entry"),
role: z.enum(["body", "resource"]),
/** Resource table position; null for the body. */
table_index: uint32.nullable(),
/** The resource name as declared, such as `res\\Close.bmp`; null for the body. */
name: z.string().max(64).nullable(),
/** Record field 0x0C; 2 for every bitmap observed. Null for the body. */
resource_kind: uint32.nullable(),
/** Record field 0x10; its ordering is unknown. Null for the body. */
record_index: uint32.nullable(),
/** Declared size before the unknown stored encoding. Null for the body. */
unpacked_size: uint32.nullable(),
});
export type MqlProgramEntryMetadata = z.infer<
typeof mqlProgramEntryMetadataSchema
>;
+83
View File
@@ -0,0 +1,83 @@
/**
* Synthetic MetaTrader `.ex4` and `.ex5` programs. Not compiled by MetaEditor: the header
* follows the layout `mqlProgram.ts` documents, and the body and payloads are
* placeholder bytes.
*/
import {
MQL_PROGRAM_HEADER_BYTES,
MQL_PROGRAM_RESOURCE_RECORD_BYTES,
} from "./mqlProgram.js";
export interface MqlFixtureResource {
readonly name: string;
readonly payload: Buffer;
readonly unpackedSize?: number;
readonly kind?: number;
readonly recordIndex?: number;
}
export interface MqlFixtureOptions {
readonly container?: "ex4" | "ex5";
readonly programType?: number;
readonly build?: number;
readonly copyright?: string;
readonly link?: string;
readonly version?: string;
readonly body?: Buffer;
readonly resources?: readonly MqlFixtureResource[];
}
const align16 = (length: number): number => (length + 15) & ~15;
const writeSlot = (header: Buffer, offset: number, text: string): void => {
header.write(text, offset, "utf16le");
};
/** An EX4 or EX5 program with the given header facts, body and resources. */
export const mqlProgram = (options: MqlFixtureOptions = {}): Buffer => {
const ex4 = options.container === "ex4";
const header = Buffer.alloc(MQL_PROGRAM_HEADER_BYTES);
header.write(ex4 ? "EX-" : "EX5", 0, "latin1");
header.writeUInt8(options.programType ?? 2, 3);
header.writeUInt16LE(ex4 ? 112 : 113, 0x04);
header.writeUInt16LE(options.build ?? (ex4 ? 2421 : 6275), 0x06);
header.writeUInt32LE(0x400, 0x08);
header.writeUInt16LE(1, 0x0e);
header.writeUInt32LE(1252, 0x10);
writeSlot(header, 0xa8, options.copyright ?? "Copyright 2026, Example");
writeSlot(header, 0x1a8, options.link ?? "https://example.test");
writeSlot(header, 0x2a8, options.version ?? "1.00");
const body = options.body ?? Buffer.from("opaque-body-bytes");
const resources = options.resources ?? [];
if (resources.length === 0) return Buffer.concat([header, body]);
const table = Buffer.alloc(
resources.length * MQL_PROGRAM_RESOURCE_RECORD_BYTES,
);
const payloads: Buffer[] = [];
let payloadOffset = 0;
resources.forEach((resource, index) => {
const record = index * MQL_PROGRAM_RESOURCE_RECORD_BYTES;
table.writeUInt32LE(payloadOffset, record);
table.writeUInt32LE(
resource.unpackedSize ?? resource.payload.length * 2,
record + 0x04,
);
table.writeUInt32LE(resource.payload.length, record + 0x08);
table.writeUInt32LE(resource.kind ?? 2, record + 0x0c);
table.writeUInt32LE(
resource.recordIndex ?? resources.length - 1 - index,
record + 0x10,
);
table.write(resource.name, record + 0x1c, "utf16le");
const padded = Buffer.alloc(align16(resource.payload.length));
resource.payload.copy(padded);
payloads.push(padded);
payloadOffset += padded.length;
});
const tableOffset = header.length + body.length;
header.writeUInt32LE(resources.length, 0x14);
header.writeUInt32LE(tableOffset, 0x18);
header.writeUInt32LE(table.length + payloadOffset, 0x1c);
return Buffer.concat([header, body, table, ...payloads]);
};
+275
View File
@@ -0,0 +1,275 @@
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"),
]);
});
});
+368
View File
@@ -0,0 +1,368 @@
import type {
MqlProgramEntryMetadata,
MqlProgramMetadata,
} from "./formatMetadata/mqlProgramMetadata.js";
import { BinaryReader } from "./binaryContainer.js";
import {
malformedInput,
ParseFailureError,
truncatedInput,
unrecognizedInput,
} from "./parseFailure.js";
/**
* MetaTrader compiled MQL programs: MetaTrader 4 `.ex4` (magic `EX-`) and
* MetaTrader 5 `.ex5` (magic `EX5`). Both share one header and resource table
* layout. Only the plaintext header and resource table are read. The layout
* was established from 28 `.ex4` programs (build value 2421) and 170 `.ex5`
* programs (builds 3802, 3808 and 6275) with matching sources; MetaQuotes
* does not publish it. All integers are little-endian.
*
* - `0x00` the three-byte magic, then the program type byte.
* - `0x06` u16 build value.
* - `0x14` u32 resource count, `0x18` u32 resource table offset, `0x1C` u32
* resource section size (table plus payloads, ending at end of file).
* - `0xA8` and `0x1A8`: 256-byte UTF-16LE `copyright` and `link` slots;
* `0x2A8`: 64-byte UTF-16LE `version` slot.
* - `0x2E8` onward: an opaque body. `0x20..0x2F` and `0x78..0xA7` are opaque
* too and are not reported.
*/
export const MQL_PROGRAM_FORMAT = "mql-program";
export const MQL_PROGRAM_HEADER_BYTES = 0x2e8;
export const MQL_PROGRAM_RESOURCE_RECORD_BYTES = 0x9c;
/**
* Resource records admitted from one program. Real programs embed tens; the
* cap bounds retained inventory rows before the table is read.
*/
export const MQL_PROGRAM_MAX_RESOURCES = 65_536;
export const MQL_PROGRAM_RESOURCES_LIMIT = "mql_program_resources";
type Container = MqlProgramMetadata["container"];
type ProgramType = Exclude<MqlProgramMetadata["program_type"], "unknown">;
const MAGICS: Readonly<Record<Container, readonly number[]>> = {
ex4: [0x45, 0x58, 0x2d],
ex5: [0x45, 0x58, 0x35],
};
/** Type codes observed in each container; code 3 has only been seen in EX4. */
const PROGRAM_TYPES: Readonly<
Record<Container, Readonly<Record<number, ProgramType>>>
> = {
ex4: { 1: "script", 2: "expert", 3: "library", 4: "indicator" },
ex5: { 1: "script", 2: "expert", 4: "indicator" },
};
const PROPERTY_SLOTS = {
copyright: { offset: 0xa8, bytes: 0x100 },
link: { offset: 0x1a8, bytes: 0x100 },
version: { offset: 0x2a8, bytes: 0x40 },
} as const;
const RECORD_NAME_OFFSET = 0x1c;
const RECORD_NAME_BYTES =
MQL_PROGRAM_RESOURCE_RECORD_BYTES - RECORD_NAME_OFFSET;
/**
* Header fields outside the established ones and the opaque blocks. Only
* nonzero values are reported.
*/
const UNKNOWN_FIELDS: readonly (readonly [offset: number, width: 2 | 4])[] = [
[0x04, 2],
[0x08, 4],
[0x0c, 2],
[0x0e, 2],
[0x10, 4],
...Array.from(
{ length: (0x78 - 0x30) / 4 },
(_, index) => [0x30 + index * 4, 4] as const,
),
];
/** The container whose magic the leading bytes carry, if any. */
export const mqlProgramContainer = (
prefix: Uint8Array,
): Container | undefined =>
(Object.keys(MAGICS) as Container[]).find((container) =>
MAGICS[container].every((byte, index) => prefix[index] === byte),
);
/** Whether the leading bytes carry the `EX-` or `EX5` magic. */
export const hasMqlProgramMagic = (prefix: Uint8Array): boolean =>
mqlProgramContainer(prefix) !== undefined;
export interface MqlProgramHeader {
readonly container: Container;
readonly programTypeCode: number;
readonly build: number;
readonly properties: MqlProgramMetadata["properties"];
readonly resourceCount: number;
readonly resourceTableOffset: number;
readonly resourceSectionBytes: number;
readonly unknownFields: MqlProgramMetadata["unknown_header_fields"];
}
/** Little-endian, range-checked reads over caller-sized bytes. */
const reader = (bytes: Uint8Array): BinaryReader =>
new BinaryReader(
Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),
true,
MQL_PROGRAM_FORMAT,
);
/** Refuses lone surrogates instead of substituting U+FFFD. */
// Slot text is declared content, so a leading U+FEFF is kept, not stripped.
const STRICT_UTF16LE = new TextDecoder("utf-16le", {
fatal: true,
ignoreBOM: true,
});
/** UTF-16LE text up to the first NUL unit; null when not well-formed. */
const utf16Text = (
bytes: Uint8Array,
): { readonly text: string | null; readonly empty: boolean } => {
const data = reader(bytes);
let units = 0;
while (units * 2 + 1 < bytes.length && data.u16(units * 2) !== 0) units += 1;
if (units === 0) return { text: "", empty: true };
try {
return {
text: STRICT_UTF16LE.decode(bytes.subarray(0, units * 2)),
empty: false,
};
} catch {
// A lone surrogate: the stored value is not text, so none is reported.
return { text: null, empty: false };
}
};
const propertySlot = (
header: Uint8Array,
{ offset, bytes }: { readonly offset: number; readonly bytes: number },
): MqlProgramMetadata["properties"]["copyright"] => {
const { text, empty } = utf16Text(header.subarray(offset, offset + bytes));
if (empty) return { offset, state: "empty", text: null };
return text === null
? { offset, state: "malformed", text: null }
: { offset, state: "declared", text };
};
/**
* Decode the fixed header from the file's first
* {@link MQL_PROGRAM_HEADER_BYTES}.
* @throws ParseFailureError when the bytes are not EX4 or EX5 or end early.
*/
export const parseMqlProgramHeader = (
bytes: Uint8Array,
fileSize: number,
): MqlProgramHeader => {
const container = mqlProgramContainer(bytes);
if (container === undefined)
throw unrecognizedInput(MQL_PROGRAM_FORMAT, "EX4 or EX5 magic is absent.", {
offset: 0,
field: "magic",
});
if (
fileSize < MQL_PROGRAM_HEADER_BYTES ||
bytes.length < MQL_PROGRAM_HEADER_BYTES
)
throw truncatedInput(
MQL_PROGRAM_FORMAT,
`${container.toUpperCase()} header needs ${String(MQL_PROGRAM_HEADER_BYTES)} bytes; the file has ${String(fileSize)}.`,
{
offset: 0,
field: "header",
extent: {
availableBytes: fileSize,
requiredBytes: MQL_PROGRAM_HEADER_BYTES,
},
},
);
const data = reader(bytes);
const unknownFields = UNKNOWN_FIELDS.flatMap(([offset, width]) => {
const value = width === 2 ? data.u16(offset) : data.u32(offset);
return value === 0 ? [] : [{ offset, width, value }];
});
return {
container,
programTypeCode: data.u8(3),
build: data.u16(0x06),
properties: {
copyright: propertySlot(bytes, PROPERTY_SLOTS.copyright),
link: propertySlot(bytes, PROPERTY_SLOTS.link),
version: propertySlot(bytes, PROPERTY_SLOTS.version),
},
resourceCount: data.u32(0x14),
resourceTableOffset: data.u32(0x18),
resourceSectionBytes: data.u32(0x1c),
unknownFields,
};
};
/**
* The resource table's file range, or undefined when the program declares no
* resources.
* @throws ParseFailureError when the declared table does not fit the file or
* exceeds {@link MQL_PROGRAM_MAX_RESOURCES}.
*/
export const mqlProgramResourceTableRange = (
header: MqlProgramHeader,
fileSize: number,
): { readonly offset: number; readonly length: number } | undefined => {
const { resourceCount: count, resourceTableOffset: offset } = header;
const label = header.container.toUpperCase();
if (count === 0) return undefined;
if (count > MQL_PROGRAM_MAX_RESOURCES)
throw new ParseFailureError({
kind: "limit",
format: MQL_PROGRAM_FORMAT,
detail: `${label} declares ${String(count)} resources, above the ${String(MQL_PROGRAM_MAX_RESOURCES)}-record allowance. This release has no runtime override.`,
offset: 0x14,
field: "resource_count",
limit: {
name: MQL_PROGRAM_RESOURCES_LIMIT,
maximum: MQL_PROGRAM_MAX_RESOURCES,
required: count,
},
});
const length = count * MQL_PROGRAM_RESOURCE_RECORD_BYTES;
if (offset < MQL_PROGRAM_HEADER_BYTES)
throw malformedInput(
MQL_PROGRAM_FORMAT,
`${label} resource table offset 0x${offset.toString(16)} is inside the ${String(MQL_PROGRAM_HEADER_BYTES)}-byte header.`,
{ offset: 0x18, field: "resource_table_offset" },
);
if (offset + length > fileSize)
throw truncatedInput(
MQL_PROGRAM_FORMAT,
`${label} resource table of ${String(count)} records at 0x${offset.toString(16)} ends past the ${String(fileSize)}-byte file.`,
{
offset,
field: "resource_table",
extent: { availableBytes: fileSize, requiredBytes: offset + length },
},
);
if (offset + header.resourceSectionBytes !== fileSize)
throw malformedInput(
MQL_PROGRAM_FORMAT,
`${label} resource section of ${String(header.resourceSectionBytes)} bytes at 0x${offset.toString(16)} does not end at the ${String(fileSize)}-byte file end.`,
{ offset: 0x1c, field: "resource_section_bytes" },
);
return { offset, length };
};
export interface MqlProgramRegion {
readonly path: string;
readonly offset: number;
readonly length: number;
readonly metadata: MqlProgramEntryMetadata;
}
export interface MqlProgramLayout {
readonly metadata: MqlProgramMetadata;
readonly regions: readonly MqlProgramRegion[];
readonly limitations: readonly string[];
}
const resourcePath = (index: number): string =>
`resources/${String(index).padStart(4, "0")}.stored`;
/**
* Describe the body and resource payloads as stored ranges. `table` holds the
* bytes {@link mqlProgramResourceTableRange} named, or is undefined without
* one.
*/
export const parseMqlProgramLayout = (
header: MqlProgramHeader,
table: Uint8Array | undefined,
fileSize: number,
): MqlProgramLayout => {
const label = header.container.toUpperCase();
const limitations: string[] = [];
const regions: MqlProgramRegion[] = [];
const tableOffset =
table === undefined ? undefined : header.resourceTableOffset;
if (
table === undefined &&
(header.resourceTableOffset !== 0 || header.resourceSectionBytes !== 0)
)
limitations.push(
`${label} declares no resources but a resource table offset of 0x${header.resourceTableOffset.toString(16)} and a section of ${String(header.resourceSectionBytes)} bytes; the body is reported to the end of the file.`,
);
const bodyEnd = tableOffset ?? fileSize;
const body = {
offset: MQL_PROGRAM_HEADER_BYTES,
length: bodyEnd - MQL_PROGRAM_HEADER_BYTES,
};
if (body.length > 0)
regions.push({
path: "body.stored",
...body,
metadata: {
kind: "mql-program-entry",
role: "body",
table_index: null,
name: null,
resource_kind: null,
record_index: null,
unpacked_size: null,
},
});
if (table !== undefined && tableOffset !== undefined) {
const data = reader(table);
const payloadStart = tableOffset + table.length;
const payloadBytes = fileSize - payloadStart;
for (let index = 0; index < header.resourceCount; index += 1) {
const record = index * MQL_PROGRAM_RESOURCE_RECORD_BYTES;
const payloadOffset = data.u32(record);
const unpackedSize = data.u32(record + 0x04);
const storedSize = data.u32(record + 0x08);
const { text: name } = utf16Text(
table.subarray(
record + RECORD_NAME_OFFSET,
record + RECORD_NAME_OFFSET + RECORD_NAME_BYTES,
),
);
if (name === null)
limitations.push(
`${label} resource record ${String(index)} name is not well-formed UTF-16LE.`,
);
if (payloadOffset + storedSize > payloadBytes) {
limitations.push(
`${label} resource record ${String(index)} payload of ${String(storedSize)} bytes at payload offset ${String(payloadOffset)} ends past the ${String(payloadBytes)}-byte payload area; it is omitted.`,
);
continue;
}
regions.push({
path: resourcePath(index),
offset: payloadStart + payloadOffset,
length: storedSize,
metadata: {
kind: "mql-program-entry",
role: "resource",
table_index: index,
name,
resource_kind: data.u32(record + 0x0c),
record_index: data.u32(record + 0x10),
unpacked_size: unpackedSize,
},
});
}
}
return {
metadata: {
kind: "mql-program",
container: header.container,
program_type:
PROGRAM_TYPES[header.container][header.programTypeCode] ?? "unknown",
program_type_code: header.programTypeCode,
build: header.build,
properties: header.properties,
body,
resource_count: header.resourceCount,
resource_section:
tableOffset === undefined
? null
: { offset: tableOffset, length: header.resourceSectionBytes },
unknown_header_fields: header.unknownFields,
},
regions,
limitations,
};
};
+1
View File
@@ -100,6 +100,7 @@ export const PE_OVERLAY_LEADING_FORMATS = [
"swf",
"qualcomm-mbn",
"apple-img4",
"mql-program",
"ntfs-mft",
"plist",
"tar",
+1
View File
@@ -48,6 +48,7 @@ export const BINARY_TARGET_FORMAT_KINDS = {
iso9660: "archive",
"qualcomm-mbn": "archive",
"apple-img4": "archive",
"mql-program": "archive",
dmg: "archive",
pkg: "archive",
"intel-hex": "archive",
+1
View File
@@ -309,6 +309,7 @@ export interface ArtifactReader {
| "mcuboot"
| "qualcomm-mbn"
| "apple-img4"
| "mql-program"
| "ntfs-mft"
| "systemd-journal"
| "auditd-log"
@@ -9,6 +9,7 @@ import { expect, it } from "vitest";
import { im4p } from "../../../../src/domain/apple/image4.fixture.js";
import { bfltFile } from "../../../../src/domain/bfltExecutable.fixture.js";
import { megaDriveRom } from "../../../../src/domain/megaDriveRom.fixture.js";
import { mqlProgram } from "../../../../src/domain/mqlProgram.fixture.js";
import { n64RomImage } from "../../../../src/domain/n64Rom.fixture.js";
import { windowsShortcutBytes } from "../../../fixtures/binaryDiagnostics/windowsShortcut.js";
import { createSqliteDatabaseFixture } from "../../../fixtures/sqlite/database.js";
@@ -239,6 +240,43 @@ it("inventories an Image4 IM4P payload", async () => {
).toBe(true);
});
it.each(["ex4", "ex5"] as const)(
"inventories a MetaTrader %s program's header and stored ranges",
async (container) => {
const directory = await createTestTempDirectory("rea-standalone-format-");
const path = await writeBytes(`Expert.${container}`, () =>
mqlProgram({
container,
resources: [{ name: "res\\Close.bmp", payload: Buffer.from("bitmap") }],
}),
)(directory);
const evidence = parseEvidence(
await runProviderAnalysis(path, "inspect_artifact", {}).then(
projectCliAnalysisResult,
),
);
const inspection = artifactInspectionResultSchema.parse(
evidence.normalized_result,
);
expect(inspection.subject.root_format).toBe("mql-program");
const inventory = artifactInventoryResultSchema.parse(
inspection.substeps[0]?.evidence.normalized_result,
);
expect(
inventory.occurrences.find((row) => row.logical_path === ".")
?.format_metadata,
).toMatchObject({
kind: "mql-program",
container,
program_type: "expert",
properties: { link: { state: "declared", text: "https://example.test" } },
});
expect(inventory.occurrences.map((row) => row.logical_path).sort()).toEqual(
[".", "body.stored", "resources/0000.stored"],
);
},
);
it("classifies a synthetic Mega Drive ROM", async () => {
const directory = await createTestTempDirectory("rea-standalone-format-");
const path = await writeBytes("game.bin", () => megaDriveRom())(directory);