cwextab 1.0.2

CodeWarrior Exception Table decoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
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
use thiserror::Error;

mod mem_utils;

#[derive(Error, Debug)]
pub enum ExtabDecodeError {
    #[error("Data array should at least be 8 bytes long. Given array is {0} bytes long.")]
    ArrayTooSmall(u32),
    #[error("Invalid action value {0} at offset 0x{1:X}")]
    InvalidActionValue(u32, u32),
    #[error("Table is 8 bytes long but terminator is not zero.")]
    InvalidSmallTableTerminator,
    #[error("Internal error")]
    Internal,
}

/// Enum holding the data for each action type.
#[derive(Debug, Clone)]
pub enum ExActionData {
    EndOfList,
    Branch {
        target_offset: u16,
    },
    DestroyLocal {
        local_offset: u16,
        dtor_address: u32,
    },
    DestroyLocalCond {
        condition: u16,
        local_offset: u16,
        unk4: u16,
        dtor_address: u32,
    },
    DestroyLocalPointer {
        local_pointer: u16,
        dtor_address: u32,
    },
    DestroyLocalArray {
        local_array: u16,
        elements: u16,
        element_size: u16,
        dtor_address: u32,
    },
    DestroyBase {
        object_pointer: u16,
        member_offset: u32,
        dtor_address: u32,
    },
    DestroyMember {
        object_pointer: u16,
        member_offset: u32,
        dtor_address: u32,
    },
    DestroyMemberCond {
        condition: u16,
        object_pointer: u16,
        member_offset: u32,
        unk8: u16,
        dtor_address: u32,
    },
    DestroyMemberArray {
        object_pointer: u16,
        member_offset: u32,
        elements: u32,
        element_size: u32,
        dtor_address: u32,
    },
    DeletePointer {
        object_pointer: u16,
        dtor_address: u32,
    },
    DeletePointerCond {
        condition: u16,
        object_pointer: u16,
        unk4: u16,
        dtor_address: u32,
    },
    CatchBlock {
        unk0: u16,
        catch_type: u32,
        catch_pc_offset: u16,
        cinfo_ref: u16,
    },
    ActiveCatchBlock {
        cinfo_ref: u16,
    },
    Terminate,
    Specification {
        specs: u16,
        pc_offset: u32,
        cinfo_ref: u32,
        spec: Vec<u32>,
    },
    CatchBlock32 {
        unk0: u16,
        catch_type: u32,
        catch_pc_offset: u32,
        cinfo_ref: u32,
    },
}

/// Base enum for exception actions.
#[derive(Debug, Copy, Clone)]
pub enum ExAction {
    EndOfList,
    Branch,
    DestroyLocal,
    DestroyLocalCond,
    DestroyLocalPointer,
    DestroyLocalArray,
    DestroyBase,
    DestroyMember,
    DestroyMemberCond,
    DestroyMemberArray,
    DeletePointer,
    DeletePointerCond,
    CatchBlock,
    ActiveCatchBlock,
    Terminate,
    Specification,
    CatchBlock32,
}

impl ExAction {
    pub fn to_int(&self) -> i32 {
        match self {
            ExAction::EndOfList => 0,
            ExAction::Branch => 1,
            ExAction::DestroyLocal => 2,
            ExAction::DestroyLocalCond => 3,
            ExAction::DestroyLocalPointer => 4,
            ExAction::DestroyLocalArray => 5,
            ExAction::DestroyBase => 6,
            ExAction::DestroyMember => 7,
            ExAction::DestroyMemberCond => 8,
            ExAction::DestroyMemberArray => 9,
            ExAction::DeletePointer => 10,
            ExAction::DeletePointerCond => 11,
            ExAction::CatchBlock => 12,
            ExAction::ActiveCatchBlock => 13,
            ExAction::Terminate => 14,
            ExAction::Specification => 15,
            ExAction::CatchBlock32 => 16,
        }
    }

