simple-frame-rs 0.3.0

Parse SFrame (Simple Frame) stack trace information
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
//! SFrame Version 2 types and implementation.
//!
//! Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html>

use std::{cmp::Ordering, fmt::Write};

use bitflags::bitflags;
use fallible_iterator::FallibleIterator;

use crate::{SFrameError, SFrameResult, read_binary, read_struct};

/// SFrame ABI/arch Identifier
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-ABI_002farch-Identifier>
#[derive(Debug, Clone, Copy)]
pub enum SFrameABI {
    /// SFRAME_ABI_AARCH64_ENDIAN_BIG
    AArch64BigEndian,
    /// SFRAME_ABI_AARCH64_ENDIAN_LITTLE
    AArch64LittleEndian,
    /// SFRAME_ABI_AMD64_ENDIAN_LITTLE
    AMD64LittleEndian,
    /// SFRAME_ABI_S390X_ENDIAN_BIG
    S390XBigEndian,
}

/// s390x-specific constants and helpers from binutils-gdb sframe.h
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#s390x>
pub mod s390x {
    /// On s390x, the CFA is defined as SP at call site + 160.
    /// Therefore the SP value offset from CFA is -160.
    pub const SFRAME_S390X_SP_VAL_OFFSET: i32 = -160;

    /// On s390x, the CFA offset from CFA base register is by definition a minimum
    /// of 160. Store it adjusted by -160 to enable use of 8-bit SFrame offsets.
    pub const SFRAME_S390X_CFA_OFFSET_ADJUSTMENT: i32 = SFRAME_S390X_SP_VAL_OFFSET;

    /// Additionally scale by an alignment factor of 8, as the SP and thus CFA
    /// offset on s390x is always 8-byte aligned.
    pub const SFRAME_S390X_CFA_OFFSET_ALIGNMENT_FACTOR: i32 = 8;

    /// Invalid RA offset.  Currently used for s390x as padding to represent FP
    /// without RA saved.
    pub const SFRAME_FRE_RA_OFFSET_INVALID: i32 = 0;

    /// Decode a CFA offset from the FRE stored value.
    pub const fn cfa_offset_decode(offset: i32) -> i32 {
        (offset * SFRAME_S390X_CFA_OFFSET_ALIGNMENT_FACTOR) - SFRAME_S390X_CFA_OFFSET_ADJUSTMENT
    }

    /// Check if an offset represents a DWARF register number.
    pub const fn offset_is_regnum(offset: i32) -> bool {
        (offset & 1) != 0
    }

    /// Decode a DWARF register number from an offset.
    pub const fn offset_decode_regnum(offset: i32) -> i32 {
        offset >> 1
    }
}

bitflags! {
    /// SFrame Flags
    ///
    /// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Flags>
    #[derive(Debug, Clone, Copy)]
    pub struct SFrameFlags: u8 {
        /// Function Descriptor Entries are sorted on PC.
        const SFRAME_F_FDE_SORTED = 0x1;
        /// All functions in the object file preserve frame pointer.
        const SFRAME_F_FRAME_POINTER = 0x2;
        /// The sfde_func_start_address field in the SFrame FDE is an offset in bytes to the function’s start address, from the field itself. If unset, the sfde_func_start_address field in the SFrame FDE is an offset in bytes to the function’s start address, from the start of the SFrame section.
        const SFRAME_F_FDE_FUNC_START_PCREL = 0x4;
    }
}

/// SFrame section
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Section>
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub struct SFrameSection<'a> {
    data: &'a [u8],
    section_base: u64,
    little_endian: bool,
    flags: SFrameFlags,
    abi: SFrameABI,
    cfa_fixed_fp_offset: i8,
    cfa_fixed_ra_offset: i8,
    auxhdr_len: u8,
    num_fdes: u32,
    num_fres: u32,
    fre_len: u32,
    fdeoff: u32,
    freoff: u32,
}

/// The magic number for SFrame section: 0xdee2
const SFRAME_MAGIC: u16 = 0xdee2;

