systemless 0.37.0

High-Level Emulation for classic Macintosh applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! CPU backend built on the [`m68k`] crate.
//!
//! [`M68kCpu`] initializes the canonical guest CPU model and exposes both
//! precise single-instruction stepping and JIT-enabled native batch execution.
//! WebAssembly builds retain the same batch API through m68k's portable trace
//! executor.

use crate::memory::MacMemoryBus;

pub use m68k::HleHandler;

/// 68k CPU register identifiers: eight data registers (D0–D7), eight
/// address registers (A0–A7, with A7 selecting the active stack pointer),
/// and the program counter.
#[derive(Debug, Clone, Copy)]
pub enum Register {
    D0,
    D1,
    D2,
    D3,
    D4,
    D5,
    D6,
    D7,
    A0,
    A1,
    A2,
    A3,
    A4,
    A5,
    A6,
    A7,
    PC,
}

/// Outcome of a single 68k instruction step. Returned by
/// [`FixtureRunner::step`](crate::runner::FixtureRunner::step).
pub enum StepResult {
    /// The instruction completed normally and execution may continue.
    Ok,
    /// The CPU executed `STOP`, or the wrapper normalized an unsupported
    /// terminal condition to a stopped result.
    Stopped,
    /// The instruction was an A-line trap; the carried value is the trap word
    /// for the dispatcher.
    Aline(u16),
    /// The instruction was an unhandled F-line opcode. The runner decides
    /// whether the active profile handles it or delegates through vector 11.
    Fline(u16),
}

/// Classic task state beyond the integer registers exposed by [`CpuOps`].
///
/// Inside Macintosh: Thread Manager (1999), p. 15, Table 1-1 requires the
/// full SR, floating-point registers and FPU frame. Raw extended-precision
/// values preserve NaN payloads and values that cannot round-trip through f64.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct M68kExtendedContext {
    /// Full status register, including CCR and stack-bank selection.
    pub sr: u16,
    /// FP0 through FP7 in the backend's exact 80-bit representation.
    pub fpr: [m68k::fpu::FloatX80; 8],
    /// Floating-point control register.
    pub fpcr: u32,
    /// Floating-point status register.
    pub fpsr: u32,
    /// Floating-point instruction address register.
    pub fpiar: u32,
    /// Distinguishes the backend's null and idle FSAVE frames.
    pub fpu_just_reset: bool,
}

/// Register interface used by the trap dispatcher.
///
/// Keeping handlers generic over this subset lets them operate on both the
/// production [`M68kCpu`] backend and test doubles without exposing the full
/// m68k architectural state.
pub trait CpuOps {
    /// Read the current value of a single register.
    fn read_reg(&self, reg: Register) -> u32;
    /// Write a value into a single register.
    fn write_reg(&mut self, reg: Register, value: u32);
    /// Read the condition code register (CCR) byte.
    fn get_ccr(&self) -> u8;
    /// Set the condition code register (CCR).
    ///
    /// The low five bits are X(4), N(3), Z(2), V(1), and C(0).
    fn set_ccr(&mut self, ccr: u8);

    /// Capture additional architectural task state when this adapter has it.
    /// Register-only adapters retain their existing integer/CCR behavior.
    fn capture_extended_context(&self) -> Option<M68kExtendedContext> {
        None
    }

    /// Restore state captured by this adapter before installing A7: restoring
    /// SR can change the selected stack bank. Register-only adapters have no
    /// additional state; backends returning `Some` must implement this method.
    fn restore_extended_context(&mut self, _context: &M68kExtendedContext) {}
}

/// Systemless wrapper around [`m68k::CpuCore`].
///
/// Construction selects the CPU type from
/// [`crate::machine_profile::REFERENCE_MACHINE_PROFILE`]. Callers with a
/// specialized embedding may subsequently reconfigure the public core.
#[derive(Debug)]
pub struct M68kCpu {
    /// Complete m68k CPU state and execution API.
    ///
    /// This is public for diagnostics and specialized embedding beyond the
    /// register-only [`CpuOps`] interface.
    pub core: m68k::CpuCore,
}

