framehop-stackpulse 0.17.2

StackPulse's maintained Framehop stack unwinder
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
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
use core::{cmp::Ordering, marker::PhantomData, ops::Range};

use alloc::vec::Vec;
use gimli::{
    CfaRule, CieOrFde, DebugFrame, DwEhPe, EhFrame, EhFrameHdr, Encoding, EndianSlice, Evaluation,
    EvaluationResult, EvaluationStorage, Expression, LittleEndian, Location, ParsedEhFrameHdr,
    Reader, ReaderOffset, Register, RegisterRule, UnwindContext, UnwindContextStorage,
    UnwindOffset, UnwindSection, UnwindTableRow, Value, Vendor,
};

pub(crate) use gimli::BaseAddresses;

use crate::{arch::Arch, unwind_result::UnwindResult, ModuleSectionInfo};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DwarfUnwinderError {
    FdeFromOffsetFailed(gimli::Error),
    UnwindInfoForAddressFailed(gimli::Error),
    StackPointerMovedBackwards,
    DidNotAdvance,
    CouldNotRecoverCfa,
    CouldNotRecoverReturnAddress,
    CouldNotRecoverFramePointer,
}

impl core::fmt::Display for DwarfUnwinderError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::FdeFromOffsetFailed(err) => {
                write!(f, "Could not get the FDE for the supplied offset: {err}")
            }
            Self::UnwindInfoForAddressFailed(err) => write!(
                f,
                "Could not find DWARF unwind info for the requested address: {err}"
            ),
            Self::StackPointerMovedBackwards => write!(f, "Stack pointer moved backwards"),
            Self::DidNotAdvance => write!(f, "Did not advance"),
            Self::CouldNotRecoverCfa => write!(f, "Could not recover the CFA"),
            Self::CouldNotRecoverReturnAddress => write!(f, "Could not recover the return address"),
            Self::CouldNotRecoverFramePointer => write!(f, "Could not recover the frame pointer"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DwarfUnwinderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::FdeFromOffsetFailed(e) => Some(e),
            Self::UnwindInfoForAddressFailed(e) => Some(e),
            _ => None,
        }
    }
}

pub(crate) fn register_rule_to_cfa_offset<RO: ReaderOffset>(
    rule: Option<&RegisterRule<RO>>,
) -> Option<Option<i64>> {
    match rule {
        None | Some(RegisterRule::Undefined) | Some(RegisterRule::SameValue) => Some(None),
        Some(RegisterRule::Offset(offset)) => Some(Some(*offset)),
        _ => None,
    }
}

pub trait DwarfUnwinding: Arch {
    /// Selects vendor-specific call frame instructions, such as aarch64's
    /// `DW_CFA_AARCH64_negate_ra_state`.
    const CFI_VENDOR: Vendor = Vendor::Default;

    fn unwind_frame<F, R, UCS, ES>(
        section: &impl UnwindSection<R>,
        unwind_info: &UnwindTableRow<R::Offset, UCS>,
        encoding: Encoding,
        regs: &mut Self::UnwindRegs,
        is_first_frame: bool,
        read_stack: &mut F,
    ) -> Result<UnwindResult<Self::UnwindRule>, DwarfUnwinderError>
    where
        F: FnMut(u64) -> Result<u64, ()>,
        R: Reader,
        UCS: UnwindContextStorage<R::Offset>,
        ES: EvaluationStorage<R>;

    fn rule_if_uncovered_by_fde() -> Self::UnwindRule;
}

pub enum UnwindSectionType {
    EhFrame,
    DebugFrame,
}

pub struct DwarfUnwinder<'a, R, A, UCS>
where
    R: Reader,
    A: DwarfUnwinding,
    UCS: UnwindContextStorage<R::Offset>,
{
    unwind_section_data: R,
    unwind_section_type: UnwindSectionType,
    eh_frame_hdr: Option<ParsedEhFrameHdr<EndianSlice<'a, R::Endian>>>,
    unwind_context: &'a mut UnwindContext<R::Offset, UCS>,
    base_svma: u64,
    bases: BaseAddresses,
    _arch: PhantomData<A>,
}

