MikroAss.java

package libsidplay.components.cart.supported;

import libsidplay.components.cart.Cartridge;
import libsidplay.components.pla.Bank;
import libsidplay.components.pla.PLA;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;

/**
 * CRT 28, Mikro Assembler: one 8 KiB ROM at $8000-$9FFF, with its last
 * two pages mirrored at $DE00-$DFFF. All cartridge writes are passive.
 * Reference: VICE vice/src/c64/cart/mikroass.c.
 */
public class MikroAss extends Cartridge {
    protected final byte[] romL = new byte[0x2000];

    public MikroAss(final DataInputStream input, final PLA pla) throws IOException {
        super(pla);
        byte[] header = new byte[16];
        int records = 0;
        for (;;) {
            int count = readChipHeader(input, header);
            if (count == 0) break;
            if (count != header.length) throw new EOFException("Truncated Mikro Assembler CHIP header");
            if (header[0] != 'C' || header[1] != 'H' || header[2] != 'I' || header[3] != 'P') {
                throw new IOException("Invalid Mikro Assembler CHIP signature");
            }
            if (++records > 1) throw new IOException("Too many Mikro Assembler CHIP records");
            long length = (long) u16(header, 4) << 16 | u16(header, 6);
            int type = u16(header, 8), bank = u16(header, 10), size = u16(header, 14);
            // Load-address metadata cannot change the physical ROM decoder.
            if (length < header.length + (long) size || (type != 0 && type != 2)
                    || bank != 0 || size != romL.length) {
                throw new IOException("Invalid Mikro Assembler CHIP record");
            }
            try {
                input.readFully(romL);
            } catch (EOFException e) {
                throw new EOFException("Truncated Mikro Assembler CHIP payload");
            }
            skipFully(input, length - header.length - size, "Truncated Mikro Assembler CHIP padding");
        }
        if (records != 1) throw new IOException("Mikro Assembler requires one CHIP record");
    }

    private static int u16(byte[] bytes, int offset) {
        return (bytes[offset] & 255) << 8 | bytes[offset + 1] & 255;
    }

    // Masking the CPU address also selects the correct $9E/$9F page in I/O space.
    private final Bank romBank = new Bank() {
        @Override public byte read(int address) { return romL[address & 0x1fff]; }
        @Override public void write(int address, byte value) { }
    };

    @Override public void reset() {
        super.reset();
        pla.setGameExrom(true, false);
    }

    @Override public void onDetach() { pla.setGameExrom(true, true); }
    @Override public Bank getRoml() { return romBank; }
    @Override public Bank getIO1() { return romBank; }
    @Override public Bank getIO2() { return romBank; }
    @Override public String toString() { return "Mikro Assembler"; }
}