systemless 0.104.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
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
use super::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PpcMath64Operation {
    LongDoubleToSInt64,
    LongDoubleToUInt64,
    S32Set,
    S64Absolute,
    S64Add,
    S64And,
    S64BitwiseAnd,
    S64BitwiseEor,
    S64BitwiseNot,
    S64BitwiseOr,
    S64Compare,
    S64Divide,
    S64Eor,
    S64Max,
    S64Min,
    S64Multiply,
    S64Negate,
    S64Not,
    S64Or,
    S64Set,
    S64SetU,
    S64ShiftLeft,
    S64ShiftRight,
    S64Subtract,
    SInt64ToLongDouble,
    SInt64ToUInt64,
    U32SetU,
    U64Add,
    U64And,
    U64BitwiseAnd,
    U64BitwiseEor,
    U64BitwiseNot,
    U64BitwiseOr,
    U64Compare,
    U64Divide,
    U64Eor,
    U64Max,
    U64Multiply,
    U64Not,
    U64Or,
    U64Set,
    U64SetU,
    U64ShiftLeft,
    U64ShiftRight,
    U64Subtract,
    UInt64ToLongDouble,
    UInt64ToSInt64,
}

pub(super) fn ppc_decimal_read(memory: &mut PpcSectionMem, decimal: u32) -> Option<f64> {
    let negative = memory.read_u8(decimal)? != 0;
    let exponent = memory.read_u16_be(decimal.checked_add(2)?)? as i16;
    let length = usize::from(memory.read_u8(decimal.checked_add(4)?)?);
    if !(1..=36).contains(&length) {
        return None;
    }
    let digits = ppc_memory_read_bytes(memory, decimal.checked_add(5)?, length as u32)?;
    let mut value = match digits[0] {
        b'0' => 0.0,
        b'N' => f64::NAN,
        b'I' => f64::INFINITY,
        _ => {
            let digits = std::str::from_utf8(&digits).ok()?;
            if !digits.bytes().all(|byte| byte.is_ascii_digit()) {
                return None;
            }
            format!("{digits}e{exponent}").parse::<f64>().ok()?
        }
    };
    if negative {
        value = -value;
    }
    Some(value)
}

pub(super) fn ppc_decimal_write(
    memory: &mut PpcSectionMem,
    decimal: u32,
    value: f64,
    digits: usize,
) -> bool {
    if decimal == 0 || !ppc_memory_can_write_bytes(memory, decimal, 42) {
        return false;
    }
    let negative = value.is_sign_negative();
    let (significand, exponent) = if value.is_nan() {
        (b"NAN".to_vec(), 0i16)
    } else if value.is_infinite() {
        (b"INF".to_vec(), 0)
    } else if value == 0.0 {
        (b"0".to_vec(), 0)
    } else {
        let digits = digits.clamp(1, 36);
        let scientific = format!("{:.*e}", digits - 1, value.abs());
        let (mantissa, exponent_text) = scientific.split_once('e').unwrap_or((&scientific, "0"));
        let significand = mantissa
            .bytes()
            .filter(|byte| *byte != b'.')
            .collect::<Vec<_>>();
        let scientific_exponent = exponent_text.parse::<i32>().unwrap_or(0);
        let decimal_exponent = scientific_exponent - (significand.len() as i32 - 1);
        (
            significand,
            decimal_exponent.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        )
    };
    let _ = ppc_zero_guest_bytes(memory, decimal, 42);
    let _ = memory.write_u8(decimal, u8::from(negative));
    let _ = memory.write_u16_be(decimal + 2, exponent as u16);
    let _ = memory.write_u8(decimal + 4, significand.len().min(36) as u8);
    memory
        .write_bytes(decimal + 5, &significand[..significand.len().min(36)])
        .is_some()
}

fn ppc_math64_read_gprs(cpu: &PpcCpu, high_register: usize) -> u64 {
    (u64::from(cpu.gpr[high_register]) << 32) | u64::from(cpu.gpr[high_register + 1])
}

