vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
mod atomic;
mod exclusive;
mod float;
mod integer;
mod lanes;
mod memory;
mod simd;
mod structures;
mod system;
mod vector;

pub(super) use atomic::recover_atomic_loops;
#[cfg(test)]
use float::half_immediate;
use float::{lift_float, lift_vector_float};
use integer::{
    destination, extend_shift, immediate, lift_alu, lift_bic, lift_bitfield, lift_bitfield_insert,
    lift_conditional_compare, lift_count, lift_cs_family, lift_csel, lift_extract, lift_inverted,
    lift_long_multiply, lift_madd, lift_mov, lift_movk, lift_msub, lift_mul_high, lift_reverse,
    lift_variable_shift, lift_with_carry, mask_bits, register_width,
};
use lanes::{
    absolute_difference, by_halves, complement, doubling_mul_high, halves, immediate_lane, lane,
    lane_shift, lane_value, lanewise, narrowed, replicate, replicated, reverse_lanes,
    rounding_shift, shift_count, simd, source_halves, unzip, vector, widened, window, write_narrow,
};
use memory::{lift_load, lift_pair, lift_store};
use vector::lift_vector;

use yaxpeax_arch::{Decoder, ReaderBuilder};
use yaxpeax_arm::armv8::a64::{self, Instruction, Operand, SizeCode};

use super::calls::bare;
use super::flags::{Flags, Test};
use super::{Decoded, Machine, Write, flags, reverse_bytes, rotate};
use vlk_arch::arch::aarch64::LR;
use vlk_ir::ir::{BinOp, Cond, Expr, LaneOp, Operation, RegRef, Rounding, Stmt};
use vlk_types::types::{CallKind, Precision};

#[derive(Clone, Copy)]
pub(super) enum LaneParity {
    Odd,
    Even,
}

#[derive(Clone, Copy)]
pub(super) enum VectorHalf {
    Upper,
    Lower,
}

#[derive(Clone, Copy)]
pub(super) enum MemoryAccess {
    Store,
    Load,
}

#[derive(Clone, Copy)]
pub(super) enum FlagUpdate {
    Set,
    Preserve,
}

#[derive(Clone, Copy)]
pub(super) enum Signedness {
    Signed,
    Unsigned,
}

pub(super) struct Lifter<'a> {
    out: super::Emitter,
    image: &'a vlk_loader::loader::Image,
    /// The convention of a call through a register: the procedure call
    /// standard's in Go's assembly, which calls C code such as the vDSO
    /// that way and keeps values in the registers C preserves.
    indirect: vlk_types::types::Convention,
}

impl<'a> Lifter<'a> {
    pub(super) fn new(image: &'a vlk_loader::loader::Image, addr: u64) -> Self {
        let indirect = if crate::lift::convention_of(image, addr).go_assembly() {
            vlk_types::types::Convention::Aapcs64
        } else {
            vlk_types::types::Convention::of(image.isa, image.format, image.go)
        };
        Self {
            out: super::Emitter::default(),
            image,
            indirect,
        }
    }

    /// A pending relocation overrides the encoded branch offset.
    fn target_of(&self, operand: Operand, pc: u64) -> Option<u64> {
        if let Some(target) = self.image.relocations.get(&pc) {
            return Some(*target);
        }
        relative_target(operand, pc)
    }

    /// `cond` under the flags; flags set in another block are unknown.
    fn test(&self, cond: Cond) -> Test {
        self.out.test(cond, vlk_base::target::Isa::AArch64)
    }

    /// Copies `value` into a register of its own and reads it from there.
    fn hold(&mut self, value: Expr) -> Expr {
        self.out.hold(value)
    }

    /// The low `bits` of a vector register.
    fn read_simd(&self, slot: u16, bits: u16) -> Expr {
        let register = Expr::reg(slot, 64);
        if bits >= 64 {
            register
        } else {
            Expr::bin(BinOp::And, register, Expr::constant((1 << bits) - 1))
        }
    }