    pub fn from_int(val: i32) -> Option<ExAction> {
        let result: ExAction = match val {
            0 => ExAction::EndOfList,
            1 => ExAction::Branch,
            2 => ExAction::DestroyLocal,
            3 => ExAction::DestroyLocalCond,
            4 => ExAction::DestroyLocalPointer,
            5 => ExAction::DestroyLocalArray,
            6 => ExAction::DestroyBase,
            7 => ExAction::DestroyMember,
            8 => ExAction::DestroyMemberCond,
            9 => ExAction::DestroyMemberArray,
            10 => ExAction::DeletePointer,
            11 => ExAction::DeletePointerCond,
            12 => ExAction::CatchBlock,
            13 => ExAction::ActiveCatchBlock,
            14 => ExAction::Terminate,
            15 => ExAction::Specification,
            16 => ExAction::CatchBlock32,
            _ => {
                //The action value is invalid, return None
                return None;
            }
        };
        Some(result)
    }

    const ACTION_NAMES: [&'static str; 17] = [
        "NULL",
        "BRANCH",
        "DESTROYLOCAL",
        "DESTROYLOCALCOND",
        "DESTROYLOCALPOINTER",
        "DESTROYLOCALARRAY",
        "DESTROYBASE",
        "DESTROYMEMBER",
        "DESTROYMEMBERCOND",
        "DESTROYMEMBERARRAY",
        "DELETEPOINTER",
        "DELETEPOINTERCOND",
        "CATCHBLOCK (Small)",
        "ACTIVECATCHBLOCK",
        "TERMINATE",
        "SPECIFICATION",
        "CATCHBLOCK (Large)",
    ];

    fn convert_to_string(&self) -> String {
        String::from(Self::ACTION_NAMES[self.to_int() as usize])
    }
}

/// Struct for exception actions.
#[derive(Debug, Clone)]
pub struct ExceptionAction {
    //General values
    pub action_offset: u32,
    pub action_type: ExAction, //0x0
    pub action_param: u8,      //0x1
    pub has_end_bit: bool,     //true if action type byte has bit 7 set (type & 0x80)
    pub bytes: Vec<u8>,
}

impl ExceptionAction {
    pub fn new() -> Self {
        Self {
            action_offset: 0,
            action_type: ExAction::EndOfList,
            action_param: 0,
            has_end_bit: false,
            bytes: vec![],
        }
    }

    /// Returns whether this action has a destuctor reference or not.
    pub fn has_dtor_ref(&self) -> bool {
        match self.action_type {
            ExAction::EndOfList => {
                println!("Warning: null action passed");
                false
            }
            ExAction::Branch
            | ExAction::CatchBlock
            | ExAction::ActiveCatchBlock
            | ExAction::Terminate
            | ExAction::Specification
            | ExAction::CatchBlock32 => false,
            _ => true,
        }
    }

    /// Calculates the offset of the dtor function address value in this action entry.
    /// If the entry does not have one, this function returns none.
    fn get_dtor_address_value_offset(&self) -> Option<u32> {
        let offset: u32 =
        match self.action_type {
            ExAction::DestroyLocal => 2,
            ExAction::DestroyLocalCond => 6,
            ExAction::DestroyLocalPointer => 2,
            ExAction::DestroyLocalArray => 6,
            ExAction::DestroyBase
            | ExAction::DestroyMember => 6,
            ExAction::DestroyMemberCond => 10,
            ExAction::DestroyMemberArray => 14,
            ExAction::DeletePointer => 2,
            ExAction::DeletePointerCond => 6,
            _ => return None,
        };

        Some(offset)
    }

    /// Returns the relocation data for the dtor function in this action entry, if any.
    pub fn get_dtor_relocation(&self) -> Option<(u32, u32)> {
        if !self.has_dtor_ref() {
            //If the action entry doesn't have a dtor reference, return none
            return None;
        }

        let offset: u32 = match self.get_dtor_address_value_offset() {
            Some(val) => val,
            None => {
                println!("Error: tried to get dtor address value offset for table which doesn't have it");
                return None;
            }
        };

        let address: u32 = mem_utils::read_uint32(&self.bytes, &mut (offset as i32), true);
        Some((offset, address))
    }

