checksmix 0.4.3

An assembler, emulator and source-level debugger for Knuth's MMIX.
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! `TrapCode`, `FileHandle`, and the TRAP #0-#82 handlers behind them.

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

/// The size of the host buffer `Fread`, `Fwrite`, `Fputs` and `Fputws` each
/// reuse to move a request of any length, so host memory never scales with
/// the guest's count. A request larger than this crosses in several chunks;
/// nothing bounds the request itself. Even, because `write_string` fills a
/// chunk one whole character at a time: an odd size would let a wyde chunk
/// overshoot it by a byte.
const TRANSFER_CHUNK: usize = 1_048_576;

/// TRAP code identifiers for MMIX, numbered per the MMIXAL reference: every
/// call is `TRAP 0,Code,Z`. `Z` means a different thing per code: ignored
/// for `Halt`; the handle (0-255) for the file calls and `Fputc`; the unit
/// for `Time` (0 seconds, 1 milliseconds, 2 microseconds); and for `Debug`,
/// the 0-based index, in program order, of a `debug "text"` directive,
/// looked up in the table `set_debug_strings` installed. `$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 halt as an unsimulated `TRAP` rather than running 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` and fixed capabilities. Fd 1 and 2 writes, and
/// a fd 0 read, route through the installed [`Host`]. 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)
    }

    /// `Fread`, `Fgets` and `Fgetws`' one read path: `handle`'s byte
    /// source, `Host::read` for handle 0 and the open `File` otherwise.
    fn read_from_handle(&mut self, handle: u8, buf: &mut [u8]) -> std::io::Result<usize> {
        if handle == 0 {
            self.host.read(0, buf)
        } else {
            self.open_file(handle).read(buf)
        }
    }

    /// Fills a whole wyde from `handle`'s byte source, retrying past a short
    /// read the way `File::read_exact` does — `Host::read`'s only per-call
    /// guarantee is "at most a full buffer". `None` at end of file, mid-wyde
    /// or otherwise, or on an I/O error; either way any bytes already read
    /// are discarded, matching `read_exact`.
    fn read_wyde_from_handle(&mut self, handle: u8) -> Option<[u8; 2]> {
        let mut wyde = [0u8; 2];
        let mut total = 0;
        while total < wyde.len() {
            match self.read_from_handle(handle, &mut wyde[total..]) {
                Ok(0) => return None,
                Ok(n) => total += n,
                Err(e) if e.kind() == ErrorKind::Interrupted => continue,
                Err(_) => return None,
            }
        }
        Some(wyde)
    }

    /// 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;
        }
    }

    /// Fails `Fopen` on a non-standard handle: closes it (a failed open
    /// leaves it closed, whether or not it was open before), sets `$255`
    /// to -1, advances the PC, and reports the call handled. Every
    /// `Fopen` failure past the standard-handle check goes through here,
    /// so none can leave a stale handle open. Handles 0-2 never reach
    /// this: `Fopen`/`Fclose` leave them exactly as they were.
    fn fail_fopen(&mut self, handle: u8) -> bool {
        self.file_handles.remove(&handle);
        self.set_register(255, (-1i64) as u64);
        self.advance_pc();
        true
    }

    /// Reads `Fopen`'s name argument: the guest's bytes at `name_addr` up to
    /// their terminating zero, passed through unchanged. Returns `None`,
    /// having already logged the reason through `debug!`, when the bytes are
    /// not valid UTF-8. Walks memory with wrapping arithmetic so `name_addr`
    /// near `u64::MAX` cannot panic.
    fn read_fopen_name(&self, handle: u8, name_addr: u64) -> Option<String> {
        let mut name_bytes = Vec::new();
        let mut cur = name_addr;
        loop {
            let byte = self.read_byte(cur);
            if byte == 0 {
                break;
            }
            name_bytes.push(byte);
            cur = cur.wrapping_add(1);
        }
        match String::from_utf8(name_bytes) {
            Ok(filename) => Some(filename),
            Err(_) => {
                debug!(handle, "TRAP: Fopen name is not valid UTF-8");
                None
            }
        }
    }

    /// 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, leaving the stream
    /// as it was. Opening a handle already open closes it first; on
    /// failure the handle is left closed.
    ///
    /// The name is the guest's bytes up to its terminating zero, passed to
    /// the filesystem unchanged and whole; the filesystem's own path limit
    /// rejects a long one. A name that is not valid UTF-8 fails with -1 and
    /// touches no file; every such failure logs through `debug!` only, like
    /// any other `Fopen` failure. **Departure from the reference:** a name
    /// that is valid bytes on the host's filesystem but not UTF-8, such as a
    /// Latin-1 name on a Linux filesystem, cannot be opened.
    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 Some(filename) = self.read_fopen_name(handle, name_addr) else {
            return self.fail_fopen(handle);
        };

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

        if mode_octa > 4 {
            debug!(mode = mode_octa, "Invalid file open mode");
            return self.fail_fopen(handle);
        }
        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");
                self.advance_pc();
                true
            }
            Err(_) => {
                debug!(handle, "File open failed");
                self.fail_fopen(handle)
            }
        }
    }

    /// 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, read as a full
    /// octabyte so no target narrows it. Reads in chunks of at most
    /// `TRANSFER_CHUNK`, so no allocation scales with the guest's
    /// request; the loop ends at the guest's 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. Every result is mod 2^64.
    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));

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

        if self.fail_unless(
            self.handle_readable(handle),
            u64::MAX.wrapping_sub(size) as i64,
        ) {
            return true;
        }
        self.note_read(handle);

        // Sized to what this call could possibly need: a size below one
        // chunk allocates and zeroes only that many bytes, so many small
        // reads don't each pay for a 1 MiB buffer they never fill.
        let chunk_size = size.min(TRANSFER_CHUNK as u64) as usize;
        let mut chunk = vec![0u8; chunk_size];
        let mut total: u64 = 0;
        let mut had_error = false;
        while total < size {
            let want = (size - total).min(chunk_size as u64) as usize;
            match self.read_from_handle(handle, &mut chunk[..want]) {
                Ok(0) => break,
                Ok(n) => {
                    for (i, &byte) in chunk[..n].iter().enumerate() {
                        self.write_byte(
                            buffer_addr.wrapping_add(total.wrapping_add(i as u64)),
                            byte,
                        );
                    }
                    total += n as u64;
                }
                Err(_) => {
                    had_error = true;
                    break;
                }
            }
        }

        let result = if had_error && total == 0 {
            u64::MAX.wrapping_sub(size)
        } else {
            total.wrapping_sub(size)
        };
        self.set_register(255, result);
        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);
        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];
            match self.read_from_handle(handle, &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);
        if self.fail_unless(ok, -1) {
            return true;
        }
        self.note_read(handle);

        let mut count = 0usize;
        while count < max_wydes - 1 {
            match self.read_wyde_from_handle(handle) {
                Some(wyde) => {
                    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;
                    }
                }
                None => 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, read as a full
    /// octabyte so no target narrows it. Writes all `size` bytes, in chunks
    /// of at most `TRANSFER_CHUNK` so no allocation scales with the guest's
    /// request, and stops at the first chunk that writes short, so a short
    /// underlying write is reflected in the result rather than masked.
    /// A `size` of 0 on handle 1 or 2 still makes one `Host::write` call,
    /// with an empty slice. Returns 0 if all `size` bytes were written, else
    /// `n - size` mod 2^64 for the `n` bytes actually written (`-size`
    /// mod 2^64 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));

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

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

        let chunk_size = size.min(TRANSFER_CHUNK as u64) as usize;
        let mut chunk = vec![0u8; chunk_size];
        let mut written: u64 = 0;
        loop {
            let want = (size - written).min(chunk_size as u64) as usize;
            let chunk_addr = buffer_addr.wrapping_add(written);
            for (i, slot) in chunk[..want].iter_mut().enumerate() {
                *slot = self.read_byte(chunk_addr.wrapping_add(i as u64));
            }
            let landed = self.write_counted(handle, &chunk[..want]);
            written += landed as u64;
            if landed < want || written == size {
                break;
            }
        }

        self.set_register(255, written.wrapping_sub(size));
        self.advance_pc();
        true
    }

    /// Writes `bytes` to `handle` and returns how many landed. Handle 1 and
    /// 2 cross `Host::write` whole or not at all; a file takes partial
    /// writes until one writes nothing or fails.
    fn write_counted(&mut self, handle: u8, bytes: &[u8]) -> usize {
        match handle {
            1 | 2 => match self.host.write(handle, bytes) {
                Ok(()) => bytes.len(),
                Err(_) => 0,
            },
            _ => {
                let file = self.open_file(handle);
                let mut total = 0usize;
                while total < bytes.len() {
                    match file.write(&bytes[total..]) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => total += n,
                    }
                }
                total
            }
        }
    }

    /// The open `File` behind `handle`, for a write/seek call past its
    /// capability check, or a read past `read_from_handle`'s handle-0
    /// dispatch. Infallible there: `handle_readable`/`handle_writable`/
    /// `handle_seekable` already confirmed an entry exists, and every
    /// caller excludes handle 1/2 (whose entries carry no `File`) and, for
    /// a read, routes handle 0 to `Host::read` 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")),
            },
        }
    }

    /// Streams the zero-terminated string of `UNIT`-byte characters at `addr`
    /// to `handle` in chunks of at most `TRANSFER_CHUNK` bytes, so host
    /// memory never scales with the string's length. Returns the character
    /// count written; a write error after earlier chunks landed is still an
    /// error. An empty string still makes one write, with an empty slice.
    /// Walks memory with wrapping arithmetic so `addr` near `u64::MAX`
    /// cannot panic.
    fn write_string<const UNIT: usize>(&mut self, handle: u8, addr: u64) -> std::io::Result<u64> {
        let mut chunk = Vec::new();
        let mut cur = addr;
        let mut count = 0u64;
        loop {
            chunk.clear();
            let mut ended = false;
            while chunk.len() < TRANSFER_CHUNK {
                let character: [u8; UNIT] =
                    std::array::from_fn(|i| self.read_byte(cur.wrapping_add(i as u64)));
                if character == [0; UNIT] {
                    ended = true;
                    break;
                }
                chunk.extend_from_slice(&character);
                cur = cur.wrapping_add(UNIT as u64);
            }
            if !chunk.is_empty() || count == 0 {
                self.write_bytes_to_fd(handle, &chunk)?;
            }
            count += (chunk.len() / UNIT) as u64;
            if ended {
                return Ok(count);
            }
        }
    }

    /// 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, in chunks so no allocation scales with the
    /// string's length. Returns the byte count written, or -1 on a write
    /// error, even one after earlier chunks landed.
    fn handle_fputs(&mut self, handle: u8) -> bool {
        let str_addr = self.get_register(255);
        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_string::<1>(handle, str_addr) {
            Ok(count) => self.set_register(255, count),
            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, in chunks so no allocation scales
    /// with the string's length. Returns the wyde count written, or -1 on a
    /// write error, even one after earlier chunks landed.
    fn handle_fputws(&mut self, handle: u8) -> bool {
        let str_addr = self.get_register(255);
        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_string::<2>(handle, str_addr) {
            Ok(count) => self.set_register(255, count),
            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
    }
}