    /// A write of `bits` to a vector register, given as its low and high
    /// halves: below 128 bits the high half is zero, and a scalar clears
    /// the bits above it.
    fn write_simd(&mut self, slot: u16, bits: u16, (low, high): (Expr, Expr)) {
        let low = if bits < 64 {
            Expr::bin(BinOp::And, low, Expr::constant((1 << bits) - 1))
        } else {
            low
        };
        self.assign(
            RegRef {
                index: slot,
                width: 64,
            },
            low,
        );
        self.assign(
            RegRef {
                index: slot + 1,
                width: 64,
            },
            high,
        );
    }

    /// A write of a vector's halves; a 64-bit vector clears the high half.
    /// The high half is held first when it reads the low one it replaces.
    fn write_vector(&mut self, (slot, full, _): (u16, bool, u8), low: Expr, high: Expr) {
        let high = if full {
            let mut read = std::collections::HashSet::new();
            vlk_ir::ir::visit::collect_reads(&high, &mut read);
            if read.contains(&slot) {
                self.hold(high)
            } else {
                high
            }
        } else {
            Expr::constant(0)
        };
        self.write_simd(slot, 128, (low, high));
    }

    fn simd_store(&mut self, slot: u16, bits: u16, address: &Expr) {
        self.out.preserve(Write::Memory);
        if bits == 128 {
            let high = Expr::bin(BinOp::Add, address.clone(), Expr::constant(8));
            self.out.stmts.push(Stmt::Store {
                addr: address.clone(),
                value: Expr::reg(slot, 64),
                width: 8,
                at: None,
            });
            self.out.stmts.push(Stmt::Store {
                addr: high,
                value: Expr::reg(slot + 1, 64),
                width: 8,
                at: None,
            });
        } else {
            self.out.stmts.push(Stmt::Store {
                addr: address.clone(),
                value: self.read_simd(slot, bits),
                width: (bits / 8) as u8,
                at: None,
            });
        }
    }

    /// The condition encoded as `code`; `al` and `nv` both always hold.
    fn test_code(&self, code: u8) -> Test {
        match Cond::from_code(code) {
            Some(cond) => self.test(cond),
            None => Test::Always,
        }
    }

    /// Writes `then` or `els` to `dest` as `test` decides.
    fn select(&mut self, dest: RegRef, test: Test, then: Expr, els: Expr) {
        match test.select(then, els) {
            Some(value) => self.assign(dest, value),
            None => self.out.stmts.push(Stmt::unsupported(
                "conditional select on flags not modelled here".to_owned(),
            )),
        }
    }

    fn read_reg(index: u16, width: u8) -> Expr {
        if index == 31 && width == 32 {
            return Expr::constant(0);
        }
        let slot = Expr::reg(index, 64);
        if width == 32 {
            Expr::bin(BinOp::And, slot, Expr::constant(0xffff_ffff))
        } else {
            slot
        }
    }

    fn assign(&mut self, dest: RegRef, value: Expr) {
        self.out.preserve(Write::Register(dest.index, Some(&value)));
        let value = if dest.width == 32 {
            Expr::bin(BinOp::And, value, Expr::constant(0xffff_ffff))
        } else {
            value
        };
        self.out.stmts.push(Stmt::Assign {
            dest: RegRef {
                index: dest.index,
                width: 64,
            },
            value,
            at: None,
        });
    }