impl<'a, R, A, UCS> DwarfUnwinder<'a, R, A, UCS>
where
    R: Reader,
    A: DwarfUnwinding,
    UCS: UnwindContextStorage<R::Offset>,
{
    pub fn new(
        unwind_section_data: R,
        unwind_section_type: UnwindSectionType,
        eh_frame_hdr_data: Option<&'a [u8]>,
        unwind_context: &'a mut UnwindContext<R::Offset, UCS>,
        bases: BaseAddresses,
        base_svma: u64,
    ) -> Self {
        let eh_frame_hdr = match eh_frame_hdr_data {
            Some(eh_frame_hdr_data) => {
                let hdr = EhFrameHdr::new(eh_frame_hdr_data, unwind_section_data.endian());
                hdr.parse(&bases, 8).ok()
            }
            None => None,
        };
        Self {
            unwind_section_data,
            unwind_section_type,
            eh_frame_hdr,
            unwind_context,
            bases,
            base_svma,
            _arch: PhantomData,
        }
    }

    pub fn get_fde_offset_for_relative_address(&self, rel_lookup_address: u32) -> Option<u32> {
        let lookup_svma = self.base_svma + rel_lookup_address as u64;
        let eh_frame_hdr = self.eh_frame_hdr.as_ref()?;
        let table = eh_frame_hdr.table()?;
        // Gimli's lookup returns the first entry even for an earlier address.
        // Preserve the missing-index fallback instead of evaluating that FDE.
        let (first_address, _) = table.iter(&self.bases).next().ok()??;
        if lookup_svma < first_address.direct().ok()? {
            return None;
        }
        let fde_ptr = table.lookup(lookup_svma, &self.bases).ok()?;
        let fde_offset = table.pointer_to_offset(fde_ptr).ok()?;
        fde_offset.0.into_u64().try_into().ok()
    }

    pub fn unwind_frame_with_fde<F, ES>(
        &mut self,
        regs: &mut A::UnwindRegs,
        is_first_frame: bool,
        rel_lookup_address: u32,
        fde_offset: u32,
        read_stack: &mut F,
    ) -> Result<UnwindResult<A::UnwindRule>, DwarfUnwinderError>
    where
        F: FnMut(u64) -> Result<u64, ()>,
        ES: EvaluationStorage<R>,
    {
        let lookup_svma = self.base_svma + rel_lookup_address as u64;
        let unwind_section_data = self.unwind_section_data.clone();
        match self.unwind_section_type {
            UnwindSectionType::EhFrame => {
                let mut eh_frame = EhFrame::from(unwind_section_data);
                eh_frame.set_address_size(8);
                eh_frame.set_vendor(A::CFI_VENDOR);
                self.unwind_frame_in_section::<_, F, ES>(
                    &eh_frame,
                    lookup_svma,
                    fde_offset,
                    regs,
                    is_first_frame,
                    read_stack,
                )
            }
            UnwindSectionType::DebugFrame => {
                let mut debug_frame = DebugFrame::from(unwind_section_data);
                debug_frame.set_address_size(8);
                debug_frame.set_vendor(A::CFI_VENDOR);
                self.unwind_frame_in_section::<_, F, ES>(
                    &debug_frame,
                    lookup_svma,
                    fde_offset,
                    regs,
                    is_first_frame,
                    read_stack,
                )
            }
        }
    }

    fn unwind_frame_in_section<US, F, ES>(
        &mut self,
        unwind_section: &US,
        lookup_svma: u64,
        fde_offset: u32,
        regs: &mut A::UnwindRegs,
        is_first_frame: bool,
        read_stack: &mut F,
    ) -> Result<UnwindResult<A::UnwindRule>, DwarfUnwinderError>
    where
        US: UnwindSection<R>,
        F: FnMut(u64) -> Result<u64, ()>,
        ES: EvaluationStorage<R>,
    {
        let fde = unwind_section.fde_from_offset(
            &self.bases,
            US::Offset::from(R::Offset::from_u32(fde_offset)),
            US::cie_from_offset,
        );
        let fde = fde.map_err(DwarfUnwinderError::FdeFromOffsetFailed)?;
        let encoding = fde.cie().encoding();
        let unwind_info = match fde.unwind_info_for_address(
            unwind_section,
            &self.bases,
            self.unwind_context,
            lookup_svma,
        ) {
            Ok(unwind_info) => unwind_info,
            Err(error) => {
                return Ok(UnwindResult::ExecRuleWithFallback(
                    A::rule_if_uncovered_by_fde(),
                    DwarfUnwinderError::UnwindInfoForAddressFailed(error).into(),
                ));
            }
        };
        A::unwind_frame::<F, R, UCS, ES>(
            unwind_section,
            unwind_info,
            encoding,
            regs,
            is_first_frame,
            read_stack,
        )
    }
}