impl M68kCpu {
    /// Create a CPU configured for the canonical Systemless machine profile.
    pub fn new() -> Self {
        let mut core = m68k::CpuCore::new();
        core.set_cpu_type(crate::machine_profile::REFERENCE_MACHINE_PROFILE.cpu_type());
        Self { core }
    }

    /// Read one data, address, or program-counter register.
    #[inline]
    pub fn read_reg(&self, reg: Register) -> u32 {
        match reg {
            Register::D0 => self.core.d(0),
            Register::D1 => self.core.d(1),
            Register::D2 => self.core.d(2),
            Register::D3 => self.core.d(3),
            Register::D4 => self.core.d(4),
            Register::D5 => self.core.d(5),
            Register::D6 => self.core.d(6),
            Register::D7 => self.core.d(7),
            Register::A0 => self.core.a(0),
            Register::A1 => self.core.a(1),
            Register::A2 => self.core.a(2),
            Register::A3 => self.core.a(3),
            Register::A4 => self.core.a(4),
            Register::A5 => self.core.a(5),
            Register::A6 => self.core.a(6),
            Register::A7 => self.core.a(7),
            Register::PC => self.core.pc,
        }
    }

    /// Write one data, address, or program-counter register.
    #[inline]
    pub fn write_reg(&mut self, reg: Register, value: u32) {
        match reg {
            Register::D0 => self.core.set_d(0, value),
            Register::D1 => self.core.set_d(1, value),
            Register::D2 => self.core.set_d(2, value),
            Register::D3 => self.core.set_d(3, value),
            Register::D4 => self.core.set_d(4, value),
            Register::D5 => self.core.set_d(5, value),
            Register::D6 => self.core.set_d(6, value),
            Register::D7 => self.core.set_d(7, value),
            Register::A0 => self.core.set_a(0, value),
            Register::A1 => self.core.set_a(1, value),
            Register::A2 => self.core.set_a(2, value),
            Register::A3 => self.core.set_a(3, value),
            Register::A4 => self.core.set_a(4, value),
            Register::A5 => self.core.set_a(5, value),
            Register::A6 => self.core.set_a(6, value),
            Register::A7 => self.core.set_a(7, value),
            Register::PC => self.core.pc = value,
        }
    }

    /// Return whether the CPU is stopped by a `STOP` instruction.
    #[inline]
    pub fn is_stopped(&self) -> bool {
        self.core.is_stopped()
    }

    /// Reset the CPU from the initial stack-pointer and program-counter vectors.
    pub fn reset(&mut self, bus: &mut MacMemoryBus) {
        self.core.reset(bus);
    }

    /// Execute at most `max_instructions` through m68k's throughput path.
    ///
    /// Native builds enable Cranelift compilation for eligible hot traces;
    /// WebAssembly executes the same traces through the portable executor.
    /// Execution returns on the first event the runner must handle: a trap,
    /// stopped CPU, watched PC, or exhausted instruction budget.
    ///
    /// See [`m68k::CpuCore::run_batch`] for the exit/accounting
    /// contract; the trapping instruction is *not* included in
    /// `instructions` and `core.ppc` holds its address.
    #[inline]
    pub fn run_batch(
        &mut self,
        bus: &mut MacMemoryBus,
        max_instructions: u32,
        watch_pcs: &[u32],
    ) -> m68k::BatchResult {
        self.core.run_batch(bus, max_instructions, watch_pcs)
    }