    /// Decodes the action data from the byte array depending on the set action type, and converts it
    /// to an ExActionData enum containing the decoded data.
    pub fn get_exaction_data(&self) -> ExActionData {
        let mut offset: i32 = 0;

        match self.action_type {
            ExAction::EndOfList => ExActionData::EndOfList {},
            ExAction::Branch => {
                let target_offset = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                ExActionData::Branch { target_offset }
            }
            ExAction::DestroyLocal => {
                let local_offset = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyLocal {
                    local_offset,
                    dtor_address,
                }
            }
            ExAction::DestroyLocalCond => {
                let condition = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let local_offset = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let unk4 = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyLocalCond {
                    condition,
                    local_offset,
                    unk4,
                    dtor_address,
                }
            }
            ExAction::DestroyLocalPointer => {
                let local_pointer = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyLocalPointer {
                    local_pointer,
                    dtor_address,
                }
            }
            ExAction::DestroyLocalArray => {
                let local_array = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let elements = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let element_size = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyLocalArray {
                    local_array,
                    elements,
                    element_size,
                    dtor_address,
                }
            }
            ExAction::DestroyBase => {
                let object_pointer = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let member_offset = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyBase {
                    object_pointer,
                    member_offset,
                    dtor_address,
                }
            }
            ExAction::DestroyMember => {
                let object_pointer = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let member_offset = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyMember {
                    object_pointer,
                    member_offset,
                    dtor_address,
                }
            }
            ExAction::DestroyMemberCond => {
                let condition = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let object_pointer = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let member_offset = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let unk8 = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyMemberCond {
                    condition,
                    object_pointer,
                    member_offset,
                    unk8,
                    dtor_address,
                }
            }
            ExAction::DestroyMemberArray => {
                let object_pointer = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let member_offset = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let elements = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let element_size = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DestroyMemberArray {
                    object_pointer,
                    member_offset,
                    elements,
                    element_size,
                    dtor_address,
                }
            }
            ExAction::DeletePointer => {
                let object_pointer = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DeletePointer {
                    object_pointer,
                    dtor_address,
                }
            }
            ExAction::DeletePointerCond => {
                let condition = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let object_pointer = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let unk4 = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let dtor_address = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::DeletePointerCond {
                    condition,
                    object_pointer,
                    unk4,
                    dtor_address,
                }
            }
            ExAction::CatchBlock => {
                let unk0 = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let catch_type = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let catch_pc_offset = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let cinfo_ref = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                ExActionData::CatchBlock {
                    unk0,
                    catch_type,
                    catch_pc_offset,
                    cinfo_ref,
                }
            }
            ExAction::ActiveCatchBlock => {
                let cinfo_ref = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                ExActionData::ActiveCatchBlock { cinfo_ref }
            }
            ExAction::Terminate => ExActionData::Terminate {},
            ExAction::Specification => {
                let specs = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let pc_offset = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let cinfo_ref = mem_utils::read_uint32(&self.bytes, &mut offset, true);

                //Read the specified number of 32 bit values and add them to the list
                let length = specs as i32;
                let mut spec: Vec<u32> = vec![];
                for _i in 0..length {
                    spec.push(mem_utils::read_uint32(&self.bytes, &mut offset, true));
                }
                ExActionData::Specification {
                    specs,
                    pc_offset,
                    cinfo_ref,
                    spec,
                }
            }
            ExAction::CatchBlock32 => {
                let unk0 = mem_utils::read_uint16(&self.bytes, &mut offset, true);
                let catch_type = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let catch_pc_offset = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                let cinfo_ref = mem_utils::read_uint32(&self.bytes, &mut offset, true);
                ExActionData::CatchBlock32 {
                    unk0,
                    catch_type,
                    catch_pc_offset,
                    cinfo_ref,
                }
            }
        }
    }
}

impl Default for ExceptionAction {
    fn default() -> Self {
        Self::new()
    }
}

/// Struct for pc actions.
#[derive(Debug, Clone)]
pub struct PCAction {
    pub start_pc: u32,
    pub end_pc: u32,
    pub action_offset: u32,
}

impl PCAction {
    pub fn new() -> Self {
        Self {
            start_pc: 0,
            end_pc: 0,
            action_offset: 0,
        }
    }
}

impl Default for PCAction {
    fn default() -> Self {
        Self::new()
    }
}

/// Struct for exception table relocation (always dtor function address)
#[derive(Debug, Clone)]
pub struct Relocation {
    pub offset: u32,
    pub address: u32,
}

