zisk-core 1.1.0-alpha

Core types and proving primitives for the ZisK zkVM
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
//! Zisk program memory
//!
//! # Memory map
//!
//! * The Zisk processor memory stores data in little-endian format.
//! * The addressable memory space is divided into several regions described in the following map:
//!
//! `|--------------- ROM_ENTRY: first BIOS instruction   (    0x1000)`
//! `|--------------- ROM_EXIT: last BIOS instruction     (    0x1004)`
//! `|`
//! `| Performs memory initialization, calls program at ROM_ADDR,`
//! `| and after returning it performs memory finalization.`
//! `| Contains ecall/system call management code.`
//! `|`
//! `|---------------`
//! `      ...`
//! `|--------------- INPUT_ADDR                          (0x40000000)`
//! `|`
//! `| Contains program input data.`
//! `|`
//! `|--------------- ROM_ADDR: first program instruction (0x80000000)`
//! `|`
//! `| Contains program instructions.`
//! `| Calls ecalls/system calls when required.`
//! `|`
//! `|--- FLOAT_LIB_ROM_ADDR: first float lib instruction (0x87F00000)`
//! `|`
//! `| Contains float library instructions. 1M before ROM_ADDR_MAX.`
//! `|`
//! `| Initial value of the float library stack pointer.`
//! `|`
//! `|--------------- RAM_ADDR                            (0xa0000000)`
//! `|`
//! `|--------------- RAM_ADDR + STACK_SIZE - 16          (0xa03ffff0)`
//! `|`
//! `|--------------- SYS_ADDR (= RAM_ADDR + STACK_SIZE)  (0xa0400000)`
//! `|`
//! `| Contains system address.`
//! `| The first 256 bytes contain 32 8-byte registers`
//! `| The address UART_ADDR is used as a stdout at addr = 0xa0400200`
//! `| The first float register is at         FREG_FIRST = 0xa0401000`
//! `| The first CSR register is at             CSR_ADDR = 0xa0408000`
//! `|`
//! `|--------------- OUTPUT_ADDR                         (0xa0410000)`
//! `|`
//! `| Contains output data, which is written during`
//! `| program execution and read during memory finalization`
//! `|`
//! `|--------------- general-purpose RAM                 (0xa0430000)`
//! `|`
//! `| Contains program memory, available for normal R/W`
//! `| used during program execution.`
//! `|`
//! `|--------------- FLOAT_LIB_RAM_ADDR = 0xbfff0000     (0xc0000000 - 0x10000)`
//! `|`
//! `| Contains float library memory, available for normal R/W`
//! `| used during library execution (bottom-up).`
//! `|`
//! `| Contains float library stack memory (top-down).`
//! `|`
//! `|--------------- FLOAT_LIB_SP = 0xbffffff0           (0xc0000000 - 16)`
//! `|`
//! `|--------------- END OF RAM                          (0xc0000000)`
//! `      ...`
//!
//! ## ROM_ENTRY / ROM_ADDR / ROM_EXIT
//! * The program will start executing at the first BIOS address `ROM_ENTRY`.
//! * The first instructions do the basic program setup, including writing the input data into
//!   memory, configuring the ecall (system call) program address, and configuring the program
//!   completion return address.
//! * After the program set1, the program counter jumps to `ROM_ADDR`, executing the actual program.
//! * During the execution, the program can make system calls that will jump to the configured ecall
//!   program address, and return once the task has completed. The precompiled are implemented via
//!   ecall.
//! * After the program is completed, the program counter will jump to the configured return
//!   address, where the finalization tasks will happen, including reading the output data from
//!   memory.
//! * The address before the last one will jump to `ROM_EXIT`, the last insctruction of the
//!   execution.
//! * In general, setup and finalization instructions are located in low addresses, while the actual
//!   program instructions are located in high addresses.
//!
//! ## INPUT_ADDR
//! * During the program initialization the input data for the program execution is copied in this
//!   memory region, beginning with `INPUT_ADDR`.
//! * After the data has been written by the setup process, this data can only be read by the
//!   program execution, i.e. it becomes a read-only (RO) memory region.
//!
//! ## SYS_ADDR / OUTPUT_ADDR / general-purpose RAM
//! * This memory section can be written and read by the program execution many times, i.e. it is a
//!   read-write (RW) memory region.
//! * The first RW memory region going from `SYS_ADDR` to `OUTPUT_ADDR` is reserved for the system
//!   operation.
//! * The lower addresses of this region is used to store 32 registers of 8 bytes each, i.e. 256
//!   bytes in total.  These registers are the equivalent to the RISC-V registers.
//! * Any data of exactly 1-byte length written to UART_ADDR will be sent to the standard output of
//!   the system.
//! * The second RW memory region going from `OUTPUT_ADDR` onwards, up to where the general-purpose
//!   RAM starts, is reserved to copy the output data during the program execution.
//! * The third RW memory region, the general-purpose RAM that follows the output region, can be
//!   used during the program execution as general purpose memory.

use crate::{M16, M3, M32, M8, REG_FIRST, REG_LAST};
use core::fmt;

