gbf_core/
bytecode_loader.rs

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
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
#![deny(missing_docs)]

use crate::{
    graal_io::{GraalIoError, GraalReader},
    instruction::Instruction,
    opcode::{Opcode, OpcodeError},
    operand::{Operand, OperandError},
    utils::Gs2BytecodeAddress,
};

use std::{
    collections::{BTreeSet, HashMap},
    io::Read,
};

use log::warn;
use petgraph::graph::{DiGraph, NodeIndex};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Error type for bytecode operations.
#[derive(Error, Debug)]
pub enum BytecodeLoaderError {
    /// Error for when an invalid section type is encountered.
    #[error("Invalid section type: {0}")]
    InvalidSectionType(u32),

    /// Error for when an invalid section length is encountered.
    #[error("Invalid section length for {0}: {1}")]
    InvalidSectionLength(SectionType, u32),

    /// Error when string index is out of bounds.
    #[error("String index {0} is out of bounds. Length: {1}")]
    StringIndexOutOfBounds(usize, usize),

    /// Error for when there is no previous instruction when setting an operand.
    #[error("No previous instruction to set operand")]
    NoPreviousInstruction,

    /// Unreachable block error.
    #[error("Block at address {0} is unreachable")]
    UnreachableBlock(Gs2BytecodeAddress),

    /// Error for when an I/O error occurs.
    #[error("GraalIo error: {0}")]
    GraalIo(#[from] GraalIoError),

    /// Error for when an invalid opcode is encountered.
    #[error("Invalid opcode: {0}")]
    OpcodeError(#[from] OpcodeError),

    /// Error for when an invalid operand is encountered.
    #[error("Invalid operand: {0}")]
    InvalidOperand(#[from] OperandError),
}

impl std::fmt::Display for SectionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SectionType::Gs1Flags => write!(f, "Gs1Flags"),
            SectionType::Functions => write!(f, "Functions"),
            SectionType::Strings => write!(f, "Strings"),
            SectionType::Instructions => write!(f, "Instructions"),
        }
    }
}

/// Represents a section type in a module.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
pub enum SectionType {
    /// The section contains flags for the module.
    Gs1Flags = 1,

    /// The section contains the module's functions.
    Functions = 2,

    /// The section contains the module's strings.
    Strings = 3,

    /// The section contains the module's instructions.
    Instructions = 4,
}

/// A builder for a BytecodeLoader.
pub struct BytecodeLoaderBuilder<R> {
    reader: R,
}

impl<R: std::io::Read> BytecodeLoaderBuilder<R> {
    /// Creates a new BytecodeLoaderBuilder.
    ///
    /// # Arguments
    /// - `reader`: The reader to read the bytecode from.
    ///
    /// # Returns
    /// - A new `BytecodeLoaderBuilder` instance.
    ///
    /// # Example
    /// ```
    /// use gbf_core::bytecode_loader::BytecodeLoaderBuilder;
    ///
    /// let reader = std::io::Cursor::new(vec![0x00, 0x00, 0x00, 0x00]);
    /// let builder = BytecodeLoaderBuilder::new(reader);
    /// ```
    pub fn new(reader: R) -> Self {
        Self { reader }
    }

    /// Builds a `BytecodeLoader` from the builder.
    ///
    /// # Returns
    /// - A `Result` containing the `BytecodeLoader` if successful.
    ///
    /// # Errors
    /// - `BytecodeLoaderError::InvalidSectionType` if an invalid section type is encountered.
    /// - `BytecodeLoaderError::InvalidSectionLength` if an invalid section length is encountered.
    /// - `BytecodeLoaderError::StringIndexOutOfBounds` if a string index is out of bounds.
    /// - `BytecodeLoaderError::NoPreviousInstruction` if there is no previous instruction when setting an operand.
    /// - `BytecodeLoaderError::GraalIo` if an I/O error occurs.
    /// - `BytecodeLoaderError::OpcodeError` if an invalid opcode is encountered.
    pub fn build(self) -> Result<BytecodeLoader<R>, BytecodeLoaderError> {
        let mut loader = BytecodeLoader {
            block_breaks: BTreeSet::new(),
            reader: GraalReader::new(self.reader),
            function_map: HashMap::new(),
            strings: Vec::new(),
            instructions: Vec::new(),
            raw_block_graph: DiGraph::new(),
            raw_block_address_to_node: HashMap::new(),
            block_address_to_function: HashMap::new(),
        };
        loader.load()?; // Load data during construction
        Ok(loader)
    }
}

/// A structure for loading bytecode from a reader.
pub struct BytecodeLoader<R: Read> {
    reader: GraalReader<R>,
    strings: Vec<String>,

    /// A map of function names to their addresses.
    pub function_map: HashMap<Option<String>, Gs2BytecodeAddress>,

    /// The instructions in the module.
    pub instructions: Vec<Instruction>,

    // A HashSet of where block breaks occur.
    block_breaks: BTreeSet<Gs2BytecodeAddress>,

