ckb-vm 0.20.0-alpha

CKB's Virtual machine
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
mod emitter;
use emitter::Emitter;

use std::collections::{HashMap, HashSet};
use std::mem;
use std::rc::Rc;

use bytes::Bytes;
use memmap::{Mmap, MmapMut};
use scroll::Pread;

use super::super::{
    decoder::build_decoder,
    instructions::{
        ast::Value, execute, instruction_length, is_basic_block_end_instruction,
        is_slowpath_instruction, Instruction,
    },
    machine::{elf_adaptor, SupportMachine, VERSION1},
    CoreMachine, DefaultCoreMachine, Error, FlatMemory, InstructionCycleFunc, Machine, Memory,
    Register, RISCV_MAX_MEMORY,
};

const MAXIMUM_INSTRUCTIONS_PER_BLOCK: usize = 1024;
const MAXIMUM_LABELS: usize = 65535;
const MAXIMUM_SECTIONS: usize = 1024;
const MAXIMUM_DUMMY_SECTIONS: usize = 64;

const ADDRESS_WRITE_ONLY_FLAG: u64 = 0x8000_0000_0000_0000;
const ADDRESS_LABEL_FLAG: u64 = 0x4000_0000_0000_0000;
const MAXIMUM_ENCODED_ADDRESS: u64 = 0x8000_0000;

#[derive(Debug, Clone)]
pub enum Write {
    Memory {
        address: Value,
        size: u8,
        value: Value,
    },
    Register {
        index: usize,
        value: Value,
    },
    Pc {
        value: Value,
    },
    Ecall,
    Ebreak,
    Slowpath,
}

fn init_registers() -> [Value; 32] {
    [
        Value::Imm(0),
        Value::Register(1),
        Value::Register(2),
        Value::Register(3),
        Value::Register(4),
        Value::Register(5),
        Value::Register(6),
        Value::Register(7),
        Value::Register(8),
        Value::Register(9),
        Value::Register(10),
        Value::Register(11),
        Value::Register(12),
        Value::Register(13),
        Value::Register(14),
        Value::Register(15),
        Value::Register(16),
        Value::Register(17),
        Value::Register(18),
        Value::Register(19),
        Value::Register(20),
        Value::Register(21),
        Value::Register(22),
        Value::Register(23),
        Value::Register(24),
        Value::Register(25),
        Value::Register(26),
        Value::Register(27),
        Value::Register(28),
        Value::Register(29),
        Value::Register(30),
        Value::Register(31),
    ]
}

struct LabelGatheringMachine {
    registers: [Value; 32],
    pc: Value,
    next_pc: Value,
    labels_to_test: Vec<u64>,
    isa: u8,
    version: u32,

    // A memory segment which contains code loaded from ELF
    memory: FlatMemory<u64>,
    labels: HashSet<u64>,
    sections: Vec<(u64, u64)>,
    dummy_sections: HashMap<u64, u64>,
}