/// Fist input data memory address
pub const INPUT_ADDR: u64 = 0x4000_0000;
/// Maximum size of the input data
pub const MAX_INPUT_SIZE: u64 = 0x4000_0000; // 128M,
/// Free input data memory address = first input address
pub const FREE_INPUT_ADDR: u64 = INPUT_ADDR;
/// First global RW memory address
pub const RAM_ADDR: u64 = 0xa0000000;
/// Size of the global RW memory
pub const RAM_SIZE: u64 = 0x20000000; // 512M
/// Program stack addr
pub const STACK_ADDR: u64 = RAM_ADDR;
/// Program stack size
pub const STACK_SIZE: u64 = 0x400000; // 4MB
/// First system RW memory address
pub const SYS_ADDR: u64 = RAM_ADDR + STACK_SIZE;
/// Size of the system RW memory
pub const SYS_SIZE: u64 = 0x10000;
/// First output RW memory address
pub const OUTPUT_ADDR: u64 = SYS_ADDR + SYS_SIZE;
/// Size of the output RW memory
pub const OUTPUT_MAX_SIZE: u64 = 0x20000; // 128K
/// First BIOS instruction address, i.e. first instruction executed
pub const ROM_ENTRY: u64 = 0x1000;
/// Size of the BIOS instruction area
pub const ROM_ENTRY_SIZE: u64 = 1 << 20;
/// Last BIOS instruction address, i.e. last instruction executed
pub const ROM_EXIT: u64 = 0x1004;
/// Maximum Zisk OS ROM instruction address, i.e. last instruction of the BIOS
pub const MAX_ZISK_OS_ROM_ADDR: u64 = 0x10000000 - 1;
/// First program ROM instruction address, i.e. first RISC-V transpiled instruction
pub const ROM_ADDR: u64 = 0x80000000;
/// Size of the program ROM instruction area
pub const ROM_SIZE: u64 = 0x08000000; // 128M
/// Maximum program ROM instruction address
pub const ROM_ADDR_MAX: u64 = ROM_ADDR + ROM_SIZE - 1;
/// Size of float library ROM
pub const FLOAT_LIB_ROM_SIZE: u64 = 0x100000; // 1M
/// First float library ROM instruction address
pub const FLOAT_LIB_ROM_ADDR: u64 = ROM_ADDR + ROM_SIZE - FLOAT_LIB_ROM_SIZE;
/// Maximum float library ROM instruction address
pub const FLOAT_LIB_ROM_ADDR_MAX: u64 = FLOAT_LIB_ROM_ADDR + FLOAT_LIB_ROM_SIZE - 1;
/// Size of float library RAM
pub const FLOAT_LIB_RAM_SIZE: u64 = 0x10000; // 64K
/// First float library RAM address
pub const FLOAT_LIB_RAM_ADDR: u64 = RAM_ADDR + RAM_SIZE - FLOAT_LIB_RAM_SIZE;
/// Maximum float library RAM address
pub const FLOAT_LIB_RAM_ADDR_MAX: u64 = FLOAT_LIB_RAM_ADDR + FLOAT_LIB_RAM_SIZE - 1;
/// Float library stack pointer address
pub const FLOAT_LIB_SP: u64 = RAM_ADDR + RAM_SIZE - 16;
/// Zisk architecture ID
pub const ARCH_ID_ZISK: u64 = 0xFFFEEEE;
/// UART memory address; single bytes written here will be copied to the standard output
pub const UART_ADDR: u64 = SYS_ADDR + 0x200;
/// Extra parameters of repcompiles are stored in fixed memory area (256 bytes => 32 parameters)
pub const EXTRA_PARAMS_ADDR: u64 = SYS_ADDR + 0x0F00;
/// Float registers first address
pub const FREG_FIRST: u64 = SYS_ADDR + 0x1000;
/// CSR memory address; contains control and status registers
pub const CSR_ADDR: u64 = SYS_ADDR + 0x8000;
/// Machine trap-vector base-address register
pub const MTVEC: u64 = CSR_ADDR + 0x305 * 8;
/// Floating-point Control and Status Register
pub const FCSR: u64 = CSR_ADDR + 0x003 * 8;
/// Architecture ID Control and Status Register
pub const ARCH_ID_CSR: u64 = 0xF12;
/// Architecture ID Control and Status Register address
pub const ARCH_ID_CSR_ADDR: u64 = CSR_ADDR + (ARCH_ID_CSR * 8);

/// Raw bytes of `data` that will live at `addr` once the ROM has booted.
#[derive(Debug, Clone)]
pub struct DataSection {
    pub addr: u64,
    pub data: Vec<u8>,
}

/// Memory section data, including a buffer (a vector of bytes) and start and end program
/// memory addresses.
pub struct MemSection {
    pub start: u64,
    pub end: u64,
    pub real_end: u64,
    pub buffer: Vec<u8>,
}

/// Default constructor for MemSection structure
impl Default for MemSection {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for MemSection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.to_text())
    }
}

/// Memory section structure implementation
impl MemSection {
    /// Memory section constructor
    pub fn new() -> MemSection {
        MemSection { start: 0, end: 0, real_end: 0, buffer: Vec::new() }
    }
    pub fn to_text(&self) -> String {
        format!(
            "start={:x} real_end={:x} end={:x} diff={:x}={} buffer.len={:x}={}",
            self.start,
            self.real_end,
            self.end,
            self.end - self.start,
            self.end - self.start,
            self.buffer.len(),
            self.buffer.len()
        )
    }
}