pub(crate) fn base_addresses_and_text_range<D>(
    section_info: &mut impl ModuleSectionInfo<D>,
) -> (BaseAddresses, Option<Range<u64>>) {
    let text_range = section_info.section_svma_range(b"__text");
    let text_start = text_range
        .clone()
        .or_else(|| section_info.section_svma_range(b".text"))
        .map(|range| range.start)
        .unwrap_or_default();
    let mut start_addr = |names: &[&[u8]]| -> u64 {
        names
            .iter()
            .find_map(|name| section_info.section_svma_range(name))
            .map(|r| r.start)
            .unwrap_or_default()
    };
    let bases = BaseAddresses::default()
        .set_eh_frame(start_addr(&[b"__eh_frame", b".eh_frame"]))
        .set_eh_frame_hdr(start_addr(&[b"__eh_frame_hdr", b".eh_frame_hdr"]))
        .set_text(text_start)
        .set_got(start_addr(&[b"__got", b".got"]));
    (bases, text_range)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DwarfCfiIndexError {
    Gimli(gimli::Error),
    CouldNotSubtractBaseAddress,
    RelativeAddressTooBig,
    FdeOffsetTooBig,
}

impl core::fmt::Display for DwarfCfiIndexError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Gimli(e) => write!(f, "EhFrame processing failed: {e}"),
            Self::CouldNotSubtractBaseAddress => {
                write!(f, "Could not subtract base address to create relative pc")
            }
            Self::RelativeAddressTooBig => write!(f, "Relative address did not fit into u32"),
            Self::FdeOffsetTooBig => write!(f, "FDE offset did not fit into u32"),
        }
    }
}

impl From<gimli::Error> for DwarfCfiIndexError {
    fn from(e: gimli::Error) -> Self {
        Self::Gimli(e)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DwarfCfiIndexError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Gimli(e) => Some(e),
            _ => None,
        }
    }
}

/// A binary search table for eh_frame FDEs. We generate this whenever a module
/// without eh_frame_hdr is added.
pub struct DwarfCfiIndex {
    /// Contains the initial address for every FDE, relative to the base address.
    /// This vector is sorted so that it can be used for binary search.
    /// It has the same length as `fde_offsets`.
    sorted_fde_pc_starts: Vec<u32>,
    /// Contains the FDE offset for every FDE. The FDE at offset `fde_offsets[i]`
    /// has a PC range which starts at `sorted_fde_pc_starts[i]`.
    fde_offsets: Vec<u32>,
}

impl DwarfCfiIndex {
    pub fn try_new<R, US>(
        unwind_section: US,
        bases: &BaseAddresses,
        base_svma: u64,
    ) -> Result<Self, DwarfCfiIndexError>
    where
        R: Reader,
        R::Offset: TryInto<u32>,
        US: UnwindSection<R>,
    {
        let mut fde_pc_and_offset = Vec::new();

        let mut cur_cie = None;
        let mut entries_iter = unwind_section.entries(bases);
        while let Some(entry) = entries_iter.next()? {
            let fde = match entry {
                CieOrFde::Cie(cie) => {
                    cur_cie = Some(cie);
                    continue;
                }
                CieOrFde::Fde(partial_fde) => {
                    partial_fde.parse(|unwind_section, bases, cie_offset| {
                        if let Some(cie) = &cur_cie {
                            if cie.offset()
                                == <US::Offset as UnwindOffset<R::Offset>>::into(cie_offset)
                            {
                                return Ok(cie.clone());
                            }
                        }
                        let cie = unwind_section.cie_from_offset(bases, cie_offset);
                        if let Ok(cie) = &cie {
                            cur_cie = Some(cie.clone());
                        }
                        cie
                    })?
                }
            };
            let pc = fde.initial_address();
            let relative_pc = pc
                .checked_sub(base_svma)
                .ok_or(DwarfCfiIndexError::CouldNotSubtractBaseAddress)?;
            let relative_pc = u32::try_from(relative_pc)
                .map_err(|_| DwarfCfiIndexError::RelativeAddressTooBig)?;
            let fde_offset = <R::Offset as TryInto<u32>>::try_into(fde.offset())
                .map_err(|_| DwarfCfiIndexError::FdeOffsetTooBig)?;
            fde_pc_and_offset.push((relative_pc, fde_offset));
        }
        fde_pc_and_offset.sort_by_key(|(pc, _)| *pc);
        let sorted_fde_pc_starts = fde_pc_and_offset.iter().map(|(pc, _)| *pc).collect();
        let fde_offsets = fde_pc_and_offset.into_iter().map(|(_, fde)| fde).collect();
        Ok(Self {
            sorted_fde_pc_starts,
            fde_offsets,
        })
    }

    pub fn try_new_eh_frame(
        eh_frame_data: &[u8],
        bases: &BaseAddresses,
        base_svma: u64,
    ) -> Result<Self, DwarfCfiIndexError> {
        let mut eh_frame = EhFrame::from(EndianSlice::new(eh_frame_data, LittleEndian));
        eh_frame.set_address_size(8);

        Self::try_new(eh_frame, bases, base_svma)
    }

    pub fn try_new_debug_frame(
        debug_frame_data: &[u8],
        bases: &BaseAddresses,
        base_svma: u64,
    ) -> Result<Self, DwarfCfiIndexError> {
        let mut debug_frame = DebugFrame::from(EndianSlice::new(debug_frame_data, LittleEndian));
        debug_frame.set_address_size(8);

        Self::try_new(debug_frame, bases, base_svma)
    }