    /// Execute one instruction through m68k's precise stepping path.
    ///
    /// Systemless surfaces completed instructions, A-line traps, and STOP
    /// directly. Illegal instructions, `TRAP`, and `BKPT` exits are reported
    /// and converted to [`StepResult::Stopped`].
    #[inline]
    pub fn step(&mut self, bus: &mut MacMemoryBus) -> StepResult {
        match self.core.step(bus) {
            m68k::StepResult::Ok { .. } => StepResult::Ok,
            m68k::StepResult::AlineTrap { opcode } => StepResult::Aline(opcode),
            m68k::StepResult::FlineTrap { opcode } => StepResult::Fline(opcode),
            m68k::StepResult::Stopped => {
                eprintln!("[CPU] StepResult::Stopped");
                StepResult::Stopped
            }
            m68k::StepResult::IllegalInstruction { opcode } => {
                eprintln!(
                    "[CPU] IllegalInstruction: ${:04X} at PC=${:08X}",
                    opcode, self.core.pc
                );
                StepResult::Stopped
            }
            m68k::StepResult::TrapInstruction { trap_num } => {
                eprintln!("[CPU] TrapInstruction: #{}", trap_num);
                StepResult::Stopped
            }
            m68k::StepResult::Breakpoint { bp_num } => {
                eprintln!("[CPU] Breakpoint: #{}", bp_num);
                StepResult::Stopped
            }
        }
    }
}

impl Default for M68kCpu {
    fn default() -> Self {
        Self::new()
    }
}

impl CpuOps for M68kCpu {
    #[inline]
    fn read_reg(&self, reg: Register) -> u32 {
        M68kCpu::read_reg(self, reg)
    }
    #[inline]
    fn write_reg(&mut self, reg: Register, value: u32) {
        M68kCpu::write_reg(self, reg, value)
    }
    #[inline]
    fn get_ccr(&self) -> u8 {
        self.core.get_ccr()
    }
    #[inline]
    fn set_ccr(&mut self, ccr: u8) {
        self.core.set_ccr(ccr);
    }

    fn capture_extended_context(&self) -> Option<M68kExtendedContext> {
        Some(M68kExtendedContext {
            sr: self.core.get_sr(),
            fpr: self.core.fpr,
            fpcr: self.core.fpcr,
            fpsr: self.core.fpsr,
            fpiar: self.core.fpiar,
            fpu_just_reset: self.core.fpu_just_reset,
        })
    }

    fn restore_extended_context(&mut self, context: &M68kExtendedContext) {
        self.core.set_sr(context.sr);
        self.core.fpr = context.fpr;
        self.core.fpcr = context.fpcr;
        self.core.fpsr = context.fpsr;
        self.core.fpiar = context.fpiar;
        self.core.fpu_just_reset = context.fpu_just_reset;
    }
}

#[cfg(test)]
mod tests {
    use super::{M68kCpu, Register, StepResult};
    use crate::memory::{MacMemoryBus, MemoryBus};

    #[test]
    fn custom_zero_divide_handler_receives_68020_format_two_frame() {
        let mut cpu = M68kCpu::new();
        let mut bus = MacMemoryBus::new(0x400000);
        let prog = 0x0010_0000;
        let handler = 0x0010_0100;
        let initial_sp = 0x003F_FFC0;

        // DIVSL.L D1,D2:D0; NOP
        bus.write_word(prog, 0x4C41);
        bus.write_word(prog + 2, 0x0C02);
        bus.write_word(prog + 4, 0x4E71);
        bus.write_long(0x0014, handler);

        // A classic format-2 skip handler: discard SR/PC/format, advance
        // the saved instruction address by the four-byte DIVSL, then RTS.
        bus.write_word(handler, 0x508F); // ADDQ.L #8,A7
        bus.write_word(handler + 2, 0x5897); // ADDQ.L #4,(A7)
        bus.write_word(handler + 4, 0x4E75); // RTS

        cpu.write_reg(Register::PC, prog);
        cpu.write_reg(Register::A7, initial_sp);
        cpu.write_reg(Register::D0, 100);
        cpu.write_reg(Register::D1, 0);
        cpu.write_reg(Register::D2, 0);

        let first = cpu.run_batch(&mut bus, 1, &[]);
        assert_eq!(first.instructions, 1);
        assert_eq!(cpu.read_reg(Register::PC), handler);

        let second = cpu.run_batch(&mut bus, 4, &[]);
        assert_eq!(second.instructions, 4);
        assert_eq!(cpu.read_reg(Register::PC), prog + 6);
        assert_eq!(cpu.read_reg(Register::A7), initial_sp);
    }