impl LabelGatheringMachine {
    pub fn load(program: &Bytes, isa: u8, version: u32) -> Result<Self, Error> {
        let section_headers: Vec<elf_adaptor::SectionHeader> = if version < VERSION1 {
            use goblin_v023::container::Ctx;
            use goblin_v023::elf::{Header, SectionHeader};

            let header = program.pread::<Header>(0).map_err(|_e| Error::ParseError)?;
            let container = header.container().map_err(|_e| Error::InvalidElfBits)?;
            let endianness = header.endianness().map_err(|_e| Error::InvalidElfBits)?;
            if <Self as CoreMachine>::REG::BITS != if container.is_big() { 64 } else { 32 } {
                return Err(Error::InvalidElfBits);
            }
            let ctx = Ctx::new(container, endianness);
            SectionHeader::parse(
                program,
                header.e_shoff as usize,
                header.e_shnum as usize,
                ctx,
            )
            .map_err(|_e| Error::ParseError)?
            .iter()
            .map(elf_adaptor::SectionHeader::from_v0)
            .collect()
        } else {
            use goblin_v040::container::Ctx;
            use goblin_v040::elf::{Header, SectionHeader};

            let header = program.pread::<Header>(0).map_err(|_e| Error::ParseError)?;
            let container = header.container().map_err(|_e| Error::InvalidElfBits)?;
            let endianness = header.endianness().map_err(|_e| Error::InvalidElfBits)?;
            if <Self as CoreMachine>::REG::BITS != if container.is_big() { 64 } else { 32 } {
                return Err(Error::InvalidElfBits);
            }
            let ctx = Ctx::new(container, endianness);
            SectionHeader::parse(
                program,
                header.e_shoff as usize,
                header.e_shnum as usize,
                ctx,
            )
            .map_err(|_e| Error::ParseError)?
            .iter()
            .map(elf_adaptor::SectionHeader::from_v1)
            .collect()
        };
        if section_headers.len() > MAXIMUM_SECTIONS {
            return Err(Error::LimitReached);
        }
        let mut sections: Vec<(u64, u64)> = section_headers
            .iter()
            .filter_map(|section_header| {
                if section_header.sh_flags & u64::from(elf_adaptor::SHF_EXECINSTR) != 0 {
                    Some((
                        section_header.sh_addr,
                        section_header.sh_addr.wrapping_add(section_header.sh_size),
                    ))
                } else {
                    None
                }
            })
            .rev()
            .collect();
        // Test there's no empty section
        if sections.iter().any(|(s, e)| s >= e) {
            return Err(Error::OutOfBound);
        }
        // Test no section overlaps with one another. We first sort section
        // list by start, then we test if each end is equal or less than
        // the next start.
        sections.sort_by_key(|section| section.0);
        if sections.windows(2).any(|w| w[0].1 > w[1].0) {
            return Err(Error::OutOfBound);
        }
        // DefaultCoreMachine is only used here for loading ELF binaries
        // into memory.
        let mut inner = DefaultCoreMachine::new(isa, version, 0);
        inner.load_elf(&program, false)?;

        Ok(Self {
            isa,
            version,
            registers: init_registers(),
            pc: Value::from_u64(0),
            next_pc: Value::from_u64(0),
            labels: HashSet::default(),
            labels_to_test: Vec::new(),
            memory: inner.take_memory(),
            sections,
            dummy_sections: HashMap::default(),
        })
    }

    fn read_pc(&self) -> Result<u64, Error> {
        match &self.pc {
            Value::Imm(pc) => Ok(*pc),
            _ => Err(Error::Unexpected),
        }
    }

    pub fn gather(&mut self) -> Result<(), Error> {
        let decoder = build_decoder::<u64>(self.isa());
        for i in 0..self.sections.len() {
            let (section_start, section_end) = self.sections[i];
            self.pc = Value::from_u64(section_start);
            let mut start_of_basic_block = true;
            while self.read_pc()? < section_end {
                let pc = self.read_pc()?;
                match decoder.decode(&mut self.memory, pc) {
                    Ok(instruction) => {
                        if start_of_basic_block {
                            self.labels.insert(pc);
                        }
                        start_of_basic_block = is_basic_block_end_instruction(instruction);
                        let next_pc = pc + u64::from(instruction_length(instruction));
                        self.update_pc(Value::from_u64(next_pc));
                        execute(instruction, self)?;
                        for label in self.labels_to_test.drain(..) {
                            if label != next_pc && label < section_end && label >= section_start {
                                self.labels.insert(label);
                            }
                        }
                        if self.labels.len() > MAXIMUM_LABELS {
                            return Err(Error::LimitReached);
                        }
                        self.pc = Value::from_u64(next_pc);
                    }
                    Err(Error::InvalidInstruction(i)) if i == 0 => {
                        // Due to alignment or other reasons, the code might
                        // certain invalid instructions in the executable
                        // sections, for a normal VM instance that's executing
                        // instructions, this is usually fine since the invalid
                        // regions might never be touched. But for an AOT
                        // solution, this won't work since we have to
                        // pre-process the whole text section without knowing
                        // which part would be touched. The solution here, is
                        // to skip sections containing invalid instructions,
                        // keep a note of them, and ignore them in the code
                        // generation phase. One caveat here,
                        // is that a malicious program might choose to include
                        // invalid instructions everywhere, hence creating
                        // numerous sections hoping to bring the program down.
                        // To tackle that, we will add an upper bound on the
                        // number of dummy sections allowed here. That
                        // allow us to signal correct error and revert back
                        // to assembly VM for those quirky programs.
                        if !start_of_basic_block {
                            return Err(Error::OutOfBound);
                        }
                        let mut dummy_end = pc + 2;
                        while dummy_end < section_end && self.memory.execute_load16(dummy_end)? == 0
                        {
                            dummy_end += 2;
                        }
                        // We checked no sections are overlapped, so dummy
                        // sections won't overlap with each other as well.
                        self.dummy_sections.insert(pc, dummy_end);
                        if self.dummy_sections.len() > MAXIMUM_DUMMY_SECTIONS {
                            return Err(Error::LimitReached);
                        }
                        self.pc = Value::from_u64(dummy_end);
                    }
                    Err(e) => return Err(e),
                }
            }
            // A section must end a basic block, otherwise we would run into
            // out of bound error;
            if !start_of_basic_block {
                return Err(Error::OutOfBound);
            }
            debug_assert!(!self.labels.contains(&section_end));
        }
        // Remove all labels pointed to dummy sections, since we won't generate
        // code for dummy sections
        for (dummy_start, dummy_end) in &self.dummy_sections {
            self.labels
                .retain(|label| *label < *dummy_start || *label >= *dummy_end);
        }
        Ok(())
    }
}