    pub fn fde_offset_for_relative_address(&self, rel_lookup_address: u32) -> Option<u32> {
        let i = match self.sorted_fde_pc_starts.binary_search(&rel_lookup_address) {
            Err(0) => return None,
            Ok(i) => i,
            Err(i) => i - 1,
        };
        Some(self.fde_offsets[i])
    }
}

/// The binary search table of an `.eh_frame_hdr` section in the layout that GNU ld,
/// gold, lld and mold emit: a 4-byte `.eh_frame` pointer, a `udata4` FDE count and
/// `datarel | sdata4` rows. We check the header once when the module is added, so
/// that lookups can search the rows in place instead of re-parsing the header and
/// decoding every probed row through gimli's generic pointer decoder.
pub struct EhFrameHdrTable {
    fde_count: usize,
    base_svma: u64,
    eh_frame_hdr_svma: u64,
    eh_frame_ptr: u64,
}

impl EhFrameHdrTable {
    const TABLE_OFFSET: usize = 12;
    const ROW_SIZE: usize = 8;

    /// Returns `None` for other header layouts, which keep using gimli's lookup.
    pub fn try_new(
        eh_frame_hdr_data: &[u8],
        bases: &BaseAddresses,
        base_svma: u64,
    ) -> Option<Self> {
        let [1, eh_frame_ptr_enc, fde_count_enc, table_enc] = *eh_frame_hdr_data.first_chunk()?
        else {
            return None;
        };
        if !matches!(
            DwEhPe(eh_frame_ptr_enc).format(),
            gimli::DW_EH_PE_udata4 | gimli::DW_EH_PE_sdata4
        ) || DwEhPe(fde_count_enc) != gimli::DW_EH_PE_udata4
            || DwEhPe(table_enc) != DwEhPe(gimli::DW_EH_PE_datarel.0 | gimli::DW_EH_PE_sdata4.0)
        {
            return None;
        }
        let hdr = EhFrameHdr::new(eh_frame_hdr_data, LittleEndian)
            .parse(bases, 8)
            .ok()?;
        let eh_frame_ptr = hdr.eh_frame_ptr().direct().ok()?;
        let fde_count = u32::from_le_bytes(*eh_frame_hdr_data.get(8..)?.first_chunk()?);
        let fde_count = usize::try_from(fde_count).ok()?;
        let table_end = fde_count
            .checked_mul(Self::ROW_SIZE)?
            .checked_add(Self::TABLE_OFFSET)?;
        if fde_count == 0 || table_end > eh_frame_hdr_data.len() {
            return None;
        }
        Some(Self {
            fde_count,
            base_svma,
            eh_frame_hdr_svma: bases.eh_frame_hdr.data?,
            eh_frame_ptr,
        })
    }

    pub fn fde_offset_for_relative_address(
        &self,
        eh_frame_hdr_data: &[u8],
        rel_lookup_address: u32,
    ) -> Option<u32> {
        let lookup_svma = self.base_svma + rel_lookup_address as u64;
        let table = eh_frame_hdr_data.get(Self::TABLE_OFFSET..)?;
        if lookup_svma < self.read_pointer(table, 0)? {
            return None;
        }
        // Same search as gimli's `EhHdrTable::lookup`, so that tables with duplicate
        // initial locations resolve to the same row.
        let mut row = 0;
        let mut len = self.fde_count;
        while len > 1 {
            let pivot = row + len / 2;
            match self
                .read_pointer(table, pivot * Self::ROW_SIZE)?
                .cmp(&lookup_svma)
            {
                Ordering::Equal => {
                    row = pivot;
                    break;
                }
                Ordering::Less => {
                    row = pivot;
                    len -= len / 2;
                }
                Ordering::Greater => len /= 2,
            }
        }
        let fde_ptr = self.read_pointer(table, row * Self::ROW_SIZE + 4)?;
        fde_ptr.checked_sub(self.eh_frame_ptr)?.try_into().ok()
    }

    fn read_pointer(&self, table: &[u8], offset: usize) -> Option<u64> {
        let value = i32::from_le_bytes(*table.get(offset..)?.first_chunk()?);
        Some(self.eh_frame_hdr_svma.wrapping_add(value as i64 as u64))
    }
}

pub trait DwarfUnwindRegs {
    fn get(&self, register: Register) -> Option<u64>;
}

pub fn eval_cfa_rule<R, F, UR, S>(
    section: &impl UnwindSection<R>,
    rule: &CfaRule<R::Offset>,
    encoding: Encoding,
    regs: &UR,
    read_stack: &mut F,
) -> Option<u64>
where
    R: Reader,
    F: FnMut(u64) -> Result<u64, ()>,
    UR: DwarfUnwindRegs,
    S: EvaluationStorage<R>,
{
    match rule {
        CfaRule::RegisterAndOffset { register, offset } => {
            let val = regs.get(*register)?;
            u64::try_from(i64::try_from(val).ok()?.checked_add(*offset)?).ok()
        }
        CfaRule::Expression(expr) => {
            let expr = expr.get(section).ok()?;
            eval_expr::<R, F, UR, S>(expr, encoding, regs, read_stack)
        }
    }
}