    fn operand(&self, operand: Operand, width: u8) -> Option<Expr> {
        match operand {
            Operand::Register(_, 31) => Some(Expr::constant(0)),
            Operand::Register(_, index) => Some(Self::read_reg(index, width)),
            Operand::RegisterOrSP(_, 31) => Some(Expr::reg(31, 64)),
            // A 32-bit operand reads only the register's low half.
            Operand::RegisterOrSP(size, index) => {
                if size == SizeCode::X {
                    Some(Expr::reg(index, 64))
                } else {
                    Some(Self::read_reg(index, 32))
                }
            }
            Operand::Immediate(value) => Some(Expr::constant(value as u64)),
            Operand::Imm16(value) => Some(Expr::constant(value as u64)),
            Operand::Imm64(value) => Some(Expr::constant(value)),
            Operand::ImmShift(value, shift) => Some(Expr::constant((value as u64) << shift)),
            Operand::RegShift(style, amount, size, index) => {
                let source = if size == SizeCode::X { 64 } else { 32 };
                let value = if index == 31 {
                    Expr::constant(0)
                } else {
                    Self::read_reg(index, source)
                };
                let extended = extend_shift(style, amount as u64, value, size)?;
                // A sign-extended source of a 32-bit operation keeps its low half.
                let signed = matches!(
                    style,
                    a64::ShiftStyle::SXTB
                        | a64::ShiftStyle::SXTH
                        | a64::ShiftStyle::SXTW
                        | a64::ShiftStyle::SXTX
                );
                Some(if width == 32 && signed {
                    Expr::bin(BinOp::And, extended, Expr::constant(0xffff_ffff))
                } else {
                    extended
                })
            }
            Operand::PCOffset(offset) => Some(Expr::constant(offset as u64)),
            Operand::Nothing => None,
            // A vector operand, which the scalar handlers cannot express.
            _ => {
                self.out.incomplete.set(true);
                None
            }
        }
    }
}

/// Whether an instruction writes NZCV; `msr` stands for the writes to PSTATE
/// (`cfinv`, `axflag`) the decoder shows as one.
fn sets_flags(opcode: a64::Opcode) -> bool {
    use a64::Opcode as O;
    matches!(
        opcode,
        O::ADDS
            | O::SUBS
            | O::ANDS
            | O::BICS
            | O::ADCS
            | O::SBCS
            | O::CCMP
            | O::CCMN
            | O::FCMP
            | O::FCMPE
            | O::FCCMP
            | O::FCCMPE
            | O::MSR
            | O::RMIF
            | O::SETF8
            | O::SETF16
            | O::SUBPS
    )
}

/// The registers, as the IR numbers them, an instruction may write: every
/// register it names, and a base it writes back.
fn possibly_written_registers(instruction: &Instruction) -> Vec<u16> {
    let vector = |number: u16| {
        let slot = vlk_arch::arch::aarch64::V0 + 2 * number;
        [slot, slot + 1]
    };
    let mut out = Vec::new();
    for operand in instruction.operands {
        match operand {
            Operand::Register(_, 31) => {}
            Operand::Register(_, index) | Operand::RegisterOrSP(_, index) => out.push(index),
            Operand::SIMDRegister(_, number)
            | Operand::SIMDRegisterElements(_, number, _)
            | Operand::SIMDRegisterElementsLane(_, number, ..)
            | Operand::SIMDRegisterElementsMultipleLane(_, number, ..) => {
                out.extend(vector(number))
            }
            Operand::SIMDRegisterGroup(_, number, _, count)
            | Operand::SIMDRegisterGroupLane(number, _, count, _) => {
                for offset in 0..u16::from(count) {
                    out.extend(vector((number + offset) % 32));
                }
            }
            Operand::RegPreIndex(base, _, true)
            | Operand::RegPostIndex(base, _)
            | Operand::RegPostIndexReg(base, _) => out.push(base),
            _ => {}
        }
    }
    out.sort_unstable();
    out.dedup();
    out
}

/// A call's write of the address after it, at `pc`, to the link register.
fn link(lifter: &mut Lifter, pc: u64) {
    let dest = RegRef {
        index: LR,
        width: 64,
    };
    lifter.assign(dest, Expr::constant(pc.wrapping_add(4)));
}

fn relative_target(operand: Operand, pc: u64) -> Option<u64> {
    match operand {
        Operand::PCOffset(offset) => Some(pc.wrapping_add(offset as u64)),
        _ => None,
    }
}

fn lift_conditional_branch(lifter: &mut Lifter, operands: [Operand; 4], code: u8, pc: u64) -> bool {
    let Some(target) = lifter.target_of(operands[0], pc) else {
        lifter
            .out
            .stmts
            .push(Stmt::unsupported("branch target".to_owned()));
        return true;
    };
    let test = lifter.test_code(code);
    // Only a condition the flags here leave open names itself in the branch.
    let cond = Cond::from_code(code).unwrap_or(Cond::Eq);
    lifter.out.stmts.extend(test.branch(cond, target));
    true
}