impl<'a> SFrameSection<'a> {
    /// Parse SFrame section from data
    pub fn from(data: &'a [u8], section_base: u64) -> SFrameResult<SFrameSection<'a>> {
        // parse sframe_header
        if data.len() < core::mem::size_of::<RawSFrameHeader>() {
            return Err(SFrameError::UnexpectedEndOfData);
        }

        // probe magic
        let magic_offset = core::mem::offset_of!(RawSFrameHeader, magic);
        let mut magic_bytes: [u8; 2] = [0; 2];
        magic_bytes.copy_from_slice(&data[magic_offset..magic_offset + 2]);
        let magic_le = u16::from_le_bytes(magic_bytes);
        let little_endian;
        if magic_le == SFRAME_MAGIC {
            little_endian = true;
        } else {
            let magic_be = u16::from_be_bytes(magic_bytes);
            if magic_be == SFRAME_MAGIC {
                little_endian = false;
            } else {
                return Err(SFrameError::InvalidMagic);
            }
        }

        // probe version
        let version_offset = core::mem::offset_of!(RawSFrameHeader, version);
        let version = data[version_offset];
        if version != 2 {
            return Err(SFrameError::UnsupportedVersion);
        }

        // probe flag
        let flags_offset = core::mem::offset_of!(RawSFrameHeader, flags);
        let flags = data[flags_offset];
        let flags = match SFrameFlags::from_bits(flags) {
            Some(flags) => flags,
            None => return Err(SFrameError::UnsupportedFlags),
        };

        // probe abi
        let abi_offset = core::mem::offset_of!(RawSFrameHeader, abi_arch);
        let abi = data[abi_offset];
        let abi = match abi {
            1 => SFrameABI::AArch64BigEndian,
            2 => SFrameABI::AArch64LittleEndian,
            3 => SFrameABI::AMD64LittleEndian,
            4 => SFrameABI::S390XBigEndian,
            _ => return Err(SFrameError::UnsupportedABI),
        };

        let cfa_fixed_fp_offset =
            data[core::mem::offset_of!(RawSFrameHeader, cfa_fixed_fp_offset)] as i8;
        let cfa_fixed_ra_offset =
            data[core::mem::offset_of!(RawSFrameHeader, cfa_fixed_ra_offset)] as i8;
        let auxhdr_len = data[core::mem::offset_of!(RawSFrameHeader, auxhdr_len)];

        // initial validation
        let num_fdes = read_struct!(RawSFrameHeader, data, little_endian, num_fdes, u32);
        let fdeoff = read_struct!(RawSFrameHeader, data, little_endian, fdeoff, u32);
        if data.len() - core::mem::size_of::<RawSFrameHeader>() < fdeoff as usize {
            return Err(SFrameError::UnexpectedEndOfData);
        } else if (data.len() - core::mem::size_of::<RawSFrameHeader>() - fdeoff as usize)
            / core::mem::size_of::<RawSFrameFDE>()
            < num_fdes as usize
        {
            return Err(SFrameError::UnexpectedEndOfData);
        }

        Ok(SFrameSection {
            data,
            section_base,
            little_endian,
            flags,
            abi,
            cfa_fixed_fp_offset,
            cfa_fixed_ra_offset,
            auxhdr_len,
            num_fdes,
            num_fres: read_struct!(RawSFrameHeader, data, little_endian, num_fres, u32),
            fre_len: read_struct!(RawSFrameHeader, data, little_endian, fre_len, u32),
            fdeoff,
            freoff: read_struct!(RawSFrameHeader, data, little_endian, freoff, u32),
        })
    }

    /// Get the count of FDE entries
    pub fn get_fde_count(&self) -> u32 {
        self.num_fdes
    }

    /// Access FDE by index
    pub fn get_fde(&self, index: u32) -> SFrameResult<Option<SFrameFDE>> {
        if index >= self.num_fdes {
            // out of bounds
            return Ok(None);
        }

        // The sub-section offsets, namely sfh_fdeoff and sfh_freoff, in the
        // SFrame header are relative to the end of the SFrame header; they are
        // each an offset in bytes into the SFrame section where the SFrame FDE
        // sub-section and the SFrame FRE sub-section respectively start.
        let offset = self.fdeoff as usize
            + index as usize * core::mem::size_of::<RawSFrameFDE>()
            + core::mem::size_of::<RawSFrameHeader>();
        if offset + core::mem::size_of::<RawSFrameFDE>() > self.data.len() {
            return Err(SFrameError::UnexpectedEndOfData);
        }

        Ok(Some(SFrameFDE {
            offset,
            func_start_address: read_struct!(
                RawSFrameFDE,
                &self.data[offset..],
                self.little_endian,
                func_start_address,
                i32
            ),
            func_size: read_struct!(
                RawSFrameFDE,
                &self.data[offset..],
                self.little_endian,
                func_size,
                u32
            ),
            func_start_fre_off: read_struct!(
                RawSFrameFDE,
                &self.data[offset..],
                self.little_endian,
                func_start_fre_off,
                u32
            ),
            func_num_fres: read_struct!(
                RawSFrameFDE,
                &self.data[offset..],
                self.little_endian,
                func_num_fres,
                u32
            ),
            func_info: SFrameFDEInfo(
                self.data[offset + core::mem::offset_of!(RawSFrameFDE, func_info)],
            ),
            func_rep_size: self.data[offset + core::mem::offset_of!(RawSFrameFDE, func_rep_size)],
        }))
    }

    /// Print the section in string in the same way as objdump
    pub fn to_string(&self) -> SFrameResult<String> {
        let mut s = String::new();
        writeln!(&mut s, "Header :")?;
        writeln!(&mut s)?;
        writeln!(&mut s, "  Version: SFRAME_VERSION_2")?;
        writeln!(
            &mut s,
            "  Flags: {}",
            self.flags
                .iter_names()
                .map(|(name, _flag)| name)
                .collect::<Vec<_>>()
                .join(",\n         ")
        )?;
        if self.cfa_fixed_fp_offset != 0 {
            writeln!(
                &mut s,
                "  CFA fixed FP offset: {:?}",
                self.cfa_fixed_fp_offset
            )?;
        }
        if self.cfa_fixed_ra_offset != 0 {
            writeln!(
                &mut s,
                "  CFA fixed RA offset: {:?}",
                self.cfa_fixed_ra_offset
            )?;
        }
        writeln!(&mut s, "  Num FDEs: {:?}", self.num_fdes)?;
        writeln!(&mut s, "  Num FREs: {:?}", self.num_fres)?;
        writeln!(&mut s)?;
        writeln!(&mut s, "Function Index :")?;
        writeln!(&mut s)?;
        for i in 0..self.num_fdes {
            let fde = self.get_fde(i)?.unwrap();
            let pc = fde.get_pc(self);
            let mut suffix = String::new();

            // aarch64 pauth
            if let SFrameAArch64PAuthKey::KeyB = fde.func_info.get_aarch64_pauth_key()? {
                suffix += ", pauth = B key";
            }

            writeln!(
                &mut s,
                "  func idx [{i}]: pc = 0x{:x}, size = {} bytes{}",
                pc, fde.func_size, suffix
            )?;

            match fde.func_info.get_fde_type()? {
                SFrameFDEType::PCInc => {
                    writeln!(&mut s, "  STARTPC           CFA      FP     RA")?;
                }
                SFrameFDEType::PCMask => {
                    writeln!(&mut s, "  STARTPC[m]        CFA      FP     RA")?;
                }
            }
            let mut iter = fde.iter_fre(self);
            while let Some(fre) = iter.next()? {
                let start_pc = match fde.func_info.get_fde_type()? {
                    SFrameFDEType::PCInc => pc + fre.start_address.get() as u64,
                    SFrameFDEType::PCMask => fre.start_address.get() as u64,
                };
                let base_reg = if fre.info.get_cfa_base_reg_id() == 0 {
                    "fp"
                } else {
                    "sp"
                };
                let cfa = format!("{}+{}", base_reg, fre.stack_offsets[0].get());
                let fp = match fre.get_fp_offset(self) {
                    Some(offset) => format!("c{:+}", offset),
                    None => "u".to_string(), // without offset
                };
                let mut ra = if self.cfa_fixed_ra_offset != 0 {
                    "f".to_string() // fixed
                } else {
                    match fre.get_ra_offset(self) {
                        Some(offset) => format!("c{:+}", offset),
                        None => "u".to_string(), // without offset
                    }
                };
                if fre.info.get_mangled_ra_p() {
                    // ra is mangled with signature
                    ra.push_str("[s]");
                }
                let rest = format!("{cfa:8} {fp:6} {ra}");
                writeln!(&mut s, "  {:016x}  {}", start_pc, rest)?;
            }
            writeln!(&mut s,)?;
        }
        Ok(s)
    }

    /// Iterate FDE entries
    pub fn iter_fde(&self) -> SFrameFDEIterator<'_> {
        SFrameFDEIterator {
            section: self,
            index: 0,
        }
    }