/// Memory structure, containing several read sections and one single write section
#[derive(Debug, Default)]
pub struct Mem {
    pub read_sections: Vec<MemSection>,
    pub write_section: MemSection,
    pub free_input: u64,
}

impl Mem {
    /// Memory structure constructor
    pub fn new() -> Mem {
        //println!("Mem::new()");
        Mem { read_sections: Vec::new(), write_section: MemSection::new(), free_input: 0 }
    }

    /// Adds a read section to the memory structure
    pub fn add_read_section(&mut self, start: u64, buffer: &[u8]) {
        // Check that the start address is alligned to 8 bytes
        if (start & 0x07) != 0 {
            panic!("Mem::add_read_section() got a start address={start:x} not alligned to 8 bytes");
        }

        // Calculate the end address
        let end = start + buffer.len() as u64;

        // If there exists a read section next to this one, reuse it
        for existing_section in self.read_sections.iter_mut() {
            if existing_section.real_end == start {
                // Sanity check
                assert!(existing_section.real_end <= existing_section.end);
                assert!((existing_section.end - existing_section.real_end) < 8);

                // Pop tail zeros until end matches real_end
                while existing_section.real_end > existing_section.end {
                    existing_section.buffer.pop();
                    existing_section.end -= 1;
                }

                // Append buffer
                existing_section.buffer.extend(buffer);
                existing_section.real_end += buffer.len() as u64;
                existing_section.end = existing_section.real_end;

                // Append zeros until end is multiple of 8, so that we can read non-alligned reads
                while (existing_section.end & 0x07) != 0 {
                    existing_section.buffer.push(0);
                    existing_section.end += 1;
                }

                /*println!(
                    "Mem::add_read_section() start={:x} len={} existing section={}",
                    start,
                    buffer.len(),
                    existing_section.to_text()
                );*/

                return;
            }
        }

        // Create a new memory section
        let mut new_section = MemSection { start, end, real_end: end, buffer: buffer.to_owned() };

        // Append zeros until end is multiple of 8, so that we can read non-alligned reads
        while (new_section.end & 0x07) != 0 {
            new_section.buffer.push(0);
            new_section.end += 1;
        }

        //println!("Mem::add_read_section() new section={}", new_section.to_text());

        // Add the new section to the read sections
        self.read_sections.push(new_section);
    }

    /// Adds a write section to the memory structure, which cannot be written twice
    pub fn add_write_section(&mut self, start: u64, size: u64) {
        //println!("Mem::add_write_section() start={:x}={} size={:x}={}", start, start, size,
        // size);

        // Check that the start address is alligned to 8 bytes
        if (start & 0x07) != 0 {
            panic!(
                "Mem::add_write_section() got a start address={start:x} not alligned to 8 bytes"
            );
        }

        // Check the start address is not zero
        if start == 0 {
            panic!("Mem::add_write_section() got invalid start={start}");
        }

        // Check the write section address has not been set before this call, since one only write
        // section is allowed
        if self.write_section.start != 0 {
            panic!(
                "Mem::add_write_section() only one write section allowed, write_section.start={}",
                self.write_section.start
            );
        }

        // Create an empty vector of size bytes
        let mem: Vec<u8> = vec![0; size as usize];

        // Store as the write section
        self.write_section.start = start;
        self.write_section.end = start + mem.len() as u64;
        self.write_section.buffer = mem;
    }