impl CoreMachine for LabelGatheringMachine {
    type REG = Value;
    type MEM = Self;

    fn pc(&self) -> &Value {
        &self.pc
    }

    fn update_pc(&mut self, pc: Self::REG) {
        self.next_pc = pc;
    }

    fn commit_pc(&mut self) {
        match self.next_pc.clone() {
            Value::Imm(pc) => self.labels_to_test.push(pc),
            Value::Cond(_, t, f) => {
                if let (Value::Imm(t), Value::Imm(f)) = (&*t, &*f) {
                    self.labels_to_test.push(*t);
                    self.labels_to_test.push(*f);
                }
            }
            _ => (),
        }
    }

    fn memory(&self) -> &Self {
        &self
    }

    fn memory_mut(&mut self) -> &mut Self {
        self
    }

    fn registers(&self) -> &[Value] {
        &self.registers
    }

    fn set_register(&mut self, _idx: usize, _value: Value) {
        // This is a NOP since we only care about PC writes
    }

    fn isa(&self) -> u8 {
        self.isa
    }

    fn version(&self) -> u32 {
        self.version
    }
}

impl Machine for LabelGatheringMachine {
    fn ecall(&mut self) -> Result<(), Error> {
        // This is a basic block end instruction, main loop will record the
        // address after this instruction.
        Ok(())
    }

    fn ebreak(&mut self) -> Result<(), Error> {
        // This is a basic block end instruction, main loop will record the
        // address after this instruction.
        Ok(())
    }
}

impl Memory for LabelGatheringMachine {
    type REG = Value;

    fn init_pages(
        &mut self,
        _addr: u64,
        _size: u64,
        _flags: u8,
        _source: Option<Bytes>,
        _offset_from_addr: u64,
    ) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn fetch_flag(&mut self, _page: u64) -> Result<u8, Error> {
        Err(Error::Unimplemented)
    }

    fn set_flag(&mut self, _page: u64, _flag: u8) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn clear_flag(&mut self, _page: u64, _flag: u8) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn store_byte(&mut self, _addr: u64, _size: u64, _value: u8) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn store_bytes(&mut self, _addr: u64, _value: &[u8]) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn execute_load16(&mut self, _addr: u64) -> Result<u16, Error> {
        Err(Error::Unimplemented)
    }

    fn execute_load32(&mut self, _addr: u64) -> Result<u32, Error> {
        Err(Error::Unimplemented)
    }