    #[test]
    fn cmp_word_address_indirect_sets_lt_and_branches() {
        let mut cpu = M68kCpu::new();
        let mut bus = MacMemoryBus::new(0x400000);

        cpu.write_reg(Register::PC, 0x001000);
        cpu.write_reg(Register::A2, 0x002000);
        cpu.write_reg(Register::D1, 56);

        // CMP.W (A2),D1 ; BLT +2 ; NOP ; NOP(target)
        bus.write_word(0x001000, 0xB252);
        bus.write_word(0x001002, 0x6D02);
        bus.write_word(0x001004, 0x4E71);
        bus.write_word(0x001006, 0x4E71);
        bus.write_word(0x002000, 202);

        match cpu.step(&mut bus) {
            StepResult::Ok => {}
            _ => panic!("CMP.W should execute normally"),
        }
        assert_eq!(
            cpu.core.get_ccr() & 0x0F,
            0x09,
            "CMP.W 56 - 202 should set N and C for a signed less-than result"
        );

        match cpu.step(&mut bus) {
            StepResult::Ok => {}
            _ => panic!("BLT should execute normally"),
        }
        assert_eq!(
            cpu.read_reg(Register::PC),
            0x001006,
            "BLT should branch when D1 is less than the word at (A2)"
        );
    }

    #[test]
    fn precise_step_preserves_the_complete_fline_word_for_vector_routing() {
        let mut cpu = M68kCpu::new();
        let mut bus = MacMemoryBus::new(0x400000);
        cpu.write_reg(Register::PC, 0x001000);
        bus.write_word(0x001000, 0xF000);

        assert!(matches!(cpu.step(&mut bus), StepResult::Fline(0xF000)));
        assert_eq!(cpu.core.ppc, 0x001000);
    }

    #[test]
    fn addq_cmp_blt_loop_reaches_count_limit() {
        let mut cpu = M68kCpu::new();
        let mut bus = MacMemoryBus::new(0x400000);
        let base = 0x003000u32;
        let count_ptr = 0x002000u32;

        cpu.write_reg(Register::PC, 0x001000);
        cpu.write_reg(Register::A2, count_ptr);
        cpu.write_reg(Register::A4, base);

        // CLR.W D1
        // loop: ADDQ.W #1,D1 ; ADDQ.W #6,A4 ; CMP.W (A2),D1 ; BLT.S loop
        // MOVE.L A4,A0
        bus.write_word(0x001000, 0x4241);
        bus.write_word(0x001002, 0x5241);
        bus.write_word(0x001004, 0x5C4C);
        bus.write_word(0x001006, 0xB252);
        bus.write_word(0x001008, 0x6DF8);
        bus.write_word(0x00100A, 0x204C);
        bus.write_word(count_ptr, 202);

        for _ in 0..1000 {
            match cpu.step(&mut bus) {
                StepResult::Ok => {}
                _ => panic!("loop program should execute normally"),
            }
            if cpu.read_reg(Register::PC) == 0x00100C {
                break;
            }
        }

        assert_eq!(cpu.read_reg(Register::D1) & 0xFFFF, 202);
        assert_eq!(
            cpu.read_reg(Register::A4),
            base + 202 * 6,
            "A4 should advance by six bytes for every loop iteration until D1 reaches count"
        );
        assert_eq!(cpu.read_reg(Register::A0), base + 202 * 6);
    }
}