fn lift_compare_branch(
    lifter: &mut Lifter,
    operands: [Operand; 4],
    pc: u64,
    non_zero: bool,
) -> bool {
    // `cbz w0` tests only the low half.
    let width = destination(operands[0]).map_or(64, |register| register.width);
    let Some(value) = lifter.operand(operands[0], width) else {
        return true;
    };
    let Some(target) = relative_target(operands[1], pc) else {
        return true;
    };
    lifter.out.stmts.push(Stmt::Brif {
        cond: if non_zero { Cond::Ne } else { Cond::Eq },
        lhs: value,
        rhs: Expr::constant(0),
        target,
        at: None,
    });
    true
}

fn lift_test_branch(lifter: &mut Lifter, operands: [Operand; 4], pc: u64, non_zero: bool) -> bool {
    let Some(value) = lifter.operand(operands[0], 64) else {
        return true;
    };
    let Some(bit) = immediate(operands[1]) else {
        return true;
    };
    let Some(target) = relative_target(operands[2], pc) else {
        return true;
    };
    let masked = Expr::bin(BinOp::And, value, Expr::constant(1u64 << (bit & 63)));
    lifter.out.stmts.push(Stmt::Brif {
        cond: if non_zero { Cond::Ne } else { Cond::Eq },
        lhs: masked,
        rhs: Expr::constant(0),
        target,
        at: None,
    });
    true
}

