// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); const bus_log = @import("bus.zig"); const Options = bus_log.Options; const memory_size = std.math.maxInt(u16) + 1; /// Which addresses are read-only. /// /// Hand rolled rather than std.StaticBitSet, whose isSet takes the set by /// value. At sixty-four thousand bits that is eight kilobytes, so testing one /// bit copied the whole set, and every write tests one bit. It was a quarter /// of the emulator's running time. const ReadOnly = struct { const word_bits = @bitSizeOf(usize); const words = memory_size / word_bits; masks: [words]usize = @splat(0), fn isSet(self: *const ReadOnly, address: u16) bool { return self.masks[address / word_bits] & bit(address) != 0; } fn setRange(self: *ReadOnly, start: usize, end: usize) void { for (start..end) |address| { self.masks[address / word_bits] |= bit(@intCast(address)); } } fn clear(self: *ReadOnly) void { self.masks = @splat(0); } inline fn bit(address: u16) usize { return @as(usize, 1) << @intCast(address % word_bits); } }; /// Sixty-four kilobytes of RAM and nothing else: every address is what it /// says it is, and stays that way. This is the memory a bare 6502 sees, and /// the only model the SingleStepTests corpus can run against, since it uses /// the whole address space as ordinary memory including the page a real /// machine would fill with I/O. /// /// A memory model is generic over the CPU it belongs to so that it can find /// its way back for the clock, and must offer init, reset, peek, poke, read /// and write, along with an Access type and the bus log that goes with it. /// Machines with banking or memory mapped devices go alongside this rather /// than inside it. pub fn Flat(comptime options: Options) fn (type) type { return struct { fn model(comptime CPU: type) type { return struct { const Self = @This(); pub const Access = bus_log.Access; bus: bus_log.Log(options.bus_log) = .{}, size: usize, memory: [memory_size]u8 = undefined, read_only: ReadOnly, /// The CPU this belongs to, recovered from the field it is embedded in. inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("memory", self)); } /// Appends an access to the bus log, dropping it if the log is full. /// Zeroes all of memory and marks all of it writable. pub fn init(self: *Self, size: ?usize) void { self.* = .{ .size = size orelse memory_size, .memory = [_]u8{0} ** memory_size, .read_only = .{}, }; } /// What the reset line does to sixty-four kilobytes of nothing but /// RAM, which is nothing at all. /// /// There are no switches here to put back, and memory itself is not /// something a reset touches: RAM keeps what it held, which is the /// whole reason a machine can be reset and carry on rather than /// starting from nothing. Clearing it out is what init is for. pub fn reset(self: *Self) void { _ = self; } /// Copies a program in and marks that range read-only, so writes to it /// are driven onto the bus but never stored. pub fn loadROM(self: *Self, location: u16, program: []const u8) !void { const start: usize = @intCast(location); const end: usize = start + program.len; if (end > self.memory.len) return error.Overflow; @memcpy(self.memory[start..end], program); self.read_only.setRange(start, end); } /// Loads a ROM so that its last byte sits at $ffff, which is where a /// 6502 expects to find its vectors. pub fn loadROMAtEnd(self: *Self, program: []const u8) !void { // An image larger than the address space keeps its tail, as the // machine models do. Truncating the start address instead, which // is what this did, wrapped it somewhere arbitrary. const tail = if (program.len > memory_size) program[program.len - memory_size ..] else program; try self.loadROM(@truncate(memory_size - tail.len), tail); } /// Copies a program in and leaves it writable. pub fn loadProgram(self: *Self, location: u16, program: []const u8) !void { const start: usize = @intCast(location); const end: usize = start + program.len; if (end > self.memory.len) return error.Overflow; @memcpy(self.memory[start..end], program); } /// Reads a byte without the processor being involved: no cycle is /// spent, nothing is written to the bus log, and a memory mapped /// device would not notice. For debuggers and tests, which want to /// look at memory without disturbing the machine they are looking at. pub fn peek(self: *const Self, address: u16) u8 { return self.memory[address]; } /// Writes a byte without the processor being involved, as `peek`. It /// ignores the read-only mask, because the point of it is to put a /// machine into a state rather than to be one. pub fn poke(self: *Self, address: u16, value: u8) void { self.memory[address] = value; } /// Reads memory, spending a cycle per byte and logging each one. A word /// is read low byte first. pub fn read(self: *Self, comptime T: type, offset: u16) T { const cpu = self.getCPU(); const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { cpu.clock.sleep(1); self.bus.record(offset, self.memory[offset], .read); return self.memory[offset]; }, 16 => { const low = self.read(u8, offset); const high = self.read(u8, offset +% 1); return @as(u16, high) << 8 | low; }, else => @compileError("must be a u8 or a u16"), } } /// Writes memory, spending a cycle per byte and logging each one. A /// word is written low byte first. pub fn write(self: *Self, comptime T: type, offset: u16, value: T) void { const cpu = self.getCPU(); const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { cpu.clock.sleep(1); self.bus.record(offset, value, .write); // The processor drives the write cycle whether or not // anything is listening, and ROM simply declines to latch // it. So the cycle is spent and the bus carries the access // either way; only the store is skipped. if (self.read_only.isSet(offset)) return; self.memory[offset] = value; }, 16 => { self.write(u8, offset, @truncate(value)); self.write(u8, offset +% 1, @truncate(value >> 8)); }, else => @compileError("must be a u8 or a u16"), } } }; } }.model; } test "readByte" { const CPU = @import("../cpu8.zig").Bare; var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); cpu.memory.poke(0x0100, 0x69); try std.testing.expectEqual(@as(u8, 0x69), cpu.memory.read(u8, 0x0100)); try std.testing.expectEqual(@as(usize, 1), cpu.clock.cycles); } test "writeByte to ROM spends the cycle without storing" { // With the log on, since the point is that the write reaches the bus even // though it reaches no memory. const CPU = @import("../cpu8.zig").CPU( @import("../clock.zig").FakeClock, Flat(.{ .bus_log = true }), ); var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadROM(0x0100, &[_]u8{0x42}); cpu.memory.write(u8, 0x0100, 0x69); try std.testing.expectEqual(@as(u8, 0x42), cpu.memory.peek(0x0100)); try std.testing.expectEqual(@as(usize, 1), cpu.clock.cycles); try std.testing.expectEqual(@as(usize, 1), cpu.memory.bus.len); try std.testing.expectEqual(@as(u16, 0x0100), cpu.memory.bus.entries[0].address); try std.testing.expectEqual(CPU.Memory.Access.Direction.write, cpu.memory.bus.entries[0].direction); } test "writeWord" { const CPU = @import("../cpu8.zig").Bare; var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); cpu.memory.write(u16, 0x0100, 0x1234); try std.testing.expectEqual(@as(u8, 0x34), cpu.memory.peek(0x0100)); try std.testing.expectEqual(@as(u8, 0x12), cpu.memory.peek(0x0101)); try std.testing.expectEqual(@as(usize, 2), cpu.clock.cycles); } test "writeByte" { const CPU = @import("../cpu8.zig").Bare; var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); cpu.memory.write(u8, 0x0100, 0x69); try std.testing.expectEqual(@as(u8, 0x69), cpu.memory.peek(0x0100)); try std.testing.expectEqual(@as(usize, 1), cpu.clock.cycles); }