    /// Find FDE entry by pc
    pub fn find_fde(&self, pc: u64) -> SFrameResult<Option<SFrameFDE>> {
        if self.flags.contains(SFrameFlags::SFRAME_F_FDE_SORTED) {
            // binary search
            // mimic binary_search_by impl from rust std
            let mut size = self.num_fdes;
            if size == 0 {
                return Ok(None);
            }
            let mut base = 0;

            while size > 1 {
                let half = size / 2;
                let mid = base + half;

                let cmp = self.get_fde(mid)?.unwrap().get_pc(self).cmp(&pc);
                if cmp != Ordering::Greater {
                    base = mid;
                }
                size -= half;
            }

            let base_fde = self.get_fde(base)?.unwrap();
            let base_pc = base_fde.get_pc(self);
            let cmp = base_pc.cmp(&pc);
            match cmp {
                Ordering::Equal | Ordering::Less if pc < base_pc + base_fde.func_size as u64 => {
                    Ok(Some(base_fde))
                }
                _ => Ok(None),
            }
        } else {
            // linear scan
            let mut iter = self.iter_fde();
            while let Some(fde) = iter.next()? {
                let start = fde.get_pc(self);
                if start <= pc && pc - start < fde.func_size as u64 {
                    return Ok(Some(fde));
                }
            }
            Ok(None)
        }
    }