fn lift_instruction(lifter: &mut Lifter, instruction: &Instruction, pc: u64) -> bool {
    if atomic::lift(lifter, instruction)
        || exclusive::lift(lifter, instruction)
        || structures::lift(lifter, instruction)
        || simd::lift(lifter, instruction)
        || system::lift(lifter, instruction)
    {
        return false;
    }
    use a64::Opcode as O;
    let operands = instruction.operands;
    if lift_float(lifter, instruction).is_some()
        || lift_vector(lifter, instruction).is_some()
        || lift_vector_float(lifter, instruction).is_some()
    {
        return false;
    }
    // Only loads and stores handle vector operands past this point.
    let vector_operand = instruction.operands.iter().any(|operand| {
        matches!(
            operand,
            Operand::SIMDRegister(..)
                | Operand::SIMDRegisterElements(..)
                | Operand::SIMDRegisterElementsLane(..)
                | Operand::SIMDRegisterElementsMultipleLane(..)
                | Operand::SIMDRegisterGroup(..)
                | Operand::SIMDRegisterGroupLane(..)
        )
    });
    if vector_operand
        && !matches!(
            instruction.opcode,
            O::LDR | O::LDUR | O::STR | O::STUR | O::LDP | O::STP | O::LDNP | O::STNP
        )
    {
        lifter.out.stmts.push(Stmt::unsupported(format!(
            "{:?} at 0x{pc:x}",
            instruction.opcode
        )));
        return false;
    }

    match instruction.opcode {
        O::ADD => lift_alu(lifter, operands, BinOp::Add, false),
        O::ADDS => lift_alu(lifter, operands, BinOp::Add, true),
        O::SUB => lift_alu(lifter, operands, BinOp::Sub, false),
        O::SUBS => lift_alu(lifter, operands, BinOp::Sub, true),
        O::AND => lift_alu(lifter, operands, BinOp::And, false),
        O::ANDS => lift_alu(lifter, operands, BinOp::And, true),
        O::ORR => lift_alu(lifter, operands, BinOp::Or, false),
        O::EOR => lift_alu(lifter, operands, BinOp::Xor, false),
        O::BIC => lift_bic(lifter, operands, false),
        O::BICS => lift_bic(lifter, operands, true),
        O::MUL => lift_madd(lifter, operands, false),
        O::UMULH => lift_mul_high(lifter, operands, false),
        O::SMULH => lift_mul_high(lifter, operands, true),
        O::MADD => lift_madd(lifter, operands, true),
        O::CSEL => lift_csel(lifter, operands),
        O::CSINC | O::CSINV | O::CSNEG => lift_cs_family(lifter, operands, instruction.opcode),
        O::MSUB => lift_msub(lifter, operands),
        O::UMADDL => {
            lift_long_multiply(
                lifter,
                operands,
                Signedness::Unsigned,
                /* subtract */ false,
            )
        }
        O::SMADDL => lift_long_multiply(
            lifter,
            operands,
            Signedness::Signed,
            /* subtract */ false,
        ),
        O::UMSUBL => {
            lift_long_multiply(
                lifter,
                operands,
                Signedness::Unsigned,
                /* subtract */ true,
            )
        }
        O::SMSUBL => lift_long_multiply(
            lifter,
            operands,
            Signedness::Signed,
            /* subtract */ true,
        ),
        O::CCMP => lift_conditional_compare(lifter, operands, false),
        O::CCMN => lift_conditional_compare(lifter, operands, true),
        O::ADC => lift_with_carry(
            lifter,
            operands,
            /* subtract */ false,
            FlagUpdate::Preserve,
        ),
        O::ADCS => lift_with_carry(lifter, operands, /* subtract */ false, FlagUpdate::Set),
        O::SBC => lift_with_carry(
            lifter,
            operands,
            /* subtract */ true,
            FlagUpdate::Preserve,
        ),
        O::SBCS => lift_with_carry(lifter, operands, /* subtract */ true, FlagUpdate::Set),
        O::BFM => lift_bitfield_insert(lifter, operands),
        O::MOVZ => lift_mov(lifter, operands, false),
        O::MOVN => lift_mov(lifter, operands, true),
        O::MOVK => lift_movk(lifter, operands),
        O::UBFM => lift_bitfield(lifter, operands, false),
        O::SBFM => lift_bitfield(lifter, operands, true),
        O::LSLV => lift_variable_shift(lifter, operands, a64::ShiftStyle::LSL),
        O::LSRV => lift_variable_shift(lifter, operands, a64::ShiftStyle::LSR),
        O::ASRV => lift_variable_shift(lifter, operands, a64::ShiftStyle::ASR),
        O::RORV => lift_variable_shift(lifter, operands, a64::ShiftStyle::ROR),
        O::EXTR => lift_extract(lifter, operands),
        O::ORN => lift_inverted(lifter, operands, BinOp::Or),
        O::EON => lift_inverted(lifter, operands, BinOp::Xor),
        O::REV => lift_reverse(lifter, operands, None),
        O::CLZ | O::CLS | O::RBIT => lift_count(lifter, operands, instruction.opcode),
        O::REV16 => lift_reverse(lifter, operands, Some(2)),
        O::REV32 => lift_reverse(lifter, operands, Some(4)),
        O::LDR | O::LDRAA | O::LDRAB => lift_load(lifter, operands, O::LDR, pc),
        O::LDRB => lift_load(lifter, operands, O::LDRB, pc),
        O::LDRH => lift_load(lifter, operands, O::LDRH, pc),
        O::LDRSB => lift_load(lifter, operands, O::LDRSB, pc),
        O::LDRSH => lift_load(lifter, operands, O::LDRSH, pc),
        O::LDRSW => lift_load(lifter, operands, O::LDRSW, pc),
        O::STR => lift_store(lifter, operands, O::STR),
        O::STRB => lift_store(lifter, operands, O::STRB),
        O::STRH => lift_store(lifter, operands, O::STRH),
        // The unscaled forms differ only in how the offset is encoded.
        O::LDUR => lift_load(lifter, operands, O::LDR, pc),
        O::LDURB => lift_load(lifter, operands, O::LDRB, pc),
        O::LDURH => lift_load(lifter, operands, O::LDRH, pc),
        O::LDURSB => lift_load(lifter, operands, O::LDRSB, pc),
        O::LDURSH => lift_load(lifter, operands, O::LDRSH, pc),
        O::LDURSW => lift_load(lifter, operands, O::LDRSW, pc),
        O::STUR => lift_store(lifter, operands, O::STR),
        O::STURB => lift_store(lifter, operands, O::STRB),
        O::STURH => lift_store(lifter, operands, O::STRH),
        O::SDIV => lift_alu(lifter, operands, BinOp::DivS, false),
        O::UDIV => lift_alu(lifter, operands, BinOp::DivU, false),
        O::LDP | O::LDNP => lift_pair(
            lifter,
            operands,
            MemoryAccess::Load,
            /* signed */ false,
        ),
        O::LDPSW => lift_pair(lifter, operands, MemoryAccess::Load, /* signed */ true),
        O::STP | O::STNP => lift_pair(
            lifter,
            operands,
            MemoryAccess::Store,
            /* signed */ false,
        ),
        O::B => {
            let target = lifter.target_of(operands[0], pc);
            // In an object a branch to itself is an unresolved reference to
            // another function; lift it as a tail call. In a linked image it
            // is an endless loop.
            if target == Some(pc) && lifter.image.relocatable {
                lifter.out.stmts.extend([
                    bare(CallKind::Tail, lifter.image, None),
                    Stmt::Ret {
                        value: Expr::reg(vlk_arch::arch::RETURN, 64),
                        at: None,
                    },
                ]);
                return true;
            }
            // Whether a branch out of the function is a tail call is
            // decided once its blocks are known.
            lifter.out.stmts.push(Stmt::Br { target, at: None });
            return true;
        }
        O::Bcc(code) => return lift_conditional_branch(lifter, operands, code, pc),
        O::CBZ => return lift_compare_branch(lifter, operands, pc, false),
        O::CBNZ => return lift_compare_branch(lifter, operands, pc, true),
        O::TBZ => return lift_test_branch(lifter, operands, pc, false),
        O::TBNZ => return lift_test_branch(lifter, operands, pc, true),
        O::BR | O::BRAA | O::BRAAZ | O::BRAB | O::BRABZ => {
            if let Some(target) = lifter.operand(operands[0], 64) {
                lifter.out.stmts.push(Stmt::BrIndirect { target, at: None });
            }
            return true;
        }
        O::BLR | O::BLRAA | O::BLRAAZ | O::BLRAB | O::BLRABZ => {
            // A call leaves the flags undefined.
            lifter.out.flags.pending = None;
            if let Some(through) = lifter.operand(operands[0], 64) {
                // `blr x30` jumps to the address x30 held before the link.
                let through = if matches!(through, Expr::Reg { index: LR, .. }) {
                    lifter.hold(through)
                } else {
                    through
                };
                link(lifter, pc);
                lifter.out.stmts.push(super::call_through_as(
                    CallKind::Invoke,
                    lifter.image,
                    through,
                    lifter.indirect,
                ));
            }
        }
        O::BL => {
            let target = lifter.target_of(operands[0], pc);
            // An outlined sequence runs as part of its caller: it reads and
            // leaves flags and registers no call would.
            if let Some(body) = target.and_then(|target| outlined_body(lifter.image, target)) {
                link(lifter, pc);
                for step in &body {
                    Machine::step(lifter, &step.instruction, step.pc);
                }
                return false;
            }
            lifter.out.flags.pending = None;
            link(lifter, pc);
            lifter
                .out
                .stmts
                .push(bare(CallKind::Invoke, lifter.image, target));
        }
        O::BRK | O::UDF => {
            lifter.out.stmts.push(Stmt::Trap { at: None });
            return true;
        }
        O::RET | O::RETAA | O::RETAB => {
            let value = Lifter::read_reg(0, 64);
            lifter.out.stmts.push(Stmt::Ret { value, at: None });
            return true;
        }
        O::ADRP => {
            if let (Some(dest), Operand::PCOffset(offset)) = (destination(operands[0]), operands[1])
            {
                let page = pc & !0xfff;
                let value = Expr::constant(page.wrapping_add(offset as u64));
                lifter.assign(dest, value);
            }
        }
        O::ADR => {
            if let (Some(dest), Operand::PCOffset(offset)) = (destination(operands[0]), operands[1])
            {
                let value = Expr::constant(pc.wrapping_add(offset as u64));
                lifter.assign(dest, value);
            }
        }
        // Pointers hold valid addresses without authentication codes in this model.
        // Signing, authentication and stripping therefore preserve their values.
        O::PACIA
        | O::PACIB
        | O::PACDA
        | O::PACDB
        | O::AUTIA
        | O::AUTIB
        | O::AUTDA
        | O::AUTDB
        | O::PACIZA
        | O::PACIZB
        | O::PACDZA
        | O::PACDZB
        | O::AUTIZA
        | O::AUTIZB
        | O::AUTDZA
        | O::AUTDZB
        | O::PACIASP
        | O::PACIAZ
        | O::PACIA1716
        | O::PACIBSP
        | O::PACIBZ
        | O::PACIB1716
        | O::AUTIASP
        | O::AUTIAZ
        | O::AUTIA1716
        | O::AUTIBSP
        | O::AUTIBZ
        | O::AUTIB1716
        | O::XPACI
        | O::XPACD
        | O::XPACLRI
        | O::HINT => {}
        O::CRC32B
        | O::CRC32H
        | O::CRC32W
        | O::CRC32X
        | O::CRC32CB
        | O::CRC32CH
        | O::CRC32CW
        | O::CRC32CX => {
            let (castagnoli, bits) = match instruction.opcode {
                O::CRC32B => (false, 8),
                O::CRC32H => (false, 16),
                O::CRC32W => (false, 32),
                O::CRC32X => (false, 64),
                O::CRC32CB => (true, 8),
                O::CRC32CH => (true, 16),
                O::CRC32CW => (true, 32),
                _ => (true, 64),
            };
            if let (Some(dest), Some(crc), Some(data)) = (
                destination(operands[0]),
                lifter.operand(operands[1], 32),
                lifter.operand(operands[2], bits.max(32)),
            ) {
                let value = Expr::apply(Operation::Crc32 { castagnoli, bits }, vec![crc, data]);
                lifter.assign(dest, value);
            }
        }
        // The kernel's call: its number and arguments in registers.
        O::SVC
            if matches!(
                operands[0],
                Operand::Immediate(0) | Operand::Imm16(0) | Operand::Imm64(0)
            ) =>
        {
            lifter.out.stmts.push(Stmt::Call {
                kind: CallKind::Syscall,
                target: None,
                through: None,
                convention: vlk_types::types::Convention::SyscallArm,
                args: None,
                // The kernel reads no floating-point register.
                floats_named: true,
                abi: None,
                clobbers: None,
                outputs: vlk_ir::ir::fallback_call_outputs(
                    vlk_types::types::Convention::SyscallArm,
                    None,
                ),
                via: None,
                at: None,
            })
        }
        other => {
            lifter
                .out
                .stmts
                .push(Stmt::unsupported(format!("{other:?} at 0x{pc:x}")));
        }
    }
    false
}

