diff --git a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md index 3bf9f3a069e..ad3f241ab83 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -1153,6 +1153,24 @@ under `artifact_limits.expanded_bytes`; revision 2 bodies are read as stored. Open `text.bin` as a raw binary with a chosen architecture. See [uClinux bFLT flat executables](https://github.com/morluto/rea/blob/main/docs/bflt-executables.md). +Game Boy and Game Boy Color ROMs (`game-boy-rom`) are detected from the boot +logo at `0x104` (at least its first 24 bytes), not the filename. Game Boy +Advance ROMs (`gba-rom`) are detected from an ARM branch at `0x00`, the fixed +value `0x96` at `0xB2`, and the boot logo or a matching complement check. +Both use the same inspection and extraction workflows. `root_format_metadata` +holds the header facts: for Game Boy the entry code, logo match, title, CGB +and SGB flags, mapper and features, declared ROM and RAM sizes, licensee +codes, version, and declared and computed header and global checksums; for +GBA the entry branch target, logo match, title, game and maker codes, fixed +value, unit and device type, version, complement check, and whether the +multiboot fields could apply. Members are `header.bin` and `program.bin`, +both stored ranges. A checksum, logo or size disagreement leaves coverage +`unknown`; nothing is executed or patched. A header cut short is refused as +truncated with the offset where the file ends. See +[Game Boy ROMs](https://github.com/morluto/rea/blob/main/docs/guides/firmware/game-boy-roms.md) +and +[Game Boy Advance ROMs](https://github.com/morluto/rea/blob/main/docs/guides/firmware/gba-roms.md). + Nintendo DS ROMs (`nds`) are detected from the header (logo CRC `0xCF56`, unit code, ARM9 offset, and a matching logo or header CRC), not the filename, and use the same inspection and extraction workflows. `root_format_metadata` diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md index 3bf9f3a069e..ad3f241ab83 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -1153,6 +1153,24 @@ under `artifact_limits.expanded_bytes`; revision 2 bodies are read as stored. Open `text.bin` as a raw binary with a chosen architecture. See [uClinux bFLT flat executables](https://github.com/morluto/rea/blob/main/docs/bflt-executables.md). +Game Boy and Game Boy Color ROMs (`game-boy-rom`) are detected from the boot +logo at `0x104` (at least its first 24 bytes), not the filename. Game Boy +Advance ROMs (`gba-rom`) are detected from an ARM branch at `0x00`, the fixed +value `0x96` at `0xB2`, and the boot logo or a matching complement check. +Both use the same inspection and extraction workflows. `root_format_metadata` +holds the header facts: for Game Boy the entry code, logo match, title, CGB +and SGB flags, mapper and features, declared ROM and RAM sizes, licensee +codes, version, and declared and computed header and global checksums; for +GBA the entry branch target, logo match, title, game and maker codes, fixed +value, unit and device type, version, complement check, and whether the +multiboot fields could apply. Members are `header.bin` and `program.bin`, +both stored ranges. A checksum, logo or size disagreement leaves coverage +`unknown`; nothing is executed or patched. A header cut short is refused as +truncated with the offset where the file ends. See +[Game Boy ROMs](https://github.com/morluto/rea/blob/main/docs/guides/firmware/game-boy-roms.md) +and +[Game Boy Advance ROMs](https://github.com/morluto/rea/blob/main/docs/guides/firmware/gba-roms.md). + Nintendo DS ROMs (`nds`) are detected from the header (logo CRC `0xCF56`, unit code, ARM9 offset, and a matching logo or header CRC), not the filename, and use the same inspection and extraction workflows. `root_format_metadata` diff --git a/docs/.vitepress/documentation.ts b/docs/.vitepress/documentation.ts index dac08000e3a..e175b91f0ba 100644 --- a/docs/.vitepress/documentation.ts +++ b/docs/.vitepress/documentation.ts @@ -454,6 +454,16 @@ export const documentationSections = [ guideAtRoute("Godot PCK archives", "/godot-pck"), guideAtRoute("UnityFS AssetBundle archives", "/unityfs"), guideAtRoute("iNES containers", "/ines-containers"), + { + text: "Game Boy ROMs", + source: "guides/firmware/game-boy-roms.md", + route: "/game-boy-roms", + }, + { + text: "Game Boy Advance ROMs", + source: "guides/firmware/gba-roms.md", + route: "/gba-roms", + }, { text: "Nintendo DS ROMs", source: "guides/firmware/nds-roms.md", diff --git a/docs/README.md b/docs/README.md index 29a34cde1cf..fc6abd82361 100644 --- a/docs/README.md +++ b/docs/README.md @@ -152,6 +152,8 @@ The [REA website](https://rea.tools/) has worked examples and product pages. - [Godot PCK archives](godot-pck.md) - [UnityFS AssetBundle archives](unityfs.md) - [iNES containers](ines-containers.md) +- [Game Boy ROMs](guides/firmware/game-boy-roms.md) +- [Game Boy Advance ROMs](guides/firmware/gba-roms.md) - [Nintendo DS ROMs](guides/firmware/nds-roms.md) - [Sega Mega Drive ROMs](guides/firmware/mega-drive-roms.md) - [Nintendo 64 ROMs](guides/firmware/n64-roms.md) diff --git a/docs/getting-started/cli.md b/docs/getting-started/cli.md index 099fa73bbad..82c9dc636b1 100644 --- a/docs/getting-started/cli.md +++ b/docs/getting-started/cli.md @@ -529,6 +529,17 @@ rea extract-artifact ./busybox.bflt --json See [uClinux bFLT flat executables](../bflt-executables.md) for header facts, segments, gzip and gzdata bodies, and the limitations kept beside the facts. +Inventory and extract a Game Boy, Game Boy Color or Game Boy Advance ROM: + +```sh +rea inspect-artifact ./game.gb --detail summary --json +rea extract-artifact ./game.gba --json +``` + +See [Game Boy ROMs](../guides/firmware/game-boy-roms.md) and +[Game Boy Advance ROMs](../guides/firmware/gba-roms.md) for the header facts, +checksums, logo match, and the limitations kept beside them. + Inventory and extract a Nintendo DS ROM's CPU binaries, overlays, and files: ```sh diff --git a/docs/guides/firmware/game-boy-roms.md b/docs/guides/firmware/game-boy-roms.md new file mode 100644 index 00000000000..0b3de4b3132 --- /dev/null +++ b/docs/guides/firmware/game-boy-roms.md @@ -0,0 +1,106 @@ +# Game Boy ROMs + +`inspect-artifact` and `extract-artifact` read a Game Boy or Game Boy Color +cartridge ROM (`.gb`, `.gbc`) offline. The file name does not matter. +Recognition reads the boot logo at `0x104`: at least its first 24 bytes, the +half every boot ROM compares, must match. REA compares SHA-256 digests and +does not carry the logo bytes. A file that has those logo bytes but ends +before the header does (`0x150`) is refused as truncated, and the refusal +names the offset where the file ends. + +Nothing is executed, decompressed or patched. A checksum, logo or size +disagreement is reported and left unchanged. + +## What the root reports + +Root `format_metadata` (`kind: "game-boy-rom"`) holds the header at +`0x100..0x150`: + +- `rom_bytes`: the file length. +- `entry_hex`: the four bytes at `0x100`, where the boot ROM hands over. + `entry_jump_target` is the address of a `JP a16` there, after an optional + `NOP`, or null. +- `nintendo_logo`: `match`, `top-half` or `mismatch`. `top-half` means the + first 24 bytes match and the rest do not. The Game Boy Color boot ROM + compares only the first half; the original Game Boy compares all 48 bytes. +- `title_raw_hex` (the 16 bytes at `0x134`) and `title`. When the CGB flag is + set and `0x13F..0x143` holds four uppercase letters or digits, those bytes + are `manufacturer_code` and the title stops before them. Otherwise the + title runs to `0x143` (CGB flag set) or `0x144`. `title` keeps printable + ASCII before the first NUL and shows other bytes as `?`. +- `cgb_flag` and `cgb`: `compatible` (`0x80`), `required` (`0xC0`), `none` + (bit 7 clear) or `other`. +- `sgb_flag` and `sgb_supported`. Super Game Boy functions need flag `0x03` + and old licensee code `0x33`. +- `cartridge_type`, `mapper` (`none`, `mbc1`, `mbc2`, `mmm01`, `mbc3`, + `mbc4`, `mbc5`, `mbc6`, `mbc7`, `pocket-camera`, `tama5`, `huc3`, `huc1`, + or null for an undocumented byte) and `features` (`ram`, `battery`, + `timer`, `rumble`, `sensor`). +- `rom_size_code` and `declared_rom_bytes` (32 KiB shifted by codes + `0x00..0x08`; codes `0x52`, `0x53` and `0x54` declare 72, 80 and 96 banks + of 16 KiB; otherwise null). +- `ram_size_code` and `declared_ram_bytes` (2 KiB for code `0x01`; null for + undocumented codes). MBC2 has built-in RAM that the header does not + declare. +- `destination_code` and `destination` (`japan`, `overseas` or null). +- `old_licensee_code` and `new_licensee_code` (two characters at `0x144`, + meaningful when the old code is `0x33`). REA does not map licensee codes to + publisher names. +- `version`. +- `header_checksum`: declared byte at `0x14D` and the value computed over + `0x134..0x14C`, with `status` `match` or `mismatch`. +- `global_checksum`: the big-endian word at `0x14E` and the 16-bit sum of + every other byte in the file, with `status` `match` or `mismatch`. The + boot ROM does not check this value. + +## Members + +| Path | Holds | +| ------------- | ------------------------------------ | +| `header.bin` | The 80-byte header at `0x100..0x150` | +| `program.bin` | The whole file, as stored | + +Each member's `format_metadata` (`kind: "game-boy-rom-entry"`) records +`role` (`header` or `program`). Both are stored ranges and are counted +separately toward `artifact_limits.expanded_bytes`. + +## Limitations + +Coverage is `complete` only when nothing below applies. Otherwise coverage is +`unknown` and a limitation names the cause: + +- The logo matches only in its first half, or not at all. +- The declared header or global checksum differs from the computed one. +- The file is shorter than the declared ROM size (the limitation names the + offset where the file ends) or longer (it names the offset where the + bytes outside the declared size begin). +- The cartridge type, ROM size code or RAM size code is outside the + documented table. + +There is no fixed size ceiling. The header is parsed and the global checksum +is summed in bounded reads, so the file is not held in memory. Inventory +still reads the stored members, including `program.bin`, to hash them. + +## CLI + +```sh +rea inspect-artifact ./game.gb --detail summary --json +rea extract-artifact ./game.gbc --json +``` + +## Opening the program image + +REA does not disassemble SM83 code. `raw-binary` does not admit SM83, and +routing a console image through an installed Ghidra language is the open +design in [#5657](https://github.com/morluto/rea/issues/5657). Bank 0 maps at +`0x0000..0x3FFF` and the switchable bank at `0x4000..0x7FFF`; the mapper +decides which file range is visible there. + +## Verification scope + +Synthetic images cover header facts, every CGB flag form, matching and +mismatched header and global checksums, a top-half and a full logo mismatch, +short and long files against the declared size, undocumented type and size +codes, a truncated header, a 2 MiB image summed in more than one read, and +the expanded-bytes allowance. The fixtures carry a test logo pattern that +tests register, not the boot logo. No commercial ROM was used. diff --git a/docs/guides/firmware/gba-roms.md b/docs/guides/firmware/gba-roms.md new file mode 100644 index 00000000000..34400bf47af --- /dev/null +++ b/docs/guides/firmware/gba-roms.md @@ -0,0 +1,90 @@ +# Game Boy Advance ROMs + +`inspect-artifact` and `extract-artifact` read a Game Boy Advance cartridge +ROM (`.gba`) offline. The file name does not matter. Recognition needs the +192-byte header: an ARM `B` at `0x00`, the fixed value `0x96` at `0xB2`, and +either the boot logo at `0x04..0xA0` or a matching complement check. REA +compares the logo by SHA-256 digest and does not carry the logo bytes. A +prefix shorter than the header does not claim the format; a file cut short +inside the header is refused as truncated with the offset where it ends. + +Nothing is executed, decompressed or patched. A logo or complement mismatch +is reported and left unchanged. + +## What the root reports + +Root `format_metadata` (`kind: "gba-rom"`) holds: + +- `rom_bytes`: the file length. +- `entry`: the stored word at `0x00` and `target_offset`, the file offset its + ARM `B` reaches, or null when the word is not a branch. A cartridge maps + file offset 0 at `0x08000000`. +- `nintendo_logo`: `match` or `mismatch`. +- `title_raw_hex` and `title` (12 bytes at `0xA0`), `game_code` (4 bytes at + `0xAC`) and `maker_code` (2 bytes at `0xB0`). Non-printable bytes show as + `?`. +- `fixed_value` (`0x96` in a valid header), `unit_code`, `device_type` and + `software_version`. +- `complement_check`: the declared byte at `0xBD` and the value computed over + `0xA0..0xBC`, with `status` `match` or `mismatch`. +- `multiboot_layout` and `multiboot`. A multiboot image is sent over the link + cable into 256 KiB of work RAM at `0x02000000` and repeats this header with + extra fields at `0xC0..0xE4`. The layout is `possible` when the file fits + in 256 KiB and the word at `0xC0` is an ARM `B`; `multiboot` then holds + `ram_entry`, `boot_mode`, `slave_id` and `joybus_entry`. A field the file + ends before is null, not zero. Nothing in the + header states how an image is booted, so `possible` is not a claim that it + is a multiboot image. + +## Members + +| Path | Holds | +| ------------- | ----------------------------------- | +| `header.bin` | The 192-byte header at `0x00..0xC0` | +| `program.bin` | The whole file, as stored | + +Each member's `format_metadata` (`kind: "gba-rom-entry"`) records `role` +(`header` or `program`). Both are stored ranges and are counted separately +toward `artifact_limits.expanded_bytes`. + +## Limitations + +Coverage is `complete` only when nothing below applies. Otherwise coverage is +`unknown` and a limitation names the cause: + +- The word at `0x00` is not an ARM branch, so the entry point is unknown. +- The logo differs from the boot logo the BIOS compares. +- The fixed value at `0xB2` is not `0x96`. +- The declared complement check differs from the computed one. +- Reserved bytes at `0xB5..0xBC` or `0xBE..0xC0` are not zero. +- The multiboot layout could apply but the file ends before `0xE4`; the + limitation names that offset. +- The file is longer than the 32 MiB cartridge window; the limitation names + the offset where the extra bytes begin. + +There is no fixed size ceiling. Only the header is parsed. Inventory still +reads the stored members, including `program.bin`, to hash them. + +## CLI + +```sh +rea inspect-artifact ./game.gba --detail summary --json +rea extract-artifact ./game.gba --json +``` + +## Opening the program image + +`program.bin` is ARM7TDMI code with the cartridge mapped at `0x08000000`, and +REA's `raw-binary` lane admits `arm`. The `base_address` option is available +only with an ARM M-profile `architecture_variant`, which the ARM7TDMI is not, +so REA cannot map the image at `0x08000000` today. Routing a console image +through an installed Ghidra language is the open design in +[#5657](https://github.com/morluto/rea/issues/5657). + +## Verification scope + +Synthetic images cover header facts, a logo, complement and fixed-value +mismatch, recognition by logo or by complement check, the multiboot fields, +a file above 256 KiB, a backward and a non-branch entry word, and a truncated +header. The fixtures carry a test logo pattern that tests register, not the +boot logo. No commercial ROM was used. diff --git a/docs/reference/supported-targets.md b/docs/reference/supported-targets.md index 2cc688bc8c1..50f1135f3bf 100644 --- a/docs/reference/supported-targets.md +++ b/docs/reference/supported-targets.md @@ -18,6 +18,8 @@ The table lists what REA returns for each target and which tools or host it requ | Switch NSO/NRO | Module id, segment layout and hashes, NRO icon/NACP/RomFS ranges; LZ4 segments decompressed | Built-in static header parsing; [Switch executables](../guides/firmware/switch-executables.md) | | GPU asset headers | DDS (incl. DX10), GLB, KTX and KTX2 header facts and declared regions; payloads not decoded | Built-in static header parsing; [GPU asset headers](../gpu-asset-headers.md) | | 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) | +| Game Boy ROMs | Cartridge header, logo match, cartridge type, declared sizes, header and global checksums; nothing executed | Built-in static header parsing; [Game Boy ROMs](../guides/firmware/game-boy-roms.md) | +| Game Boy Advance ROMs | Entry branch, logo match, title and codes, complement check, multiboot fields; nothing executed | Built-in static header parsing; [Game Boy Advance ROMs](../guides/firmware/gba-roms.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) | diff --git a/scripts/ci/scopes.mjs b/scripts/ci/scopes.mjs index 38b96b88bee..8a8ad61ac15 100644 --- a/scripts/ci/scopes.mjs +++ b/scripts/ci/scopes.mjs @@ -162,6 +162,9 @@ const PATH_SCOPES = { "tests/acceptance/inesContainer.test.ts", "tests/boundary/filesystem/inesArtifact.test.ts", "tests/boundary/filesystem/inesCancellation.test.ts", + "src/artifacts/HandheldRomArtifactReader*.ts", + "src/domain/gameBoyRomHeader*.ts", + "src/domain/gbaRomHeader*.ts", "src/artifacts/NdsRomArtifactReader*.ts", "src/domain/ndsRom*.ts", "src/artifacts/Image4ArtifactReader*.ts", diff --git a/src/application/binary/TargetFormatVocabularies.test.ts b/src/application/binary/TargetFormatVocabularies.test.ts index 37e74ef2a53..10625512445 100644 --- a/src/application/binary/TargetFormatVocabularies.test.ts +++ b/src/application/binary/TargetFormatVocabularies.test.ts @@ -105,6 +105,8 @@ const TARGETS: TargetFixtures = { "app-pack": { ...archive, format: "app-pack" }, asar: { ...archive, format: "asar" }, ines: { ...archive, format: "ines" }, + "game-boy-rom": { ...archive, format: "game-boy-rom" }, + "gba-rom": { ...archive, format: "gba-rom" }, nds: { ...archive, format: "nds" }, "mega-drive-rom": { ...archive, format: "mega-drive-rom" }, "n64-rom": { ...archive, format: "n64-rom" }, diff --git a/src/artifacts/HandheldRomArtifactReader.test.ts b/src/artifacts/HandheldRomArtifactReader.test.ts new file mode 100644 index 00000000000..e1ce8439eb4 --- /dev/null +++ b/src/artifacts/HandheldRomArtifactReader.test.ts @@ -0,0 +1,178 @@ +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { classifyArtifactBytesAtPath } from "../../tests/fixtures/artifactClassification.js"; +import { readArtifactEntries } from "../../tests/fixtures/artifactEntries.js"; +import { + inventoryArtifact, + materializeArtifactInventory, + scanCanonicalArtifactInventory, +} from "../../tests/fixtures/artifactInventory.js"; +import { + createTestTempDirectory, + createTestTempFile, +} from "../../tests/fixtures/temporaryDirectory.js"; +import { parseBinaryTarget } from "../application/BinaryTargetResolver.js"; +import { gameBoyRom, gbaRom } from "../domain/handheldRom.fixture.js"; +import { + GameBoyRomArtifactReader, + GbaRomArtifactReader, +} from "./HandheldRomArtifactReader.js"; + +const digest = (bytes: Uint8Array): string => + createHash("sha256").update(bytes).digest("hex"); + +const write = (bytes: Buffer, name: string): Promise => + createTestTempFile("rea-handheld-", name, bytes); + +describe("Game Boy ROM reader", () => { + it("serves the header and the whole image as stored ranges", async () => { + const rom = gameBoyRom({ romSizeCode: 0x06, cartridgeType: 0x13 }); + // A 2 MiB image takes more than one checksum read. + expect(rom.length).toBe(2 * 1024 * 1024); + const result = await readArtifactEntries( + new GameBoyRomArtifactReader(await write(rom, "game.gb")), + ); + expect(result.metadata).toMatchObject({ + kind: "game-boy-rom", + mapper: "mbc3", + features: ["ram", "battery"], + declared_rom_bytes: rom.length, + header_checksum: { status: "match" }, + global_checksum: { status: "match" }, + }); + expect(result.coverage).toEqual([{ status: "complete", limitations: [] }]); + expect(result.entries.map((entry) => entry.formatMetadata)).toEqual([ + { kind: "game-boy-rom-entry", role: "header" }, + { kind: "game-boy-rom-entry", role: "program" }, + ]); + expect( + result.contents.get("header.bin")?.equals(rom.subarray(0x100, 0x150)), + ).toBe(true); + expect(result.contents.get("program.bin")?.equals(rom)).toBe(true); + }); + + it("classifies by content, ignoring the name", async () => { + const rom = gameBoyRom(); + expect(classifyArtifactBytesAtPath("rom.bin", rom)).toEqual({ + kind: "container", + format: "game-boy-rom", + }); + expect(await parseBinaryTarget(await write(rom, "rom.bin"))).toMatchObject({ + ok: true, + value: { kind: "archive", format: "game-boy-rom" }, + }); + }); + + it("inventories a bad global checksum as unknown coverage", async () => { + const rom = gameBoyRom({ badGlobalChecksum: true }); + const graph = await inventoryArtifact(await write(rom, "game.gbc")); + expect(graph.manifest.root_format).toBe("game-boy-rom"); + expect(graph.manifest.root_sha256).toBe(digest(rom)); + expect(graph.coverage.status).toBe("unknown"); + expect( + graph.occurrences.find((row) => row.logical_path === ".") + ?.format_metadata, + ).toMatchObject({ + kind: "game-boy-rom", + global_checksum: { status: "mismatch" }, + }); + }); + + it("refuses a header cut short with the offset where the file ends", async () => { + const rom = gameBoyRom().subarray(0, 0x140); + await expect( + readArtifactEntries( + new GameBoyRomArtifactReader(await write(rom, "short.gb")), + ), + ).rejects.toMatchObject({ + reason: "truncated", + parseFailure: { + kind: "truncated", + format: "game-boy-rom", + offset: 0x140, + }, + }); + expect(await parseBinaryTarget(await write(rom, "short.gb"))).toMatchObject( + { ok: false, error: { constraint: "file_format_rejected" } }, + ); + }); + + it("charges both members against artifact_limits.expanded_bytes", async () => { + const rom = gameBoyRom(); + const reader = new GameBoyRomArtifactReader( + await write(rom, "game.gb"), + undefined, + 16, + ); + try { + await expect(async () => { + for await (const entry of reader.entries()) void entry; + }).rejects.toMatchObject({ + reason: "limit", + readerLimit: { + parameter: "artifact_limits.expanded_bytes", + effective_value: 16, + required_value: 0x50 + rom.length, + }, + }); + } finally { + await reader.close(); + } + }); +}); + +describe("Game Boy Advance ROM reader", () => { + it("serves the header and the whole image as stored ranges", async () => { + const rom = gbaRom(); + const result = await readArtifactEntries( + new GbaRomArtifactReader(await write(rom, "game.gba")), + ); + expect(result.metadata).toMatchObject({ + kind: "gba-rom", + entry: { target_offset: 0xc0 }, + nintendo_logo: "match", + game_code: "AREE", + complement_check: { status: "match" }, + multiboot_layout: "possible", + }); + expect(result.coverage).toEqual([{ status: "complete", limitations: [] }]); + expect( + result.contents.get("header.bin")?.equals(rom.subarray(0, 0xc0)), + ).toBe(true); + expect(result.contents.get("program.bin")?.equals(rom)).toBe(true); + }); + + it("classifies by content and extracts program.bin byte-identical", async () => { + const rom = gbaRom({ badComplement: true }); + expect(classifyArtifactBytesAtPath("rom.bin", rom)).toEqual({ + kind: "container", + format: "gba-rom", + }); + const path = await write(rom, "game.gba"); + const snapshot = await scanCanonicalArtifactInventory(path); + expect(snapshot.coverage.status).toBe("unknown"); + const selected = snapshot.occurrences + .filter((row) => row.logical_path === "program.bin") + .map((row) => row.occurrence_id); + const output = join(await createTestTempDirectory("rea-gba-out-"), "out"); + await materializeArtifactInventory( + { + inputPath: path, + inputFormat: "gba-rom", + outputRoot: output, + occurrenceIds: selected, + environment: process.env, + integrityPolicy: "fail", + }, + path, + snapshot, + ); + expect((await readFile(join(output, "program.bin"))).equals(rom)).toBe( + true, + ); + }); +}); diff --git a/src/artifacts/HandheldRomArtifactReader.ts b/src/artifacts/HandheldRomArtifactReader.ts new file mode 100644 index 00000000000..71ff4091605 --- /dev/null +++ b/src/artifacts/HandheldRomArtifactReader.ts @@ -0,0 +1,201 @@ +import { artifactExpansionBudgetBytes } from "../domain/artifactExpansionBudget.js"; +import { + addGameBoyGlobalChecksum, + GAME_BOY_FORMAT, + GAME_BOY_HEADER_END, + gameBoyRomRegions, + parseGameBoyRom, + type GameBoyRomMetadata, +} from "../domain/gameBoyRomHeader.js"; +import { + GBA_FORMAT, + GBA_HEADER_BYTES, + GBA_MULTIBOOT_HEADER_END, + gbaRomRegions, + parseGbaRom, + type GbaRomMetadata, +} from "../domain/gbaRomHeader.js"; +import { ParseFailureError } from "../domain/parseFailure.js"; +import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; +import { + artifactParseFailure, + artifactReaderLimitFailure, +} from "../resources/index.js"; +import { createExactArtifactRead } from "./ArtifactFileRange.js"; +import { + PositionalArtifactReader, + positionalRegionEntry, + type PositionalArtifactEntries, +} from "./PositionalArtifactReader.js"; + +// The Game Boy global checksum sums the whole file in bounded reads. +const CHECKSUM_CHUNK_BYTES = 1024 * 1024; + +interface HandheldImage { + readonly metadata: Metadata; + readonly limitations: readonly string[]; + readonly entries: readonly { + readonly path: string; + readonly offset: number; + readonly length: number; + readonly metadata: Parameters[2]; + }[]; +} + +type ExactRead = ReturnType; + +/** + * Shared shape of the Game Boy and Game Boy Advance readers: header facts + * from the domain parser, and members that are stored ranges of the file. + * Nothing is decrypted, decompressed or executed; checksum and logo + * disagreements stay limitations. + */ +abstract class HandheldRomArtifactReader< + Metadata extends GameBoyRomMetadata | GbaRomMetadata, +> extends PositionalArtifactReader { + constructor( + path: string, + label: string, + admitted?: StableRegularFileDescriptor, + private readonly expandedBytes?: number, + ) { + super(path, label, admitted); + } + + formatMetadata(): Metadata | undefined { + const metadata = this.preparedFormatMetadata; + return metadata === undefined ? undefined : structuredClone(metadata); + } + + /** Bytes the header occupies; a shorter file is refused by the parser. */ + protected abstract readonly headerEnd: number; + + /** Member ranges, which depend only on the file size. */ + protected abstract memberRegions( + fileSize: number, + ): readonly { readonly length: number }[]; + + protected abstract parse( + read: ExactRead, + fileSize: number, + signal?: AbortSignal, + ): Promise>; + + protected override async prepareEntries( + signal?: AbortSignal, + ): Promise> { + const { handle, initial } = await this.verifyCarrier(signal); + const fileSize = initial.size; + // The members follow from the size alone, so the allowance is charged + // before the Game Boy checksum reads the whole file. + if (fileSize >= this.headerEnd) this.#admitMembers(fileSize); + let image: HandheldImage; + try { + image = await this.parse( + createExactArtifactRead(this.format, handle, fileSize, signal), + fileSize, + signal, + ); + this.assertOpen(signal); + } catch (cause: unknown) { + if (cause instanceof ParseFailureError) + throw artifactParseFailure(cause, signal); + throw cause; + } + return { + entries: image.entries.map((region) => + positionalRegionEntry(region, this.format, region.metadata), + ), + coverage: { + status: image.limitations.length === 0 ? "complete" : "unknown", + limitations: [...image.limitations], + }, + formatMetadata: image.metadata, + }; + } + + /** The program member repeats the header range; each is hashed separately. */ + #admitMembers(fileSize: number): void { + const expansionBudget = + this.expandedBytes ?? artifactExpansionBudgetBytes(fileSize); + let declared = 0n; + for (const region of this.memberRegions(fileSize)) + declared += BigInt(region.length); + if (declared > BigInt(expansionBudget)) + throw artifactReaderLimitFailure( + "artifact_limits.expanded_bytes", + expansionBudget, + "bytes", + declared, + "memory", + ); + } +} + +/** + * Game Boy and Game Boy Color cartridge ROM. `header.bin` is 0x100..0x150 and + * `program.bin` is the whole file. The global checksum is summed over the + * file in bounded reads. + */ +export class GameBoyRomArtifactReader extends HandheldRomArtifactReader { + override readonly format = GAME_BOY_FORMAT; + + constructor( + path: string, + admitted?: StableRegularFileDescriptor, + expandedBytes?: number, + ) { + super(path, "Game Boy ROM", admitted, expandedBytes); + } + + protected override readonly headerEnd = GAME_BOY_HEADER_END; + + protected override memberRegions(fileSize: number) { + return gameBoyRomRegions(fileSize); + } + + protected override async parse( + read: ExactRead, + fileSize: number, + signal?: AbortSignal, + ) { + const header = await read(0, Math.min(fileSize, GAME_BOY_HEADER_END)); + let sum = 0; + if (fileSize >= GAME_BOY_HEADER_END) + for (let offset = 0; offset < fileSize; offset += CHECKSUM_CHUNK_BYTES) { + this.assertOpen(signal); + const length = Math.min(CHECKSUM_CHUNK_BYTES, fileSize - offset); + sum = addGameBoyGlobalChecksum(sum, await read(offset, length), offset); + } + return parseGameBoyRom(header, fileSize, sum); + } +} + +/** + * Game Boy Advance cartridge ROM. `header.bin` is 0x00..0xC0 and + * `program.bin` is the whole file. + */ +export class GbaRomArtifactReader extends HandheldRomArtifactReader { + override readonly format = GBA_FORMAT; + + constructor( + path: string, + admitted?: StableRegularFileDescriptor, + expandedBytes?: number, + ) { + super(path, "Game Boy Advance ROM", admitted, expandedBytes); + } + + protected override readonly headerEnd = GBA_HEADER_BYTES; + + protected override memberRegions(fileSize: number) { + return gbaRomRegions(fileSize); + } + + protected override async parse(read: ExactRead, fileSize: number) { + return parseGbaRom( + await read(0, Math.min(fileSize, GBA_MULTIBOOT_HEADER_END)), + fileSize, + ); + } +} diff --git a/src/artifacts/artifactFormats.ts b/src/artifacts/artifactFormats.ts index a2f264c7753..938376d9fbe 100644 --- a/src/artifacts/artifactFormats.ts +++ b/src/artifacts/artifactFormats.ts @@ -46,6 +46,10 @@ import { McubootArtifactReader } from "./McubootArtifactReader.js"; import type { GodotPckAdmission } from "./GodotPckLocation.js"; import { GodotPckArtifactReader } from "./GodotPckArtifactReader.js"; import { InesArtifactReader } from "./InesArtifactReader.js"; +import { + GameBoyRomArtifactReader, + GbaRomArtifactReader, +} from "./HandheldRomArtifactReader.js"; import { MegaDriveRomArtifactReader } from "./MegaDriveRomArtifactReader.js"; import { N64RomArtifactReader } from "./N64RomArtifactReader.js"; import { NdsRomArtifactReader } from "./NdsRomArtifactReader.js"; @@ -473,6 +477,28 @@ const NON_ZIP_FORMATS = { options.readerLimits?.tar, ), }), + "game-boy-rom": container("game-boy-rom", { + ...EXTRACTABLE_ROLE_CONTAINER, + readerLimitation: + "Game Boy ROM inventory reports the cartridge header at 0x100..0x150: entry code, boot logo match, title, CGB and SGB flags, cartridge type, declared ROM and RAM sizes, licensee codes, version, and the declared and computed header and global checksums. header.bin and program.bin are stored ranges. Nothing is executed or patched; a checksum, logo or size disagreement is a limitation.", + createReader: (path, options) => + new GameBoyRomArtifactReader( + path, + sourceOf(options), + options.readerLimits?.expanded_bytes, + ), + }), + "gba-rom": container("gba-rom", { + ...EXTRACTABLE_ROLE_CONTAINER, + readerLimitation: + "Game Boy Advance ROM inventory reports the cartridge header at 0x00..0xC0: entry branch, boot logo match, title, game and maker codes, fixed value, unit and device type, version, the declared and computed complement check, and whether the multiboot fields could apply. header.bin and program.bin are stored ranges. Nothing is executed or patched; a logo or complement disagreement is a limitation.", + createReader: (path, options) => + new GbaRomArtifactReader( + path, + sourceOf(options), + options.readerLimits?.expanded_bytes, + ), + }), nds: container("nds", { ...EXTRACTABLE_ROLE_CONTAINER, readerLimitation: diff --git a/src/domain/analysisView/artifactInventoryView.ts b/src/domain/analysisView/artifactInventoryView.ts index cd8f24dacdf..7fc70bfcb34 100644 --- a/src/domain/analysisView/artifactInventoryView.ts +++ b/src/domain/analysisView/artifactInventoryView.ts @@ -407,6 +407,8 @@ export const projectArtifactInventoryView = ( inventory.manifest.root_format === "fit" || inventory.manifest.root_format === "swf" || inventory.manifest.root_format === "mcuboot" || + inventory.manifest.root_format === "game-boy-rom" || + inventory.manifest.root_format === "gba-rom" || inventory.manifest.root_format === "nds" || inventory.manifest.root_format === "mega-drive-rom" || inventory.manifest.root_format === "n64-rom" || diff --git a/src/domain/artifactFormatMetadata.ts b/src/domain/artifactFormatMetadata.ts index 69562a098ee..4b522bfd832 100644 --- a/src/domain/artifactFormatMetadata.ts +++ b/src/domain/artifactFormatMetadata.ts @@ -4,6 +4,12 @@ import { androidSuperImageMetadataSchema, androidSuperPartitionMetadataSchema, } from "./formatMetadata/androidSuperImageMetadata.js"; +import { + gameBoyRomEntryMetadataSchema, + gameBoyRomMetadataSchema, + gbaRomEntryMetadataSchema, + gbaRomMetadataSchema, +} from "./formatMetadata/handheldRomMetadata.js"; import { macosPkgEntryMetadataSchema, macosPkgMetadataSchema, @@ -185,6 +191,10 @@ export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [ ndsEntryMetadataSchema, megaDriveRomMetadataSchema, megaDriveRomEntryMetadataSchema, + gameBoyRomMetadataSchema, + gameBoyRomEntryMetadataSchema, + gbaRomMetadataSchema, + gbaRomEntryMetadataSchema, n64RomMetadataSchema, n64RomEntryMetadataSchema, ]); @@ -438,6 +448,14 @@ const declarationsByKind: { }, }, }, + "game-boy-rom": + "Its header and checksum facts come from the ROM's own bytes, which content comparison covers.", + "game-boy-rom-entry": + "Its role is in its path; content comparison covers its bytes.", + "gba-rom": + "Its header and checksum facts come from the ROM's own bytes, which content comparison covers.", + "gba-rom-entry": + "Its role is in its path; content comparison covers its bytes.", "mega-drive-rom": "Its header and vector facts come from the ROM's own bytes, which content comparison covers.", "mega-drive-rom-entry": diff --git a/src/domain/artifactFormatRecognition.ts b/src/domain/artifactFormatRecognition.ts index 725e8a2c559..47d9aade44e 100644 --- a/src/domain/artifactFormatRecognition.ts +++ b/src/domain/artifactFormatRecognition.ts @@ -16,6 +16,8 @@ import { hasUf2Block } from "./firmware/uf2.js"; import { hasGodotPckHeader } from "./godotPckFormat.js"; import { nesContainerFormat, parseInesLayout } from "./inesContainer.js"; import { type MegaDriveLayout, recognizeMegaDriveRom } from "./megaDriveRom.js"; +import { gameBoyRomRecognition } from "./gameBoyRomHeader.js"; +import { gbaRomRecognition } from "./gbaRomHeader.js"; import { n64RomRecognition } from "./n64Rom.js"; import { hasNdsHeader } from "./ndsRom.js"; import { @@ -75,6 +77,8 @@ import { hasZipSignature } from "./zipPackageFormat.js"; export type RecognizedArtifactFormat = Extract< ArtifactFormatId, | "ines" + | "game-boy-rom" + | "gba-rom" | "nds" | "mega-drive-rom" | "n64-rom" @@ -418,6 +422,12 @@ export const ARTIFACT_FORMAT_RECOGNIZERS: readonly ArtifactFormatRecognizer[] = !claimsExecutableHeader(prefix, fileSize) ? { state: "recognized", format: "android-super-image" } : undefined, + // No magic: the boot logo at 0x104 claims a Game Boy image. Its first 24 + // bytes, the half every boot ROM compares, must match. + whenClaimed("game-boy-rom", gameBoyRomRecognition), + // No magic: an ARM branch at 0, the fixed 0x96 at 0xB2, and the boot logo + // or a matching complement check claim a GBA image. + whenClaimed("gba-rom", gbaRomRecognition), // No magic: the stored logo CRC and a matching checksum claim it, after // every format with a leading signature. when("nds", hasNdsHeader), diff --git a/src/domain/artifactGraph.ts b/src/domain/artifactGraph.ts index a276ad2da82..90c9f7c81c7 100644 --- a/src/domain/artifactGraph.ts +++ b/src/domain/artifactGraph.ts @@ -72,6 +72,8 @@ export const ARTIFACT_FORMAT_IDS = [ "pkg", "asar", "ines", + "game-boy-rom", + "gba-rom", "nds", "mega-drive-rom", "n64-rom", @@ -154,6 +156,8 @@ const artifactFormatSchema = z.enum(ARTIFACT_FORMAT_IDS); /** Formats established from bytes or a virtual directory tree, independent of path roles. */ const artifactContentFormatSchema = artifactFormatSchema.extract([ "ines", + "game-boy-rom", + "gba-rom", "nds", "mega-drive-rom", "n64-rom", diff --git a/src/domain/formatMetadata/handheldRomMetadata.ts b/src/domain/formatMetadata/handheldRomMetadata.ts new file mode 100644 index 00000000000..2eddd2db695 --- /dev/null +++ b/src/domain/formatMetadata/handheldRomMetadata.ts @@ -0,0 +1,157 @@ +import { z } from "zod"; + +import { offset, uint16, uint32, uint8 } from "./primitives.js"; + +/** + * Whether stored logo bytes equal the boot logo the console's boot ROM + * compares. REA compares SHA-256 digests and carries no logo bytes. + * `top-half` is a Game Boy header whose first 24 logo bytes match and whose + * last 24 do not: the Game Boy Color boot ROM compares only the first half. + */ +export const HANDHELD_LOGO_STATUSES = [ + "match", + "top-half", + "mismatch", +] as const; + +const checksumSchema = (value: typeof uint8 | typeof uint16) => + z.strictObject({ + status: z.enum(["match", "mismatch"]), + declared: value, + computed: value, + }); + +/** Memory bank controller named by the Game Boy cartridge type byte. */ +export const GAME_BOY_MAPPERS = [ + "none", + "mbc1", + "mbc2", + "mmm01", + "mbc3", + "mbc4", + "mbc5", + "mbc6", + "mbc7", + "pocket-camera", + "tama5", + "huc3", + "huc1", +] as const; + +/** Cartridge hardware the type byte declares beside the mapper. */ +export const GAME_BOY_CARTRIDGE_FEATURES = [ + "ram", + "battery", + "timer", + "rumble", + "sensor", +] as const; + +/** + * Game Boy and Game Boy Color cartridge header at 0x100..0x150. Title bytes + * stay in `title_raw_hex`; `title` keeps printable ASCII before the first NUL + * and replaces other bytes with `?`. + */ +export const gameBoyRomMetadataSchema = z.strictObject({ + kind: z.literal("game-boy-rom"), + rom_bytes: offset, + /** The four bytes at 0x100, where the boot ROM hands over. */ + entry_hex: z.string().regex(/^[0-9a-f]{8}$/u), + /** Target of a `JP a16` at 0x100 or 0x101 (after a `NOP`); null otherwise. */ + entry_jump_target: uint16.nullable(), + nintendo_logo: z.enum(HANDHELD_LOGO_STATUSES), + /** The 16 bytes at 0x134..0x144, including the CGB flag byte. */ + title_raw_hex: z.string().regex(/^[0-9a-f]{32}$/u), + title: z.string().max(16), + /** + * Four uppercase letters or digits at 0x13F when the CGB flag is set; null + * when those bytes are part of an older title. + */ + manufacturer_code: z.string().length(4).nullable(), + cgb_flag: uint8, + /** `compatible` is 0x80, `required` is 0xC0, `none` has bit 7 clear. */ + cgb: z.enum(["none", "compatible", "required", "other"]), + sgb_flag: uint8, + /** SGB functions need flag 0x03 and old licensee code 0x33. */ + sgb_supported: z.boolean(), + cartridge_type: uint8, + /** Null when the type byte is outside the documented table. */ + mapper: z.enum(GAME_BOY_MAPPERS).nullable(), + features: z.array(z.enum(GAME_BOY_CARTRIDGE_FEATURES)), + rom_size_code: uint8, + /** 32 KiB shifted by the size code (0x00..0x08); null otherwise. */ + declared_rom_bytes: offset.nullable(), + ram_size_code: uint8, + /** Null for code 0x01 and codes outside the documented table. */ + declared_ram_bytes: offset.nullable(), + destination_code: uint8, + destination: z.enum(["japan", "overseas"]).nullable(), + old_licensee_code: uint8, + /** Two characters at 0x144; meaningful when the old code is 0x33. */ + new_licensee_code: z.string().length(2), + version: uint8, + header_checksum: checksumSchema(uint8), + global_checksum: checksumSchema(uint16), +}); +export type GameBoyRomMetadata = z.infer; + +/** One stored range of a Game Boy ROM: the header or the whole image. */ +export const gameBoyRomEntryMetadataSchema = z.strictObject({ + kind: z.literal("game-boy-rom-entry"), + role: z.enum(["header", "program"]), +}); +export type GameBoyRomEntryMetadata = z.infer< + typeof gameBoyRomEntryMetadataSchema +>; + +const armBranchSchema = z.strictObject({ + /** The little-endian word as stored. */ + instruction: uint32, + /** File offset the ARM `B` reaches; null when the word is not `B` (always). */ + target_offset: offset.nullable(), +}); + +/** The multiboot fields at 0xC0..0xE4, read when they could apply. */ +const gbaMultibootSchema = z.strictObject({ + ram_entry: armBranchSchema, + /** Null when the file ends before the field. */ + boot_mode: uint8.nullable(), + slave_id: uint8.nullable(), + joybus_entry: armBranchSchema.nullable(), +}); + +/** + * Game Boy Advance cartridge header at 0x00..0xC0. Text fields keep printable + * ASCII before the first NUL and replace other bytes with `?`. + */ +export const gbaRomMetadataSchema = z.strictObject({ + kind: z.literal("gba-rom"), + rom_bytes: offset, + entry: armBranchSchema, + nintendo_logo: z.enum(["match", "mismatch"]), + title_raw_hex: z.string().regex(/^[0-9a-f]{24}$/u), + title: z.string().max(12), + game_code: z.string().length(4), + maker_code: z.string().length(2), + /** Must be 0x96. */ + fixed_value: uint8, + unit_code: uint8, + device_type: uint8, + software_version: uint8, + complement_check: checksumSchema(uint8), + /** + * `possible` when the file fits the 256 KiB of work RAM a multiboot image + * loads into and the word at 0xC0 is an ARM `B`. Nothing in the header + * states which way the image is booted. + */ + multiboot_layout: z.enum(["possible", "not-applicable"]), + multiboot: gbaMultibootSchema.nullable(), +}); +export type GbaRomMetadata = z.infer; + +/** One stored range of a GBA ROM: the header or the whole image. */ +export const gbaRomEntryMetadataSchema = z.strictObject({ + kind: z.literal("gba-rom-entry"), + role: z.enum(["header", "program"]), +}); +export type GbaRomEntryMetadata = z.infer; diff --git a/src/domain/gameBoyRomHeader.ts b/src/domain/gameBoyRomHeader.ts new file mode 100644 index 00000000000..3b3dbce08db --- /dev/null +++ b/src/domain/gameBoyRomHeader.ts @@ -0,0 +1,451 @@ +import { byteToHex } from "../kernel/byteToHex.js"; +import { BinaryReader } from "./binaryContainer.js"; +import { sha256Hex as sha256 } from "../kernel/sha256Hex.js"; +import type { + GameBoyRomEntryMetadata, + GameBoyRomMetadata, +} from "./formatMetadata/handheldRomMetadata.js"; +import { malformedInput, truncatedInput } from "./parseFailure.js"; + +export type { GameBoyRomMetadata }; + +/** + * Game Boy and Game Boy Color cartridge image. The header occupies + * 0x100..0x150: entry code at 0x100, the boot logo at 0x104, title at 0x134, + * CGB flag at 0x143, new licensee code at 0x144, SGB flag at 0x146, cartridge + * type at 0x147, ROM and RAM size codes at 0x148 and 0x149, destination at + * 0x14A, old licensee code at 0x14B, version at 0x14C, header checksum at + * 0x14D and the big-endian global checksum at 0x14E (Pan Docs, "The + * Cartridge Header"). Nothing here is executed, decompressed or patched. + */ +export const GAME_BOY_FORMAT = "game-boy-rom"; + +export const GAME_BOY_HEADER_OFFSET = 0x100; +/** First byte after the cartridge header. */ +export const GAME_BOY_HEADER_END = 0x150; +export const GAME_BOY_LOGO_OFFSET = 0x104; +export const GAME_BOY_LOGO_BYTES = 48; +/** The Game Boy Color boot ROM compares only this many logo bytes. */ +export const GAME_BOY_LOGO_TOP_HALF_BYTES = 24; +/** Bytes a prefix needs before the logo can claim the format. */ +export const GAME_BOY_RECOGNITION_BYTES = + GAME_BOY_LOGO_OFFSET + GAME_BOY_LOGO_TOP_HALF_BYTES; + +export const GAME_BOY_FIELD = { + title: [0x134, 0x144], + manufacturerCode: [0x13f, 0x143], + cgbFlag: 0x143, + newLicensee: [0x144, 0x146], + sgbFlag: 0x146, + cartridgeType: 0x147, + romSize: 0x148, + ramSize: 0x149, + destination: 0x14a, + oldLicensee: 0x14b, + version: 0x14c, + headerChecksum: 0x14d, + globalChecksum: 0x14e, +} as const; + +/** + * SHA-256 of the 48-byte boot logo the DMG boot ROM compares, and of its + * first 24 bytes, which the CGB boot ROM compares. Digests keep the logo + * itself out of the source. + */ +const LOGO_SHA256 = + "daf4cabdc852baa0291849203f0b41fd0b4ecd58e0d7aff4a509f5de4d7f9a2e"; +const LOGO_TOP_HALF_SHA256 = + "bb66a9cb4abb502bbc966828af0f70be5e61cb9eeb5e5ae37f78b0c6660e1b08"; + +export const GAME_BOY_HEADER_ENTRY = "header.bin"; +export const GAME_BOY_PROGRAM_ENTRY = "program.bin"; + +type Mapper = NonNullable; +type Feature = GameBoyRomMetadata["features"][number]; + +/** Cartridge type byte at 0x147 (Pan Docs table). */ +const CARTRIDGE_TYPES: Readonly< + Record +> = { + 0x00: ["none"], + 0x01: ["mbc1"], + 0x02: ["mbc1", "ram"], + 0x03: ["mbc1", "ram", "battery"], + 0x05: ["mbc2"], + 0x06: ["mbc2", "battery"], + 0x08: ["none", "ram"], + 0x09: ["none", "ram", "battery"], + 0x0b: ["mmm01"], + 0x0c: ["mmm01", "ram"], + 0x0d: ["mmm01", "ram", "battery"], + 0x0f: ["mbc3", "timer", "battery"], + 0x10: ["mbc3", "timer", "ram", "battery"], + 0x11: ["mbc3"], + 0x12: ["mbc3", "ram"], + 0x13: ["mbc3", "ram", "battery"], + 0x15: ["mbc4"], + 0x16: ["mbc4", "ram"], + 0x17: ["mbc4", "ram", "battery"], + 0x19: ["mbc5"], + 0x1a: ["mbc5", "ram"], + 0x1b: ["mbc5", "ram", "battery"], + 0x1c: ["mbc5", "rumble"], + 0x1d: ["mbc5", "rumble", "ram"], + 0x1e: ["mbc5", "rumble", "ram", "battery"], + 0x20: ["mbc6"], + 0x22: ["mbc7", "sensor", "rumble", "ram", "battery"], + 0xfc: ["pocket-camera"], + 0xfd: ["tama5"], + 0xfe: ["huc3"], + 0xff: ["huc1", "ram", "battery"], +}; + +/** RAM size byte at 0x149 (Pan Docs table). */ +const RAM_BYTES: Readonly> = { + 0x00: 0, + 0x01: 2 * 1024, + 0x02: 8 * 1024, + 0x03: 32 * 1024, + 0x04: 128 * 1024, + 0x05: 64 * 1024, +}; + +/** ROM size byte 0x00..0x08 declares 32 KiB << code. */ +const MAX_ROM_SIZE_CODE = 0x08; + +/** Documented special ROM size codes: 72, 80 and 96 banks of 16 KiB. */ +const SPECIAL_ROM_BYTES: Readonly> = { + 0x52: 72 * 16 * 1024, + 0x53: 80 * 16 * 1024, + 0x54: 96 * 16 * 1024, +}; + +const testLogos = new Set(); +const testTopHalves = new Set(); + +/** + * Accept a synthetic 48-byte logo in tests, so fixtures need not carry the + * boot logo. A pattern that equals the published logo, or either half of it, + * is refused. Production readers do not call this. + */ +export const registerGameBoyTestLogo = (logo: Uint8Array): void => { + if (logo.length !== GAME_BOY_LOGO_BYTES) + throw new Error(`test logo must be ${String(GAME_BOY_LOGO_BYTES)} bytes`); + const full = sha256(logo); + const top = sha256(logo.subarray(0, GAME_BOY_LOGO_TOP_HALF_BYTES)); + if (full === LOGO_SHA256 || top === LOGO_TOP_HALF_SHA256) + throw new Error("test logo collides with the published boot logo"); + testLogos.add(full); + testTopHalves.add(top); +}; + +const hexBytes = (bytes: Uint8Array): string => + Array.from(bytes, (byte) => byteToHex(byte)).join(""); + +const hex = (value: number, digits: number): string => + `0x${value.toString(16).padStart(digits, "0")}`; + +/** Printable ASCII before the first NUL; any other byte renders as `?`. */ +export const handheldText = (bytes: Uint8Array): string => { + let text = ""; + for (const byte of bytes) { + if (byte === 0) break; + text += byte >= 0x20 && byte <= 0x7e ? String.fromCharCode(byte) : "?"; + } + return text; +}; + +const logoStatus = ( + prefix: Uint8Array, +): GameBoyRomMetadata["nintendo_logo"] => { + const logo = prefix.subarray( + GAME_BOY_LOGO_OFFSET, + GAME_BOY_LOGO_OFFSET + GAME_BOY_LOGO_BYTES, + ); + if (logo.length === GAME_BOY_LOGO_BYTES) { + const full = sha256(logo); + if (full === LOGO_SHA256 || testLogos.has(full)) return "match"; + } + const top = sha256(logo.subarray(0, GAME_BOY_LOGO_TOP_HALF_BYTES)); + return top === LOGO_TOP_HALF_SHA256 || testTopHalves.has(top) + ? "top-half" + : "mismatch"; +}; + +const truncatedHeader = (fileSize: number) => + truncatedInput( + GAME_BOY_FORMAT, + `Game Boy cartridge header ends at ${hex(GAME_BOY_HEADER_END, 3)}; the file ends at offset ${hex(fileSize, 3)}.`, + { + offset: fileSize, + field: "header", + extent: { + availableBytes: fileSize, + requiredBytes: GAME_BOY_HEADER_END, + }, + }, + ); + +export type GameBoyRomClaim = + | { readonly state: "recognized" } + | { readonly state: "refused"; readonly reason: string }; + +/** + * Claim a Game Boy image when at least the first 24 logo bytes, the half every + * boot ROM compares, match. A file that ends before the header does is + * refused with the offset where it ends. + */ +export const gameBoyRomRecognition = ( + prefix: Uint8Array, + fileSize: number, +): GameBoyRomClaim | undefined => { + if (prefix.length < GAME_BOY_RECOGNITION_BYTES) return undefined; + if (logoStatus(prefix) === "mismatch") return undefined; + if (fileSize < GAME_BOY_HEADER_END) + return { + state: "refused", + reason: truncatedHeader(fileSize).message.replace(/\.$/u, ""), + }; + return { state: "recognized" }; +}; + +/** Header checksum over 0x134..0x14C: `x = x - byte - 1`, low eight bits. */ +export const gameBoyHeaderChecksum = (header: Uint8Array): number => { + let sum = 0; + for (let offset = 0x134; offset <= 0x14c; offset++) + sum = (sum - (header[offset] ?? 0) - 1) & 0xff; + return sum; +}; + +/** + * Add one chunk at `chunkOffset` to the running global checksum: the 16-bit + * sum of every byte except the two checksum bytes at 0x14E and 0x14F. + */ +export const addGameBoyGlobalChecksum = ( + sum: number, + chunk: Uint8Array, + chunkOffset: number, +): number => { + let total = sum; + for (let index = 0; index < chunk.length; index++) { + const position = chunkOffset + index; + if ( + position === GAME_BOY_FIELD.globalChecksum || + position === GAME_BOY_FIELD.globalChecksum + 1 + ) + continue; + total += chunk[index] ?? 0; + } + return total & 0xffff; +}; + +const entryJumpTarget = (reader: BinaryReader): number | null => { + // JP a16 is C3 lo hi; headers usually put a NOP (00) first. + const first = reader.u8(GAME_BOY_HEADER_OFFSET); + const at = + first === 0xc3 + ? GAME_BOY_HEADER_OFFSET + : first === 0x00 && reader.u8(GAME_BOY_HEADER_OFFSET + 1) === 0xc3 + ? GAME_BOY_HEADER_OFFSET + 1 + : -1; + return at < 0 ? null : reader.u16(at + 1); +}; + +const cgbMode = (flag: number): GameBoyRomMetadata["cgb"] => { + if (flag === 0x80) return "compatible"; + if (flag === 0xc0) return "required"; + return (flag & 0x80) === 0 ? "none" : "other"; +}; + +const manufacturerCode = ( + header: Uint8Array, + cgbFlag: number, +): string | null => { + if ((cgbFlag & 0x80) === 0) return null; + const [start, end] = GAME_BOY_FIELD.manufacturerCode; + const bytes = header.subarray(start, end); + const code = String.fromCharCode(...bytes); + return /^[0-9A-Z]{4}$/u.test(code) ? code : null; +}; + +/** A listed stored range. */ +export interface GameBoyRomRegion { + readonly path: string; + readonly offset: number; + readonly length: number; + readonly metadata: GameBoyRomEntryMetadata; +} + +export interface GameBoyRomImage { + readonly metadata: GameBoyRomMetadata; + readonly limitations: readonly string[]; + readonly entries: readonly GameBoyRomRegion[]; +} + +/** The members of a ROM of `fileSize` bytes; the layout depends only on it. */ +export const gameBoyRomRegions = ( + fileSize: number, +): readonly GameBoyRomRegion[] => [ + { + path: GAME_BOY_HEADER_ENTRY, + offset: GAME_BOY_HEADER_OFFSET, + length: GAME_BOY_HEADER_END - GAME_BOY_HEADER_OFFSET, + metadata: { kind: "game-boy-rom-entry", role: "header" }, + }, + { + path: GAME_BOY_PROGRAM_ENTRY, + offset: 0, + length: fileSize, + metadata: { kind: "game-boy-rom-entry", role: "program" }, + }, +]; + +/** + * Interpret a cartridge header. `header` holds at least the first 0x150 bytes; + * `globalSum` is {@link addGameBoyGlobalChecksum} over the whole file. + * Checksum, logo and size disagreements are reported as limitations, not + * refusals. + */ +export const parseGameBoyRom = ( + header: Uint8Array, + fileSize: number, + globalSum: number, +): GameBoyRomImage => { + if (fileSize < GAME_BOY_HEADER_END) throw truncatedHeader(fileSize); + if (header.length < GAME_BOY_HEADER_END) + throw malformedInput( + GAME_BOY_FORMAT, + `The header needs ${String(GAME_BOY_HEADER_END)} leading bytes; ${String(header.length)} were supplied.`, + { offset: 0, field: "header" }, + ); + const limitations: string[] = []; + // The length was checked above, so every header read stays in range. + const reader = new BinaryReader( + Buffer.from(header.buffer, header.byteOffset, header.byteLength), + true, + GAME_BOY_FORMAT, + ); + const byte = (offset: number): number => reader.u8(offset); + + const nintendoLogo = logoStatus(header); + if (nintendoLogo === "top-half") + limitations.push( + "Logo bytes 0x11C..0x134 differ from the boot logo. The Game Boy Color boot ROM compares only 0x104..0x11C; the original Game Boy compares all 48 bytes.", + ); + else if (nintendoLogo === "mismatch") + limitations.push( + "Logo bytes 0x104..0x134 differ from the boot logo the boot ROM compares.", + ); + + const cgbFlag = byte(GAME_BOY_FIELD.cgbFlag); + const manufacturer = manufacturerCode(header, cgbFlag); + const [titleStart, titleEnd] = GAME_BOY_FIELD.title; + const titleSpanEnd = + manufacturer !== null + ? GAME_BOY_FIELD.manufacturerCode[0] + : (cgbFlag & 0x80) !== 0 + ? GAME_BOY_FIELD.cgbFlag + : titleEnd; + + const typeByte = byte(GAME_BOY_FIELD.cartridgeType); + const type = CARTRIDGE_TYPES[typeByte]; + if (type === undefined) + limitations.push( + `Cartridge type ${hex(typeByte, 2)} is outside the documented table, so the mapper is unknown.`, + ); + + const romSizeCode = byte(GAME_BOY_FIELD.romSize); + const declaredRomBytes = + romSizeCode <= MAX_ROM_SIZE_CODE + ? 0x8000 << romSizeCode + : (SPECIAL_ROM_BYTES[romSizeCode] ?? null); + if (declaredRomBytes === null) + limitations.push( + `ROM size code ${hex(romSizeCode, 2)} is outside the documented table, so the declared ROM size is unknown.`, + ); + else if (fileSize < declaredRomBytes) + limitations.push( + `The header declares ${String(declaredRomBytes)} ROM bytes; the file ends at offset ${hex(fileSize, 1)}, ${String(declaredRomBytes - fileSize)} bytes short.`, + ); + else if (fileSize > declaredRomBytes) + limitations.push( + `The header declares ${String(declaredRomBytes)} ROM bytes; the ${String(fileSize - declaredRomBytes)} bytes from offset ${hex(declaredRomBytes, 1)} to the end of the file are outside it.`, + ); + + const ramSizeCode = byte(GAME_BOY_FIELD.ramSize); + const declaredRamBytes = RAM_BYTES[ramSizeCode] ?? null; + if (declaredRamBytes === null) + limitations.push( + `RAM size code ${hex(ramSizeCode, 2)} has no documented size, so the declared RAM size is unknown.`, + ); + + const destinationCode = byte(GAME_BOY_FIELD.destination); + const oldLicensee = byte(GAME_BOY_FIELD.oldLicensee); + const sgbFlag = byte(GAME_BOY_FIELD.sgbFlag); + + const declaredHeader = byte(GAME_BOY_FIELD.headerChecksum); + const computedHeader = gameBoyHeaderChecksum(header); + if (declaredHeader !== computedHeader) + limitations.push( + `Declared header checksum ${hex(declaredHeader, 2)} differs from computed ${hex(computedHeader, 2)} over 0x134..0x14C.`, + ); + const declaredGlobal = + (byte(GAME_BOY_FIELD.globalChecksum) << 8) | + byte(GAME_BOY_FIELD.globalChecksum + 1); + const computedGlobal = globalSum & 0xffff; + if (declaredGlobal !== computedGlobal) + limitations.push( + `Declared global checksum ${hex(declaredGlobal, 4)} differs from the computed 16-bit sum ${hex(computedGlobal, 4)} of the file's bytes outside 0x14E..0x150.`, + ); + + const [licenseeStart, licenseeEnd] = GAME_BOY_FIELD.newLicensee; + const metadata = { + kind: "game-boy-rom", + rom_bytes: fileSize, + entry_hex: hexBytes( + header.subarray(GAME_BOY_HEADER_OFFSET, GAME_BOY_LOGO_OFFSET), + ), + entry_jump_target: entryJumpTarget(reader), + nintendo_logo: nintendoLogo, + title_raw_hex: hexBytes(header.subarray(titleStart, titleEnd)), + title: handheldText(header.subarray(titleStart, titleSpanEnd)), + manufacturer_code: manufacturer, + cgb_flag: cgbFlag, + cgb: cgbMode(cgbFlag), + sgb_flag: sgbFlag, + sgb_supported: sgbFlag === 0x03 && oldLicensee === 0x33, + cartridge_type: typeByte, + mapper: type?.[0] ?? null, + features: type === undefined ? [] : (type.slice(1) as Feature[]), + rom_size_code: romSizeCode, + declared_rom_bytes: declaredRomBytes, + ram_size_code: ramSizeCode, + declared_ram_bytes: declaredRamBytes, + destination_code: destinationCode, + destination: + destinationCode === 0 + ? "japan" + : destinationCode === 1 + ? "overseas" + : null, + old_licensee_code: oldLicensee, + new_licensee_code: Array.from( + header.subarray(licenseeStart, licenseeEnd), + (value) => + value >= 0x20 && value <= 0x7e ? String.fromCharCode(value) : "?", + ).join(""), + version: byte(GAME_BOY_FIELD.version), + header_checksum: { + status: declaredHeader === computedHeader ? "match" : "mismatch", + declared: declaredHeader, + computed: computedHeader, + }, + global_checksum: { + status: declaredGlobal === computedGlobal ? "match" : "mismatch", + declared: declaredGlobal, + computed: computedGlobal, + }, + } satisfies GameBoyRomMetadata; + + return { metadata, limitations, entries: gameBoyRomRegions(fileSize) }; +}; diff --git a/src/domain/gbaRomHeader.ts b/src/domain/gbaRomHeader.ts new file mode 100644 index 00000000000..25f966945c6 --- /dev/null +++ b/src/domain/gbaRomHeader.ts @@ -0,0 +1,311 @@ +import { byteToHex } from "../kernel/byteToHex.js"; +import { BinaryReader } from "./binaryContainer.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; +import type { + GbaRomEntryMetadata, + GbaRomMetadata, +} from "./formatMetadata/handheldRomMetadata.js"; +import { handheldText } from "./gameBoyRomHeader.js"; +import { malformedInput, truncatedInput } from "./parseFailure.js"; + +export type { GbaRomMetadata }; + +/** + * Game Boy Advance cartridge image. The 192-byte header starts with an ARM + * `B` to the entry point, then the 156-byte boot logo at 0x04, title at 0xA0, + * game code at 0xAC, maker code at 0xB0, fixed value 0x96 at 0xB2, unit code + * at 0xB3, device type at 0xB4, software version at 0xBC and the complement + * check at 0xBD (GBATEK, "GBA Cartridge Header"). A multiboot image repeats + * the layout and adds fields at 0xC0..0xE4. Nothing here is executed, + * decompressed or patched. + */ +export const GBA_FORMAT = "gba-rom"; + +export const GBA_HEADER_BYTES = 0xc0; +/** First byte after the multiboot fields at 0xC0..0xE4. */ +export const GBA_MULTIBOOT_HEADER_END = 0xe4; +/** Work RAM a multiboot image is transferred into. */ +export const GBA_MULTIBOOT_MAX_BYTES = 0x4_0000; + +export const GBA_FIELD = { + entry: 0x00, + logo: [0x04, 0xa0], + title: [0xa0, 0xac], + gameCode: [0xac, 0xb0], + makerCode: [0xb0, 0xb2], + fixedValue: 0xb2, + unitCode: 0xb3, + deviceType: 0xb4, + reserved: [0xb5, 0xbc], + softwareVersion: 0xbc, + complement: 0xbd, + reservedTail: [0xbe, 0xc0], + ramEntry: 0xc0, + bootMode: 0xc4, + slaveId: 0xc5, + joybusEntry: 0xe0, +} as const; + +export const GBA_FIXED_VALUE = 0x96; + +/** SHA-256 of the 156-byte boot logo, so the logo stays out of the source. */ +const LOGO_SHA256 = + "08a0153cfd6b0ea54b938f7d209933fa849da0d56f5a34c481060c9ff2fad818"; + +export const GBA_HEADER_ENTRY = "header.bin"; +export const GBA_PROGRAM_ENTRY = "program.bin"; + +const hexBytes = (bytes: Uint8Array): string => + Array.from(bytes, (byte) => byteToHex(byte)).join(""); + +const hex = (value: number, digits: number): string => + `0x${value.toString(16).padStart(digits, "0")}`; + +/** A little-endian {@link BinaryReader} over caller-validated header bytes. */ +const headerReader = (bytes: Uint8Array): BinaryReader => + new BinaryReader( + Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), + true, + GBA_FORMAT, + ); + +/** Whether `word` is ARM `B` with condition AL (top byte 0xEA). */ +const isArmBranch = (word: number): boolean => word >>> 24 === 0xea; + +/** The file offset an ARM `B` stored at `at` reaches, or null. */ +export const armBranchTarget = (word: number, at: number): number | null => { + if (!isArmBranch(word)) return null; + const immediate = word & 0x00ff_ffff; + const signed = immediate & 0x0080_0000 ? immediate - 0x0100_0000 : immediate; + const target = at + 8 + signed * 4; + return target >= 0 ? target : null; +}; + +const branchAt = (reader: BinaryReader, at: number) => { + const instruction = reader.u32(at); + return { instruction, target_offset: armBranchTarget(instruction, at) }; +}; + +/** Complement check: `-(sum of 0xA0..0xBC) - 0x19`, low eight bits. */ +export const gbaComplementCheck = (header: Uint8Array): number => { + let sum = 0; + for (let offset = 0xa0; offset <= 0xbc; offset++) sum += header[offset] ?? 0; + return -(sum + 0x19) & 0xff; +}; + +const testLogos = new Set(); +const GBA_LOGO_BYTES = GBA_FIELD.logo[1] - GBA_FIELD.logo[0]; + +/** + * Accept a synthetic 156-byte logo in tests, so fixtures need not carry the + * boot logo. The published logo is refused. Production readers do not call + * this. + */ +export const registerGbaTestLogo = (logo: Uint8Array): void => { + if (logo.length !== GBA_LOGO_BYTES) + throw new Error(`test logo must be ${String(GBA_LOGO_BYTES)} bytes`); + const digest = sha256Hex(logo); + if (digest === LOGO_SHA256) + throw new Error("test logo collides with the published boot logo"); + testLogos.add(digest); +}; + +const logoMatches = (header: Uint8Array): boolean => { + const [start, end] = GBA_FIELD.logo; + const digest = sha256Hex(header.subarray(start, end)); + return digest === LOGO_SHA256 || testLogos.has(digest); +}; + +/** + * Claim a GBA image from a header-length prefix: an ARM `B` at 0, the fixed + * value 0x96 at 0xB2, and either the boot logo or a matching complement + * check. A prefix shorter than the header does not claim the format. + */ +export const hasGbaRomHeader = (prefix: Uint8Array): boolean => { + if (prefix.length < GBA_HEADER_BYTES) return false; + if (!isArmBranch(headerReader(prefix).u32(GBA_FIELD.entry))) return false; + if (prefix[GBA_FIELD.fixedValue] !== GBA_FIXED_VALUE) return false; + return ( + logoMatches(prefix) || + gbaComplementCheck(prefix) === prefix[GBA_FIELD.complement] + ); +}; + +export type GbaRomClaim = + | { readonly state: "recognized" } + | { readonly state: "refused"; readonly reason: string }; + +/** + * Claim a GBA image once the entry branch and fixed value can be checked. + * A file that ends before the header does is refused with the offset where + * it ends, like a Game Boy image; a shorter prefix makes no claim. + */ +export const gbaRomRecognition = ( + prefix: Uint8Array, + fileSize: number, +): GbaRomClaim | undefined => { + if (prefix.length <= GBA_FIELD.fixedValue) return undefined; + if (!isArmBranch(headerReader(prefix).u32(GBA_FIELD.entry))) return undefined; + if (prefix[GBA_FIELD.fixedValue] !== GBA_FIXED_VALUE) return undefined; + if (fileSize < GBA_HEADER_BYTES) + return { + state: "refused", + reason: `GBA cartridge header ends at ${hex(GBA_HEADER_BYTES, 2)}; the file ends at offset ${hex(fileSize, 2)}`, + }; + return hasGbaRomHeader(prefix) ? { state: "recognized" } : undefined; +}; + +export interface GbaRomRegion { + readonly path: string; + readonly offset: number; + readonly length: number; + readonly metadata: GbaRomEntryMetadata; +} + +export interface GbaRomImage { + readonly metadata: GbaRomMetadata; + readonly limitations: readonly string[]; + readonly entries: readonly GbaRomRegion[]; +} + +export const gbaRomRegions = (fileSize: number): readonly GbaRomRegion[] => [ + { + path: GBA_HEADER_ENTRY, + offset: 0, + length: GBA_HEADER_BYTES, + metadata: { kind: "gba-rom-entry", role: "header" }, + }, + { + path: GBA_PROGRAM_ENTRY, + offset: 0, + length: fileSize, + metadata: { kind: "gba-rom-entry", role: "program" }, + }, +]; + +/** The 32 MiB cartridge window at 0x08000000. */ +const GBA_ROM_WINDOW_BYTES = 0x200_0000; + +/** + * Interpret a cartridge header. `header` holds the first + * {@link GBA_MULTIBOOT_HEADER_END} bytes, or the whole file when it is + * shorter. A logo or complement mismatch is reported, not refused. + */ +export const parseGbaRom = ( + header: Uint8Array, + fileSize: number, +): GbaRomImage => { + if (fileSize < GBA_HEADER_BYTES) + throw truncatedInput( + GBA_FORMAT, + `GBA cartridge header ends at ${hex(GBA_HEADER_BYTES, 2)}; the file ends at offset ${hex(fileSize, 2)}.`, + { + offset: fileSize, + field: "header", + extent: { availableBytes: fileSize, requiredBytes: GBA_HEADER_BYTES }, + }, + ); + const supplied = Math.min(fileSize, GBA_MULTIBOOT_HEADER_END); + if (header.length < supplied) + throw malformedInput( + GBA_FORMAT, + `The header needs ${String(supplied)} leading bytes; ${String(header.length)} were supplied.`, + { offset: 0, field: "header" }, + ); + const limitations: string[] = []; + // Every read below stays within the supplied bytes: fields past 0xC0 are + // read only when the file reaches them. + const reader = headerReader(header); + const byte = (offset: number): number => reader.u8(offset); + + const entry = branchAt(reader, GBA_FIELD.entry); + if (entry.target_offset === null) + limitations.push( + `The word at 0x00 is ${hex(entry.instruction, 8)}, not an ARM branch, so the entry point is unknown.`, + ); + const logo = logoMatches(header) ? "match" : "mismatch"; + if (logo === "mismatch") + limitations.push( + "Logo bytes 0x04..0xA0 differ from the boot logo the BIOS compares.", + ); + const fixedValue = byte(GBA_FIELD.fixedValue); + if (fixedValue !== GBA_FIXED_VALUE) + limitations.push( + `The fixed value at 0xB2 is ${hex(fixedValue, 2)}, not 0x96.`, + ); + const declaredComplement = byte(GBA_FIELD.complement); + const computedComplement = gbaComplementCheck(header); + if (declaredComplement !== computedComplement) + limitations.push( + `Declared complement check ${hex(declaredComplement, 2)} differs from computed ${hex(computedComplement, 2)} over 0xA0..0xBC.`, + ); + const [reservedStart, reservedEnd] = GBA_FIELD.reserved; + const [tailStart, tailEnd] = GBA_FIELD.reservedTail; + const reserved = header.subarray(reservedStart, reservedEnd); + const tail = header.subarray(tailStart, tailEnd); + if (![...reserved, ...tail].every((value) => value === 0)) + limitations.push( + `Reserved header bytes at 0xB5..0xBC are ${hexBytes(reserved)} and at 0xBE..0xC0 are ${hexBytes(tail)}.`, + ); + if (fileSize > GBA_ROM_WINDOW_BYTES) + limitations.push( + `The ${String(fileSize - GBA_ROM_WINDOW_BYTES)} bytes from offset ${hex(GBA_ROM_WINDOW_BYTES, 1)} lie past the 32 MiB cartridge window.`, + ); + + const ramEntry = + fileSize >= GBA_FIELD.ramEntry + 4 + ? branchAt(reader, GBA_FIELD.ramEntry) + : undefined; + const multiboot = + fileSize <= GBA_MULTIBOOT_MAX_BYTES && + ramEntry !== undefined && + ramEntry.target_offset !== null + ? { + ram_entry: ramEntry, + boot_mode: + fileSize > GBA_FIELD.bootMode ? byte(GBA_FIELD.bootMode) : null, + slave_id: + fileSize > GBA_FIELD.slaveId ? byte(GBA_FIELD.slaveId) : null, + joybus_entry: + fileSize >= GBA_MULTIBOOT_HEADER_END + ? branchAt(reader, GBA_FIELD.joybusEntry) + : null, + } + : null; + // A missing field stays null instead of reading as zero. + if (multiboot !== null && fileSize < GBA_MULTIBOOT_HEADER_END) + limitations.push( + `The multiboot fields run to ${hex(GBA_MULTIBOOT_HEADER_END, 2)}; the file ends at offset ${hex(fileSize, 2)}, so the fields past it are unknown.`, + ); + + const [titleStart, titleEnd] = GBA_FIELD.title; + const [gameStart, gameEnd] = GBA_FIELD.gameCode; + const [makerStart, makerEnd] = GBA_FIELD.makerCode; + const fixedWidth = (bytes: Uint8Array): string => + Array.from(bytes, (value) => + value >= 0x20 && value <= 0x7e ? String.fromCharCode(value) : "?", + ).join(""); + const metadata = { + kind: "gba-rom", + rom_bytes: fileSize, + entry, + nintendo_logo: logo, + title_raw_hex: hexBytes(header.subarray(titleStart, titleEnd)), + title: handheldText(header.subarray(titleStart, titleEnd)), + game_code: fixedWidth(header.subarray(gameStart, gameEnd)), + maker_code: fixedWidth(header.subarray(makerStart, makerEnd)), + fixed_value: fixedValue, + unit_code: byte(GBA_FIELD.unitCode), + device_type: byte(GBA_FIELD.deviceType), + software_version: byte(GBA_FIELD.softwareVersion), + complement_check: { + status: declaredComplement === computedComplement ? "match" : "mismatch", + declared: declaredComplement, + computed: computedComplement, + }, + multiboot_layout: multiboot === null ? "not-applicable" : "possible", + multiboot, + } satisfies GbaRomMetadata; + + return { metadata, limitations, entries: gbaRomRegions(fileSize) }; +}; diff --git a/src/domain/handheldRom.fixture.ts b/src/domain/handheldRom.fixture.ts new file mode 100644 index 00000000000..05bcb5068a1 --- /dev/null +++ b/src/domain/handheldRom.fixture.ts @@ -0,0 +1,129 @@ +import { + addGameBoyGlobalChecksum, + gameBoyHeaderChecksum, + registerGameBoyTestLogo, +} from "./gameBoyRomHeader.js"; +import { gbaComplementCheck, registerGbaTestLogo } from "./gbaRomHeader.js"; + +/** + * Synthetic Game Boy and GBA images. The logo areas carry test patterns, not + * the boot logos; importing this module registers those patterns so the + * parsers treat them as matching. Field offsets are written out from Pan Docs + * and GBATEK rather than taken from the parsers, so a misplaced read in a + * parser shows up as a wrong value. Checksums use the production functions; + * the checksum vectors in handheldRom.test.ts pin those functions on their + * own. No commercial ROM bytes are used. + */ + +const pattern = (length: number, seed: number): Buffer => { + const bytes = Buffer.alloc(length); + for (let index = 0; index < length; index++) + bytes[index] = (seed + index * 7) & 0xff; + return bytes; +}; + +export const GAME_BOY_TEST_LOGO = pattern(48, 0x31); +registerGameBoyTestLogo(GAME_BOY_TEST_LOGO); + +export const GBA_TEST_LOGO = pattern(156, 0x5a); +registerGbaTestLogo(GBA_TEST_LOGO); + +export interface GameBoyRomFixtureOptions { + /** File length; defaults to the declared ROM size. */ + readonly length?: number; + readonly romSizeCode?: number; + readonly ramSizeCode?: number; + readonly cartridgeType?: number; + readonly cgbFlag?: number; + /** Bytes at 0x134..0x143, or 0x134..0x13F when a manufacturer code is set. */ + readonly title?: string; + readonly manufacturerCode?: string; + readonly sgbFlag?: number; + readonly oldLicensee?: number; + readonly newLicensee?: string; + /** Overwrite logo bytes from this index on (0..47) to break the match. */ + readonly breakLogoAt?: number; + /** Store a wrong header checksum. */ + readonly badHeaderChecksum?: boolean; + /** Store a wrong global checksum. */ + readonly badGlobalChecksum?: boolean; +} + +/** A Game Boy image whose header and global checksums match unless told not to. */ +export const gameBoyRom = (options: GameBoyRomFixtureOptions = {}): Buffer => { + const romSizeCode = options.romSizeCode ?? 0x00; + const declared = romSizeCode <= 8 ? 0x8000 << romSizeCode : 0x8000; + const length = options.length ?? declared; + const rom = Buffer.alloc(Math.max(length, 0x150), 0xff); + // NOP; JP 0x0150 + rom.set([0x00, 0xc3, 0x50, 0x01], 0x100); + GAME_BOY_TEST_LOGO.copy(rom, 0x104); + if (options.breakLogoAt !== undefined) + for (let index = options.breakLogoAt; index < 48; index++) + rom.writeUInt8(rom.readUInt8(0x104 + index) ^ 0xff, 0x104 + index); + rom.fill(0, 0x134, 0x144); + rom.write(options.title ?? "REA TEST", 0x134, "latin1"); + if (options.manufacturerCode !== undefined) + rom.write(options.manufacturerCode, 0x13f, "latin1"); + // A DMG title may use 0x143, so the flag is written only when given. + if (options.cgbFlag !== undefined) rom[0x143] = options.cgbFlag; + rom.write(options.newLicensee ?? "01", 0x144, "latin1"); + rom[0x146] = options.sgbFlag ?? 0x00; + rom[0x147] = options.cartridgeType ?? 0x00; + rom[0x148] = romSizeCode; + rom[0x149] = options.ramSizeCode ?? 0x00; + rom[0x14a] = 0x01; + rom[0x14b] = options.oldLicensee ?? 0x33; + rom[0x14c] = 0x02; + for (let offset = 0x150; offset < rom.length; offset++) + rom[offset] = offset & 0xff; + rom[0x14d] = + (gameBoyHeaderChecksum(rom) ^ (options.badHeaderChecksum ? 0x5a : 0)) & + 0xff; + const sum = + addGameBoyGlobalChecksum(0, rom, 0) ^ (options.badGlobalChecksum ? 1 : 0); + rom.writeUInt16BE(sum, 0x14e); + return length < 0x150 ? rom.subarray(0, length) : rom; +}; + +export interface GbaRomFixtureOptions { + readonly length?: number; + /** ARM `B` offset in words from the entry word plus 8. */ + readonly entryWords?: number; + readonly entryWord?: number; + readonly title?: string; + readonly gameCode?: string; + readonly makerCode?: string; + readonly fixedValue?: number; + readonly breakLogo?: boolean; + readonly badComplement?: boolean; + /** Word stored at 0xC0; an ARM `B` by default. */ + readonly ramEntryWord?: number; +} + +/** A GBA image whose complement check matches unless told not to. */ +export const gbaRom = (options: GbaRomFixtureOptions = {}): Buffer => { + const length = options.length ?? 0x1000; + const rom = Buffer.alloc(Math.max(length, 0xe4), 0x00); + rom.writeUInt32LE( + options.entryWord ?? (0xea00_0000 | (options.entryWords ?? 0x2e)) >>> 0, + 0x00, + ); + const logo = Buffer.from(GBA_TEST_LOGO); + if (options.breakLogo) logo.writeUInt8(logo.readUInt8(0) ^ 0xff, 0); + logo.copy(rom, 0x04); + rom.write(options.title ?? "REA TEST", 0xa0, "latin1"); + rom.write(options.gameCode ?? "AREE", 0xac, "latin1"); + rom.write(options.makerCode ?? "01", 0xb0, "latin1"); + rom[0xb2] = options.fixedValue ?? 0x96; + rom[0xbc] = 0x01; + rom[0xbd] = + (gbaComplementCheck(rom) ^ (options.badComplement ? 0x33 : 0)) & 0xff; + rom.writeUInt32LE(options.ramEntryWord ?? 0xea00_0006, 0xc0); + rom[0xc4] = 0x03; + rom[0xc5] = 0x01; + rom.writeUInt32LE(0xea00_0010, 0xe0); + for (let offset = 0xe4; offset < rom.length; offset++) + rom[offset] = offset & 0xff; + return length < 0xe4 ? rom.subarray(0, length) : rom; +}; diff --git a/src/domain/handheldRom.test.ts b/src/domain/handheldRom.test.ts new file mode 100644 index 00000000000..1d58d01e387 --- /dev/null +++ b/src/domain/handheldRom.test.ts @@ -0,0 +1,387 @@ +import { describe, expect, it } from "vitest"; + +import { recognizeArtifactFormat } from "./artifactFormatRecognition.js"; +import { + gameBoyRomMetadataSchema, + gbaRomMetadataSchema, +} from "./formatMetadata/handheldRomMetadata.js"; +import { + addGameBoyGlobalChecksum, + gameBoyHeaderChecksum, + parseGameBoyRom, + registerGameBoyTestLogo, +} from "./gameBoyRomHeader.js"; +import { + armBranchTarget, + gbaComplementCheck, + parseGbaRom, +} from "./gbaRomHeader.js"; +import { gameBoyRom, gbaRom } from "./handheldRom.fixture.js"; + +const parseGb = (rom: Buffer) => + parseGameBoyRom(rom, rom.length, addGameBoyGlobalChecksum(0, rom, 0)); + +const recognize = (bytes: Buffer) => + recognizeArtifactFormat({ + prefix: bytes, + fileSize: bytes.length, + espFlashLayout: false, + }); + +// Hand-derived from the published formulas, independent of the fixtures: +// header x = x - byte - 1 over 0x134..0x14C (25 bytes); global = 16-bit sum +// of every byte but 0x14E and 0x14F; GBA complement = -(sum 0xA0..0xBC) - 0x19. +describe("checksum vectors", () => { + it("computes the Game Boy header checksum over 0x134..0x14C only", () => { + const header = new Uint8Array(0x150); + expect(gameBoyHeaderChecksum(header)).toBe(0xe7); + header[0x134] = 0x41; + expect(gameBoyHeaderChecksum(header)).toBe(0xa6); + // Bytes before 0x134 and from 0x14D on are outside the range. + header[0x133] = 0x55; + header[0x14d] = 0x55; + expect(gameBoyHeaderChecksum(header)).toBe(0xa6); + }); + + it("sums the Game Boy global checksum without its own two bytes", () => { + const rom = new Uint8Array(0x150).fill(0x01); + rom[0x14e] = 0xff; + rom[0x14f] = 0xff; + expect(addGameBoyGlobalChecksum(0, rom, 0)).toBe(0x014e); + // Chunks at their file offsets give the same sum, and the sum wraps. + const large = new Uint8Array(70_000).fill(0xff); + const split = addGameBoyGlobalChecksum( + addGameBoyGlobalChecksum(0, large.subarray(0, 0x14f), 0), + large.subarray(0x14f), + 0x14f, + ); + expect(split).toBe(0x5c92); + expect(addGameBoyGlobalChecksum(0, large, 0)).toBe(0x5c92); + }); + + it("parses a zeroed header whose declared checksum is 0xE7 as a match", () => { + const rom = new Uint8Array(0x8000); + rom[0x14d] = 0xe7; + rom[0x14e] = 0x00; + rom[0x14f] = 0xe7; + expect(parseGameBoyRom(rom, rom.length, 0xe7).metadata).toMatchObject({ + header_checksum: { status: "match", declared: 0xe7, computed: 0xe7 }, + global_checksum: { status: "match", declared: 0x00e7, computed: 0x00e7 }, + }); + }); + + it("computes the GBA complement check over 0xA0..0xBC only", () => { + const header = new Uint8Array(0xc0); + expect(gbaComplementCheck(header)).toBe(0xe7); + header[0xa0] = 0x41; + expect(gbaComplementCheck(header)).toBe(0xa6); + header[0x9f] = 0x55; + header[0xbd] = 0x55; + expect(gbaComplementCheck(header)).toBe(0xa6); + }); +}); + +describe("Game Boy cartridge header", () => { + it("reports every header fact with matching checksums and complete coverage", () => { + const image = parseGb( + gameBoyRom({ + romSizeCode: 0x01, + ramSizeCode: 0x03, + cartridgeType: 0x1b, + cgbFlag: 0x80, + title: "REATEST", + manufacturerCode: "AREJ", + sgbFlag: 0x03, + }), + ); + expect(image.limitations).toEqual([]); + expect(gameBoyRomMetadataSchema.parse(image.metadata)).toEqual({ + kind: "game-boy-rom", + rom_bytes: 0x10000, + entry_hex: "00c35001", + entry_jump_target: 0x150, + nintendo_logo: "match", + title_raw_hex: Buffer.from("REATEST\0\0\0\0AREJ\x80", "latin1").toString( + "hex", + ), + title: "REATEST", + manufacturer_code: "AREJ", + cgb_flag: 0x80, + cgb: "compatible", + sgb_flag: 0x03, + sgb_supported: true, + cartridge_type: 0x1b, + mapper: "mbc5", + features: ["ram", "battery"], + rom_size_code: 0x01, + declared_rom_bytes: 0x10000, + ram_size_code: 0x03, + declared_ram_bytes: 32 * 1024, + destination_code: 0x01, + destination: "overseas", + old_licensee_code: 0x33, + new_licensee_code: "01", + version: 0x02, + header_checksum: { + status: "match", + declared: 0x74, + computed: 0x74, + }, + global_checksum: { + status: "match", + declared: 0x0f2b, + computed: 0x0f2b, + }, + }); + expect( + image.entries.map((entry) => [entry.path, entry.offset, entry.length]), + ).toEqual([ + ["header.bin", 0x100, 0x50], + ["program.bin", 0, 0x10000], + ]); + }); + + it("keeps a sixteen-byte title for a DMG header and flags CGB-only images", () => { + expect( + parseGb(gameBoyRom({ title: "SIXTEEN BYTE TTL" })).metadata, + ).toMatchObject({ + title: "SIXTEEN BYTE TTL", + manufacturer_code: null, + cgb: "none", + }); + expect( + parseGb(gameBoyRom({ cgbFlag: 0xc0, title: "COLOR ONLY" })).metadata, + ).toMatchObject({ + title: "COLOR ONLY", + cgb: "required", + manufacturer_code: null, + }); + }); + + it("reports checksum mismatches as facts, not refusals", () => { + const image = parseGb( + gameBoyRom({ badHeaderChecksum: true, badGlobalChecksum: true }), + ); + expect(image.metadata.header_checksum.status).toBe("mismatch"); + expect(image.metadata.global_checksum.status).toBe("mismatch"); + expect(image.limitations).toEqual([ + expect.stringMatching(/^Declared header checksum 0x[0-9a-f]{2} differs/u), + expect.stringMatching(/^Declared global checksum 0x[0-9a-f]{4} differs/u), + ]); + }); + + it("distinguishes a top-half logo match from a full mismatch", () => { + const topHalf = parseGb(gameBoyRom({ breakLogoAt: 30 })); + expect(topHalf.metadata.nintendo_logo).toBe("top-half"); + expect(topHalf.limitations[0]).toContain("0x11C..0x134"); + expect(parseGb(gameBoyRom({ breakLogoAt: 0 })).metadata.nintendo_logo).toBe( + "mismatch", + ); + }); + + it("names missing and trailing bytes against the declared ROM size", () => { + const short = parseGb(gameBoyRom({ romSizeCode: 0x01, length: 0x9000 })); + expect(short.limitations).toContain( + "The header declares 65536 ROM bytes; the file ends at offset 0x9000, 28672 bytes short.", + ); + const long = parseGb(gameBoyRom({ length: 0x8010 })); + expect(long.limitations).toContain( + "The header declares 32768 ROM bytes; the 16 bytes from offset 0x8000 to the end of the file are outside it.", + ); + }); + + it("leaves undocumented type and size codes unknown", () => { + const image = parseGb( + gameBoyRom({ cartridgeType: 0x04, romSizeCode: 0x55, ramSizeCode: 0x06 }), + ); + expect(image.metadata).toMatchObject({ + mapper: null, + features: [], + declared_rom_bytes: null, + declared_ram_bytes: null, + }); + expect(image.limitations).toHaveLength(3); + }); + + it("reads the documented special ROM sizes, RAM code 0x01 and MBC4 types", () => { + expect(parseGb(gameBoyRom({ romSizeCode: 0x52 })).metadata).toMatchObject({ + declared_rom_bytes: 72 * 16 * 1024, + }); + expect(parseGb(gameBoyRom({ romSizeCode: 0x53 })).metadata).toMatchObject({ + declared_rom_bytes: 80 * 16 * 1024, + }); + expect(parseGb(gameBoyRom({ romSizeCode: 0x54 })).metadata).toMatchObject({ + declared_rom_bytes: 96 * 16 * 1024, + }); + expect(parseGb(gameBoyRom({ ramSizeCode: 0x01 })).metadata).toMatchObject({ + declared_ram_bytes: 2048, + }); + expect(parseGb(gameBoyRom({ cartridgeType: 0x15 })).metadata).toMatchObject( + { mapper: "mbc4", features: [] }, + ); + expect(parseGb(gameBoyRom({ cartridgeType: 0x17 })).metadata).toMatchObject( + { mapper: "mbc4", features: ["ram", "battery"] }, + ); + }); + + it("refuses a header cut short with the offset where the file ends", () => { + const rom = gameBoyRom().subarray(0, 0x140); + expect(() => parseGb(rom)).toThrow( + expect.objectContaining({ + failure: expect.objectContaining({ + kind: "truncated", + format: "game-boy-rom", + offset: 0x140, + }), + }), + ); + expect(recognize(rom)).toMatchObject({ + state: "refused", + format: "game-boy-rom", + reason: expect.stringContaining("file ends at offset 0x140"), + }); + }); + + it("recognizes by the logo and ignores a header without it", () => { + expect(recognize(gameBoyRom())).toMatchObject({ + state: "recognized", + format: "game-boy-rom", + }); + expect(recognize(gameBoyRom({ breakLogoAt: 30 }))).toMatchObject({ + state: "recognized", + format: "game-boy-rom", + }); + expect(recognize(gameBoyRom({ breakLogoAt: 10 }))).toBeUndefined(); + }); + + it("refuses a test logo of the wrong length", () => { + expect(() => registerGameBoyTestLogo(new Uint8Array(47))).toThrow( + "test logo must be 48 bytes", + ); + }); +}); + +describe("Game Boy Advance cartridge header", () => { + it("reports every header fact with a matching complement check", () => { + const image = parseGbaRom(gbaRom(), 0x1000); + expect(image.limitations).toEqual([]); + expect(gbaRomMetadataSchema.parse(image.metadata)).toEqual({ + kind: "gba-rom", + rom_bytes: 0x1000, + entry: { instruction: 0xea00_002e, target_offset: 0xc0 }, + nintendo_logo: "match", + title_raw_hex: Buffer.from("REA TEST\0\0\0\0", "latin1").toString("hex"), + title: "REA TEST", + game_code: "AREE", + maker_code: "01", + fixed_value: 0x96, + unit_code: 0, + device_type: 0, + software_version: 1, + complement_check: { + status: "match", + declared: 0x9a, + computed: 0x9a, + }, + multiboot_layout: "possible", + multiboot: { + ram_entry: { instruction: 0xea00_0006, target_offset: 0xe0 }, + boot_mode: 3, + slave_id: 1, + joybus_entry: { instruction: 0xea00_0010, target_offset: 0x128 }, + }, + }); + expect( + image.entries.map((entry) => [entry.path, entry.offset, entry.length]), + ).toEqual([ + ["header.bin", 0, 0xc0], + ["program.bin", 0, 0x1000], + ]); + }); + + it("reports a logo, complement and fixed-value mismatch as limitations", () => { + const rom = gbaRom({ breakLogo: true, badComplement: true, fixedValue: 0 }); + const image = parseGbaRom(rom, rom.length); + expect(image.metadata).toMatchObject({ + nintendo_logo: "mismatch", + fixed_value: 0, + complement_check: { status: "mismatch" }, + }); + expect(image.limitations).toHaveLength(3); + }); + + it("does not offer the multiboot layout past 256 KiB or without a branch at 0xC0", () => { + const large = gbaRom({ length: 0x4_0004 }); + expect(parseGbaRom(large, large.length).metadata).toMatchObject({ + multiboot_layout: "not-applicable", + multiboot: null, + }); + const code = gbaRom({ ramEntryWord: 0xe3a0_0000 }); + expect(parseGbaRom(code, code.length).metadata.multiboot).toBeNull(); + }); + + it("keeps multiboot fields past the end of the file unknown", () => { + const rom = gbaRom().subarray(0, 0xc5); + const image = parseGbaRom(rom, rom.length); + expect(image.metadata.multiboot).toEqual({ + ram_entry: { instruction: 0xea00_0006, target_offset: 0xe0 }, + boot_mode: 0x03, + slave_id: null, + joybus_entry: null, + }); + expect(image.limitations).toEqual([ + "The multiboot fields run to 0xe4; the file ends at offset 0xc5, so the fields past it are unknown.", + ]); + const shorter = gbaRom().subarray(0, 0xc4); + expect( + parseGbaRom(shorter, shorter.length).metadata.multiboot, + ).toMatchObject({ boot_mode: null, slave_id: null }); + }); + + it("decodes backward branches and leaves a non-branch entry unknown", () => { + expect(armBranchTarget(0xeaff_fffe, 0xc0)).toBe(0xc0); + expect(armBranchTarget(0xe1a0_0000, 0)).toBeNull(); + const rom = gbaRom({ entryWord: 0xe1a0_0000 }); + const image = parseGbaRom(rom, rom.length); + expect(image.metadata.entry.target_offset).toBeNull(); + expect(image.limitations[0]).toContain("not an ARM branch"); + }); + + it("refuses a header cut short with the offset where the file ends", () => { + const rom = gbaRom().subarray(0, 0xb0); + expect(() => parseGbaRom(rom, rom.length)).toThrow( + expect.objectContaining({ + failure: expect.objectContaining({ + kind: "truncated", + format: "gba-rom", + offset: 0xb0, + }), + }), + ); + expect(recognize(rom)).toBeUndefined(); + // Once the fixed value at 0xB2 can be checked, a header cut short is + // refused with the offset where the file ends, as for Game Boy. + const checkable = gbaRom().subarray(0, 0xb8); + expect(recognize(checkable)).toMatchObject({ + state: "refused", + format: "gba-rom", + reason: expect.stringContaining("file ends at offset 0xb8"), + }); + }); + + it("recognizes by the logo or the complement check, with the fixed value", () => { + for (const rom of [ + gbaRom(), + gbaRom({ breakLogo: true }), + gbaRom({ badComplement: true }), + ]) + expect(recognize(rom)).toMatchObject({ + state: "recognized", + format: "gba-rom", + }); + expect( + recognize(gbaRom({ breakLogo: true, badComplement: true })), + ).toBeUndefined(); + expect(recognize(gbaRom({ fixedValue: 0x95 }))).toBeUndefined(); + }); +}); diff --git a/src/domain/native/peOverlay.ts b/src/domain/native/peOverlay.ts index 855aeb8674b..25477430621 100644 --- a/src/domain/native/peOverlay.ts +++ b/src/domain/native/peOverlay.ts @@ -72,6 +72,8 @@ export const peOverlaySectionBudgetLimitation = (declared: number): string => export const PE_OVERLAY_LEADING_FORMATS = [ "unrecognized", "ines", + "game-boy-rom", + "gba-rom", "nds", "mega-drive-rom", "n64-rom", diff --git a/src/domain/targetFormats.ts b/src/domain/targetFormats.ts index 6c8a962298c..ee25ac9b869 100644 --- a/src/domain/targetFormats.ts +++ b/src/domain/targetFormats.ts @@ -19,6 +19,8 @@ export const BINARY_TARGET_FORMAT_KINDS = { ) as Record), asar: "archive", ines: "archive", + "game-boy-rom": "archive", + "gba-rom": "archive", nds: "archive", "mega-drive-rom": "archive", "n64-rom": "archive", diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index e9324f8a24b..a7300aefb64 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -264,6 +264,8 @@ export interface ArtifactReader { | ZipPackageFormat | "asar" | "ines" + | "game-boy-rom" + | "gba-rom" | "nds" | "mega-drive-rom" | "n64-rom" diff --git a/tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts b/tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts index 651a90b39b6..076427ee1cc 100644 --- a/tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts +++ b/tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts @@ -8,6 +8,10 @@ import { expect, it } from "vitest"; import { im4p } from "../../../../src/domain/apple/image4.fixture.js"; import { bfltFile } from "../../../../src/domain/bfltExecutable.fixture.js"; +import { + gameBoyRom, + gbaRom, +} from "../../../../src/domain/handheldRom.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"; @@ -331,6 +335,50 @@ it("inventories a Nintendo 64 ROM in any byte order as n64-rom", async () => { }); }); +it.each([ + { + name: "game.gbc", + bytes: () => gameBoyRom({ cgbFlag: 0x80, badGlobalChecksum: true }), + format: "game-boy-rom", + root: { + kind: "game-boy-rom", + cgb: "compatible", + global_checksum: { status: "mismatch" }, + }, + entry: { kind: "game-boy-rom-entry", role: "program" }, + }, + { + name: "game.gba", + bytes: () => gbaRom(), + format: "gba-rom", + root: { kind: "gba-rom", complement_check: { status: "match" } }, + entry: { kind: "gba-rom-entry", role: "program" }, + }, +])("inventories $name as $format without executing it", async (row) => { + const directory = await createTestTempDirectory("rea-handheld-rom-"); + const path = await writeBytes(row.name, row.bytes)(directory); + const evidence = parseEvidence( + await runProviderAnalysis(path, "inspect_artifact", {}).then( + projectCliAnalysisResult, + ), + ); + const inspection = artifactInspectionResultSchema.parse( + evidence.normalized_result, + ); + + expect(inspection.subject.root_format).toBe(row.format); + const inventory = inspection.substeps[0]?.evidence.normalized_result; + expect( + inventory?.occurrences.find((occurrence) => occurrence.logical_path === ".") + ?.format_metadata, + ).toMatchObject(row.root); + expect( + inventory?.occurrences.find( + (occurrence) => occurrence.logical_path === "program.bin", + )?.format_metadata, + ).toMatchObject(row.entry); +}); + it("routes a bFLT executable's text segment to open_binary", async () => { const directory = await createTestTempDirectory("rea-standalone-format-"); const path = await writeBytes("app.flt", () =>