    /// Get SFrame flags
    pub fn get_flags(&self) -> SFrameFlags {
        self.flags
    }

    /// Get SFrame ABI
    pub fn get_abi(&self) -> SFrameABI {
        self.abi
    }

    /// Get SFrame CFA fixed FP offset
    pub fn get_cfa_fixed_fp_offset(&self) -> i8 {
        self.cfa_fixed_fp_offset
    }

    /// Get SFrame CFA fixed RA offset
    pub fn get_cfa_fixed_ra_offset(&self) -> i8 {
        self.cfa_fixed_ra_offset
    }
}

/// Raw SFrame Header
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Header>
#[repr(C, packed)]
struct RawSFrameHeader {
    magic: u16,
    version: u8,
    flags: u8,
    abi_arch: u8,
    cfa_fixed_fp_offset: i8,
    cfa_fixed_ra_offset: i8,
    auxhdr_len: u8,
    num_fdes: u32,
    num_fres: u32,
    fre_len: u32,
    fdeoff: u32,
    freoff: u32,
}

/// Raw SFrame FDE
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Function-Descriptor-Entries>
#[repr(C, packed)]
#[allow(dead_code)]
struct RawSFrameFDE {
    func_start_address: i32,
    func_size: u32,
    func_start_fre_off: u32,
    func_num_fres: u32,
    func_info: u8,
    func_rep_size: u8,
    func_padding2: u16,
}

/// SFrame FDE Info Word
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#The-SFrame-FDE-Info-Word>
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct SFrameFDEInfo(u8);