/// The most instructions of an outlined sequence written into its caller.
const OUTLINED_LIMIT: usize = 32;

/// The instructions of the outlined sequence at `address`, without the
/// return that ends it: the compiler moved them out of several functions
/// and calls them with whatever registers and flags they need. Only a
/// sequence named as one, with no branch or call in it, is taken.
fn outlined_body(
    image: &vlk_loader::loader::Image,
    address: u64,
) -> Option<Vec<Decoded<Instruction>>> {
    use a64::Opcode as O;
    let Some(function) = image.functions.get(&address) else {
        return None;
    };
    let named = function.name.iter().chain(&function.aliases).any(|name| {
        name.trim_start_matches('_')
            .starts_with("OUTLINED_FUNCTION_")
    });
    let Some(size) = function.size else {
        return None;
    };
    if !named || function.size_estimated || size == 0 || size > (OUTLINED_LIMIT as u64 + 1) * 4 {
        return None;
    }
    let Some(bytes) = image.read_vaddr(address, size) else {
        return None;
    };
    // The sequence returns through the link register.
    if !bytes.ends_with(&0xd65f_03c0u32.to_le_bytes()) {
        return None;
    }
    let (mut body, stop) = decode(bytes, address);
    if stop.is_some() || body.len() as u64 * 4 != size {
        return None;
    }
    body.pop();
    let straight = body.iter().all(|step| {
        !matches!(
            step.instruction.opcode,
            O::B | O::Bcc(_)
                | O::BL
                | O::BLR
                | O::BR
                | O::CBZ
                | O::CBNZ
                | O::TBZ
                | O::TBNZ
                | O::RET
                | O::RETAA
                | O::RETAB
                | O::BRK
                | O::UDF
                | O::SVC
        )
    });
    straight.then_some(body)
}