    /// The relationship between each block start address and the next block start address.
    raw_block_graph: DiGraph<Gs2BytecodeAddress, ()>,

    /// A map of block start addresses to their corresponding node in the graph.
    raw_block_address_to_node: HashMap<Gs2BytecodeAddress, NodeIndex>,

    /// A map of block start addresses to their corresponding function name.
    pub block_address_to_function: HashMap<Gs2BytecodeAddress, Option<String>>,
}

impl<R: Read> BytecodeLoader<R> {
    /// Asserts that the section length is correct.
    ///
    /// # Arguments
    /// - `section_type`: The type of the section.
    /// - `expected_length`: The expected length of the section.
    /// - `got_length`: The actual length of the section.
    ///
    /// # Returns
    /// - A `Result` indicating success or failure.
    ///
    /// # Errors
    /// - `BytecodeLoaderError::InvalidSectionLength` if the section length is incorrect.
    fn expect_section_length(
        section_type: SectionType,
        expected_length: u32,
        got_length: u32,
    ) -> Result<(), BytecodeLoaderError> {
        if expected_length != got_length {
            return Err(BytecodeLoaderError::InvalidSectionLength(
                section_type,
                got_length,
            ));
        }
        Ok(())
    }

    /// Reads the flags section from the reader.
    ///
    /// We don't actually need to do anything with the flags section, so we just read it and ignore it.
    fn read_gs1_flags(&mut self) -> Result<(), BytecodeLoaderError> {
        let section_length = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;
        let _flags = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;

        // assert that the section length is correct
        Self::expect_section_length(SectionType::Gs1Flags, 4, section_length)?;

        Ok(())
    }

    /// Insert a block start into the graph
    ///
    /// # Arguments
    /// - `address`: The address of the block.
    fn insert_block_start(&mut self, address: Gs2BytecodeAddress) {
        self.block_breaks.insert(address);
    }

    /// Reads the functions section from the reader. This section contains the names of the functions
    /// in the module.
    ///
    /// # Returns
    /// - A `Result` indicating success or failure.
    ///
    /// # Errors
    /// - `BytecodeLoaderError::InvalidSectionLength` if the section length is incorrect.
    /// - `BytecodeLoaderError::GraalIo` if an I/O error occurs.
    fn read_functions(&mut self) -> Result<(), BytecodeLoaderError> {
        let section_length = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;

        // Insert the entry point function
        self.function_map.insert(None, 0);

        // For each function, use self.reader.read_u32() to get the location of the function,
        // and then use self.reader.read_string() to get the name of the function. We should
        // only read up to section_length bytes.
        let mut bytes_read = 0;
        while bytes_read < section_length {
            let function_location =
                self.reader.read_u32().map_err(BytecodeLoaderError::from)? as Gs2BytecodeAddress;
            let function_name = self
                .reader
                .read_string()
                .map_err(BytecodeLoaderError::from)?;
            self.function_map
                .insert(Some(function_name.clone()), function_location);
            bytes_read += 4 + function_name.len() as u32;
            bytes_read += 1; // Null terminator

            self.insert_block_start(function_location);
        }

        // assert that the section length is correct
        Self::expect_section_length(SectionType::Functions, section_length, bytes_read)?;

        Ok(())
    }

    /// Reads the strings section from the reader. This section contains the strings used in the module.
    ///
    /// # Returns
    /// - A `Result` indicating success or failure.
    ///
    /// # Errors
    /// - `BytecodeLoaderError::GraalIo` if an I/O error occurs.
    /// - `BytecodeLoaderError::InvalidSectionLength` if the section length is incorrect.
    fn read_strings(&mut self) -> Result<(), BytecodeLoaderError> {
        let section_length = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;

        // For each string, use self.reader.read_string() to get the string. We should only read up to section_length bytes.
        let mut bytes_read = 0;
        while bytes_read < section_length {
            let string = self
                .reader
                .read_string()
                .map_err(BytecodeLoaderError::from)?;
            self.strings.push(string.clone());
            bytes_read += string.len() as u32;
            bytes_read += 1; // Null terminator
        }

        // assert that the section length is correct
        Self::expect_section_length(SectionType::Strings, section_length, bytes_read)?;

        Ok(())
    }

    /// Read one opcode from the reader and return it.
    fn read_opcode(&mut self) -> Result<Opcode, BytecodeLoaderError> {
        let opcode_byte = self.reader.read_u8().map_err(BytecodeLoaderError::from)?;
        let opcode = Opcode::from_byte(opcode_byte)?;
        Ok(opcode)
    }