/// Iteration limit passed to gimli's `Evaluation::set_max_iterations`, which gimli
/// provides to stop bad DWARF bytecode from causing a denial of service. Without
/// it, gimli places no bound on evaluation, so an expression that loops forever
/// through a backward `DW_OP_skip` or `DW_OP_bra` would never finish. One iteration
/// is roughly one evaluated operation, and the count covers the whole evaluation,
/// including after each register or memory resumption. An expression that needs
/// more iterations fails with `TooManyIterations`, and `eval_expr` returns `None`,
/// the same as for any other evaluation error. Callers handle that `None` as they
/// handle any rule they cannot evaluate, which for some register rules means
/// falling back to a default value rather than failing the frame.
const MAX_EXPRESSION_ITERATIONS: u32 = 1024;

fn eval_expr<R, F, UR, S>(
    expr: Expression<R>,
    encoding: Encoding,
    regs: &UR,
    read_stack: &mut F,
) -> Option<u64>
where
    R: Reader,
    F: FnMut(u64) -> Result<u64, ()>,
    UR: DwarfUnwindRegs,
    S: EvaluationStorage<R>,
{
    let mut eval = Evaluation::<R, S>::new_in(expr.0, encoding);
    eval.set_max_iterations(MAX_EXPRESSION_ITERATIONS);
    let mut result = eval.evaluate().ok()?;
    loop {
        match result {
            EvaluationResult::Complete => break,
            EvaluationResult::RequiresRegister { register, .. } => {
                let value = regs.get(register)?;
                result = eval.resume_with_register(Value::Generic(value)).ok()?;
            }
            EvaluationResult::RequiresMemory {
                address,
                size,
                space,
                ..
            } => {
                if space.is_some() || size != encoding.address_size {
                    return None;
                }
                let value = read_stack(address).ok()?;
                result = eval.resume_with_memory(Value::Generic(value)).ok()?;
            }
            _ => return None,
        }
    }
    let x = &eval.as_result().last()?.location;
    if let Location::Address { address } = x {
        Some(*address)
    } else {
        None
    }
}