/// Struct containing all the data from the decoded exception table.
#[derive(Debug, Clone)]
pub struct ExceptionTableData {
    pub flag_val: u16, //0x0-1
    //Flag bits (16 bit value)
    pub has_elf_vector: bool,    //bit 1
    pub large_frame: bool,       //bit 3
    pub has_frame_pointer: bool, //bit 4
    pub saved_cr: bool,          //bit 5
    pub fpr_save_range: u32,     //bits 6-10
    pub gpr_save_range: u32,     //bits 11-15

    pub et_field: u16, //0x2-3

    pub pc_actions: Vec<PCAction>,
    pub exception_actions: Vec<ExceptionAction>,
    pub relocations: Vec<Relocation>,
}

impl ExceptionTableData {
    fn new() -> Self {
        Self {
            flag_val: 0,
            has_elf_vector: false,
            large_frame: false,
            has_frame_pointer: false,
            saved_cr: false,
            fpr_save_range: 0,
            gpr_save_range: 0,
            et_field: 0,
            pc_actions: vec![],
            exception_actions: vec![],
            relocations: vec![],
        }
    }

    fn calculate_flag_values(&mut self) {
        self.has_elf_vector = ((self.flag_val >> 1) & 1) == 1;
        self.large_frame = ((self.flag_val >> 3) & 1) == 1;
        self.has_frame_pointer = ((self.flag_val >> 4) & 1) == 1;
        self.saved_cr = ((self.flag_val >> 5) & 1) == 1;
        self.fpr_save_range = ((self.flag_val >> 6) & 0b11111) as u32;
        self.gpr_save_range = ((self.flag_val >> 11) & 0b11111) as u32;
    }