impl SFrameFDEInfo {
    /// Get SFrame FRE type
    pub fn get_fre_type(&self) -> SFrameResult<SFrameFREType> {
        let fretype = self.0 & 0b1111;
        match fretype {
            0 => Ok(SFrameFREType::Addr1),
            1 => Ok(SFrameFREType::Addr2),
            2 => Ok(SFrameFREType::Addr4),
            _ => Err(SFrameError::UnsupportedFREType),
        }
    }

    /// Get SFrame FDE type
    pub fn get_fde_type(&self) -> SFrameResult<SFrameFDEType> {
        let fretype = (self.0 >> 4) & 0b1;
        match fretype {
            0 => Ok(SFrameFDEType::PCInc),
            1 => Ok(SFrameFDEType::PCMask),
            _ => unreachable!(),
        }
    }

    /// Get SFrame AArch64 pauth key
    pub fn get_aarch64_pauth_key(&self) -> SFrameResult<SFrameAArch64PAuthKey> {
        let fretype = (self.0 >> 5) & 0b1;
        match fretype {
            0 => Ok(SFrameAArch64PAuthKey::KeyA),
            1 => Ok(SFrameAArch64PAuthKey::KeyB),
            _ => unreachable!(),
        }
    }
}

/// SFrame FRE Types
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#The-SFrame-FRE-Types>
#[derive(Debug, Clone, Copy)]
pub enum SFrameFREType {
    /// SFRAME_FRE_TYPE_ADDR1
    /// The start address offset (in bytes) of the SFrame FRE is an unsigned
    /// 8-bit value.
    Addr1,
    /// SFRAME_FRE_TYPE_ADDR2
    /// The start address offset (in bytes) of the SFrame FRE is an unsigned
    /// 16-bit value.
    Addr2,
    /// SFRAME_FRE_TYPE_ADDR4
    /// The start address offset (in bytes) of the SFrame FRE is an unsigned
    /// 32-bit value.
    Addr4,
}

/// SFrame FDE Types
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#The-SFrame-FDE-Types>
#[derive(Debug, Clone, Copy)]
pub enum SFrameFDEType {
    /// SFRAME_FDE_TYPE_PCINC
    PCInc,
    /// SFRAME_FDE_TYPE_PCMASK
    PCMask,
}

/// SFrame PAuth key
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#The-SFrame-FDE-Info-Word>
#[derive(Debug, Clone, Copy)]
pub enum SFrameAArch64PAuthKey {
    /// SFRAME_AARCH64_PAUTH_KEY_A
    KeyA,
    /// SFRAME_AARCH64_PAUTH_KEY_B
    KeyB,
}

/// SFrame FDE
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Function-Descriptor-Entries>
#[derive(Debug, Clone, Copy)]
pub struct SFrameFDE {
    /// Offset from the beginning of sframe section
    offset: usize,
    /// Signed 32-bit integral field denoting the virtual memory address of the
    /// described function,for which the SFrame FDE applies. If the flag
    /// SFRAME_F_FDE_FUNC_START_PCREL, See SFrame Flags, in the SFrame header is
    /// set, the value encoded in the sfde_func_start_address field is the
    /// offset in bytes to the function’s start address, from the SFrame
    /// sfde_func_start_address field.
    pub func_start_address: i32,
    /// Unsigned 32-bit integral field specifying the size of the function in
    /// bytes.
    pub func_size: u32,
    /// Unsigned 32-bit integral field specifying the offset in bytes of the
    /// function’s first SFrame FRE in the SFrame section.
    pub func_start_fre_off: u32,
    /// Unsigned 32-bit integral field specifying the total number of SFrame
    /// FREs used for the function.
    pub func_num_fres: u32,
    /// Unsigned 8-bit integral field specifying the SFrame FDE info word. See
    /// The SFrame FDE Info Word.
    pub func_info: SFrameFDEInfo,
    /// Unsigned 8-bit integral field specifying the size of the repetitive code
    /// block for which an SFrame FDE of type SFRAME_FDE_TYPE_PCMASK is used.
    /// For example, in AMD64, the size of a pltN entry is 16 bytes.
    pub func_rep_size: u8,
}