fn branch_target(instruction: &Instruction, pc: u64) -> Option<u64> {
    use a64::Opcode as O;
    match instruction.opcode {
        O::B | O::Bcc(_) | O::BL => relative_target(instruction.operands[0], pc),
        O::CBZ | O::CBNZ => relative_target(instruction.operands[1], pc),
        O::TBZ | O::TBNZ => relative_target(instruction.operands[2], pc),
        _ => None,
    }
}

/// Gives a write to a system register the register its word names. The
/// decoder reads four of the five bits, so `msr dit, xzr` came out as
/// writing x15.
pub fn written_register(word: &[u8], instruction: &mut Instruction) {
    if instruction.opcode == a64::Opcode::MSR
        && let Operand::Register(_, register) = &mut instruction.operands[1]
        && let Some(first) = word.first()
    {
        *register = u16::from(first & 31);
    }
}

/// The undefined instruction Go writes where control never arrives.
const GO_UNDEFINED: u32 = 0xbea7_1700;

pub(super) fn decode(bytes: &[u8], addr: u64) -> (Vec<Decoded<Instruction>>, Option<String>) {
    let mut reader = ReaderBuilder::<u64, u8>::read_at(bytes, 0);
    let decoder = a64::InstDecoder::default();
    let count = bytes.len() / 4;
    let mut decoded = Vec::new();
    let mut pc = addr;
    for _ in 0..count {
        let Some(next) = pc.checked_add(4) else {
            return (
                decoded,
                Some(format!("instruction address overflows at 0x{pc:x}")),
            );
        };
        match decoder.decode(&mut reader) {
            Ok(mut instruction) => {
                if let Some(word) = bytes.get((pc - addr) as usize..(next - addr) as usize) {
                    written_register(word, &mut instruction);
                }
                decoded.push(Decoded {
                    pc,
                    next,
                    instruction,
                });
            }
            // Go's assembler marks code that is never reached with this
            // word, which no processor decodes: it traps like `udf`.
            Err(_)
                if bytes.get((pc - addr) as usize..(next - addr) as usize)
                    == Some(&GO_UNDEFINED.to_le_bytes()[..])
                    && let Ok(instruction) = decoder
                        .decode(&mut ReaderBuilder::<u64, u8>::read_at(&[0u8; 4][..], 0)) =>
            {
                decoded.push(Decoded {
                    pc,
                    next,
                    instruction,
                });
            }
            Err(error) => {
                return (
                    decoded,
                    Some(format!("undecodable instruction at 0x{pc:x}: {error}")),
                );
            }
        }
        pc = next;
    }
    (decoded, None)
}