    /// Converts the table into a string, taking in an array of the function
    /// names required for the table.
    ///
    /// Returns 'None' if an error occurs.
    pub fn to_string(&self, func_names: Vec<String>) -> Option<String> {
        let mut sb = String::from("");

        sb += "Flag values:\n";
        sb += format!(
            "{}",
            format_args!(
                "Has Elf Vector: {}\n",
                if self.has_elf_vector { "Yes" } else { "No" }
            )
        )
        .as_str();
        sb += format!(
            "{}",
            format_args!(
                "Large Frame: {}\n",
                if self.large_frame { "Yes" } else { "No" }
            )
        )
        .as_str();
        sb += format!(
            "{}",
            format_args!(
                "Has Frame Pointer: {}\n",
                if self.has_frame_pointer { "Yes" } else { "No" }
            )
        )
        .as_str();
        sb += format!(
            "{}",
            format_args!("Saved CR: {}\n", if self.saved_cr { "Yes" } else { "No" })
        )
        .as_str();

        if self.fpr_save_range != 0 {
            let start_fpr = 31 - (self.fpr_save_range - 1);
            let fpr_string: String = if start_fpr == 31 {
                String::from("fp31")
            } else {
                format!("fp{start_fpr}-fp31")
            };
            sb += format!("Saved FPR range: {fpr_string}\n").as_str();
        }
        if self.gpr_save_range != 0 {
            let start_gpr = 31 - (self.gpr_save_range - 1);
            let gpr_string: String = if start_gpr == 31 {
                String::from("r31")
            } else {
                format!("r{start_gpr}-r31")
            };
            sb += format!("Saved GPR range: {gpr_string}\n").as_str();
        }
        sb += "\n";

        let num_pcactions = self.pc_actions.len();

        //Print exception range entries
        if num_pcactions > 0 {
            sb += "PC actions:\n";
            for i in 0..num_pcactions {
                let action = &self.pc_actions[i];
                let start_pc = action.start_pc;
                let end_pc = action.end_pc;
                let action_offset = action.action_offset;
                if start_pc != end_pc {
                    sb += format!("PC={start_pc:08X}:{end_pc:08X}, Action: {action_offset:06X}\n")
                        .as_str();
                } else {
                    sb += format!("PC={start_pc:08X}, Action: {action_offset:06X}\n").as_str();
                }
            }

            sb += "\n";
        }

        let num_exactions = self.exception_actions.len();

        if num_exactions > 0 {
            sb += "Exception actions:\n";
            let local_reg_string = if self.has_frame_pointer { "FP" } else { "SP" };
            let mut func_index: usize = 0;

            for i in 0..num_exactions {
                let action = &self.exception_actions[i];
                let mut line = String::from("");
                let action_offset = action.action_offset;
                let action_name = action.action_type.convert_to_string();
                line += format!("{action_offset:06X}:\nType: {action_name}\n").as_str();

                let has_dtor_ref = action.has_dtor_ref();
                let exaction_data = action.get_exaction_data();

                match exaction_data {
                    ExActionData::EndOfList => {}
                    ExActionData::Branch { target_offset } => {
                        line += format!("Action: {target_offset:06X}").as_str();
                    }
                    ExActionData::DestroyLocal { local_offset, .. } => {
                        line += format!("Local: {local_offset:#X}({local_reg_string})").as_str();
                    }
                    ExActionData::DestroyLocalCond {
                        condition,
                        local_offset,
                        ..
                    } => {
                        line += format!("Local: {local_offset:#X}({local_reg_string})").as_str();

                        //The action param is used to determine the type of reference for the condition (0: local offset, 1: register)
                        if action.action_param == 0 {
                            //Local offset
                            line += format!("\nCond: {condition:#X}({local_reg_string})").as_str();
                        } else {
                            //Register
                            //In this case, the local offset param is actually the register number
                            line += format!("\nCond: r{condition}").as_str();
                        }
                    }
                    ExActionData::DestroyLocalPointer { local_pointer, .. } => {
                        let mode = action.action_param >> 7;
                        if mode == 0 {
                            //Local offset
                            line +=
                                format!("Pointer: {local_pointer:#X}({local_reg_string})").as_str();
                        } else {
                            //Register
                            line += format!("Pointer: r{local_pointer}").as_str();
                        }
                    }
                    ExActionData::DestroyLocalArray {
                        local_array,
                        elements,
                        element_size,
                        ..
                    } => {
                        line += format!("Array: {local_array:#X}({local_reg_string})\nElements: {elements}\nSize: {element_size}").as_str();
                    }
                    ExActionData::DestroyBase {
                        object_pointer,
                        member_offset,
                        ..
                    } => {
                        let mode = action.action_param >> 7;
                        if mode == 0 {
                            line += format!("Member: {object_pointer:#X}({local_reg_string})+{member_offset:#X}").as_str();
                        } else {
                            line +=
                                format!("Member: {member_offset:#X}(r{object_pointer})").as_str();
                        }
                    }
                    ExActionData::DestroyMember {
                        object_pointer,
                        member_offset,
                        ..
                    } => {
                        let mode = action.action_param >> 7;
                        if mode == 0 {
                            line += format!("Member: {object_pointer:#X}({local_reg_string})+{member_offset:#X}").as_str();
                        } else {
                            line +=
                                format!("Member: {member_offset:#X}(r{object_pointer})").as_str();
                        }
                    }
                    ExActionData::DestroyMemberCond {
                        condition,
                        object_pointer,
                        member_offset,
                        ..
                    } => {
                        let mode = (action.action_param >> 6) & 1;
                        if mode == 0 {
                            line += format!("Member: {object_pointer:#X}({local_reg_string})+{member_offset:#X}").as_str();
                        } else {
                            //Register
                            line +=
                                format!("Member: {member_offset:#X}(r{object_pointer})").as_str();
                        }
                        let condition_mode = action.action_param >> 7;
                        if condition_mode == 0 {
                            //Local offset
                            line += format!("\nCond: {condition:#X}({local_reg_string})").as_str();
                        } else {
                            //Register
                            line += format!("\nCond: r{condition}").as_str();
                        }
                    }
                    ExActionData::DestroyMemberArray {
                        object_pointer,
                        member_offset,
                        elements,
                        element_size,
                        ..
                    } => {
                        let mode = action.action_param >> 7;
                        if mode == 0 {
                            //Local offset
                            line += format!(
                                "Member: {object_pointer:#X}({local_reg_string})+0x{member_offset}"
                            )
                            .as_str();
                        } else {
                            //Register
                            line +=
                                format!("Member: {member_offset:#X}(r{object_pointer})").as_str();
                        }
                        line += format!("\nElements: {elements}\nSize: {element_size}").as_str();
                    }
                    ExActionData::DeletePointer { object_pointer, .. } => {
                        let mode = action.action_param >> 7;
                        if mode == 0 {
                            //Local offset
                            line += format!("Pointer: {object_pointer:#X}({local_reg_string})")
                                .as_str();
                        } else {
                            //Register
                            line += format!("Pointer: r{object_pointer})").as_str();
                        }
                    }
                    ExActionData::DeletePointerCond {
                        condition,
                        object_pointer,
                        ..
                    } => {
                        let mode = (action.action_param >> 6) & 1;
                        if mode == 0 {
                            //Local offset
                            line += format!("Pointer: {object_pointer:#X}({local_reg_string})")
                                .as_str();
                        } else {
                            //Register
                            line += format!("Pointer: r{object_pointer})").as_str();
                        }
                        let condition_mode = action.action_param >> 7;
                        if condition_mode == 0 {
                            //Local offset
                            line += format!("\nCond: {condition:#X}({local_reg_string})").as_str();
                        } else {
                            //Register
                            line += format!("\nCond: r{condition}").as_str();
                        }
                    }
                    ExActionData::CatchBlock {
                        catch_type,
                        catch_pc_offset,
                        cinfo_ref,
                        ..
                    } => {
                        line += format!("Local: {cinfo_ref:#X}({local_reg_string})\nPC: {catch_pc_offset:08X}\ncatch_type_addr: {catch_type:08X}").as_str();
                    }
                    ExActionData::ActiveCatchBlock { cinfo_ref } => {
                        line += format!("Local: {cinfo_ref:#X}({local_reg_string})").as_str();
                    }
                    ExActionData::Terminate => {}
                    ExActionData::Specification {
                        specs,
                        pc_offset,
                        cinfo_ref,
                        ..
                    } => {
                        line += format!("Local: {cinfo_ref:#X}({local_reg_string})\nPC: {pc_offset:08X}\nTypes: {specs}").as_str();
                    }
                    ExActionData::CatchBlock32 {
                        catch_type,
                        catch_pc_offset,
                        cinfo_ref,
                        ..
                    } => {
                        line += format!("Local: {cinfo_ref:#X}({local_reg_string})\nPC: {catch_pc_offset:08X}\ncatch_type_addr: {catch_type:08X}").as_str();
                    }
                }

                //If the action references a dtor, print it out using the name array
                if has_dtor_ref {
                    if func_index >= func_names.len() {
                        println!("Error: Invalid function array index");
                        return None;
                    }
                    let func_name = func_names[func_index].as_str();
                    line += format!("\nDtor: \"{func_name}\"").as_str();
                    func_index += 1;
                }

                if action.has_end_bit {
                    line += "."
                }; //Add a dot to the end if the has end bit flag is set
                line += "\n";
                sb += line.as_str(); //Print the line
            }
        }

        Some(sb)
    }
}