impl SFrameFDE {
    /// Compute pc of the function
    pub fn get_pc(&self, section: &SFrameSection<'_>) -> u64 {
        // "If the flag SFRAME_F_FDE_FUNC_START_PCREL, See SFrame Flags, in the
        // SFrame header is set, the value encoded in the
        // sfde_func_start_address field is the offset in bytes to the
        // function’s start address, from the SFrame sfde_func_start_address
        // field."
        if section
            .flags
            .contains(SFrameFlags::SFRAME_F_FDE_FUNC_START_PCREL)
        {
            (self.func_start_address as i64)
                .wrapping_add_unsigned(self.offset as u64)
                .wrapping_add_unsigned(section.section_base) as u64
        } else {
            (self.func_start_address as i64).wrapping_add_unsigned(section.section_base) as u64
        }
    }

    /// Iterate FRE entries
    pub fn iter_fre<'a>(&'a self, section: &'a SFrameSection<'a>) -> SFrameFREIterator<'a> {
        // "The sub-section offsets, namely sfh_fdeoff and sfh_freoff, in the
        // SFrame header are relative to the end of the SFrame header; they are
        // each an offset in bytes into the SFrame section where the SFrame FDE
        // sub-section and the SFrame FRE sub-section respectively start."
        // "sfde_func_start_fre_off is the offset to the first SFrame FRE for
        // the function. This offset is relative to the end of the SFrame FDE
        // sub-section (unlike the sub-section offsets in the SFrame header,
        // which are relative to the end of the SFrame header)."
        let offset = section.freoff as usize
            + core::mem::size_of::<RawSFrameHeader>()
            + self.func_start_fre_off as usize;
        SFrameFREIterator {
            fde: self,
            section,
            offset,
            index: 0,
        }
    }

    /// Find FRE entry by pc
    pub fn find_fre(
        &self,
        section: &SFrameSection<'_>,
        pc: u64,
    ) -> SFrameResult<Option<SFrameFRE>> {
        let fde_pc = self.get_pc(section);
        if pc < fde_pc || pc - fde_pc >= self.func_size as u64 {
            // out of bounds
            return Ok(None);
        }

        match self.func_info.get_fde_type()? {
            SFrameFDEType::PCInc => {
                // find matching fre entry with max pc
                let mut last: Option<SFrameFRE> = None;
                let mut iter = self.iter_fre(section);
                while let Some(fre) = iter.next()? {
                    if fre.start_address.get() as u64 + fde_pc > pc {
                        // last is the matching one
                        break;
                    }
                    last = Some(fre);
                }
                if let Some(fre) = last {
                    // PC >= FRE_START_ADDR
                    if fre.start_address.get() as u64 + fde_pc <= pc {
                        return Ok(Some(fre));
                    }
                }
                Ok(None)
            }
            SFrameFDEType::PCMask => {
                // match by pc masking
                let mut iter = self.iter_fre(section);
                while let Some(fre) = iter.next()? {
                    // PC % REP_BLOCK_SIZE >= FRE_START_ADDR
                    if self.func_rep_size != 0
                        && pc % self.func_rep_size as u64 >= fre.start_address.get() as u64
                    {
                        // found
                        return Ok(Some(fre));
                    }
                }
                Ok(None)
            }
        }
    }
}

/// SFrame FRE Start Address
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Frame-Row-Entries>
#[derive(Debug, Clone, Copy)]
pub enum SFrameFREStartAddress {
    U8(u8),
    U16(u16),
    U32(u32),
}

impl SFrameFREStartAddress {
    /// Convert the variable sized address to u32
    pub fn get(&self) -> u32 {
        match self {
            SFrameFREStartAddress::U8(i) => *i as u32,
            SFrameFREStartAddress::U16(i) => *i as u32,
            SFrameFREStartAddress::U32(i) => *i,
        }
    }
}