impl Machine for Lifter<'_> {
    type Instruction = Instruction;

    fn out(&mut self) -> &mut super::Emitter {
        &mut self.out
    }

    fn branch_target(&self, instruction: &Instruction, pc: u64) -> Option<u64> {
        // In an object file a call or jump whose target the linker fills
        // in encodes its own address: its relocation says where it goes.
        if matches!(instruction.opcode, a64::Opcode::B | a64::Opcode::BL)
            && let Some(target) = self.image.relocations.get(&pc)
        {
            return Some(*target);
        }
        branch_target(instruction, pc)
    }

    fn step(&mut self, instruction: &Instruction, pc: u64) -> bool {
        lift_instruction(self, instruction, pc)
    }

    fn name(&self, instruction: &Instruction) -> String {
        format!("{:?}", instruction.opcode)
    }

    fn written(&mut self, instruction: &Instruction) -> Option<Vec<u16>> {
        Some(possibly_written_registers(instruction))
    }

    fn sets_flags(&self, instruction: &Instruction) -> bool {
        sets_flags(instruction.opcode)
    }

    fn reads_flags(&self, instruction: &Instruction) -> bool {
        matches!(
            instruction.opcode,
            a64::Opcode::CSEL | a64::Opcode::CSINC | a64::Opcode::CSINV | a64::Opcode::CSNEG
        )
    }
}

#[cfg(test)]
mod tests;