struct ExtabDecoder {
    extab_data: ExceptionTableData,
    offset: i32,
    data: Vec<u8>,
    length: i32,
}

impl ExtabDecoder {
    fn new() -> Self {
        Self {
            extab_data: ExceptionTableData::new(),
            offset: 0,
            data: vec![],
            length: 0,
        }
    }

    fn parse_exception_table(&mut self, bytes: &[u8]) -> Result<(), ExtabDecodeError> {
        self.offset = 0;
        self.data = Vec::from(bytes);
        self.length = self.data.len() as i32;

        //If the array is empty, return an error.
        if self.length < 8 {
            return Err(ExtabDecodeError::ArrayTooSmall(self.length as u32));
        }

        //Parse the header flag value
        self.extab_data.flag_val = mem_utils::read_uint16(&self.data, &mut self.offset, true);
        self.extab_data.calculate_flag_values();
        self.extab_data.et_field = mem_utils::read_uint16(&self.data, &mut self.offset, true);

        //Check whether the table is 8 bytes but the terminator isn't zero. If so,
        //throw an error.
        let terminator = mem_utils::read_uint32(&self.data, &mut self.offset, false);
        if self.length == 8 && terminator != 0 {
            return Err(ExtabDecodeError::InvalidSmallTableTerminator);
        }

        //Parse range entries until we hit the terminator (32 bit zero value)
        while mem_utils::read_uint32(&self.data, &mut self.offset, false) != 0 {
            let mut pcaction = PCAction::new();
            pcaction.start_pc = mem_utils::read_uint32(&self.data, &mut self.offset, true);
            let range_size: u32 =
                (mem_utils::read_uint16(&self.data, &mut self.offset, true) as u32) * 4; //range size is encoded as size >> 2
            pcaction.end_pc = pcaction.start_pc + range_size;
            pcaction.action_offset =
                mem_utils::read_uint16(&self.data, &mut self.offset, true) as u32;
            self.extab_data.pc_actions.push(pcaction);
        }

        self.offset += 4; //Skip the terminator

        //If there are still bytes remaining, there are action entries to process
        while self.offset < self.length {
            //Console.WriteLine("Offset: " + offset);
            self.parse_action_entry()?;
        }

        Ok(())
    }