/// SFrame FRE Stack Offset
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Frame-Row-Entries>
#[derive(Debug, Clone, Copy)]
pub enum SFrameFREStackOffset {
    I8(i8),
    I16(i16),
    I32(i32),
}

impl SFrameFREStackOffset {
    /// Convert the variable sized offset to i32
    pub fn get(&self) -> i32 {
        match self {
            SFrameFREStackOffset::I8(i) => *i as i32,
            SFrameFREStackOffset::I16(i) => *i as i32,
            SFrameFREStackOffset::I32(i) => *i,
        }
    }
}

/// SFrame FRE
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#SFrame-Frame-Row-Entries>
#[derive(Debug, Clone)]
pub struct SFrameFRE {
    /// Start address (in offset form) of the function
    pub start_address: SFrameFREStartAddress,
    /// FRE info
    pub info: SFrameFREInfo,
    /// Stack offsets to access CFA, FP and RA
    pub stack_offsets: Vec<SFrameFREStackOffset>,
}

impl SFrameFRE {
    /// Get CFA offset against base reg
    pub fn get_cfa_offset(&self, section: &SFrameSection<'_>) -> Option<i32> {
        self.stack_offsets.first().map(|offset| {
            let offset = offset.get();
            match section.abi {
                // On s390x, the CFA offset is encoded. Decode it.
                SFrameABI::S390XBigEndian => s390x::cfa_offset_decode(offset),
                _ => offset,
            }
        })
    }

    /// Get RA offset against CFA
    ///
    /// For s390x, the returned value may represent:
    /// - A stack slot offset if the LSB is 0
    /// - A DWARF register number (encoded as (regnum << 1) | 1) if the LSB is 1
    /// - SFRAME_FRE_RA_OFFSET_INVALID (0) if RA is not saved
    pub fn get_ra_offset(&self, section: &SFrameSection<'_>) -> Option<i32> {
        match section.abi {
            // the second offset for aarch64
            SFrameABI::AArch64BigEndian | SFrameABI::AArch64LittleEndian => {
                self.stack_offsets.get(1).map(|offset| offset.get())
            }
            // always fixed for amd64
            SFrameABI::AMD64LittleEndian => Some(section.cfa_fixed_ra_offset as i32),
            // the second offset for s390x
            SFrameABI::S390XBigEndian => self.stack_offsets.get(1).map(|offset| offset.get()),
        }
    }

    /// Get FP offset against CFA
    ///
    /// For s390x, the returned value may represent:
    /// - A stack slot offset if the LSB is 0
    /// - A DWARF register number (encoded as (regnum << 1) | 1) if the LSB is 1
    pub fn get_fp_offset(&self, section: &SFrameSection<'_>) -> Option<i32> {
        match section.abi {
            // the third offset for aarch64
            SFrameABI::AArch64BigEndian | SFrameABI::AArch64LittleEndian => {
                self.stack_offsets.get(2).map(|offset| offset.get())
            }
            // the second offset for amd64
            SFrameABI::AMD64LittleEndian => self.stack_offsets.get(1).map(|offset| offset.get()),
            // the third offset for s390x
            SFrameABI::S390XBigEndian => self.stack_offsets.get(2).map(|offset| offset.get()),
        }
    }
}

/// SFrame FRE Info Word
///
/// Ref: <https://sourceware.org/binutils/docs-2.45/sframe-spec.html#The-SFrame-FRE-Info-Word>
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct SFrameFREInfo(u8);

impl SFrameFREInfo {
    /// Indicate whether the return address is mangled with any authorization
    /// bits (signed RA).
    pub fn get_mangled_ra_p(&self) -> bool {
        (self.0 >> 7) & 0b1 == 1
    }

    /// Size of stack offsets in bytes.
    pub fn get_offset_size(&self) -> SFrameResult<usize> {
        match (self.0 >> 5) & 0b11 {
            // SFRAME_FRE_OFFSET_1B
            0x0 => Ok(1),
            // SFRAME_FRE_OFFSET_2B
            0x1 => Ok(2),
            // SFRAME_FRE_OFFSET_4B
            0x2 => Ok(4),
            _ => Err(SFrameError::UnsupportedFREStackOffsetSize),
        }
    }