    /// Reads a 1, 2, 4 or 8 bytes value from the memory read sections, based on the provided
    /// address and width
    #[inline(always)]
    pub fn read(&self, addr: u64, width: u64) -> u64 {
        debug_assert!(!Mem::address_is_register(addr));

        // First try to read in the write section
        if (addr >= self.write_section.start) && (addr <= (self.write_section.end - width)) {
            // Calculate the read position
            let read_position: usize = (addr - self.write_section.start) as usize;

            // Read the requested data based on the provided width
            let value: u64 = match width {
                1 => self.write_section.buffer[read_position] as u64,
                2 => u16::from_le_bytes(
                    self.write_section.buffer[read_position..read_position + 2].try_into().unwrap(),
                ) as u64,
                4 => u32::from_le_bytes(
                    self.write_section.buffer[read_position..read_position + 4].try_into().unwrap(),
                ) as u64,
                8 => u64::from_le_bytes(
                    self.write_section.buffer[read_position..read_position + 8].try_into().unwrap(),
                ),
                _ => panic!("Mem::read() invalid width={width}"),
            };

            //println!("Mem::read() addr={:x} width={} value={:x}={}", addr, width, value, value);
            return value;
        }

        // Special case for the input address, which is a read-only address that can be read at any
        // time
        if addr == INPUT_ADDR && width == 8 {
            // increment of pointer is done by the fcall_get
            return self.free_input;
        }

        // Search for the section that contains the address using binary search (dicothomic search).
        // Read sections are ordered by start address to allow this search.
        let section = if let Ok(section) = self.read_sections.binary_search_by(|section| {
            if addr < section.start {
                std::cmp::Ordering::Greater
            } else if addr > section.end - width {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        }) {
            &self.read_sections[section]
        } else if addr >= (INPUT_ADDR + 8) && addr <= (INPUT_ADDR + MAX_INPUT_SIZE - width) {
            // We allow to read from the input address range, even if it has not been set as a read
            // section, since its default value is 0 for the whole range
            match width {
                1 | 2 | 4 | 8 => return 0,
                _ => panic!("Mem::read() invalid width={width}"),
            }
        } else {
            panic!("Mem::read() section not found for addr: {addr}={addr:x} with width: {width}");
        };

        // Calculate the buffer relative read position
        let read_position: usize = (addr - section.start) as usize;

        // Read the requested data based on the provided width
        match width {
            1 => section.buffer[read_position] as u64,
            2 => u16::from_le_bytes(
                section.buffer[read_position..read_position + 2].try_into().unwrap(),
            ) as u64,
            4 => u32::from_le_bytes(
                section.buffer[read_position..read_position + 4].try_into().unwrap(),
            ) as u64,
            8 => u64::from_le_bytes(
                section.buffer[read_position..read_position + 8].try_into().unwrap(),
            ),
            _ => panic!("Mem::read() invalid width={width}"),
        }
    }

    #[inline(always)]
    pub fn read_slice(&self, addr: u64, count: u64) -> &[u8] {
        debug_assert!(!Mem::address_is_register(addr));

        // First try to read in the write section
        if (addr >= self.write_section.start) && ((addr + count) <= self.write_section.end) {
            // Calculate the read position
            let read_position: usize = (addr - self.write_section.start) as usize;
            return &self.write_section.buffer[read_position..read_position + count as usize];
        }

        // Search for the section that contains the address using binary search (dicothomic search).
        // Read sections are ordered by start address to allow this search.
        let section = if let Ok(section) = self.read_sections.binary_search_by(|section| {
            if addr < section.start {
                std::cmp::Ordering::Greater
            } else if addr > section.end - count {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        }) {
            &self.read_sections[section]
        } else {
            panic!("Mem::read() section not found for addr: {addr}={addr:x} with count: {count}");
        };

        // Calculate the buffer relative read position
        let read_position: usize = (addr - section.start) as usize;
        &section.buffer[read_position..read_position + count as usize]
    }

    /*
    Possible alignment situations:
    - Full aligned = address is aligned to 8 bytes (last 3 bits are zero) and width is 8
    - Single not aligned = not full aligned, and the data fits into one aligned slice of 8 bytes
    - Double not aligned = not full aligned, and the data needs 2 aligned slices of 8 bytes

    Data required for each situation:
    - full_aligned + RD = value
    - full_aligned + WR = value, full_value
    - single_not_aligned + RD = value, full_value  TODO: We can save the value space, optimization
    - single_not_aligned + WR = value, previous_full_value
    - double_not_aligned + RD = value, full_values_0, full_values_1
    - double_not_aligned + WR = value, previous_full_values_0, previous_full_values_1

    read_required() returns read value, and a vector of additional data required to prove it
    */

    /// Read a u64 value from the memory read sections, based on the provided address and width
    #[inline(always)]
    pub fn read_required(&self, addr: u64, width: u64) -> (u64, Vec<u64>) {
        // Calculate how aligned this operation is
        let addr_req_1 = addr & 0xFFFF_FFFF_FFFF_FFF8; // Aligned address of the first 8-bytes chunk
        let addr_req_2 = (addr + width - 1) & 0xFFFF_FFFF_FFFF_FFF8; // Aligned address of the second 8-bytes chunk, if needed
        let is_full_aligned = ((addr & 0x07) == 0) && (width == 8);
        let is_single_not_aligned = !is_full_aligned && (addr_req_1 == addr_req_2);
        let is_double_not_aligned = !is_full_aligned && !is_single_not_aligned;

        // First try to read in the write section
        if (addr >= self.write_section.start) && (addr <= (self.write_section.end - width)) {
            // Calculate the read position
            let read_position: usize = (addr - self.write_section.start) as usize;

            // Read the requested data based on the provided width
            let value: u64 = match width {
                1 => self.write_section.buffer[read_position] as u64,
                2 => u16::from_le_bytes(
                    self.write_section.buffer[read_position..read_position + 2].try_into().unwrap(),
                ) as u64,
                4 => u32::from_le_bytes(
                    self.write_section.buffer[read_position..read_position + 4].try_into().unwrap(),
                ) as u64,
                8 => u64::from_le_bytes(
                    self.write_section.buffer[read_position..read_position + 8].try_into().unwrap(),
                ),
                _ => panic!("Mem::read() invalid width={width}"),
            };

            // If is a single not aligned operation, return the aligned address value
            if is_single_not_aligned {
                let mut additional_data: Vec<u64> = Vec::new();

                assert!(addr_req_1 >= self.write_section.start);
                let read_position_req: usize = (addr_req_1 - self.write_section.start) as usize;
                let value_req = u64::from_le_bytes(
                    self.write_section.buffer[read_position_req..read_position_req + 8]
                        .try_into()
                        .unwrap(),
                );
                additional_data.push(value_req);

                return (value, additional_data);
            }

            // If is a double not aligned operation, return the aligned address value and the next
            // one
            if is_double_not_aligned {
                let mut additional_data: Vec<u64> = Vec::new();

                assert!(addr_req_1 >= self.write_section.start);
                let read_position_req_1: usize = (addr_req_1 - self.write_section.start) as usize;
                let value_req_1 = u64::from_le_bytes(
                    self.write_section.buffer[read_position_req_1..read_position_req_1 + 8]
                        .try_into()
                        .unwrap(),
                );
                additional_data.push(value_req_1);

                assert!(addr_req_2 >= self.write_section.start);
                let read_position_req_2: usize = (addr_req_2 - self.write_section.start) as usize;
                let value_req_2 = u64::from_le_bytes(
                    self.write_section.buffer[read_position_req_2..read_position_req_2 + 8]
                        .try_into()
                        .unwrap(),
                );
                additional_data.push(value_req_2);

                return (value, additional_data);
            }

            //println!("Mem::read() addr={:x} width={} value={:x}={}", addr, width, value, value);
            return (value, Vec::new());
        }

        // Search for the section that contains the address using binary search (dicothomic search)
        let section = if let Ok(section) = self.read_sections.binary_search_by(|section| {
            if addr < section.start {
                std::cmp::Ordering::Greater
            } else if (addr + width) > section.end {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        }) {
            &self.read_sections[section]
        } else {
            println!("sections: {:?}", self.read_sections);
            panic!("Mem::read() section not found for addr: {addr} with width: {width}");
        };

        // Calculate the read position
        let read_position: usize = (addr - section.start) as usize;

        // Read the requested data based on the provided width
        let value: u64 = match width {
            1 => section.buffer[read_position] as u64,
            2 => u16::from_le_bytes(
                section.buffer[read_position..read_position + 2].try_into().unwrap(),
            ) as u64,
            4 => u32::from_le_bytes(
                section.buffer[read_position..read_position + 4].try_into().unwrap(),
            ) as u64,
            8 => u64::from_le_bytes(
                section.buffer[read_position..read_position + 8].try_into().unwrap(),
            ),
            _ => panic!(
                "Mem::read() invalid addr:0x{addr:X} read_position:{read_position} width:{width}"
            ),
        };

        // If is a single not aligned operation, return the aligned address value
        if is_single_not_aligned {
            let mut additional_data: Vec<u64> = Vec::new();

            assert!(addr_req_1 >= section.start);
            let read_position_req: usize = (addr_req_1 - section.start) as usize;
            let value_req = u64::from_le_bytes(
                section.buffer[read_position_req..read_position_req + 8].try_into().unwrap(),
            );
            additional_data.push(value_req);

            return (value, additional_data);
        }

        // If is a double not aligned operation, return the aligned address value and the next
        // one
        if is_double_not_aligned {
            let mut additional_data: Vec<u64> = Vec::new();

            assert!(addr_req_1 >= section.start);
            let read_position_req_1: usize = (addr_req_1 - section.start) as usize;
            let value_req_1 = u64::from_le_bytes(
                section.buffer[read_position_req_1..read_position_req_1 + 8].try_into().unwrap(),
            );
            additional_data.push(value_req_1);

            assert!(addr_req_2 >= section.start);
            let read_position_req_2: usize = (addr_req_2 - section.start) as usize;
            let value_req_2 = u64::from_le_bytes(
                section.buffer[read_position_req_2..read_position_req_2 + 8].try_into().unwrap(),
            );
            additional_data.push(value_req_2);

            return (value, additional_data);
        }

        //println!("Mem::read() addr={:x} width={} value={:x}={}", addr, width, value, value);

        (value, Vec::new())
    }

    /// Initializes the memory write section with the data from the provided data section, which is
    /// expected to be located in the write section address range
    pub fn init_write_section_data(&mut self, section: &DataSection) {
        // Check that the section is not empty
        if section.data.is_empty() {
            return;
        }

        // Check that the section start address and size are valid
        if (section.addr < self.write_section.start)
            || ((section.addr + section.data.len() as u64) > self.write_section.end)
        {
            panic!(
                "Mem::init_write_section_data() invalid section start={:x} end={:x} write section start={:x} end={:x}",
                section.addr,
                section.addr + section.data.len() as u64,
                self.write_section.start,
                self.write_section.end
            );
        }

        // Write the data into the write section buffer
        let write_position: usize = (section.addr - self.write_section.start) as usize;
        self.write_section.buffer[write_position..write_position + section.data.len()]
            .copy_from_slice(&section.data);
    }

    /// Write a u64 value to the memory write section, based on the provided address and width
    #[inline(always)]
    pub fn write(&mut self, addr: u64, val: u64, width: u64) {
        debug_assert!(!Mem::address_is_register(addr));

        // Call write_silent to perform the real work
        self.write_silent(addr, val, width);

        // Log to console bytes written to UART address
        if (addr == UART_ADDR) && (width == 1) {
            print!("{}", String::from(val as u8 as char));
        }
    }

    /// Write a u64 value to the memory write section, based on the provided address and width
    #[inline(always)]
    pub fn write_silent(&mut self, addr: u64, val: u64, width: u64) {
        debug_assert!(!Mem::address_is_register(addr));

        //println!("Mem::write() addr={:x}={} width={} value={:x}={}", addr, addr, width, val,
        // val);

        // Search for the section that contains the address using binary search (dicothomic search)
        let section = &mut self.write_section;

        // Check that the address and width fall into this section address range
        if (addr < section.start) || ((addr + width) > section.end) {
            panic!(
                "Mem::write_silent() invalid addr={}={:x} write section start={:x} end={:x}",
                addr, addr, section.start, section.end
            );
        }

        // Calculate the write position
        let write_position: usize = (addr - section.start) as usize;

        // Write the value based on the provided width
        match width {
            1 => section.buffer[write_position] = val as u8,
            2 => section.buffer[write_position..write_position + 2]
                .copy_from_slice(&(val as u16).to_le_bytes()),
            4 => section.buffer[write_position..write_position + 4]
                .copy_from_slice(&(val as u32).to_le_bytes()),
            8 => section.buffer[write_position..write_position + 8]
                .copy_from_slice(&val.to_le_bytes()),
            _ => panic!("Mem::write_silent() invalid width={width}"),
        };
    }

    /// Write a u64 value to the memory write section, based on the provided address and width
    #[inline(always)]
    pub fn write_silent_required(&mut self, addr: u64, val: u64, width: u64) -> Vec<u64> {
        //println!("Mem::write() addr={:x}={} width={} value={:x}={}", addr, addr, width, val,
        // val);

        // Search for the section that contains the address using binary search (dicothomic search)
        let section = if let Ok(section) = self.read_sections.binary_search_by(|section| {
            if addr < section.start {
                std::cmp::Ordering::Greater
            } else if addr > (section.end - width) {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        }) {
            &mut self.read_sections[section]
        } else {
            /*panic!(
                "Mem::write_silent() section not found for addr={:x}={} with width: {}",
                addr, addr, width
            );*/
            &mut self.write_section
        };

        // Check that the address and width fall into this section address range
        if (addr < section.start) || ((addr + width) > section.end) {
            panic!(
                "Mem::write_silent() invalid addr={}={:x} write section start={:x} end={:x}",
                addr, addr, section.start, section.end
            );
        }

        // Calculate how aligned this operation is
        let addr_req_1 = addr & 0xFFFF_FFFF_FFFF_FFF8; // Aligned address of the first 8-bytes chunk
        let addr_req_2 = (addr + width - 1) & 0xFFFF_FFFF_FFFF_FFF8; // Aligned address of the second 8-bytes chunk, if needed
        let is_full_aligned = ((addr & 0x07) == 0) && (width == 8);
        let is_single_not_aligned = !is_full_aligned && (addr_req_1 == addr_req_2);
        let is_double_not_aligned = !is_full_aligned && !is_single_not_aligned;

        // Declare an empty vector
        let mut additional_data: Vec<u64> = Vec::new();

        // If is a single not aligned operation, return the aligned address value
        if is_single_not_aligned {
            assert!(
                addr_req_1 >= section.start,
                "addr_req_1: 0x{:X} 0x{:X}]",
                addr_req_1,
                section.start
            );
            let read_position_req: usize = (addr_req_1 - section.start) as usize;
            let value_req = u64::from_le_bytes(
                section.buffer[read_position_req..read_position_req + 8].try_into().unwrap(),
            );
            additional_data.push(value_req);
        }

        // If is a double not aligned operation, return the aligned address value and the next
        // one
        if is_double_not_aligned {
            assert!(
                addr_req_1 >= section.start,
                "addr_req_1(d): 0x{:X} 0x{:X}]",
                addr_req_1,
                section.start
            );
            let read_position_req_1: usize = (addr_req_1 - section.start) as usize;
            let value_req_1 = u64::from_le_bytes(
                section.buffer[read_position_req_1..read_position_req_1 + 8].try_into().unwrap(),
            );
            additional_data.push(value_req_1);

            assert!(
                addr_req_2 >= section.start,
                "addr_req_2(d): 0x{:X} 0x{:X}]",
                addr_req_2,
                section.start
            );
            let read_position_req_2: usize = (addr_req_2 - section.start) as usize;
            let value_req_2 = u64::from_le_bytes(
                section.buffer[read_position_req_2..read_position_req_2 + 8].try_into().unwrap(),
            );
            additional_data.push(value_req_2);
        }

        // Calculate the write position
        let write_position: usize = (addr - section.start) as usize;

        // Write the value based on the provided width
        match width {
            1 => section.buffer[write_position] = val as u8,
            2 => section.buffer[write_position..write_position + 2]
                .copy_from_slice(&(val as u16).to_le_bytes()),
            4 => section.buffer[write_position..write_position + 4]
                .copy_from_slice(&(val as u32).to_le_bytes()),
            8 => section.buffer[write_position..write_position + 8]
                .copy_from_slice(&val.to_le_bytes()),
            _ => panic!("Mem::write_silent() invalid width={width}"),
        }

        additional_data
    }

    #[inline(always)]
    pub fn address_is_register(address: u64) -> bool {
        ((address & 0x7) == 0) && (REG_FIRST..=REG_LAST).contains(&address)
    }

    #[inline(always)]
    pub fn address_to_register_index(address: u64) -> usize {
        debug_assert!(Mem::address_is_register(address));
        ((address - REG_FIRST) >> 3) as usize
    }

    /// Returns true if the address and width are fully aligned
    #[inline(always)]
    pub fn is_full_aligned(address: u64, width: u64) -> bool {
        ((address & 0x07) == 0) && (width == 8)
    }

    /// Returns true if the address and width are single non aligned
    #[inline(always)]
    pub fn is_single_not_aligned(address: u64, width: u64) -> bool {
        if Self::is_full_aligned(address, width) {
            return true;
        }
        let (address_required_1, address_required_2) = Self::required_addresses(address, width);
        address_required_1 == address_required_2
    }

    /// Returns true if the address and width are double non aligned
    #[inline(always)]
    pub fn is_double_not_aligned(address: u64, width: u64) -> bool {
        if Self::is_full_aligned(address, width) {
            return true;
        }
        let (address_required_1, address_required_2) = Self::required_addresses(address, width);
        address_required_1 != address_required_2
    }

    /// Aligned addresses of the first and second 8-bytes chunks
    /// They can be equal if the required data fits into one single chunk of 8 bytes, or if it is
    /// a fully aligned data
    #[inline(always)]
    pub fn required_addresses(address: u64, width: u64) -> (u64, u64) {
        (address & 0xFFFF_FFFF_FFFF_FFF8, (address + width - 1) & 0xFFFF_FFFF_FFFF_FFF8)
    }

    /// Get single not aligned data from the raw data
    #[inline(always)]
    pub fn get_single_not_aligned_data(address: u64, width: u64, raw_data: u64) -> u64 {
        debug_assert!(width < 8);
        let offset = address & M3;
        let raw_data = raw_data >> (8 * offset);
        match width {
            1 => raw_data & M8,
            2 => raw_data & M16,
            4 => raw_data & M32,
            _ => panic!("Mem::get_single_not_aligned_data() invalid width={width}"),
        }
    }

    /// Get double not aligned data from the raw data
    #[inline(always)]
    pub fn get_double_not_aligned_data(
        address: u64,
        width: u64,
        raw_data_1: u64,
        raw_data_2: u64,
    ) -> u64 {
        //println!("Mem::get_double_not_aligned_data() address={:x} width={} raw_data_1={:x}
        // raw_data_2={:x}", address, width, raw_data_1, raw_data_2);
        debug_assert!(width <= 8);
        let offset = address & M3;
        let raw_data = ((raw_data_1 as u128 + ((raw_data_2 as u128) << 64)) >> (8 * offset)) as u64;
        match width {
            1 => raw_data & M8,
            2 => raw_data & M16,
            4 => raw_data & M32,
            8 => raw_data,
            _ => panic!("Mem::get_double_not_aligned_data() invalid width={width}"),
        }
    }

    #[inline(always)]
    pub fn get_writeable_section(&mut self, addr: u64, count: u64) -> &mut MemSection {
        if let Ok(section) = self.read_sections.binary_search_by(|section| {
            if addr < section.start {
                std::cmp::Ordering::Greater
            } else if addr > (section.end - count) {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        }) {
            panic!(
            "Mem::get_write_section() invalid addr={addr}={addr:x},count={count} write section start={:x} end={:x} is read only section",
            self.read_sections[section].start, self.read_sections[section].end);
        };

        // If not found in read sections, try write section
        let section = &mut self.write_section;

        // Check that the address and count fall into this section address range
        if (addr < section.start) || ((addr + count) > section.end) {
            panic!(
            "Mem::get_section() invalid addr={addr}={addr:x},count={count} write section start={:x} end={:x}",
            section.start, section.end
        );
        }
        section
    }

    #[inline(always)]
    pub fn get_readable_section(&self, addr: u64, count: u64) -> &MemSection {
        let section = if let Ok(section) = self.read_sections.binary_search_by(|section| {
            if addr < section.start {
                std::cmp::Ordering::Greater
            } else if addr > (section.end - count) {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        }) {
            &self.read_sections[section]
        } else {
            &self.write_section
        };
        if (addr < section.start) || ((addr + count) > section.end) {
            panic!(
                "Mem::get_read_section() invalid addr={addr}={addr:x},count={count} read section start={:x} end={:x}",
                section.start, section.end
            );
        }
        section
    }

    #[inline(always)]
    pub fn memcpy(&mut self, dst: u64, src: u64, count: u64) {
        // Early return if source and destination are the same or count is zero
        if dst == src || count == 0 {
            return;
        }

        let dst_end = dst + count;
        let src_end = src + count;
        let count_usize = count as usize;

        // Check if there is an overlap between source and destination
        let overlaps = (dst < src_end) && (src < dst_end);

        if overlaps {
            // Overlapping case: use temporary buffer to avoid data corruption
            let temp_buffer: Vec<u8> = {
                let src_section = self.get_readable_section(src, count);
                let src_offset: usize = (src - src_section.start) as usize;
                src_section.buffer[src_offset..src_offset + count_usize].to_vec()
            };

            let dst_section = self.get_writeable_section(dst, count);
            let dst_offset: usize = (dst - dst_section.start) as usize;
            dst_section.buffer[dst_offset..dst_offset + count_usize].copy_from_slice(&temp_buffer);
        } else {
            // Non-overlapping case: direct copy
            // First, get a copy of the source data
            let data_to_copy: Vec<u8> = {
                let src_section = self.get_readable_section(src, count);
                let src_offset: usize = (src - src_section.start) as usize;
                src_section.buffer[src_offset..src_offset + count_usize].to_vec()
            };

            // Then, write to destination
            let dst_section = self.get_writeable_section(dst, count);
            let dst_offset: usize = (dst - dst_section.start) as usize;
            dst_section.buffer[dst_offset..dst_offset + count_usize].copy_from_slice(&data_to_copy);
        }
    }

    pub fn memcpy_from_data(&mut self, dst: u64, count: u64, data: &[u64], data_offset: usize) {
        // Early return if source and destination are the same or count is zero
        if count == 0 {
            return;
        }

        let data_bytes: &[u8] =
            unsafe { core::slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * 8) };

        // Then, write to destination
        let dst_section = self.get_writeable_section(dst, count);
        let dst_offset: usize = (dst - dst_section.start) as usize;

        let count = count as usize;
        let bytes = &data_bytes[data_offset..data_offset + count];
        dst_section.buffer[dst_offset..dst_offset + count].copy_from_slice(bytes);
    }

    pub fn memset(&mut self, dst: u64, count: u64, data: u8) {
        // Early return if source and destination are the same or count is zero
        if count == 0 {
            return;
        }

        // Then, write to destination
        let dst_section = self.get_writeable_section(dst, count);
        let dst_offset: usize = (dst - dst_section.start) as usize;

        let count = count as usize;
        dst_section.buffer[dst_offset..dst_offset + count].fill(data);
    }

    /// Reads `count` bytes from memory starting at `addr` and appends them as u64 values to `data`.
    /// The data is read in 64-bit aligned chunks and pushed to the vector.
    pub fn push_from_mem(&mut self, data: &mut Vec<u64>, addr: u64, count: u64) {
        if count == 0 {
            return;
        }

        let section = self.get_readable_section(addr, count);
        let addr64 = addr >> 3;
        let to_addr64 = (addr + count - 1) >> 3;
        let count64 = (to_addr64 - addr64 + 1) as usize;
        let addr_offset: usize = (addr - section.start) as usize & !0x07;
        let addr_offset64: usize = addr_offset >> 3;

        let mem64: &[u64] = unsafe {
            core::slice::from_raw_parts(
                section.buffer.as_ptr() as *const u64,
                section.buffer.len() / 8,
            )
        };
        data.extend_from_slice(&mem64[addr_offset64..addr_offset64 + count64]);
    }

    pub fn memcmp(&self, a: u64, b: u64, count: u64) -> (u64, usize) {
        if count == 0 {
            return (0, 0);
        }

        let count_usize = count as usize;

        // Get sections for both addresses
        let a_section = self.get_readable_section(a, count);
        let b_section = self.get_readable_section(b, count);

        let a_offset: usize = (a - a_section.start) as usize;
        let b_offset: usize = (b - b_section.start) as usize;

        // Compare byte by byte
        for i in 0..count_usize {
            let byte_a = a_section.buffer[a_offset + i];
            let byte_b = b_section.buffer[b_offset + i];

            if byte_a != byte_b {
                // Sign extend the difference to 64 bits
                let diff = (byte_a as i64) - (byte_b as i64);
                // return effective count, needs the last byte to compare.
                // println!("BYTE_DIFF[{i:>4}] = {diff} BYTE_A[0x{a:08X} + {i:>4}](0x{byte_a:02X}) ? BYTE_B[0x{b:08X} + {i:>4}](0x{byte_b:02X}) S:{step}");
                // if i > 0 {
                //     println!("PREV BYTE_A[0x{a:08X} + {:>4}](0x{:02X}) ? BYTE_B[0x{b:08X} + {:>4}](0x{:02X}) S:{step}",
                //     i - 1, a_section.buffer[a_offset + i - 1], i - 1, b_section.buffer[b_offset + i - 1]);
                // }
                // println!("POST BYTE_A[0x{a:08X} + {:>4}](0x{:02X}) ? BYTE_B[0x{b:08X} + {:>4}](0x{:02X}) S:{step}",
                // i + 1, a_section.buffer[a_offset + i + 1], i + 1, b_section.buffer[b_offset + i + 1]);
                return (diff as u64, i + 1);
            }
        }
        // All bytes are equal
        (0, count_usize)
    }

    pub fn memdump(&self, addr: u64, count: u64) -> String {
        if count == 0 {
            return String::new();
        }

        let count_usize = count as usize;

        // Get section for the address range
        let section = self.get_readable_section(addr, count);
        let offset: usize = (addr - section.start) as usize;

        // Convert bytes to hex string
        section.buffer[offset..offset + count_usize]
            .iter()
            .map(|byte| format!("{:02x}", byte))
            .collect::<Vec<String>>()
            .join("")
    }

    //pub fn get_non_aligned_data_from_required(address: u64, width: u8,)
}