    /// Read one operand from the reader and return it along with the number of bytes read.
    fn read_operand(
        &mut self,
        opcode: Opcode,
    ) -> Result<Option<(Operand, usize)>, BytecodeLoaderError> {
        match opcode {
            Opcode::ImmStringByte => {
                let string_index = self.reader.read_u8().map_err(BytecodeLoaderError::from)?;
                let string = self.strings.get(string_index as usize).ok_or(
                    BytecodeLoaderError::StringIndexOutOfBounds(
                        string_index as usize,
                        self.strings.len(),
                    ),
                )?;
                Ok(Some((Operand::new_string(string), 1)))
            }
            Opcode::ImmStringShort => {
                let string_index = self.reader.read_u16().map_err(BytecodeLoaderError::from)?;
                let string = self.strings.get(string_index as usize).ok_or(
                    BytecodeLoaderError::StringIndexOutOfBounds(
                        string_index as usize,
                        self.strings.len(),
                    ),
                )?;
                Ok(Some((Operand::new_string(string), 2)))
            }
            Opcode::ImmStringInt => {
                let string_index = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;
                let string = self.strings.get(string_index as usize).ok_or(
                    BytecodeLoaderError::StringIndexOutOfBounds(
                        string_index as usize,
                        self.strings.len(),
                    ),
                )?;
                Ok(Some((Operand::new_string(string), 4)))
            }
            Opcode::ImmByte => {
                let value = self.reader.read_u8().map_err(BytecodeLoaderError::from)?;
                Ok(Some((Operand::new_number(value as i32), 1)))
            }
            Opcode::ImmShort => {
                let value = self.reader.read_u16().map_err(BytecodeLoaderError::from)?;
                Ok(Some((Operand::new_number(value as i32), 2)))
            }
            Opcode::ImmInt => {
                let value = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;
                Ok(Some((Operand::new_number(value as i32), 4)))
            }
            Opcode::ImmFloat => {
                let value = self
                    .reader
                    .read_string()
                    .map_err(BytecodeLoaderError::from)?;
                Ok(Some((Operand::new_float(value.clone()), value.len() + 1)))
            }
            _ => Ok(None),
        }
    }

    /// Reads the instructions section from the reader. This section contains the bytecode instructions.
    fn read_instructions(&mut self) -> Result<(), BytecodeLoaderError> {
        // Add the first block start address
        self.insert_block_start(0);

        let section_length = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;

        let mut bytes_read = 0;
        while bytes_read < section_length {
            let opcode = self.read_opcode()?;
            bytes_read += 1;

            let operand = self.read_operand(opcode)?;

            if let Some(operand) = operand {
                // Separate scope for mutable borrow of instructions
                {
                    let last_instruction = self
                        .instructions
                        .last_mut()
                        .ok_or(BytecodeLoaderError::NoPreviousInstruction)?;

                    last_instruction.set_operand(operand.0.clone());
                }

                bytes_read += operand.1 as u32;

                debug_assert!(self.instructions.last().is_some());

                // We can unwrap here because we know that the last instruction exists in the scope above
                if self.instructions.last().unwrap().opcode.has_jump_target() {
                    self.insert_block_start(operand.0.get_number_value()? as Gs2BytecodeAddress);
                }
            } else {
                // Create a new instruction
                let address = self.instructions.len();
                self.instructions.push(Instruction::new(opcode, address));

                if opcode.is_block_end() {
                    let current_address = address as Gs2BytecodeAddress;
                    self.insert_block_start(current_address + 1);
                }
            }
        }

        // Verify the section length
        Self::expect_section_length(SectionType::Instructions, section_length, bytes_read)?;

        // Handle the case of empty instructions
        if self.instructions.is_empty() {
            warn!("No instructions were loaded.");
            self.block_breaks.clear();
        }

        // Validate all addresses
        let instruction_count = self.instructions.len() as Gs2BytecodeAddress;
        for address in self.block_breaks.iter() {
            // It is legal to jump to the "end" of the instructions, but not past it.
            if *address > instruction_count {
                return Err(BytecodeLoaderError::InvalidOperand(
                    OperandError::InvalidJumpTarget(*address),
                ));
            }
        }

        Ok(())
    }