    /// The number of stack offsets in the FRE
    pub fn get_offset_count(&self) -> u8 {
        (self.0 >> 1) & 0b1111
    }

    /// Distinguish between SP or FP based CFA recovery.
    pub fn get_cfa_base_reg_id(&self) -> u8 {
        self.0 & 0b1
    }
}

/// Iterator for SFrame FRE
pub struct SFrameFREIterator<'a> {
    fde: &'a SFrameFDE,
    section: &'a SFrameSection<'a>,
    index: u32,
    offset: usize,
}

impl<'a> FallibleIterator for SFrameFREIterator<'a> {
    type Item = SFrameFRE;
    type Error = SFrameError;

    fn next(&mut self) -> SFrameResult<Option<SFrameFRE>> {
        if self.index >= self.fde.func_num_fres {
            return Ok(None);
        }

        let fre_type = self.fde.func_info.get_fre_type()?;
        let entry_size = match fre_type {
            SFrameFREType::Addr1 => 1 + 1,
            SFrameFREType::Addr2 => 2 + 1,
            SFrameFREType::Addr4 => 4 + 1,
        } as usize;
        let offset = self.offset;
        if offset + entry_size > self.section.data.len() {
            return Err(SFrameError::UnexpectedEndOfData);
        }

        let (start_address, info) = match self.fde.func_info.get_fre_type()? {
            SFrameFREType::Addr1 => (
                SFrameFREStartAddress::U8(self.section.data[offset]),
                SFrameFREInfo(self.section.data[offset + 1]),
            ),
            SFrameFREType::Addr2 => (
                SFrameFREStartAddress::U16(read_binary!(
                    self.section.data,
                    self.section.little_endian,
                    u16,
                    offset
                )),
                SFrameFREInfo(self.section.data[offset + 2]),
            ),
            SFrameFREType::Addr4 => (
                SFrameFREStartAddress::U32(read_binary!(
                    self.section.data,
                    self.section.little_endian,
                    u32,
                    offset
                )),
                SFrameFREInfo(self.section.data[offset + 4]),
            ),
        };

        let offset_size = info.get_offset_size()?;
        let offset_count = info.get_offset_count() as usize;
        let offset_total_size = offset_size * offset_count;
        if offset + entry_size + offset_total_size > self.section.data.len() {
            return Err(SFrameError::UnexpectedEndOfData);
        }

        let mut stack_offsets = vec![];
        for i in 0..offset_count {
            match offset_size {
                1 => stack_offsets.push(SFrameFREStackOffset::I8(
                    self.section.data[offset + entry_size + i * offset_size] as i8,
                )),
                2 => stack_offsets.push(SFrameFREStackOffset::I16(read_binary!(
                    self.section.data,
                    self.section.little_endian,
                    i16,
                    offset + entry_size + i * offset_size
                ))),
                4 => stack_offsets.push(SFrameFREStackOffset::I32(read_binary!(
                    self.section.data,
                    self.section.little_endian,
                    i32,
                    offset + entry_size + i * offset_size
                ))),
                _ => unreachable!(),
            }
        }

        self.offset += entry_size + offset_total_size;
        self.index += 1;

        Ok(Some(SFrameFRE {
            start_address,
            info,
            stack_offsets,
        }))
    }
}

/// Iterator for SFrame FDE
pub struct SFrameFDEIterator<'a> {
    section: &'a SFrameSection<'a>,
    index: u32,
}

impl<'a> FallibleIterator for SFrameFDEIterator<'a> {
    type Item = SFrameFDE;
    type Error = SFrameError;

    fn next(&mut self) -> Result<Option<Self::Item>, Self::Error> {
        let res = self.section.get_fde(self.index);
        if let Ok(Some(_)) = res {
            self.index += 1;
        }
        res
    }
}