checksmix 0.3.13

A simplified MMIX simulator - Donald Knuth's hypothetical computer for teaching and learning assembly language programming.
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! `TrapCode`, `FileHandle`, and the TRAP #0-#82 handlers behind them.

use super::MMix;
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use tracing::debug;

/// TRAP code identifiers for MMIX, numbered per the MMIXAL reference: every
/// call is `TRAP 0,Code,Handle`, `Z` names the handle (0-255), and `$255`
/// carries any further argument (an address, for a call that takes two).
/// `Fputc`, `Time` and `Debug` are checksmix's own extensions, given codes
/// (`#80`-`#82`) well above the reference's range so an old binary's codes
/// 11-13 reach the unhandled-TRAP diagnostic rather than the wrong call.
///
/// More trap codes may be added in future releases, so downstream matches
/// must carry a wildcard arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum TrapCode {
    Halt = 0,
    Fopen = 1,
    Fclose = 2,
    Fread = 3,
    Fgets = 4,
    Fgetws = 5,
    Fwrite = 6,
    Fputs = 7,
    Fputws = 8,
    Fseek = 9,
    Ftell = 10,
    Fputc = 0x80,
    Time = 0x81,
    Debug = 0x82,
}

impl TrapCode {
    /// Convert a u8 to a TrapCode variant
    pub fn from_u8(n: u8) -> Option<Self> {
        match n {
            0 => Some(TrapCode::Halt),
            1 => Some(TrapCode::Fopen),
            2 => Some(TrapCode::Fclose),
            3 => Some(TrapCode::Fread),
            4 => Some(TrapCode::Fgets),
            5 => Some(TrapCode::Fgetws),
            6 => Some(TrapCode::Fwrite),
            7 => Some(TrapCode::Fputs),
            8 => Some(TrapCode::Fputws),
            9 => Some(TrapCode::Fseek),
            10 => Some(TrapCode::Ftell),
            0x80 => Some(TrapCode::Fputc),
            0x81 => Some(TrapCode::Time),
            0x82 => Some(TrapCode::Debug),
            _ => None,
        }
    }
}

/// One of `checksmix`'s open TRAP handles. Handles 0-2 are the standard
/// streams: no backing `File` (`Fclose`d reads and writes for them route
/// through the installed [`Host`]) and fixed capabilities. Handles 3-255 are
/// whatever `Fopen`'s mode granted.
///
/// `read`, `write` and `seek` gate `Fread`/`Fgets`/`Fgetws`,
/// `Fwrite`/`Fputs`/`Fputc`/`Fputws`, and `Fseek`/`Ftell` respectively.
/// `read_write` marks a handle opened `BinaryReadWrite`: on such a handle a
/// read clears `write` and a write clears `read`, and `Fseek` restores both
/// — the reference's read-write switching rule. A handle opened
/// `BinaryRead`/`BinaryWrite` carries `seek` without `read_write`, so its
/// single capability never toggles.
pub(super) struct FileHandle {
    pub(super) file: Option<File>,
    pub(super) read: bool,
    pub(super) write: bool,
    pub(super) seek: bool,
    pub(super) read_write: bool,
}

impl MMix {
    /// Handle TRAP system calls
    /// Returns true if execution should continue, false if halted
    pub(super) fn handle_trap(&mut self, trap_code: TrapCode, arg: u8) -> bool {
        let arg255 = self.get_register(255);
        let result = match trap_code {
            TrapCode::Halt => self.handle_halt(arg),
            TrapCode::Fopen => self.handle_fopen(arg),
            TrapCode::Fclose => self.handle_fclose(arg),
            TrapCode::Fread => self.handle_fread(arg),
            TrapCode::Fgets => self.handle_fgets(arg),
            TrapCode::Fgetws => self.handle_fgetws(arg),
            TrapCode::Fwrite => self.handle_fwrite(arg),
            TrapCode::Fputs => self.handle_fputs(arg),
            TrapCode::Fputc => self.handle_fputc(arg),
            TrapCode::Fputws => self.handle_fputws(arg),
            TrapCode::Fseek => self.handle_fseek(arg),
            TrapCode::Ftell => self.handle_ftell(arg),
            TrapCode::Time => self.handle_time(arg),
            TrapCode::Debug => self.handle_debug(arg),
        };
        let result255 = self.get_register(255);
        self.host.trap(trap_code, arg, arg255, result255);
        result
    }