    fn load8(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 1))
    }

    fn load16(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 2))
    }

    fn load32(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 4))
    }

    fn load64(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 8))
    }

    fn store8(&mut self, _addr: &Value, _value: &Value) -> Result<(), Error> {
        Ok(())
    }

    fn store16(&mut self, _addr: &Value, _value: &Value) -> Result<(), Error> {
        Ok(())
    }

    fn store32(&mut self, _addr: &Value, _value: &Value) -> Result<(), Error> {
        Ok(())
    }

    fn store64(&mut self, _addr: &Value, _value: &Value) -> Result<(), Error> {
        Ok(())
    }
}

pub struct AotCode {
    pub code: Mmap,
    /// Labels that map RISC-V addresses to offsets into the compiled x86_64
    /// assembly code. This can be used as entrypoints to start executing in
    /// AOT code.
    pub labels: HashMap<u64, u32>,
}

impl AotCode {
    pub fn base_address(&self) -> u64 {
        self.code.as_ptr() as u64
    }
}

pub struct AotCompilingMachine {
    isa: u8,
    version: u32,
    registers: [Value; 32],
    pc: Value,
    next_pc: Value,
    emitter: Emitter,
    memory: FlatMemory<u64>,
    sections: Vec<(u64, u64)>,
    dummy_sections: HashMap<u64, u64>,
    addresses_to_labels: HashMap<u64, u32>,
    writes: Vec<Write>,
    next_pc_write: Option<Value>,
    instruction_cycle_func: Option<Box<InstructionCycleFunc>>,
}

impl AotCompilingMachine {
    pub fn load(
        program: &Bytes,
        instruction_cycle_func: Option<Box<InstructionCycleFunc>>,
        isa: u8,
        version: u32,
    ) -> Result<Self, Error> {
        // First we need to gather labels
        let mut label_gathering_machine = LabelGatheringMachine::load(&program, isa, version)?;
        label_gathering_machine.gather()?;

        let mut labels: Vec<u64> = label_gathering_machine.labels.iter().cloned().collect();
        labels.sort_unstable();
        let addresses_to_labels = labels
            .iter()
            .enumerate()
            .map(|(i, address)| (*address, i as u32))
            .collect();

        Ok(Self {
            isa,
            version,
            registers: init_registers(),
            pc: Value::from_u64(0),
            next_pc: Value::from_u64(0),
            emitter: Emitter::new(labels.len(), version)?,
            addresses_to_labels,
            memory: label_gathering_machine.memory,
            sections: label_gathering_machine.sections,
            dummy_sections: label_gathering_machine.dummy_sections,
            writes: vec![],
            next_pc_write: None,
            instruction_cycle_func,
        })
    }

    fn read_pc(&self) -> Result<u64, Error> {
        match &self.pc {
            Value::Imm(pc) => Ok(*pc),
            _ => Err(Error::Unexpected),
        }
    }

    fn take_and_clear_writes(&mut self) -> Vec<Write> {
        mem::replace(&mut self.writes, vec![])
    }

    fn emit_block(&mut self, instructions: &[Instruction]) -> Result<(), Error> {
        let mut cycles = 0;
        // A block is split into 2 parts:
        //
        // * initial_writes contains writes for all sequential operations,
        // those can be processed as normal in sequential order.
        // * last_writes contains writes generated for the last operations,
        // in case of a branch instruction, this might contains a normal
        // register write, and a PC update. To correctly handle JALR, those
        // 2 operations need to happen atomically. Hence later we can ses
        // when version 1 or above is enabled, last_writes are submitted
        // together to emit correct native code.
        let mut initial_writes = vec![];

        for instruction in instructions.iter() {
            cycles += self
                .instruction_cycle_func
                .as_ref()
                .map(|f| f(*instruction))
                .unwrap_or(0);
        }
        self.emitter.emit_add_cycles(cycles)?;

        for (i, instruction) in instructions.iter().enumerate() {
            if i == instructions.len() - 1 {
                initial_writes = self.take_and_clear_writes();
            }
            let pc = self.read_pc()?;
            let length = instruction_length(*instruction);
            if is_slowpath_instruction(*instruction) {
                self.writes.push(Write::Slowpath);
            } else {
                execute(*instruction, self)?;
            }
            self.pc = Value::from_u64(pc + u64::from(length));
        }
        let pc = self.read_pc()?;
        // Emit succeeding PC write only
        if pc >= RISCV_MAX_MEMORY as u64 {
            return Err(Error::OutOfBound);
        }
        self.emitter.emit(&Write::Pc {
            value: Value::Imm(pc | ADDRESS_WRITE_ONLY_FLAG),
        })?;
        for write in initial_writes {
            self.emitter.emit(&write)?;
        }
        let mut last_writes = self.take_and_clear_writes();
        if let Some(value) = self.next_pc_write.take() {
            last_writes.push(Write::Pc {
                value: self.optimize_pc_value(value)?,
            });
        }
        // Atomic writes only accept normal register writes and PC writes.
        let all_normal_writes = last_writes
            .iter()
            .all(|write| matches!(write, Write::Register { .. } | Write::Pc { .. }));
        if self.version >= VERSION1 && last_writes.len() > 1 && all_normal_writes {
            self.emitter.emit_writes(&last_writes)?;
        } else {
            for write in last_writes {
                self.emitter.emit(&write)?;
            }
        }
        Ok(())
    }