    /// Loads the bytecode from the reader into the structure.
    ///
    /// # Returns
    /// - A `Result` indicating success or failure.
    ///
    /// # Errors
    /// - `BytecodeLoaderError::InvalidSectionType` if an invalid section type is encountered.
    /// - `BytecodeLoaderError::InvalidSectionLength` if an invalid section length is encountered.
    /// - `BytecodeLoaderError::StringIndexOutOfBounds` if a string index is out of bounds.
    /// - `BytecodeLoaderError::NoPreviousInstruction` if there is no previous instruction when setting an operand.
    /// - `BytecodeLoaderError::GraalIo` if an I/O error occurs.
    /// - `BytecodeLoaderError::OpcodeError` if an invalid opcode is encountered.
    /// - `BytecodeLoaderError::InvalidOperand` if an invalid operand is encountered.
    fn load(&mut self) -> Result<(), BytecodeLoaderError> {
        // TODO: I know there will only be 4 sections, but I'd like to make this more dynamic.
        for _ in 0..4 {
            let section_type = self.read_section_type()?;
            match section_type {
                SectionType::Gs1Flags => {
                    self.read_gs1_flags()?;
                }
                SectionType::Functions => {
                    self.read_functions()?;
                }
                SectionType::Strings => {
                    self.read_strings()?;
                }
                SectionType::Instructions => {
                    self.read_instructions()?;
                }
            }
        }

        // After reading in all of the block breaks, we can now create the graph.
        for block_break in self.block_breaks.iter() {
            let node = self.raw_block_graph.add_node(*block_break);
            self.raw_block_address_to_node.insert(*block_break, node);
        }

        // Iterate through each instruction to figure out the edges
        for instruction in self.instructions.iter() {
            let current_instruction_address = instruction.address as Gs2BytecodeAddress;
            let current_block_address = self.find_block_start_address(current_instruction_address);
            // if the instruction is the last instruction in the block
            let is_block_end = self
                .block_breaks
                .contains(&(current_instruction_address + 1));

            // If the current instruction is a jump, then we need to add an edge to the target block start
            if instruction.opcode.has_jump_target() {
                let source_node = self
                    .raw_block_address_to_node
                    .get(&current_block_address)
                    // We can unwrap here because we know that the current block address exists
                    // If it doesn't, then there is a bug that needs to be fixed in the internal
                    // logic of the loader.
                    .unwrap();

                // Unwrap here because we know that the operand exists due to a previous check in
                // `read_instructions`
                let target_address =
                    instruction.operand.as_ref().unwrap().get_number_value()? as Gs2BytecodeAddress;

                // Also unwrap here because we know that the target address exists in the block breaks
                let target_node = self.raw_block_address_to_node.get(&target_address).unwrap();

                self.raw_block_graph
                    .add_edge(*source_node, *target_node, ());
            }

            // If the current opcode has a fallthrough, then we need to add an edge to the next block start
            if is_block_end && instruction.opcode.connects_to_next_block() {
                let source_node = self
                    .raw_block_address_to_node
                    .get(&current_block_address)
                    // We can unwrap here because we know that the current block address exists
                    // If it doesn't, then there is a bug that needs to be fixed in the internal
                    // logic of the loader.
                    .unwrap();

                // Find the next block start address
                let next_block_address = current_instruction_address + 1;

                // Also unwrap here because we know that the target address exists in the block breaks
                let target_node = self
                    .raw_block_address_to_node
                    .get(&next_block_address)
                    .unwrap();

                self.raw_block_graph
                    .add_edge(*source_node, *target_node, ());
            }
        }

        // Iterate through each function
        for (function_name, function_address) in self.function_map.iter() {
            debug_assert_eq!(
                self.raw_block_graph.node_count(),
                self.raw_block_address_to_node.len(),
                "Graph node count and block address map size do not match!"
            );
            for (&block_address, &node) in &self.raw_block_address_to_node {
                debug_assert!(
                    self.raw_block_graph.node_indices().any(|n| n == node),
                    "Node {:?} for block address {} is missing in the graph.",
                    node,
                    block_address
                );
            }

            if let Some(function_node) = self.raw_block_address_to_node.get(function_address) {
                let mut dfs = petgraph::visit::Dfs::new(&self.raw_block_graph, *function_node);

                while let Some(node) = dfs.next(&self.raw_block_graph) {
                    // Map node back to block address.
                    if let Some(block_address) =
                        self.raw_block_address_to_node.iter().find_map(|(k, v)| {
                            if *v == node {
                                Some(*k)
                            } else {
                                None
                            }
                        })
                    {
                        self.block_address_to_function
                            .insert(block_address, function_name.clone());
                    } else {
                        warn!("Node {:?} has no matching block address.", node);
                    }
                }
            } else {
                warn!(
                    "Function '{:?}' at address {} has no corresponding node in raw_block_address_to_node.",
                    function_name, function_address
                );
            }
        }

        Ok(())
    }

    /// Get the function name for a given address.
    ///
    /// # Arguments
    /// - `address`: The address to get the function name for.
    ///
    /// # Returns
    /// - The function name, if it exists.
    ///
    /// # Errors
    /// - `BytecodeLoaderError::UnreachableBlock` if the block is unreachable, and therefore,
    ///   the function name cannot be determined.
    pub fn get_function_name_for_address(
        &self,
        address: Gs2BytecodeAddress,
    ) -> Result<Option<String>, BytecodeLoaderError> {
        let block_start = self.find_block_start_address(address);
        Ok(self
            .block_address_to_function
            .get(&block_start)
            // return error if the block is unreachable
            .ok_or(BytecodeLoaderError::UnreachableBlock(block_start))?
            .clone())
    }

    /// Checks if an instruction is reachable.
    ///
    /// # Arguments
    /// - `address`: The address to check.
    ///
    /// # Returns
    /// - `true` if the instruction is reachable, `false` otherwise.
    pub fn is_instruction_reachable(&self, address: Gs2BytecodeAddress) -> bool {
        let blk = self.find_block_start_address(address);
        self.block_address_to_function.contains_key(&blk)
    }

    /// Helper function to figure out what block the address is in. This basically looks
    /// at the argument, and finds the closest block start address that is less than or equal
    ///
    /// # Arguments
    /// - `address`: The address to find the block for.
    ///
    /// # Returns
    /// - The block start address.
    pub fn find_block_start_address(&self, address: Gs2BytecodeAddress) -> Gs2BytecodeAddress {
        let mut block_start = 0;
        for block_break in self.block_breaks.iter() {
            if *block_break > address {
                break;
            }
            block_start = *block_break;
        }
        block_start
    }