    /// TRAP 0: Halt - stop execution
    /// Parameter in $255: exit code (though typically ignored, could use Z parameter)
    fn handle_halt(&mut self, _arg: u8) -> bool {
        debug!("TRAP: Halt");
        let exit_code = self.get_register(255);
        self.exit_code = exit_code;
        // Halt is the machine's last chance to signal the host: the caller
        // exits without running destructors, so buffered output from earlier
        // Fputs/Fputc/Fputws calls would otherwise be discarded.
        self.host.flush();
        self.host.diagnostic(&format!(
            "HALT trap at PC={:#018x}, exit code={}",
            self.pc, exit_code
        ));
        self.advance_pc();
        false
    }

    /// Whether `handle` is open and grants read access.
    fn handle_readable(&self, handle: u8) -> bool {
        self.file_handles.get(&handle).is_some_and(|h| h.read)
    }

    /// Whether `handle` is open and grants write access.
    fn handle_writable(&self, handle: u8) -> bool {
        self.file_handles.get(&handle).is_some_and(|h| h.write)
    }

    /// Whether `handle` is open and grants seek access.
    fn handle_seekable(&self, handle: u8) -> bool {
        self.file_handles.get(&handle).is_some_and(|h| h.seek)
    }

    /// Fails a TRAP whose precondition `ok` does not hold: stores `failure`
    /// in `$255`, advances the PC, and reports `true` so the caller returns
    /// immediately. `false` when `ok` holds and the call proceeds.
    fn fail_unless(&mut self, ok: bool, failure: i64) -> bool {
        if !ok {
            self.set_register(255, failure as u64);
            self.advance_pc();
        }
        !ok
    }

    /// A read on a `BinaryReadWrite` handle clears its write capability
    /// until `Fseek` restores both.
    fn note_read(&mut self, handle: u8) {
        if let Some(entry) = self.file_handles.get_mut(&handle)
            && entry.read_write
        {
            entry.write = false;
        }
    }

    /// A write on a `BinaryReadWrite` handle clears its read capability
    /// until `Fseek` restores both.
    fn note_write(&mut self, handle: u8) {
        if let Some(entry) = self.file_handles.get_mut(&handle)
            && entry.read_write
        {
            entry.read = false;
        }
    }

    /// `Fseek` restores both capabilities on a `BinaryReadWrite` handle.
    fn note_seek(&mut self, handle: u8) {
        if let Some(entry) = self.file_handles.get_mut(&handle)
            && entry.read_write
        {
            entry.read = true;
            entry.write = true;
        }
    }