    pub fn compile(&mut self) -> Result<AotCode, Error> {
        let decoder = build_decoder::<u64>(self.isa());
        let mut instructions = [Instruction::default(); MAXIMUM_INSTRUCTIONS_PER_BLOCK];
        for i in 0..self.sections.len() {
            let (section_start, section_end) = self.sections[i];
            self.pc = Value::from_u64(section_start);
            loop {
                let pc = self.read_pc()?;
                if pc >= section_end {
                    break;
                }
                if let Some(dummy_end) = self.dummy_sections.get(&pc) {
                    self.pc = Value::from_u64(*dummy_end);
                    continue;
                }
                if let Some(label) = self.addresses_to_labels.get(&pc) {
                    self.emitter.emit_label(*label)?;
                }
                let mut count = 0;
                let mut current_pc = pc;
                while count < MAXIMUM_INSTRUCTIONS_PER_BLOCK && current_pc < section_end {
                    let instruction = decoder.decode(&mut self.memory, current_pc)?;
                    instructions[count] = instruction;
                    count += 1;
                    current_pc += u64::from(instruction_length(instruction));
                    if is_basic_block_end_instruction(instruction)
                        || self.addresses_to_labels.contains_key(&current_pc)
                    {
                        break;
                    }
                }
                self.emit_block(&instructions[0..count])?;
            }
        }
        let encoded_size = self.emitter.link()?;
        let mut buffer_mut = MmapMut::map_anon(encoded_size)?;
        self.emitter.encode(&mut buffer_mut[..])?;
        let code = buffer_mut.make_exec()?;
        let mut labels = HashMap::default();
        for (address, label) in &self.addresses_to_labels {
            let offset = self.emitter.get_label_offset(*label)?;
            labels.insert(*address, offset);
        }
        Ok(AotCode { code, labels })
    }

    // This method inspects PC value, and if any immediate encoded in the PC
    // Value matches a label, we will encode the real label directly in the
    // address for fast path jumps.
    fn optimize_pc_value(&self, value: Value) -> Result<Value, Error> {
        match value {
            Value::Imm(v) => Ok(Value::Imm(self.optimize_pc(v)?)),
            Value::Cond(c, t, f) => Ok(match (&*t, &*f) {
                (Value::Imm(t), Value::Imm(f)) => Value::Cond(
                    c,
                    Rc::new(Value::Imm(self.optimize_pc(*t)?)),
                    Rc::new(Value::Imm(self.optimize_pc(*f)?)),
                ),
                _ => Value::Cond(c, t, f),
            }),
            _ => Ok(value),
        }
    }

    fn optimize_pc(&self, pc: u64) -> Result<u64, Error> {
        if pc >= RISCV_MAX_MEMORY as u64 {
            return Err(Error::OutOfBound);
        }
        if pc < MAXIMUM_ENCODED_ADDRESS {
            if let Some(label) = self.addresses_to_labels.get(&pc) {
                return Ok(pc | (u64::from(*label) << 32) | ADDRESS_LABEL_FLAG);
            }
        }
        Ok(pc)
    }
}

impl CoreMachine for AotCompilingMachine {
    type REG = Value;
    type MEM = Self;