    /// Reads a section type from the reader.
    fn read_section_type(&mut self) -> Result<SectionType, BytecodeLoaderError> {
        let section_type = self.reader.read_u32().map_err(BytecodeLoaderError::from)?;
        match section_type {
            1 => Ok(SectionType::Gs1Flags),
            2 => Ok(SectionType::Functions),
            3 => Ok(SectionType::Strings),
            4 => Ok(SectionType::Instructions),
            _ => Err(BytecodeLoaderError::InvalidSectionType(section_type)),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{bytecode_loader::BytecodeLoaderBuilder, utils::Gs2BytecodeAddress};

    #[test]
    fn test_load() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9
            0x00, 0x00, 0x00, 0x00, // Function location: 0
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x00, // Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x61, 0x62, 0x63, 0x00, // String: "abc"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x0c, // Length: 12
            0x01, // Opcode: Jmp
            0xF3, // Opcode: ImmByte
            0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF4, // Opcode: ImmShort
            0x00, 0x01, // Operand: 1
            0x15, // Opcode: PushString
            0xF0, // Opcode: ImmStringByte
            0x00, // Operand: 0
            0x1b, // Opcode: PushPi
            0x07, // Opcode: Ret
        ]);
        let loader = BytecodeLoaderBuilder::new(reader).build().unwrap();