pub fn eval_register_rule<R, F, UR, S>(
    section: &impl UnwindSection<R>,
    rule: Option<RegisterRule<R::Offset>>,
    cfa: u64,
    encoding: Encoding,
    val: u64,
    regs: &UR,
    read_stack: &mut F,
) -> Option<u64>
where
    R: Reader,
    F: FnMut(u64) -> Result<u64, ()>,
    UR: DwarfUnwindRegs,
    S: EvaluationStorage<R>,
{
    let rule = rule?;
    match rule {
        RegisterRule::Undefined => None,
        RegisterRule::SameValue => Some(val),
        RegisterRule::Offset(offset) => {
            let cfa_plus_offset =
                u64::try_from(i64::try_from(cfa).ok()?.checked_add(offset)?).ok()?;
            read_stack(cfa_plus_offset).ok()
        }
        RegisterRule::ValOffset(offset) => {
            u64::try_from(i64::try_from(cfa).ok()?.checked_add(offset)?).ok()
        }
        RegisterRule::Register(register) => regs.get(register),
        RegisterRule::Expression(expr) => {
            let expr = expr.get(section).ok()?;
            let val = eval_expr::<R, F, UR, S>(expr, encoding, regs, read_stack)?;
            read_stack(val).ok()
        }
        RegisterRule::ValExpression(expr) => {
            let expr = expr.get(section).ok()?;
            eval_expr::<R, F, UR, S>(expr, encoding, regs, read_stack)
        }
        RegisterRule::Architectural => {
            // Unimplemented
            // TODO: Find out what the architectural rules for x86_64 and for aarch64 are, if any.
            None
        }
        RegisterRule::Constant(value) => Some(value),
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use alloc::vec;

    use gimli::{AArch64, DebugFrame, Format, StoreOnHeap, UnwindExpression, X86_64};

    use crate::{
        aarch64::UnwindRegsAarch64,
        x86_64::{Reg, UnwindRegsX86_64},
    };

    use super::*;

    /// The x86-64 entry CIE after its id: CFA = rsp + 8, return address at CFA - 8.
    pub(crate) const X86_64_CIE: [u8; 10] = [
        1,
        0,
        1,
        0x78,
        X86_64::RA.0 as u8,
        gimli::DW_CFA_def_cfa.0,
        X86_64::RSP.0 as u8,
        8,
        gimli::DW_CFA_offset.0 | X86_64::RA.0 as u8,
        1,
    ];

    /// The AArch64 entry CIE after its id: CFA = sp, return address in x30.
    pub(crate) const AARCH64_CIE: [u8; 8] = [
        1,
        0,
        4,
        0x78,
        AArch64::X30.0 as u8,
        gimli::DW_CFA_def_cfa.0,
        AArch64::SP.0 as u8,
        0,
    ];

    /// Builds an `.eh_frame` section with `cie` followed by an FDE for `range` that runs
    /// `instructions`, and returns it with the offset of the FDE.
    pub(crate) fn eh_frame_with_fde(
        cie: &[u8],
        range: Range<u64>,
        instructions: &[u8],
    ) -> (Vec<u8>, u32) {
        let mut data = (4 + cie.len() as u32).to_le_bytes().to_vec();
        data.extend(0u32.to_le_bytes());
        data.extend(cie);
        let fde_offset = data.len() as u32;
        data.extend((20 + instructions.len() as u32).to_le_bytes());
        data.extend((fde_offset + 4).to_le_bytes());
        data.extend(range.start.to_le_bytes());
        data.extend((range.end - range.start).to_le_bytes());
        data.extend(instructions);
        (data, fde_offset)
    }

    #[test]
    fn header_lookup_rejects_addresses_before_its_first_entry() {
        use crate::x86_64::ArchX86_64;

        for base in [0, 0x1_0000_0000_u64] {
            let encoding = gimli::DW_EH_PE_udata8.0;
            let mut header = vec![1, encoding, encoding, encoding];
            header.extend_from_slice(&0x9000_u64.to_le_bytes());
            header.extend_from_slice(&2_u64.to_le_bytes());
            for (address, fde) in [(base + 0x1000, 0x9020_u64), (base + 0x2000, 0x9040)] {
                header.extend_from_slice(&address.to_le_bytes());
                header.extend_from_slice(&fde.to_le_bytes());
            }
            let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
            let unwinder = DwarfUnwinder::<_, ArchX86_64, _>::new(
                EndianSlice::new(&[], LittleEndian),
                UnwindSectionType::EhFrame,
                Some(&header),
                &mut context,
                BaseAddresses::default(),
                base,
            );
            for (address, expected) in [
                (0x0fff, None),
                (0x1000, Some(0x20)),
                (0x1fff, Some(0x20)),
                (0x2000, Some(0x40)),
            ] {
                assert_eq!(
                    unwinder.get_fde_offset_for_relative_address(address),
                    expected
                );
            }
        }
    }

    #[test]
    fn eh_frame_hdr_table_matches_gimli_lookup() {
        use crate::x86_64::ArchX86_64;

        // Common layout with duplicate initial locations, at eh_frame_hdr 0x9000.
        let mut header = vec![1, 0x1b, 0x03, 0x3b];
        header.extend_from_slice(&0xfc_i32.to_le_bytes());
        header.extend_from_slice(&5_u32.to_le_bytes());
        for (address, fde) in [
            (-0x8000_i32, 0x100_i32),
            (-0x7000, 0x120),
            (-0x7000, 0x140),
            (-0x7000, 0x160),
            (-0x6000, 0x180),
        ] {
            header.extend_from_slice(&address.to_le_bytes());
            header.extend_from_slice(&fde.to_le_bytes());
        }
        let bases = BaseAddresses::default().set_eh_frame_hdr(0x9000);
        let table = EhFrameHdrTable::try_new(&header, &bases, 0).unwrap();
        let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
        let unwinder = DwarfUnwinder::<_, ArchX86_64, _>::new(
            EndianSlice::new(&[], LittleEndian),
            UnwindSectionType::EhFrame,
            Some(&header),
            &mut context,
            bases.clone(),
            0,
        );
        for address in 0..0x4000 {
            assert_eq!(
                table.fde_offset_for_relative_address(&header, address),
                unwinder.get_fde_offset_for_relative_address(address),
                "{address:#x}"
            );
        }
    }

    #[test]
    fn eh_frame_and_debug_frame_preserve_unwind_and_error_outcomes() {
        use crate::error::UnwinderError;
        use crate::x86_64::{ArchX86_64, UnwindRuleX86_64};

        for section_type in [UnwindSectionType::EhFrame, UnwindSectionType::DebugFrame] {
            let cie_id = match section_type {
                UnwindSectionType::EhFrame => 0u32,
                UnwindSectionType::DebugFrame => u32::MAX,
            };
            let mut data = 14u32.to_le_bytes().to_vec();
            data.extend(cie_id.to_le_bytes());
            data.extend(X86_64_CIE);
            let fde_offset = data.len() as u32;
            let cie_pointer = match section_type {
                UnwindSectionType::EhFrame => fde_offset + 4,
                UnwindSectionType::DebugFrame => 0,
            };
            data.extend(20u32.to_le_bytes());
            data.extend(cie_pointer.to_le_bytes());
            data.extend(0x1000u64.to_le_bytes());
            data.extend(0x10u64.to_le_bytes());
            let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
            let mut unwinder = DwarfUnwinder::<_, ArchX86_64, _>::new(
                EndianSlice::new(&data, LittleEndian),
                section_type,
                None,
                &mut context,
                BaseAddresses::default(),
                0,
            );
            let mut regs = UnwindRegsX86_64::new(0x1000, 0x2000, 0x3000);
            let mut read_stack = |_| panic!("a cacheable rule does not read the stack");
            assert!(matches!(
                unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
                    &mut regs,
                    true,
                    0x1000,
                    fde_offset,
                    &mut read_stack,
                ),
                Ok(UnwindResult::ExecRuleWithDwarfRegisterRules(
                    UnwindRuleX86_64::OffsetSp { sp_offset_by_8: 1 },
                    0,
                ))
            ));
            assert!(matches!(
                unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
                    &mut regs,
                    true,
                    0x2000,
                    fde_offset,
                    &mut read_stack,
                ),
                Ok(UnwindResult::ExecRuleWithFallback(
                    UnwindRuleX86_64::JustReturnIfFirstFrameOtherwiseFp,
                    UnwinderError::Dwarf(DwarfUnwinderError::UnwindInfoForAddressFailed(_)),
                ))
            ));
            assert!(matches!(
                unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
                    &mut regs,
                    true,
                    0x1000,
                    u32::MAX,
                    &mut read_stack,
                ),
                Err(DwarfUnwinderError::FdeFromOffsetFailed(_))
            ));
        }
    }

    #[test]
    fn aarch64_return_address_signing_does_not_abort_dwarf_unwinding() {
        use crate::aarch64::ArchAarch64;

        // CIE with CFA = sp, and an FDE for [0x1000, 0x1040) that toggles the signing state
        // like `paciasp` in a `-mbranch-protection=pac-ret` prologue.
        let (data, fde_offset) = eh_frame_with_fde(
            &AARCH64_CIE,
            0x1000..0x1040,
            &[gimli::DW_CFA_AARCH64_negate_ra_state.0],
        );
        let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
        let mut unwinder = DwarfUnwinder::<_, ArchAarch64, _>::new(
            EndianSlice::new(&data, LittleEndian),
            UnwindSectionType::EhFrame,
            None,
            &mut context,
            BaseAddresses::default(),
            0,
        );
        let mut regs = UnwindRegsAarch64::new(0x1024, 0x8000, 0x9000);
        let result = unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
            &mut regs,
            true,
            0x1010,
            fde_offset,
            &mut |_| Err(()),
        );
        assert!(matches!(result, Ok(UnwindResult::ExecRule(_))));
    }

    /// Unwinds a caller frame at `address` with an `.eh_frame` FDE for [0x1000, 0x1010)
    /// that runs `instructions` after the x86-64 entry CIE.
    fn unwind_x86_64_fde(
        instructions: &[u8],
        address: u32,
        regs: &mut UnwindRegsX86_64,
        read_stack: &mut impl FnMut(u64) -> Result<u64, ()>,
    ) -> Result<UnwindResult<crate::x86_64::UnwindRuleX86_64>, DwarfUnwinderError> {
        use crate::x86_64::ArchX86_64;

        let (data, fde_offset) = eh_frame_with_fde(&X86_64_CIE, 0x1000..0x1010, instructions);
        let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
        DwarfUnwinder::<_, ArchX86_64, _>::new(
            EndianSlice::new(&data, LittleEndian),
            UnwindSectionType::EhFrame,
            None,
            &mut context,
            BaseAddresses::default(),
            0,
        )
        .unwind_frame_with_fde::<_, StoreOnHeap>(regs, false, address, fde_offset, read_stack)
    }

    #[test]
    fn memory_backed_cfa_below_the_return_address_slot_is_an_error() {
        // DW_CFA_def_cfa_expression: DW_OP_breg6(RBP) -8; DW_OP_deref
        let instructions = [gimli::DW_CFA_def_cfa_expression.0, 3, 0x76, 0x78, 0x06];
        let mut regs = UnwindRegsX86_64::new(0x1000, 0x2000, 0x3000);
        let mut read_stack = |address| match address {
            0x2ff8 => Ok(4),
            _ => Err(()),
        };
        assert!(matches!(
            unwind_x86_64_fde(&instructions, 0x1004, &mut regs, &mut read_stack),
            Err(DwarfUnwinderError::CouldNotRecoverReturnAddress)
        ));
    }

    #[test]
    fn undefined_return_address_ends_the_stack_even_with_saved_registers() {
        use crate::x86_64::UnwindRuleX86_64;

        let instructions = [
            gimli::DW_CFA_undefined.0,
            X86_64::RA.0 as u8,
            gimli::DW_CFA_offset.0 | X86_64::RBX.0 as u8,
            2,
        ];
        let mut regs = UnwindRegsX86_64::new(0x1004, 0x2000, 0x3000);
        let result = unwind_x86_64_fde(&instructions, 0x1004, &mut regs, &mut |_| Ok(0x5555));
        assert!(
            matches!(
                result,
                Ok(UnwindResult::ExecRuleWithDwarfRegisterRules(
                    UnwindRuleX86_64::EndOfStack,
                    0,
                ))
            ),
            "{result:?}"
        );
    }

    fn encoding() -> Encoding {
        Encoding {
            address_size: 8,
            format: Format::Dwarf32,
            version: 4,
        }
    }

    #[test]
    fn eval_cfa_expression_can_read_memory_with_x86_64_regs() {
        // DW_OP_breg6(RBP) -40; DW_OP_deref
        let expression = [0x76, 0x58, 0x06];
        let mut section = DebugFrame::from(EndianSlice::new(&expression, LittleEndian));
        section.set_address_size(8);
        let rule = CfaRule::Expression(UnwindExpression {
            offset: 0,
            length: expression.len(),
        });
        let regs = UnwindRegsX86_64::new(0, 0, 0x1000);

        let mut unreadable_stack = |_| Err(());
        assert_eq!(
            eval_cfa_rule::<_, _, _, StoreOnHeap>(
                &section,
                &rule,
                encoding(),
                &regs,
                &mut unreadable_stack,
            ),
            None
        );

        let mut read_stack = |address| {
            assert_eq!(address, 0xfd8);
            Ok(0x2000)
        };

        assert_eq!(
            eval_cfa_rule::<_, _, _, StoreOnHeap>(
                &section,
                &rule,
                encoding(),
                &regs,
                &mut read_stack,
            ),
            Some(0x2000)
        );
    }

    #[test]
    fn eval_cfa_expression_can_read_memory_with_aarch64_regs() {
        // DW_OP_breg29(X29/FP) -16; DW_OP_deref
        let expression = [0x8d, 0x70, 0x06];
        let mut section = DebugFrame::from(EndianSlice::new(&expression, LittleEndian));
        section.set_address_size(8);
        let rule = CfaRule::Expression(UnwindExpression {
            offset: 0,
            length: expression.len(),
        });
        let regs = UnwindRegsAarch64::new(0, 0, 0x3000);
        assert_eq!(DwarfUnwindRegs::get(&regs, AArch64::X29), Some(0x3000));

        let mut read_stack = |address| {
            assert_eq!(address, 0x2ff0);
            Ok(0x4000)
        };

        assert_eq!(
            eval_cfa_rule::<_, _, _, StoreOnHeap>(
                &section,
                &rule,
                encoding(),
                &regs,
                &mut read_stack,
            ),
            Some(0x4000)
        );
    }

    #[test]
    fn eval_cfa_expression_rejects_partial_memory_reads() {
        // DW_OP_breg6(RBP) -40; DW_OP_deref_size 4
        let expression = [0x76, 0x58, 0x94, 0x04];
        let mut section = DebugFrame::from(EndianSlice::new(&expression, LittleEndian));
        section.set_address_size(8);
        let rule = CfaRule::Expression(UnwindExpression {
            offset: 0,
            length: expression.len(),
        });
        let regs = UnwindRegsX86_64::new(0, 0, 0x1000);

        let mut read_stack =
            |_: u64| -> Result<u64, ()> { panic!("partial memory reads are unsupported") };

        assert_eq!(
            eval_cfa_rule::<_, _, _, StoreOnHeap>(
                &section,
                &rule,
                encoding(),
                &regs,
                &mut read_stack,
            ),
            None
        );
    }

    #[cfg(feature = "std")]
    #[test]
    fn eval_rejects_looping_expressions() {
        // DW_OP_skip -3
        let expression: &[u8] = &[0x2f, 0xfd, 0xff];
        let mut section = DebugFrame::from(EndianSlice::new(expression, LittleEndian));
        section.set_address_size(8);
        let rule = CfaRule::Expression(UnwindExpression {
            offset: 0,
            length: expression.len(),
        });
        let regs = UnwindRegsX86_64::new(0x1000, 0x2000, 0x3000);
        // Evaluate on another thread so that a hang fails the test.
        let (sender, receiver) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            sender.send(eval_cfa_rule::<_, _, _, StoreOnHeap>(
                &section,
                &rule,
                encoding(),
                &regs,
                &mut |_| Err(()),
            ))
        });
        let result = receiver.recv_timeout(std::time::Duration::from_secs(2));
        assert_eq!(result, Ok(None));
    }

    #[test]
    fn x86_64_dwarf_regs_expose_provided_general_purpose_registers() {
        let mut regs = UnwindRegsX86_64::new(0, 0, 0);
        assert_eq!(DwarfUnwindRegs::get(&regs, X86_64::R10), None);

        regs.set(Reg::R10, 0x1234);

        assert_eq!(DwarfUnwindRegs::get(&regs, X86_64::R10), Some(0x1234));
        assert_eq!(DwarfUnwindRegs::get(&regs, X86_64::R11), None);
    }
}