fn ppc_math64_write_result(memory: &mut PpcSectionMem, result: u32, value: u64) {
    let _ = memory.write_u32_be(result, (value >> 32) as u32);
    let _ = memory.write_u32_be(result.wrapping_add(4), value as u32);
}

fn ppc_math64_signed_shift_right(value: i64, shift: u32) -> i64 {
    let shift = shift & 0x7f;
    if shift < 64 {
        value >> shift
    } else if value < 0 {
        -1
    } else {
        0
    }
}

fn ppc_math64_shift_left(value: u64, shift: u32) -> u64 {
    let shift = shift & 0x7f;
    if shift < 64 {
        value.wrapping_shl(shift)
    } else {
        0
    }
}

fn ppc_math64_shift_right(value: u64, shift: u32) -> u64 {
    let shift = shift & 0x7f;
    if shift < 64 {
        value >> shift
    } else {
        0
    }
}

fn ppc_math64_signed_to_long_double(value: i64) -> (f64, f64) {
    let head = value as f64;
    let tail = (i128::from(value) - head as i128) as f64;
    (head, tail)
}

fn ppc_math64_unsigned_to_long_double(value: u64) -> (f64, f64) {
    let head = value as f64;
    let tail = (i128::from(value) - head as i128) as f64;
    (head, tail)
}

fn ppc_math64_long_double_to_i128(head: f64, tail: f64) -> Option<i128> {
    if !head.is_finite() || !tail.is_finite() || head.abs() > 2f64.powi(65) {
        return None;
    }
    let head_integer = head.trunc();
    let tail_integer = tail.trunc();
    let fraction = (head - head_integer) + (tail - tail_integer);
    (head_integer as i128)
        .checked_add(tail_integer as i128)?
        .checked_add(fraction.trunc() as i128)
}

fn ppc_math64_long_double_to_signed(head: f64, tail: f64) -> i64 {
    ppc_math64_long_double_to_i128(head, tail)
        .map(|value| value.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64)
        .unwrap_or_else(|| {
            if head.is_nan() || tail.is_nan() {
                0
            } else if head.is_sign_negative() {
                i64::MIN
            } else {
                i64::MAX
            }
        })
}

fn ppc_math64_long_double_to_unsigned(head: f64, tail: f64) -> u64 {
    ppc_math64_long_double_to_i128(head, tail)
        .map(|value| value.clamp(0, i128::from(u64::MAX)) as u64)
        .unwrap_or_else(|| {
            if head.is_nan() || tail.is_nan() || head.is_sign_negative() {
                0
            } else {
                u64::MAX
            }
        })
}