    fn parse_action_entry(&mut self) -> Result<(), ExtabDecodeError> {
        let mut exaction = ExceptionAction::new();
        exaction.action_offset = self.offset as u32;
        let action_type_byte = mem_utils::read_byte(&self.data, &mut self.offset, true);
        exaction.has_end_bit = (action_type_byte & 0x80) != 0;
        let action_type_value: u32 = (action_type_byte & 0x7F) as u32;
        let result = ExAction::from_int(action_type_value as i32);
        exaction.action_type = match result {
            Some(action) => action,
            None => {
                return Err(ExtabDecodeError::InvalidActionValue(
                    action_type_value,
                    exaction.action_offset,
                ))
            }
        };
        exaction.action_param = mem_utils::read_byte(&self.data, &mut self.offset, true);

        //Since the way action data is stored is too varied, we just store the remaining data as a byte
        //array to be used later.
        let mut size: i32;

        match exaction.action_type {
            ExAction::EndOfList => {
                size = 0;
            }
            ExAction::Branch => {
                size = 2;
            }
            ExAction::DestroyLocal => {
                size = 6;
            }
            ExAction::DestroyLocalCond => {
                size = 10;
            }
            ExAction::DestroyLocalPointer => {
                size = 6;
            }
            ExAction::DestroyLocalArray => {
                size = 10;
            }
            ExAction::DestroyBase | ExAction::DestroyMember => {
                size = 10;
            }
            ExAction::DestroyMemberCond => {
                size = 14;
            }
            ExAction::DestroyMemberArray => {
                size = 18;
            }
            ExAction::DeletePointer => {
                size = 6;
            }
            ExAction::DeletePointerCond => {
                size = 10;
            }
            ExAction::CatchBlock => {
                size = 10;
            }
            ExAction::ActiveCatchBlock => {
                size = 2;
            }
            ExAction::Terminate => {
                size = 0;
            }
            ExAction::Specification => {
                size = 10;
                //Calculate the length of the array, and add it to the base size
                let length = mem_utils::read_uint16(&self.data, &mut self.offset, false) as i32;
                size += length * 4;
            }
            ExAction::CatchBlock32 => {
                size = 14;
            }
        }

        let start_index = self.offset as usize;
        let end_index = (self.offset + size) as usize;
        exaction.bytes = self.data[start_index..end_index].into();
        self.offset += size;

        //Check if the action entry has a dtor reference. If so, get the relocation information from it,
        //and add it to the list.
        if exaction.has_dtor_ref() {
            let (offset, addr) = match exaction.get_dtor_relocation() {
                Some(val) => val,
                None => {
                    //If None was returned even though the action should have a reference, return an error
                    return Err(ExtabDecodeError::Internal);
                }
            };

            let reloc_offset: u32 = (start_index as u32) + offset;
            let reloc = Relocation { offset: reloc_offset, address: addr };
            self.extab_data.relocations.push(reloc);
        }

        self.extab_data.exception_actions.push(exaction);
        Ok(())
    }
}

/// Decodes the provided exception table data.
///
/// Returns 'None' if the table is not valid.
pub fn decode_extab(data: &[u8]) -> Result<ExceptionTableData, ExtabDecodeError> {
    let mut decoder = ExtabDecoder::new();
    decoder.parse_exception_table(data)?;
    Ok(decoder.extab_data)
}