        assert_eq!(loader.function_map.len(), 2);
        assert_eq!(loader.function_map.get(&Some("main".to_string())), Some(&0));
        assert_eq!(loader.strings.len(), 1);
        assert_eq!(loader.strings.first(), Some(&"abc".to_string()));
        assert_eq!(loader.instructions.len(), 5);
        assert_eq!(loader.instructions[0].opcode, crate::opcode::Opcode::Jmp);
        assert_eq!(
            loader.instructions[1].opcode,
            crate::opcode::Opcode::PushNumber
        );
        assert_eq!(
            loader.instructions[1].operand,
            Some(crate::operand::Operand::new_number(1))
        );
        assert_eq!(
            loader.instructions[2].opcode,
            crate::opcode::Opcode::PushString
        );
        assert_eq!(
            loader.instructions[2].operand,
            Some(crate::operand::Operand::new_string("abc"))
        );
        assert_eq!(loader.instructions[3].opcode, crate::opcode::Opcode::PushPi);
        assert_eq!(loader.instructions[4].opcode, crate::opcode::Opcode::Ret);
    }

    #[test]
    fn test_complex_load() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9
            0x00, 0x00, 0x00, 0x01, // Function location: 1
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x00, // Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x61, 0x62, 0x63, 0x00, // String: "abc"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x47, // Length: 71
            // Instructions
            0x01, 0xF3, 0x19, // Jmp 0x19
            0x14, 0xF3, 0x00, // PushNumber 0
            0x01, 0xF3, 0x0c, // Jmp 0x0c
            0x14, 0xF3, 0x00, // PushNumber 0
            0x01, 0xF3, 0x17, // Jmp 0x17
            0x14, 0xF3, 0x00, // PushNumber 0
            0x01, 0xF3, 0x17, // Jmp 0x17
            0x14, 0xF3, 0x00, // PushNumber 0
            0x01, 0xF3, 0x17, // Jmp 0x17
            0x14, 0xF3, 0x00, // PushNumber 0 (unreachable)
            0x01, 0xF3, 0x17, // Jmp 0x17
            0x01, 0xF3, 0x17, // Jmp 0x17
            0x14, 0xF3, 0x00, // PushNumber 0
            0x02, 0xF3, 0x03, // Jeq 0x03
            0x14, 0xF3, 0x00, // PushNumber 0
            0x02, 0xF3, 0x03, // Jeq 0x03
            0x14, 0xF3, 0x00, // PushNumber 0
            0x02, 0xF3, 0x03, // Jeq 0x03
            0x14, 0xF3, 0x00, // PushNumber 0
            0x02, 0xF3, 0x05, // Jeq 0x05
            0x14, 0xF3, 0x00, // PushNumber 0
            0x02, 0xF3, 0x07, // Jeq 0x07
            0x01, 0xF3, 0x0b, // Jmp 0x0b
            0x20, // Pop
            0x07, // Ret
        ]);
        let loader = BytecodeLoaderBuilder::new(reader).build().unwrap();

        assert_eq!(loader.function_map.len(), 2);

        // get all of the block start addresses
        // There is a block that is unreachable. It will still appear in the block starts.
        let block_starts: Vec<Gs2BytecodeAddress> = loader.block_breaks.iter().copied().collect();

        // Ensure that the block at address 0 connects to the block at address 0x19
        let block_0 = loader.find_block_start_address(0);
        let block_0x19 = loader.find_block_start_address(0x19);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0],
            loader.raw_block_address_to_node[&block_0x19]
        ));

        // Ensure that the block at address 1 connects to the block at address 0x0c
        let block_1 = loader.find_block_start_address(1);
        let block_0x0c = loader.find_block_start_address(0x0c);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_1],
            loader.raw_block_address_to_node[&block_0x0c]
        ));

        // Ensure that the block at address 0x03 connects to the block at address 0x17
        let block_0x03 = loader.find_block_start_address(0x03);
        let block_0x17 = loader.find_block_start_address(0x17);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x03],
            loader.raw_block_address_to_node[&block_0x17]
        ));

        // 0x05 -> 0x17
        let block_0x05 = loader.find_block_start_address(0x05);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x05],
            loader.raw_block_address_to_node[&block_0x17]
        ));
        // 0x07 -> 0x17
        let block_0x07 = loader.find_block_start_address(0x07);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x07],
            loader.raw_block_address_to_node[&block_0x17]
        ));

        // 0x0b -> 0x17
        let block_0x0b = loader.find_block_start_address(0x0b);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x0b],
            loader.raw_block_address_to_node[&block_0x17]
        ));

        // 0x0c > 0x3
        let block_0x0c = loader.find_block_start_address(0x0c);
        let block_0x03 = loader.find_block_start_address(0x03);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x0c],
            loader.raw_block_address_to_node[&block_0x03]
        ));

        // 0x0c -> 0x0e
        let block_0x0e = loader.find_block_start_address(0x0e);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x0c],
            loader.raw_block_address_to_node[&block_0x0e]
        ));

        // 0x0e -> 0x3
        let block_0x0e = loader.find_block_start_address(0x0e);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x0e],
            loader.raw_block_address_to_node[&block_0x03]
        ));

        // 0x0e -> 0x10
        let block_0x10 = loader.find_block_start_address(0x10);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x0e],
            loader.raw_block_address_to_node[&block_0x10]
        ));

        // 0x10 -> 0x3
        let block_0x10 = loader.find_block_start_address(0x10);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x10],
            loader.raw_block_address_to_node[&block_0x03]
        ));

        // 0x10 -> 0x12
        let block_0x12 = loader.find_block_start_address(0x12);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x10],
            loader.raw_block_address_to_node[&block_0x12]
        ));

        // 0x12 -> 0x5
        let block_0x12 = loader.find_block_start_address(0x12);
        let block_0x05 = loader.find_block_start_address(0x05);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x12],
            loader.raw_block_address_to_node[&block_0x05]
        ));

        // 0x12 -> 0x14
        let block_0x14 = loader.find_block_start_address(0x14);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x12],
            loader.raw_block_address_to_node[&block_0x14]
        ));

        // 0x14 -> 0x7
        let block_0x14 = loader.find_block_start_address(0x14);
        let block_0x07 = loader.find_block_start_address(0x07);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x14],
            loader.raw_block_address_to_node[&block_0x07]
        ));

        // 0x14 -> 0x16
        let block_0x16 = loader.find_block_start_address(0x16);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x14],
            loader.raw_block_address_to_node[&block_0x16]
        ));

        // 0x16 -> 0xb
        let block_0x16 = loader.find_block_start_address(0x16);
        let block_0x0b = loader.find_block_start_address(0x0b);
        assert!(loader.raw_block_graph.contains_edge(
            loader.raw_block_address_to_node[&block_0x16],
            loader.raw_block_address_to_node[&block_0x0b]
        ));

        // Compare every block start address to the expected values
        let expected_block_starts = vec![
            0x0, 0x1, 0x3, 0x5, 0x7, 0x9, 0xb, 0xc, 0xe, 0x10, 0x12, 0x14, 0x16, 0x17, 0x19,
        ];
        assert_eq!(block_starts, expected_block_starts);

        // The block at address 0x09 is unreachable, so it should not have any incoming edges
        let block_0x09 = loader.find_block_start_address(0x09);
        assert_eq!(
            loader
                .raw_block_graph
                .neighbors_directed(
                    loader.raw_block_address_to_node[&block_0x09],
                    petgraph::Direction::Incoming
                )
                .count(),
            0
        );

        assert_eq!(block_starts.len(), 15);

        // Ensure that the function map is correct
        assert_eq!(loader.function_map.len(), 2);

        // For each address, ensure that the function name is correct
        for address in expected_block_starts.iter() {
            match address {
                // Start of the module
                0 => assert_eq!(loader.get_function_name_for_address(0).unwrap(), None),
                // Unreachable node
                0x09 => assert!(loader.get_function_name_for_address(9).is_err()),
                // End of the module
                0x19 => assert_eq!(loader.get_function_name_for_address(0x19).unwrap(), None),
                _ => assert_eq!(
                    loader.get_function_name_for_address(*address).unwrap(),
                    Some("main".to_string())
                ),
            }
        }
    }

    #[test]
    fn test_load_invalid_section_type() {
        let reader = std::io::Cursor::new(vec![0x00, 0x00, 0x00, 0x05]);
        let result = BytecodeLoaderBuilder::new(reader).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_load_invalid_section_length() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x05, // Length: 5
            0x00, 0x00, 0x00, 0x00, // Flags: 0
        ]);
        let result = BytecodeLoaderBuilder::new(reader).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_fmt_section_type() {
        assert_eq!(
            format!("{}", super::SectionType::Gs1Flags),
            "Gs1Flags".to_string()
        );
        assert_eq!(
            format!("{}", super::SectionType::Functions),
            "Functions".to_string()
        );
        assert_eq!(
            format!("{}", super::SectionType::Strings),
            "Strings".to_string()
        );
        assert_eq!(
            format!("{}", super::SectionType::Instructions),
            "Instructions".to_string()
        );
    }

    #[test]
    fn test_load_string_index_out_of_bounds() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9
            0x00, 0x00, 0x00, 0x00, // Function location: 0
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x00, // Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x61, 0x62, 0x63, 0x00, // String: "abc"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x0c, // Length: 12
            0x01, // Opcode: Jmp
            0xF3, // Opcode: ImmByte
            0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF4, // Opcode: ImmShort
            0x00, 0x01, // Operand: 1
            0x15, // Opcode: PushString
            0xF0, // Opcode: ImmStringByte
            0x01, // Operand: 1 (out of bounds)
            0x1b, // Opcode: PushPi
            0x07, // Opcode: Ret
        ]);

        let result = BytecodeLoaderBuilder::new(reader).build();

        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_instruction() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9
            0x00, 0x00, 0x00, 0x00, // Function location: 0
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x00, // Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x61, 0x62, 0x63, 0x00, // String: "abc"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x02, // Length: 2
            0xF3, // Opcode: ImmByte
            0x01, // Operand: 1
        ]);

        let result = BytecodeLoaderBuilder::new(reader).build();

        assert!(result.is_err());
    }

    #[test]
    fn test_load_invalid_function_section_length() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9 (invalid)
            0x00, 0x00, 0x00, 0x00, // Function location: 0
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x41, 0x00, // "A" and Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x61, 0x62, 0x63, 0x00, // String: "abc"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x0c, // Length: 12
            0x01, // Opcode: Jmp
            0xF3, // Opcode: ImmByte
            0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF4, // Opcode: ImmShort
            0x00, 0x01, // Operand: 1
            0x15, // Opcode: PushString
            0xF0, // Opcode: ImmStringByte
            0x00, // Operand: 0
            0x1b, // Opcode: PushPi
            0x07, // Opcode: Ret
        ]);

        let result = BytecodeLoaderBuilder::new(reader).build();

        assert!(result.is_err());
    }

    #[test]
    fn test_operands() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9
            0x00, 0x00, 0x00, 0x00, // Function location: 0
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x00, // Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x61, 0x62, 0x63, 0x00, // String: "abc"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x23, // Length: 35
            0x01, // Opcode: Jmp
            0xF3, // Opcode: ImmByte
            0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF4, // Opcode: ImmShort
            0x00, 0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF5, // Opcode: ImmInt
            0x00, 0x00, 0x00, 0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF6, // Opcode: ImmFloat
            0x33, 0x2e, 0x31, 0x34, 0x00, // Operand: "3.14"
            0x15, // Opcode: PushString
            0xF0, // Opcode: ImmStringByte
            0x00, // Operand: 0
            0x15, // Opcode: PushString
            0xF1, // Opcode: ImmStringShort
            0x00, 0x00, // Operand: 0
            0x15, // Opcode: PushString
            0xF2, // Opcode: ImmStringInt
            0x00, 0x00, 0x00, 0x00, // Operand: 0
            0x1b, // Opcode: PushPi
            0x07, // Opcode: Ret
        ]);
        let loader = BytecodeLoaderBuilder::new(reader).build().unwrap();

        assert_eq!(loader.function_map.len(), 2);
        assert_eq!(loader.function_map.get(&Some("main".to_string())), Some(&0));
        assert_eq!(loader.strings.len(), 1);
        assert_eq!(loader.strings.first(), Some(&"abc".to_string()));
        assert_eq!(loader.instructions.len(), 9);

        assert_eq!(loader.instructions[0].opcode, crate::opcode::Opcode::Jmp);
        assert_eq!(
            loader.instructions[0].operand,
            Some(crate::operand::Operand::new_number(1))
        );
        assert_eq!(
            loader.instructions[1].opcode,
            crate::opcode::Opcode::PushNumber
        );
        assert_eq!(
            loader.instructions[1].operand,
            Some(crate::operand::Operand::new_number(1))
        );
        assert_eq!(
            loader.instructions[2].opcode,
            crate::opcode::Opcode::PushNumber
        );
        assert_eq!(
            loader.instructions[2].operand,
            Some(crate::operand::Operand::new_number(1))
        );
        assert_eq!(
            loader.instructions[3].opcode,
            crate::opcode::Opcode::PushNumber
        );
        assert_eq!(
            loader.instructions[3].operand,
            Some(crate::operand::Operand::new_float("3.14".to_string()))
        );
        assert_eq!(
            loader.instructions[4].opcode,
            crate::opcode::Opcode::PushString
        );
        assert_eq!(
            loader.instructions[4].operand,
            Some(crate::operand::Operand::new_string("abc"))
        );
        assert_eq!(
            loader.instructions[5].opcode,
            crate::opcode::Opcode::PushString
        );
        assert_eq!(
            loader.instructions[5].operand,
            Some(crate::operand::Operand::new_string("abc"))
        );
        assert_eq!(
            loader.instructions[6].opcode,
            crate::opcode::Opcode::PushString
        );
        assert_eq!(
            loader.instructions[6].operand,
            Some(crate::operand::Operand::new_string("abc"))
        );
        assert_eq!(loader.instructions[7].opcode, crate::opcode::Opcode::PushPi);
        assert_eq!(loader.instructions[7].operand, None);
        assert_eq!(loader.instructions[8].opcode, crate::opcode::Opcode::Ret);
        assert_eq!(loader.instructions[8].operand, None);
    }

    #[test]
    fn test_start_block_addresses() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9
            0x00, 0x00, 0x00, 0x03, // Function location: 3
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x00, // Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x41, 0x42, 0x43, 0x00, // String: "ABC"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x26, // Length: 38
            0x01, // Opcode: Jmp
            0xF3, // Opcode: ImmByte
            0x05, // Operand: 5
            0x14, // Opcode: PushNumber
            0xF4, // Opcode: ImmShort
            0x00, 0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF5, // Opcode: ImmInt
            0x00, 0x00, 0x00, 0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF6, // Opcode: ImmFloat
            0x33, 0x2e, 0x31, 0x34, 0x00, // Operand: "3.14"
            0x15, // Opcode: PushString
            0xF0, // Opcode: ImmStringByte
            0x00, // Operand: 0
            0x15, // Opcode: PushString
            0xF1, // Opcode: ImmStringShort
            0x00, 0x00, // Operand: 0
            0x02, // Opcode: Jeq
            0xF3, // Opcode: ImmByte
            0x02, // Operand: 2
            0x15, // Opcode: PushString
            0xF2, // Opcode: ImmStringInt
            0x00, 0x00, 0x00, 0x00, // Operand: 0
            0x1b, // Opcode: PushPi
            0x07, // Opcode: Ret
        ]);
        let loader = BytecodeLoaderBuilder::new(reader).build().unwrap();

        assert_eq!(loader.block_breaks.len(), 7);
        assert!(loader.block_breaks.contains(&0));
        assert!(loader.block_breaks.contains(&1));
        assert!(loader.block_breaks.contains(&2));
        assert!(loader.block_breaks.contains(&3));
        assert!(loader.block_breaks.contains(&5));
        assert!(loader.block_breaks.contains(&7));
        assert!(loader.block_breaks.contains(&10));
    }

    #[test]
    fn test_invalid_blocks() {
        let reader = std::io::Cursor::new(vec![
            0x00, 0x00, 0x00, 0x01, // Section type: Gs1Flags
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x00, 0x00, 0x00, 0x00, // Flags: 0
            0x00, 0x00, 0x00, 0x02, // Section type: Functions
            0x00, 0x00, 0x00, 0x09, // Length: 9
            0x00, 0x00, 0x00, 0x00, // Function location: 0
            0x6d, 0x61, 0x69, 0x6e, // Function name: "main"
            0x00, // Null terminator
            0x00, 0x00, 0x00, 0x03, // Section type: Strings
            0x00, 0x00, 0x00, 0x04, // Length: 4
            0x41, 0x42, 0x43, 0x00, // String: "ABC"
            0x00, 0x00, 0x00, 0x04, // Section type: Instructions
            0x00, 0x00, 0x00, 0x26, // Length: 38
            0x01, // Opcode: Jmp
            0xF3, // Opcode: ImmByte
            0x05, // Operand: 5
            0x14, // Opcode: PushNumber
            0xF4, // Opcode: ImmShort
            0x00, 0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF5, // Opcode: ImmInt
            0x00, 0x00, 0x00, 0x01, // Operand: 1
            0x14, // Opcode: PushNumber
            0xF6, // Opcode: ImmFloat
            0x33, 0x2e, 0x31, 0x34, 0x00, // Operand: "3.14"
            0x15, // Opcode: PushString
            0xF0, // Opcode: ImmStringByte
            0x00, // Operand: 0
            0x15, // Opcode: PushString
            0xF1, // Opcode: ImmStringShort
            0x00, 0x00, // Operand: 0
            0x02, // Opcode: Jeq
            0xF3, // Opcode: ImmByte
            0xFF, // Operand: FF (invalid)
            0x15, // Opcode: PushString
            0xF2, // Opcode: ImmStringInt
            0x00, 0x00, 0x00, 0x00, // Operand: 0
            0x1b, // Opcode: PushPi
            0x07, // Opcode: Ret
        ]);

        // print instructions
        let loader = BytecodeLoaderBuilder::new(reader).build();
        assert!(loader.is_err());
    }
}