    /// TRAP 1: Fopen. `Z` is the handle the caller chooses, 0-255; `$255`
    /// addresses a two-octa block holding the name address and the mode.
    /// Handles 0-2 belong to the host and always fail. Opening a handle
    /// already open closes it first; on failure the handle is left closed.
    fn handle_fopen(&mut self, handle: u8) -> bool {
        if handle <= 2 {
            debug!(handle, "TRAP: Fopen rejects a standard handle");
            self.set_register(255, (-1i64) as u64);
            self.advance_pc();
            return true;
        }

        let param_addr = self.get_register(255);
        let name_addr = self.read_octa(param_addr);
        let mode_octa = self.read_octa(param_addr.wrapping_add(8));
        let filename = self.read_cstring(name_addr, 256);

        debug!(handle, filename = %filename, mode = mode_octa, "TRAP: Fopen");

        if mode_octa > 4 {
            debug!(mode = mode_octa, "Invalid file open mode");
            self.file_handles.remove(&handle);
            self.set_register(255, (-1i64) as u64);
            self.advance_pc();
            return true;
        }
        let mode = mode_octa as u8;

        // TextRead=0, TextWrite=1, BinaryRead=2, BinaryWrite=3,
        // BinaryReadWrite=4: (read, write, seek, read_write).
        let caps = match mode {
            0 => (true, false, false, false),
            1 => (false, true, false, false),
            2 => (true, false, true, false),
            3 => (false, true, true, false),
            _ => (true, true, true, true), // mode == 4, checked above
        };

        // Opening an already-open handle closes it first.
        self.file_handles.remove(&handle);

        let opened = match mode {
            0 | 2 => OpenOptions::new().read(true).open(&filename),
            1 | 3 => OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&filename),
            _ => OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&filename),
        };

        match opened {
            Ok(file) => {
                let (read, write, seek, read_write) = caps;
                self.file_handles.insert(
                    handle,
                    FileHandle {
                        file: Some(file),
                        read,
                        write,
                        seek,
                        read_write,
                    },
                );
                self.set_register(255, 0);
                debug!(handle, "File opened successfully");
            }
            Err(_) => {
                self.set_register(255, (-1i64) as u64);
                debug!(handle, "File open failed");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 2: Fclose. `Z` is the handle. Handles 0-2 belong to the host and
    /// always fail.
    fn handle_fclose(&mut self, handle: u8) -> bool {
        debug!(handle, "TRAP: Fclose");
        if handle <= 2 {
            self.set_register(255, (-1i64) as u64);
            self.advance_pc();
            return true;
        }
        match self.file_handles.remove(&handle) {
            Some(_) => self.set_register(255, 0),
            None => self.set_register(255, (-1i64) as u64),
        }
        self.advance_pc();
        true
    }

    /// TRAP 3: Fread. `Z` is the handle; `$255` addresses a two-octa block
    /// holding the buffer address and the byte count. Reads in a loop so a
    /// short `Read::read` never masks bytes the file still has to give;
    /// stops at the requested size, end of file, or an I/O error, whichever
    /// comes first, and reports a mid-read error the same as an early EOF —
    /// the short-read count, not the all-or-nothing failure value.
    fn handle_fread(&mut self, handle: u8) -> bool {
        let param_addr = self.get_register(255);
        let buffer_addr = self.read_octa(param_addr);
        let size = self.read_octa(param_addr.wrapping_add(8)) as usize;

        debug!(
            handle,
            buffer_addr = format!("0x{:X}", buffer_addr),
            size,
            "TRAP: Fread"
        );

        // Handle 0 (StdIn) has no host read primitive.
        if self.fail_unless(
            self.handle_readable(handle) && handle != 0,
            -1 - size as i64,
        ) {
            return true;
        }
        self.note_read(handle);

        let mut buffer = vec![0u8; size];
        let mut total = 0usize;
        let mut had_error = false;
        while total < size {
            let file = self.open_file(handle);
            match file.read(&mut buffer[total..]) {
                Ok(0) => break,
                Ok(n) => total += n,
                Err(_) => {
                    had_error = true;
                    break;
                }
            }
        }

        if had_error && total == 0 {
            self.set_register(255, (-1i64 - size as i64) as u64);
        } else {
            for (i, &byte) in buffer[..total].iter().enumerate() {
                self.write_byte(buffer_addr.wrapping_add(i as u64), byte);
            }
            let result = total as i64 - size as i64;
            self.set_register(255, result as u64);
        }
        self.advance_pc();
        true
    }

    /// TRAP 4: Fgets. `Z` is the handle; `$255` addresses a two-octa block
    /// holding the buffer address and the buffer size. Reads until `size -
    /// 1` characters or a newline, then a zero byte; returns the count
    /// stored, or -1 when `size` is 0 or end of file/an error comes before
    /// any character.
    fn handle_fgets(&mut self, handle: u8) -> bool {
        let param_addr = self.get_register(255);
        let buffer_addr = self.read_octa(param_addr);
        let max_size = self.read_octa(param_addr.wrapping_add(8)) as usize;

        debug!(
            handle,
            buffer_addr = format!("0x{:X}", buffer_addr),
            max_size,
            "TRAP: Fgets"
        );

        let ok = max_size != 0 && self.handle_readable(handle) && handle != 0;
        if self.fail_unless(ok, -1) {
            return true;
        }
        self.note_read(handle);

        let mut count = 0usize;
        while count < max_size - 1 {
            let mut byte = [0u8; 1];
            let file = self.open_file(handle);
            match file.read(&mut byte) {
                Ok(0) => break,
                Ok(_) => {
                    self.write_byte(buffer_addr.wrapping_add(count as u64), byte[0]);
                    count += 1;
                    if byte[0] == b'\n' {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        self.write_byte(buffer_addr.wrapping_add(count as u64), 0);
        self.set_register(
            255,
            if count == 0 {
                (-1i64) as u64
            } else {
                count as u64
            },
        );
        self.advance_pc();
        true
    }

    /// TRAP 5: Fgetws. `Z` is the handle; `$255` addresses a two-octa block
    /// holding the buffer address (rounded down to even) and the buffer
    /// size in wydes. Wydes are read raw, two bytes each in memory order;
    /// stops at the wyde `#000A`, `size - 1` wydes, end of file, or an
    /// error, then stores a zero wyde. Returns the wyde count, or -1 when
    /// `size` is 0 or nothing was read.
    fn handle_fgetws(&mut self, handle: u8) -> bool {
        let param_addr = self.get_register(255);
        let buffer_addr = self.read_octa(param_addr) & !1u64;
        let max_wydes = self.read_octa(param_addr.wrapping_add(8)) as usize;

        debug!(
            handle,
            buffer_addr = format!("0x{:X}", buffer_addr),
            max_wydes,
            "TRAP: Fgetws"
        );

        let ok = max_wydes != 0 && self.handle_readable(handle) && handle != 0;
        if self.fail_unless(ok, -1) {
            return true;
        }
        self.note_read(handle);

        let mut count = 0usize;
        while count < max_wydes - 1 {
            let mut wyde = [0u8; 2];
            let file = self.open_file(handle);
            match file.read_exact(&mut wyde) {
                Ok(_) => {
                    self.write_byte(buffer_addr.wrapping_add((count * 2) as u64), wyde[0]);
                    self.write_byte(buffer_addr.wrapping_add((count * 2 + 1) as u64), wyde[1]);
                    count += 1;
                    if wyde == [0x00, 0x0A] {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        self.write_byte(buffer_addr.wrapping_add((count * 2) as u64), 0);
        self.write_byte(buffer_addr.wrapping_add((count * 2 + 1) as u64), 0);
        self.set_register(
            255,
            if count == 0 {
                (-1i64) as u64
            } else {
                count as u64
            },
        );
        self.advance_pc();
        true
    }

    /// TRAP 6: Fwrite. `Z` is the handle; `$255` addresses a two-octa block
    /// holding the buffer address and the byte count. Writes in a loop, so
    /// a short underlying write is reflected in the result rather than
    /// masked. Returns 0 if all `size` bytes were written, else `n - size`
    /// for the `n` bytes actually written (`-size` if the handle lacks
    /// write access, `n` then being 0).
    fn handle_fwrite(&mut self, handle: u8) -> bool {
        let param_addr = self.get_register(255);
        let buffer_addr = self.read_octa(param_addr);
        let size = self.read_octa(param_addr.wrapping_add(8)) as usize;

        debug!(
            handle,
            buffer_addr = format!("0x{:X}", buffer_addr),
            size,
            "TRAP: Fwrite"
        );

        if self.fail_unless(self.handle_writable(handle), -(size as i64)) {
            return true;
        }
        self.note_write(handle);

        let mut buffer = Vec::with_capacity(size);
        for i in 0..size {
            buffer.push(self.read_byte(buffer_addr.wrapping_add(i as u64)));
        }

        let written = match handle {
            1 | 2 => match self.host.write(handle, &buffer) {
                Ok(_) => buffer.len(),
                Err(_) => 0,
            },
            _ => {
                let file = self.open_file(handle);
                let mut total = 0usize;
                while total < buffer.len() {
                    match file.write(&buffer[total..]) {
                        Ok(0) => break,
                        Ok(n) => total += n,
                        Err(_) => break,
                    }
                }
                total
            }
        };

        let result = written as i64 - size as i64;
        self.set_register(255, result as u64);
        self.advance_pc();
        true
    }

    /// Read a NUL-terminated byte string from memory starting at `addr`.
    /// Bytes are returned verbatim (no UTF-8 widening). Truncated at `max_len`
    /// bytes if no NUL is found, with a warning. Walks memory using wrapping
    /// arithmetic so str_addr near u64::MAX cannot panic.
    fn read_byte_string(&mut self, str_addr: u64, max_len: usize, label: &str) -> Vec<u8> {
        let mut bytes = Vec::new();
        let mut addr = str_addr;
        loop {
            let byte = self.read_byte(addr);
            if byte == 0 {
                break;
            }
            bytes.push(byte);
            if bytes.len() >= max_len {
                self.host
                    .diagnostic(&format!("Warning: {} string too long, truncating", label));
                break;
            }
            addr = addr.wrapping_add(1);
        }
        bytes
    }

    /// The open `File` behind `handle`, for a read/write/seek call past its
    /// capability check. Infallible there: `handle_readable`/
    /// `handle_writable`/`handle_seekable` already confirmed an entry
    /// exists, and every caller either excludes handle 0/1/2 (whose entries
    /// carry no `File`) or, for a read, has already turned handle 0 aside
    /// before reaching here.
    fn open_file(&mut self, handle: u8) -> &mut File {
        self.file_handles
            .get_mut(&handle)
            .and_then(|entry| entry.file.as_mut())
            .expect("capability check already confirmed handle is open with a real file")
    }

    /// Write raw bytes to the destination identified by an MMIX file
    /// descriptor: 1 and 2 go through the installed `Host` (locked
    /// stdout/stderr writes for `StdHost`); anything else is looked up in
    /// `file_handles`, whose retry and locking behavior is `std::fs::File`'s.
    fn write_bytes_to_fd(&mut self, fd: u8, bytes: &[u8]) -> std::io::Result<()> {
        match fd {
            1 | 2 => self.host.write(fd, bytes),
            _ => match self.file_handles.get_mut(&fd).and_then(|h| h.file.as_mut()) {
                Some(file) => file.write_all(bytes),
                None => Err(std::io::Error::other("file descriptor not open")),
            },
        }
    }

    /// TRAP 7: Fputs. `Z` is the handle; `$255` is the string address.
    /// Writes bytes up to, not including, the first zero byte, with no
    /// byte value translated. Returns the byte count written, or -1.
    fn handle_fputs(&mut self, handle: u8) -> bool {
        let str_addr = self.get_register(255);
        let bytes = self.read_byte_string(str_addr, 10000, "Fputs");
        debug!(
            handle,
            str_addr = format!("0x{:X}", str_addr),
            "TRAP: Fputs"
        );

        if self.fail_unless(self.handle_writable(handle), -1) {
            return true;
        }
        self.note_write(handle);

        match self.write_bytes_to_fd(handle, &bytes) {
            Ok(_) => self.set_register(255, bytes.len() as u64),
            Err(_) => {
                debug!(handle, "Fputs write failed");
                self.set_register(255, (-1i64) as u64);
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP #80: Fputc, checksmix's own extension. `Z` is the handle;
    /// `$255`'s low byte is the character. Shares `Fputs`'s write-capability
    /// check and read-write switching. Returns 0 on success, or -1.
    fn handle_fputc(&mut self, handle: u8) -> bool {
        let ch = (self.get_register(255) & 0xFF) as u8;
        debug!(handle, ch = format!("0x{:02X}", ch), "TRAP: Fputc");

        if self.fail_unless(self.handle_writable(handle), -1) {
            return true;
        }
        self.note_write(handle);

        match self.write_bytes_to_fd(handle, &[ch]) {
            Ok(_) => self.set_register(255, 0),
            Err(_) => {
                debug!(handle, "Fputc write failed");
                self.set_register(255, (-1i64) as u64);
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 8: Fputws. `Z` is the handle; `$255` is the string address.
    /// Wyde characters, two bytes each in memory order, written up to, not
    /// including, the first zero wyde. Returns the wyde count written, or
    /// -1.
    fn handle_fputws(&mut self, handle: u8) -> bool {
        let str_addr = self.get_register(255);
        let mut bytes = Vec::new();
        let mut addr = str_addr;
        let mut wyde_count = 0usize;
        loop {
            let hi = self.read_byte(addr);
            let lo = self.read_byte(addr.wrapping_add(1));
            if hi == 0 && lo == 0 {
                break;
            }
            bytes.push(hi);
            bytes.push(lo);
            wyde_count += 1;
            if wyde_count >= 5000 {
                self.host
                    .diagnostic("Warning: Fputws string too long, truncating");
                break;
            }
            addr = addr.wrapping_add(2);
        }
        debug!(
            handle,
            str_addr = format!("0x{:X}", str_addr),
            "TRAP: Fputws"
        );

        if self.fail_unless(self.handle_writable(handle), -1) {
            return true;
        }
        self.note_write(handle);

        match self.write_bytes_to_fd(handle, &bytes) {
            Ok(_) => self.set_register(255, wyde_count as u64),
            Err(_) => {
                debug!(handle, "Fputws write failed");
                self.set_register(255, (-1i64) as u64);
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 9: Fseek. `Z` is the handle; `$255` is the offset. `offset >= 0`
    /// positions `offset` bytes from the start; `offset < 0` positions
    /// `-offset - 1` bytes before the end. On a `BinaryReadWrite` handle,
    /// restores both read and write capability. Returns 0, or -1.
    fn handle_fseek(&mut self, handle: u8) -> bool {
        let offset = self.get_register(255) as i64;
        debug!(handle, offset, "TRAP: Fseek");

        if self.fail_unless(self.handle_seekable(handle), -1) {
            return true;
        }
        self.note_seek(handle);

        let seek_from = if offset >= 0 {
            SeekFrom::Start(offset as u64)
        } else {
            SeekFrom::End(offset + 1)
        };

        let file = self.open_file(handle);
        match file.seek(seek_from) {
            Ok(pos) => {
                self.set_register(255, 0);
                debug!(pos, "Seek successful");
            }
            Err(_) => {
                self.set_register(255, (-1i64) as u64);
                debug!("Seek failed");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 10: Ftell. `Z` is the handle. Returns the current position, or
    /// -1.
    fn handle_ftell(&mut self, handle: u8) -> bool {
        debug!(handle, "TRAP: Ftell");

        if self.fail_unless(self.handle_seekable(handle), -1) {
            return true;
        }

        let file = self.open_file(handle);
        match file.stream_position() {
            Ok(pos) => {
                self.set_register(255, pos);
                debug!(pos, "Ftell successful");
            }
            Err(_) => {
                self.set_register(255, (-1i64) as u64);
                debug!("Ftell failed");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP #82: Debug, checksmix's own extension backing the `debug
    /// "text"` directive. `Z` indexes the table `set_debug_strings`
    /// installed; writes that string and a newline to handle 1 through
    /// `Host::write`. Changes no register, `$255` included. An index past
    /// the table's end reports a diagnostic and continues.
    fn handle_debug(&mut self, index: u8) -> bool {
        match self.debug_strings.get(index as usize) {
            Some(text) => {
                let mut bytes = text.clone();
                bytes.push(b'\n');
                if let Err(err) = self.host.write(1, &bytes) {
                    self.host
                        .diagnostic(&format!("debug: write to handle 1 failed: {err}"));
                }
            }
            None => {
                self.host
                    .diagnostic(&format!("debug: index {index} has no string in the table"));
            }
        }
        self.advance_pc();
        true
    }

    fn handle_time(&mut self, unit: u8) -> bool {
        let micros = self.host.now_micros();

        let time_value = match unit {
            0 => micros / 1_000_000, // Seconds (default)
            1 => micros / 1_000,     // Milliseconds
            2 => micros,             // Microseconds
            _ => {
                debug!("Invalid time unit: {}", unit);
                0
            }
        };
        debug!("TRAP: Time (unit={}) => {}", unit, time_value);
        self.set_register(255, time_value);
        self.advance_pc();
        true
    }

    /// Helper function to read a null-terminated C string from memory
    pub(super) fn read_cstring(&self, addr: u64, max_len: usize) -> String {
        let mut result = String::new();
        for i in 0..max_len {
            let byte = self.read_byte(addr.wrapping_add(i as u64));
            if byte == 0 {
                break;
            }
            result.push(byte as char);
        }
        result
    }
}