pub(super) fn ppc_dispatch_math64(
    operation: PpcMath64Operation,
    cpu: &mut PpcCpu,
    memory: &mut PpcSectionMem,
) -> PpcImportAction {
    // Universal Interfaces 3.4 Math64.h specifies the arithmetic, Boolean,
    // shift, divide-by-zero, and conversion behavior used here. The PowerPC
    // aggregate ABI passes an 8-byte result address in r3 and starts its
    // explicit arguments in r4; scalar results use r3 directly.
    // Inside Macintosh: PowerPC System Software (1994), pp. 1-41--1-50.
    let left = ppc_math64_read_gprs(cpu, 4);
    let right = ppc_math64_read_gprs(cpu, 6);
    let unary = left;
    let value = match operation {
        PpcMath64Operation::S64Max => i64::MAX as u64,
        PpcMath64Operation::S64Min => i64::MIN as u64,
        PpcMath64Operation::S64Add => left.wrapping_add(right),
        PpcMath64Operation::S64Subtract => left.wrapping_sub(right),
        PpcMath64Operation::S64Negate => (left as i64).wrapping_neg() as u64,
        PpcMath64Operation::S64Absolute => (left as i64).wrapping_abs() as u64,
        PpcMath64Operation::S64Multiply => (left as i64).wrapping_mul(right as i64) as u64,
        PpcMath64Operation::S64BitwiseAnd | PpcMath64Operation::U64BitwiseAnd => left & right,
        PpcMath64Operation::S64BitwiseOr | PpcMath64Operation::U64BitwiseOr => left | right,
        PpcMath64Operation::S64BitwiseEor | PpcMath64Operation::U64BitwiseEor => left ^ right,
        PpcMath64Operation::S64BitwiseNot | PpcMath64Operation::U64BitwiseNot => !unary,
        PpcMath64Operation::S64ShiftRight => {
            ppc_math64_signed_shift_right(left as i64, cpu.gpr[6]) as u64
        }
        PpcMath64Operation::S64ShiftLeft | PpcMath64Operation::U64ShiftLeft => {
            ppc_math64_shift_left(left, cpu.gpr[6])
        }
        PpcMath64Operation::U64ShiftRight => ppc_math64_shift_right(left, cpu.gpr[6]),
        PpcMath64Operation::S64Set => i64::from(cpu.gpr[4] as i32) as u64,
        PpcMath64Operation::S64SetU | PpcMath64Operation::U64SetU => u64::from(cpu.gpr[4]),
        PpcMath64Operation::U64Set => (cpu.gpr[4] as i32 as i64) as u64,
        PpcMath64Operation::U64Max => u64::MAX,
        PpcMath64Operation::U64Add => left.wrapping_add(right),
        PpcMath64Operation::U64Subtract => left.wrapping_sub(right),
        PpcMath64Operation::U64Multiply => left.wrapping_mul(right),
        PpcMath64Operation::UInt64ToSInt64 | PpcMath64Operation::SInt64ToUInt64 => unary,
        PpcMath64Operation::S64Divide => {
            let dividend = left as i64;
            let divisor = right as i64;
            let (quotient, remainder) = if divisor == 0 {
                (if dividend < 0 { i64::MIN } else { i64::MAX }, dividend)
            } else if dividend == i64::MIN && divisor == -1 {
                (i64::MIN, 0)
            } else {
                (dividend / divisor, dividend % divisor)
            };
            if cpu.gpr[8] != 0 {
                ppc_math64_write_result(memory, cpu.gpr[8], remainder as u64);
            }
            quotient as u64
        }
        PpcMath64Operation::U64Divide => {
            let (quotient, remainder) = if right == 0 {
                (u64::MAX, left)
            } else {
                (left / right, left % right)
            };
            if cpu.gpr[8] != 0 {
                ppc_math64_write_result(memory, cpu.gpr[8], remainder);
            }
            quotient
        }
        PpcMath64Operation::LongDoubleToSInt64 => {
            ppc_math64_long_double_to_signed(f64::from_bits(cpu.fpr[1]), f64::from_bits(cpu.fpr[2]))
                as u64
        }
        PpcMath64Operation::LongDoubleToUInt64 => ppc_math64_long_double_to_unsigned(
            f64::from_bits(cpu.fpr[1]),
            f64::from_bits(cpu.fpr[2]),
        ),
        PpcMath64Operation::SInt64ToLongDouble => {
            let (head, tail) =
                ppc_math64_signed_to_long_double(ppc_math64_read_gprs(cpu, 3) as i64);
            cpu.fpr[1] = head.to_bits();
            cpu.fpr[2] = tail.to_bits();
            return PpcImportAction::ReturnPreserve;
        }
        PpcMath64Operation::UInt64ToLongDouble => {
            let (head, tail) = ppc_math64_unsigned_to_long_double(ppc_math64_read_gprs(cpu, 3));
            cpu.fpr[1] = head.to_bits();
            cpu.fpr[2] = tail.to_bits();
            return PpcImportAction::ReturnPreserve;
        }
        PpcMath64Operation::S32Set | PpcMath64Operation::U32SetU => {
            return PpcImportAction::Return(cpu.gpr[4]);
        }
        PpcMath64Operation::S64And | PpcMath64Operation::U64And => {
            return PpcImportAction::Return(u32::from(
                ppc_math64_read_gprs(cpu, 3) != 0 && ppc_math64_read_gprs(cpu, 5) != 0,
            ));
        }
        PpcMath64Operation::S64Or | PpcMath64Operation::U64Or => {
            return PpcImportAction::Return(u32::from(
                ppc_math64_read_gprs(cpu, 3) != 0 || ppc_math64_read_gprs(cpu, 5) != 0,
            ));
        }
        PpcMath64Operation::S64Eor | PpcMath64Operation::U64Eor => {
            return PpcImportAction::Return(u32::from(
                (ppc_math64_read_gprs(cpu, 3) != 0) ^ (ppc_math64_read_gprs(cpu, 5) != 0),
            ));
        }
        PpcMath64Operation::S64Not | PpcMath64Operation::U64Not => {
            return PpcImportAction::Return(u32::from(ppc_math64_read_gprs(cpu, 3) == 0));
        }
        PpcMath64Operation::S64Compare => {
            return PpcImportAction::Return(
                match (ppc_math64_read_gprs(cpu, 3) as i64)
                    .cmp(&(ppc_math64_read_gprs(cpu, 5) as i64))
                {
                    std::cmp::Ordering::Less => -1i32 as u32,
                    std::cmp::Ordering::Equal => 0,
                    std::cmp::Ordering::Greater => 1,
                },
            );
        }
        PpcMath64Operation::U64Compare => {
            return PpcImportAction::Return(
                match ppc_math64_read_gprs(cpu, 3).cmp(&ppc_math64_read_gprs(cpu, 5)) {
                    std::cmp::Ordering::Less => -1i32 as u32,
                    std::cmp::Ordering::Equal => 0,
                    std::cmp::Ordering::Greater => 1,
                },
            );
        }
    };
    ppc_math64_write_result(memory, cpu.gpr[3], value);
    PpcImportAction::ReturnPreserve
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PpcMathCompatibilityOperation {
    Dec2Num,
    Dec2Str,
    Fabs,
    FeClearExcept,
    FeTestExcept,
    FeRaiseExcept,
    Infinity,
    IsFiniteD,
    FpClassifyD,
    FpClassifyF,
    Floor,
    Ldexp,
    LdToX80,
    Modf,
    Modff,
    Nan,
    Num2Dec,
    Str2Dec,
    X80ToD,
    X80ToLd,
}

pub(super) fn ppc_dispatch_math_compatibility(
    operation: PpcMathCompatibilityOperation,
    cpu: &mut PpcCpu,
    memory: &mut PpcSectionMem,
) -> PpcImportAction {
    match operation {
        PpcMathCompatibilityOperation::FpClassifyD => {
            // __fpclassifyd(double) returns FP_SNAN through FP_SUBNORMAL
            // (0..=5). Inspect the IEEE double bits so signaling and quiet
            // NaNs remain distinct without performing floating-point math.
            // Inside Macintosh: PowerPC Numerics (1994), pp. 7-4--7-5,
            // Appendix C, fp.h C-9.
            let bits = cpu.fpr[1];
            let exponent = (bits >> 52) & 0x7ff;
            let fraction = bits & ((1_u64 << 52) - 1);
            cpu.gpr[3] = match (exponent, fraction) {
                (0x7ff, 0) => 2,
                (0x7ff, fraction) if fraction & (1_u64 << 51) == 0 => 0,
                (0x7ff, _) => 1,
                (0, 0) => 3,
                (0, _) => 5,
                _ => 4,
            };
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::FpClassifyF => {
            // __fpclassifyf(float) classifies the single-precision value,
            // which arrives widened to a double in fr1, with the same
            // FP_SNAN through FP_SUBNORMAL results as __fpclassifyd.
            let bits = (f64::from_bits(cpu.fpr[1]) as f32).to_bits();
            let exponent = (bits >> 23) & 0xff;
            let fraction = bits & ((1_u32 << 23) - 1);
            cpu.gpr[3] = match (exponent, fraction) {
                (0xff, 0) => 2,
                (0xff, fraction) if fraction & (1_u32 << 22) == 0 => 0,
                (0xff, _) => 1,
                (0, 0) => 3,
                (0, _) => 5,
                _ => 4,
            };
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::LdToX80 => {
            // PowerPC Numerics (1994), Appendix E: long double is a
            // double-double pair. Convert its head and tail to the 80-bit
            // interchange format used by classic Mac OS numeric APIs.
            let source = cpu.gpr[3];
            let destination = cpu.gpr[4];
            if ppc_memory_can_read_bytes(memory, source, 16)
                && ppc_memory_can_write_bytes(memory, destination, 10)
            {
                if let (Some(head), Some(tail)) =
                    (memory.read_u64_be(source), memory.read_u64_be(source + 8))
                {
                    let extended = Extended80::from(f64::from_bits(head))
                        .add(Extended80::from(f64::from_bits(tail)));
                    let _ = memory.write_u16_be(
                        destination,
                        (u16::from(extended.sign) << 15) | extended.exponent,
                    );
                    let _ = memory.write_u64_be(destination + 2, extended.significand);
                }
            }
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::X80ToLd => {
            // fp.h: x80told takes pointers to an extended80 and a PowerPC
            // long double, which consists of a double head and a double tail.
            let source = cpu.gpr[3];
            let destination = cpu.gpr[4];
            if ppc_memory_can_read_bytes(memory, source, 10)
                && ppc_memory_can_write_bytes(memory, destination, 16)
            {
                if let (Some(sign_exponent), Some(significand)) =
                    (memory.read_u16_be(source), memory.read_u64_be(source + 2))
                {
                    let head = ppc_x80_to_f64_bits(sign_exponent, significand);
                    let head_value = f64::from_bits(head);
                    let tail = if head_value.is_normal() && significand != 0 {
                        let shift = significand.leading_zeros();
                        let source_exponent =
                            i32::from((sign_exponent & 0x7fff).max(1)) - shift as i32;
                        let normalized = significand << shift;
                        let rounded = Extended80::from(head_value.abs());
                        let head_shift = (i32::from(rounded.exponent) - source_exponent) as u32;
                        let difference = i128::from(normalized)
                            - (i128::from(rounded.significand) << head_shift);
                        if difference == 0 {
                            0
                        } else {
                            let magnitude = difference.unsigned_abs() as u64;
                            let normalize = magnitude.leading_zeros();
                            let exponent = source_exponent - normalize as i32;
                            let sign = (sign_exponent & 0x8000 != 0) ^ (difference < 0);
                            ppc_x80_to_f64_bits(
                                (u16::from(sign) << 15) | exponent as u16,
                                magnitude << normalize,
                            )
                        }
                    } else {
                        0
                    };
                    let _ = memory.write_u64_be(destination, head);
                    let _ = memory.write_u64_be(destination + 8, tail);
                }
            }
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::X80ToD => {
            // MathLib `double x80tod(const extended80 *x80)` (fp.h) narrows
            // the 10-byte 68K extended interchange format to a double. The
            // conversion rounds like an IEEE 754 narrowing operation under
            // the default round-to-nearest mode, producing subnormals and
            // signed zero on underflow.
            let source = cpu.gpr[3];
            if let (Some(sign_exponent), Some(significand)) = (
                memory.read_u16_be(source),
                memory.read_u64_be(source.wrapping_add(2)),
            ) {
                cpu.fpr[1] = ppc_x80_to_f64_bits(sign_exponent, significand);
            }
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Floor => {
            // floor returns the nearest integer not greater than its argument,
            // preserving signed zero, NaN, and infinities.
            // PowerPC Numerics (1994), pp. 9-7--9-8.
            cpu.fpr[1] = f64::from_bits(cpu.fpr[1]).floor().to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Fabs => {
            cpu.fpr[1] = f64::from_bits(cpu.fpr[1]).abs().to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Ldexp => {
            // MathLib ldexp(x, exp) scales x by an exact power of two. CFM
            // places x in fr1 and reserves its two GPR slots, so `exp` is r5.
            let value = f64::from_bits(cpu.fpr[1]);
            cpu.fpr[1] = libm::scalbn(value, cpu.gpr[5] as i32).to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Nan => {
            // The C nan(tagp) payload is implementation-defined; return the
            // standard quiet NaN value while ignoring the optional tag.
            cpu.fpr[1] = f64::NAN.to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Modf => {
            let value = f64::from_bits(cpu.fpr[1]);
            let integer = if value.is_nan() { value } else { value.trunc() };
            let fractional = if value.is_infinite() {
                0.0f64.copysign(value)
            } else {
                value - integer
            };
            let pointer = cpu.gpr[5];
            let bits = integer.to_bits();
            let _ = memory.write_u32_be(pointer, (bits >> 32) as u32);
            let _ = memory.write_u32_be(pointer + 4, bits as u32);
            cpu.fpr[1] = fractional.to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Modff => {
            // modff(float x, float *iptr): x is in fr1 and takes one GPR
            // slot, so iptr is r4. The integral part is stored as a float
            // and the fractional part returned in fr1.
            let value = f64::from_bits(cpu.fpr[1]) as f32;
            let integer = if value.is_nan() { value } else { value.trunc() };
            let fractional = if value.is_infinite() {
                0.0f32.copysign(value)
            } else {
                value - integer
            };
            let _ = memory.write_u32_be(cpu.gpr[4], integer.to_bits());
            cpu.fpr[1] = f64::from(fractional).to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Dec2Num => {
            cpu.fpr[1] = ppc_decimal_read(memory, cpu.gpr[3])
                .unwrap_or(f64::NAN)
                .to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Num2Dec => {
            let digits = memory
                .read_u16_be(cpu.gpr[3] + 2)
                .map(|value| value as i16)
                .unwrap_or(16)
                .unsigned_abs() as usize;
            let _ = ppc_decimal_write(memory, cpu.gpr[6], f64::from_bits(cpu.fpr[1]), digits);
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Dec2Str => {
            let style = memory.read_u8(cpu.gpr[3]).unwrap_or(0);
            let digits = memory
                .read_u16_be(cpu.gpr[3] + 2)
                .map(|value| value as i16)
                .unwrap_or(6);
            let value = ppc_decimal_read(memory, cpu.gpr[4]).unwrap_or(f64::NAN);
            let text = if style == 1 {
                format!("{:.*}", usize::from(digits.max(0) as u16).min(36), value)
            } else {
                format!(
                    " {:.*e}",
                    usize::from(digits.max(1) as u16).saturating_sub(1).min(35),
                    value
                )
            };
            let _ = memory.write_bytes(cpu.gpr[5], text.as_bytes());
            let _ = memory.write_u8(cpu.gpr[5] + text.len() as u32, 0);
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Str2Dec => {
            let bytes = ppc_std_c_string(memory, cpu.gpr[3], 4096);
            let start = memory.read_u16_be(cpu.gpr[4]).unwrap_or(0) as usize;
            let suffix = bytes.get(start..).unwrap_or_default();
            let text = String::from_utf8_lossy(suffix);
            let token_len = text
                .bytes()
                .take_while(|byte| {
                    byte.is_ascii_digit() || matches!(*byte, b'+' | b'-' | b'.' | b'e' | b'E')
                })
                .count();
            let value = text
                .get(..token_len)
                .and_then(|text| text.parse::<f64>().ok());
            if let Some(value) = value {
                let _ = ppc_decimal_write(memory, cpu.gpr[5], value, 16);
                let _ = memory.write_u16_be(cpu.gpr[4], start.saturating_add(token_len) as u16);
                let _ = memory.write_u16_be(cpu.gpr[6], 1);
            } else {
                let _ = ppc_decimal_write(memory, cpu.gpr[5], f64::NAN, 3);
                let _ = memory.write_u16_be(cpu.gpr[6], 0);
            }
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::Infinity => {
            cpu.fpr[1] = f64::INFINITY.to_bits();
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::IsFiniteD => {
            PpcImportAction::Return(u32::from(f64::from_bits(cpu.fpr[1]).is_finite()))
        }
        PpcMathCompatibilityOperation::FeClearExcept
        | PpcMathCompatibilityOperation::FeRaiseExcept => {
            // Apple's PowerPC fenv.h uses the FPSCR exception summary bits
            // directly. VX is derived from the individual invalid causes.
            let mut flags = cpu.gpr[3] & 0x3e00_0000;
            if operation == PpcMathCompatibilityOperation::FeClearExcept {
                if flags & 0x2000_0000 != 0 {
                    flags |= 0x01f8_0700; // all invalid-operation causes
                }
                cpu.fpscr &= !flags;
            } else if flags != 0 {
                if flags & 0x2000_0000 != 0 {
                    flags |= 0x0000_0400; // VXSOFT
                }
                cpu.fpscr |= flags | 0x8000_0000; // sticky FX summary
            }
            let enabled = (cpu.fpscr >> 22) & cpu.fpscr & 0x0000_00f8 != 0;
            cpu.set_fpscr_bit(1, enabled); // derived FEX summary
            PpcImportAction::ReturnPreserve
        }
        PpcMathCompatibilityOperation::FeTestExcept => {
            PpcImportAction::Return(cpu.fpscr & cpu.gpr[3] & 0x3e00_0000)
        }
    }
}

/// Narrow an 80-bit extended value to IEEE double bits, rounding to nearest
/// with ties to even. The explicit integer bit is honoured, so unnormal and
/// pseudo-denormal encodings convert by value.
pub(crate) fn ppc_x80_to_f64_bits(sign_exponent: u16, significand: u64) -> u64 {
    let sign = u64::from(sign_exponent >> 15) << 63;
    let exponent = sign_exponent & 0x7fff;
    if exponent == 0x7fff {
        let fraction = significand & !(1 << 63);
        return if fraction == 0 {
            sign | 0x7ff0_0000_0000_0000
        } else {
            // Keep the payload's high bits and force a quiet NaN.
            sign | 0x7ff8_0000_0000_0000 | (fraction >> 11)
        };
    }
    if significand == 0 {
        return sign;
    }
    let shift = significand.leading_zeros();
    let normalized = significand << shift;
    // Unbiased exponent of the leading one bit; extended denormals use the
    // minimum exponent of 1 - 16383.
    let leading = i32::from(exponent.max(1)) - 16383 - shift as i32;
    let biased = leading + 1023;
    if biased >= 0x7ff {
        return sign | 0x7ff0_0000_0000_0000;
    }
    // Discarded low bits below the 53-bit (or subnormal) mantissa.
    let drop = if biased >= 1 {
        11
    } else {
        11 + (1 - biased) as u32
    };
    if drop > 64 {
        return sign;
    }
    let (kept, remainder, half) = if drop == 64 {
        (0, normalized, 1u64 << 63)
    } else {
        (
            normalized >> drop,
            normalized & ((1u64 << drop) - 1),
            1u64 << (drop - 1),
        )
    };
    let rounded = if remainder > half || (remainder == half && kept & 1 == 1) {
        kept + 1
    } else {
        kept
    };
    if biased >= 1 {
        // A carry out of the 53-bit mantissa bumps the exponent and may
        // overflow to infinity.
        let (mantissa, biased) = if rounded == 1 << 53 {
            (rounded >> 1, biased + 1)
        } else {
            (rounded, biased)
        };
        if biased >= 0x7ff {
            return sign | 0x7ff0_0000_0000_0000;
        }
        sign | (biased as u64) << 52 | (mantissa & 0x000f_ffff_ffff_ffff)
    } else {
        // Subnormal; a carry into bit 52 yields the smallest normal.
        sign | rounded
    }
}