    fn pc(&self) -> &Value {
        &self.pc
    }

    fn update_pc(&mut self, pc: Self::REG) {
        self.next_pc = pc;
    }

    fn commit_pc(&mut self) {
        self.next_pc_write = Some(self.next_pc.clone())
    }

    fn memory(&self) -> &Self {
        &self
    }

    fn memory_mut(&mut self) -> &mut Self {
        self
    }

    fn registers(&self) -> &[Value] {
        &self.registers
    }

    fn set_register(&mut self, index: usize, value: Value) {
        self.writes.push(Write::Register { index, value });
    }

    fn isa(&self) -> u8 {
        self.isa
    }

    fn version(&self) -> u32 {
        self.version
    }
}

impl Machine for AotCompilingMachine {
    fn ecall(&mut self) -> Result<(), Error> {
        self.writes.push(Write::Ecall);
        Ok(())
    }

    fn ebreak(&mut self) -> Result<(), Error> {
        self.writes.push(Write::Ebreak);
        Ok(())
    }
}

impl Memory for AotCompilingMachine {
    type REG = Value;

    fn init_pages(
        &mut self,
        _addr: u64,
        _size: u64,
        _flags: u8,
        _source: Option<Bytes>,
        _offset_from_addr: u64,
    ) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn fetch_flag(&mut self, _page: u64) -> Result<u8, Error> {
        Err(Error::Unimplemented)
    }

    fn set_flag(&mut self, _page: u64, _flag: u8) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn clear_flag(&mut self, _page: u64, _flag: u8) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn store_byte(&mut self, _addr: u64, _size: u64, _value: u8) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn store_bytes(&mut self, _addr: u64, _value: &[u8]) -> Result<(), Error> {
        Err(Error::Unimplemented)
    }

    fn execute_load16(&mut self, _addr: u64) -> Result<u16, Error> {
        Err(Error::Unimplemented)
    }

    fn execute_load32(&mut self, _addr: u64) -> Result<u32, Error> {
        Err(Error::Unimplemented)
    }

    fn load8(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 1))
    }

    fn load16(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 2))
    }

    fn load32(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 4))
    }

    fn load64(&mut self, addr: &Value) -> Result<Value, Error> {
        Ok(Value::Load(Rc::new(addr.clone()), 8))
    }

    fn store8(&mut self, addr: &Value, value: &Value) -> Result<(), Error> {
        self.writes.push(Write::Memory {
            address: addr.clone(),
            size: 1,
            value: value.clone(),
        });
        Ok(())
    }

    fn store16(&mut self, addr: &Value, value: &Value) -> Result<(), Error> {
        self.writes.push(Write::Memory {
            address: addr.clone(),
            size: 2,
            value: value.clone(),
        });
        Ok(())
    }

    fn store32(&mut self, addr: &Value, value: &Value) -> Result<(), Error> {
        self.writes.push(Write::Memory {
            address: addr.clone(),
            size: 4,
            value: value.clone(),
        });
        Ok(())
    }

    fn store64(&mut self, addr: &Value, value: &Value) -> Result<(), Error> {
        self.writes.push(Write::Memory {
            address: addr.clone(),
            size: 8,
            value: value.clone(),
        });
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_max_memory_should_not_overlap_with_flags() {
        assert_eq!((RISCV_MAX_MEMORY as u64) & ADDRESS_WRITE_ONLY_FLAG, 0);
        assert_eq!((RISCV_MAX_MEMORY as u64) & ADDRESS_LABEL_FLAG, 0);
    }

    #[test]
    fn test_label_number_should_fit_in_24_bit() {
        assert_eq!(((MAXIMUM_LABELS as u64) << 32) & ADDRESS_WRITE_ONLY_FLAG, 0);
        assert_eq!(((MAXIMUM_LABELS as u64) << 32) & ADDRESS_LABEL_FLAG, 0);
    }

    #[test]
    fn test_maximum_encoded_address() {
        assert!(MAXIMUM_ENCODED_ADDRESS.is_power_of_two());
        assert!((RISCV_MAX_MEMORY as u64) < MAXIMUM_ENCODED_ADDRESS);
    }
}