Skip to main content

gimli/read/
rnglists.rs

1use crate::common::{
2    DebugAddrBase, DebugAddrIndex, DebugRngListsBase, DebugRngListsIndex, DwarfFileType, Encoding,
3    RangeListsOffset, SectionId,
4};
5use crate::constants;
6use crate::endianity::Endianity;
7use crate::read::{
8    DebugAddr, EndianSlice, Error, Reader, ReaderAddress, ReaderOffset, ReaderOffsetId, Result,
9    Section, lists::ListsHeader,
10};
11
12/// The raw contents of the `.debug_ranges` section.
13#[derive(Debug, Default, Clone, Copy)]
14pub struct DebugRanges<R> {
15    pub(crate) section: R,
16}
17
18impl<'input, Endian> DebugRanges<EndianSlice<'input, Endian>>
19where
20    Endian: Endianity,
21{
22    /// Construct a new `DebugRanges` instance from the data in the `.debug_ranges`
23    /// section.
24    ///
25    /// It is the caller's responsibility to read the `.debug_ranges` section and
26    /// present it as a `&[u8]` slice. That means using some ELF loader on
27    /// Linux, a Mach-O loader on macOS, etc.
28    ///
29    /// ```
30    /// use gimli::{DebugRanges, LittleEndian};
31    ///
32    /// # let buf = [0x00, 0x01, 0x02, 0x03];
33    /// # let read_debug_ranges_section_somehow = || &buf;
34    /// let debug_ranges = DebugRanges::new(read_debug_ranges_section_somehow(), LittleEndian);
35    /// ```
36    pub fn new(section: &'input [u8], endian: Endian) -> Self {
37        Self::from(EndianSlice::new(section, endian))
38    }
39}
40
41impl<T> DebugRanges<T> {
42    /// Create a `DebugRanges` section that references the data in `self`.
43    ///
44    /// This is useful when `R` implements `Reader` but `T` does not.
45    ///
46    /// Used by `DwarfSections::borrow`.
47    pub(crate) fn borrow<'a, F, R>(&'a self, mut borrow: F) -> DebugRanges<R>
48    where
49        F: FnMut(&'a T) -> R,
50    {
51        borrow(&self.section).into()
52    }
53}
54
55impl<R> Section<R> for DebugRanges<R> {
56    fn id() -> SectionId {
57        SectionId::DebugRanges
58    }
59
60    fn reader(&self) -> &R {
61        &self.section
62    }
63}
64
65impl<R> From<R> for DebugRanges<R> {
66    fn from(section: R) -> Self {
67        DebugRanges { section }
68    }
69}
70
71/// The `DebugRngLists` struct represents the contents of the
72/// `.debug_rnglists` section.
73#[derive(Debug, Default, Clone, Copy)]
74pub struct DebugRngLists<R> {
75    section: R,
76}
77
78impl<'input, Endian> DebugRngLists<EndianSlice<'input, Endian>>
79where
80    Endian: Endianity,
81{
82    /// Construct a new `DebugRngLists` instance from the data in the
83    /// `.debug_rnglists` section.
84    ///
85    /// It is the caller's responsibility to read the `.debug_rnglists`
86    /// section and present it as a `&[u8]` slice. That means using some ELF
87    /// loader on Linux, a Mach-O loader on macOS, etc.
88    ///
89    /// ```
90    /// use gimli::{DebugRngLists, LittleEndian};
91    ///
92    /// # let buf = [0x00, 0x01, 0x02, 0x03];
93    /// # let read_debug_rnglists_section_somehow = || &buf;
94    /// let debug_rnglists =
95    ///     DebugRngLists::new(read_debug_rnglists_section_somehow(), LittleEndian);
96    /// ```
97    pub fn new(section: &'input [u8], endian: Endian) -> Self {
98        Self::from(EndianSlice::new(section, endian))
99    }
100}
101
102impl<T> DebugRngLists<T> {
103    /// Create a `DebugRngLists` section that references the data in `self`.
104    ///
105    /// This is useful when `R` implements `Reader` but `T` does not.
106    ///
107    /// Used by `DwarfSections::borrow`.
108    pub(crate) fn borrow<'a, F, R>(&'a self, mut borrow: F) -> DebugRngLists<R>
109    where
110        F: FnMut(&'a T) -> R,
111    {
112        borrow(&self.section).into()
113    }
114}
115
116impl<R> Section<R> for DebugRngLists<R> {
117    fn id() -> SectionId {
118        SectionId::DebugRngLists
119    }
120
121    fn reader(&self) -> &R {
122        &self.section
123    }
124}
125
126impl<R> From<R> for DebugRngLists<R> {
127    fn from(section: R) -> Self {
128        DebugRngLists { section }
129    }
130}
131
132#[allow(unused)]
133pub(crate) type RngListsHeader = ListsHeader;
134
135impl<Offset> DebugRngListsBase<Offset>
136where
137    Offset: ReaderOffset,
138{
139    /// Returns a `DebugRngListsBase` with the default value of DW_AT_rnglists_base
140    /// for the given `Encoding` and `DwarfFileType`.
141    pub fn default_for_encoding_and_file(
142        encoding: Encoding,
143        file_type: DwarfFileType,
144    ) -> DebugRngListsBase<Offset> {
145        if encoding.version >= 5 && file_type == DwarfFileType::Dwo {
146            // In .dwo files, the compiler omits the DW_AT_rnglists_base attribute (because there is
147            // only a single unit in the file) but we must skip past the header, which the attribute
148            // would normally do for us.
149            DebugRngListsBase(Offset::from_u8(RngListsHeader::size_for_encoding(encoding)))
150        } else {
151            DebugRngListsBase(Offset::from_u8(0))
152        }
153    }
154}
155
156/// The DWARF data found in `.debug_ranges` and `.debug_rnglists` sections.
157#[derive(Debug, Default, Clone, Copy)]
158pub struct RangeLists<R> {
159    debug_ranges: DebugRanges<R>,
160    debug_rnglists: DebugRngLists<R>,
161}
162
163impl<R> RangeLists<R> {
164    /// Construct a new `RangeLists` instance from the data in the `.debug_ranges` and
165    /// `.debug_rnglists` sections.
166    pub fn new(debug_ranges: DebugRanges<R>, debug_rnglists: DebugRngLists<R>) -> RangeLists<R> {
167        RangeLists {
168            debug_ranges,
169            debug_rnglists,
170        }
171    }
172
173    /// Return the `.debug_ranges` section.
174    pub fn debug_ranges(&self) -> &DebugRanges<R> {
175        &self.debug_ranges
176    }
177
178    /// Replace the `.debug_ranges` section.
179    ///
180    /// This is useful for `.dwo` files when using the GNU split-dwarf extension to DWARF 4.
181    pub fn set_debug_ranges(&mut self, debug_ranges: DebugRanges<R>) {
182        self.debug_ranges = debug_ranges;
183    }
184
185    /// Return the `.debug_rnglists` section.
186    pub fn debug_rnglists(&self) -> &DebugRngLists<R> {
187        &self.debug_rnglists
188    }
189}
190
191impl<T> RangeLists<T> {
192    /// Create a `RangeLists` that references the data in `self`.
193    ///
194    /// This is useful when `R` implements `Reader` but `T` does not.
195    ///
196    /// Used by `Dwarf::borrow`.
197    pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> RangeLists<R>
198    where
199        F: FnMut(&'a T) -> R,
200    {
201        RangeLists {
202            debug_ranges: borrow(&self.debug_ranges.section).into(),
203            debug_rnglists: borrow(&self.debug_rnglists.section).into(),
204        }
205    }
206}
207
208impl<R: Reader> RangeLists<R> {
209    /// Iterate over the `Range` list entries starting at the given offset.
210    ///
211    /// The `unit_version` and `address_size` must match the compilation unit that the
212    /// offset was contained in.
213    ///
214    /// The `base_address` should be obtained from the `DW_AT_low_pc` attribute in the
215    /// `DW_TAG_compile_unit` entry for the compilation unit that contains this range list.
216    pub fn ranges(
217        &self,
218        offset: RangeListsOffset<R::Offset>,
219        unit_encoding: Encoding,
220        base_address: u64,
221        debug_addr: &DebugAddr<R>,
222        debug_addr_base: DebugAddrBase<R::Offset>,
223    ) -> Result<RngListIter<R>> {
224        Ok(RngListIter::new(
225            self.raw_ranges(offset, unit_encoding)?,
226            base_address,
227            debug_addr.clone(),
228            debug_addr_base,
229        ))
230    }
231
232    /// Iterate over the `RawRngListEntry`ies starting at the given offset.
233    ///
234    /// The `unit_encoding` must match the compilation unit that the
235    /// offset was contained in.
236    ///
237    /// This iterator does not perform any processing of the range entries,
238    /// such as handling base addresses.
239    pub fn raw_ranges(
240        &self,
241        offset: RangeListsOffset<R::Offset>,
242        unit_encoding: Encoding,
243    ) -> Result<RawRngListIter<R>> {
244        let (mut input, format) = if unit_encoding.version <= 4 {
245            (self.debug_ranges.section.clone(), RangeListsFormat::Bare)
246        } else {
247            (self.debug_rnglists.section.clone(), RangeListsFormat::Rle)
248        };
249        input.skip(offset.0)?;
250        Ok(RawRngListIter::new(input, unit_encoding, format))
251    }
252
253    /// Returns the `.debug_rnglists` offset at the given `base` and `index`.
254    ///
255    /// The `base` must be the `DW_AT_rnglists_base` value from the compilation unit DIE.
256    /// This is an offset that points to the first entry following the header.
257    ///
258    /// The `index` is the value of a `DW_FORM_rnglistx` attribute.
259    ///
260    /// The `unit_encoding` must match the compilation unit that the
261    /// index was contained in.
262    pub fn get_offset(
263        &self,
264        unit_encoding: Encoding,
265        base: DebugRngListsBase<R::Offset>,
266        index: DebugRngListsIndex<R::Offset>,
267    ) -> Result<RangeListsOffset<R::Offset>> {
268        let format = unit_encoding.format;
269        let input = &mut self.debug_rnglists.section.clone();
270        input.skip(base.0)?;
271        input.skip(R::Offset::from_u64(
272            index.0.into_u64() * u64::from(format.word_size()),
273        )?)?;
274        input
275            .read_offset(format)
276            .map(|x| RangeListsOffset(base.0 + x))
277    }
278
279    /// Call `Reader::lookup_offset_id` for each section, and return the first match.
280    pub fn lookup_offset_id(&self, id: ReaderOffsetId) -> Option<(SectionId, R::Offset)> {
281        self.debug_ranges
282            .lookup_offset_id(id)
283            .or_else(|| self.debug_rnglists.lookup_offset_id(id))
284    }
285}
286
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288enum RangeListsFormat {
289    /// The bare range list format used before DWARF 5.
290    Bare,
291    /// The DW_RLE encoded range list format used in DWARF 5.
292    Rle,
293}
294
295/// A raw iterator over an address range list.
296///
297/// This iterator does not perform any processing of the range entries,
298/// such as handling base addresses.
299#[derive(Debug)]
300pub struct RawRngListIter<R: Reader> {
301    input: R,
302    encoding: Encoding,
303    format: RangeListsFormat,
304}
305
306/// A raw entry in .debug_rnglists
307#[derive(Clone, Debug)]
308pub enum RawRngListEntry<T> {
309    /// A range from DWARF version <= 4.
310    AddressOrOffsetPair {
311        /// Start of range. May be an address or an offset.
312        begin: u64,
313        /// End of range. May be an address or an offset.
314        end: u64,
315    },
316    /// DW_RLE_base_address
317    BaseAddress {
318        /// base address
319        addr: u64,
320    },
321    /// DW_RLE_base_addressx
322    BaseAddressx {
323        /// base address
324        addr: DebugAddrIndex<T>,
325    },
326    /// DW_RLE_startx_endx
327    StartxEndx {
328        /// start of range
329        begin: DebugAddrIndex<T>,
330        /// end of range
331        end: DebugAddrIndex<T>,
332    },
333    /// DW_RLE_startx_length
334    StartxLength {
335        /// start of range
336        begin: DebugAddrIndex<T>,
337        /// length of range
338        length: u64,
339    },
340    /// DW_RLE_offset_pair
341    OffsetPair {
342        /// start of range
343        begin: u64,
344        /// end of range
345        end: u64,
346    },
347    /// DW_RLE_start_end
348    StartEnd {
349        /// start of range
350        begin: u64,
351        /// end of range
352        end: u64,
353    },
354    /// DW_RLE_start_length
355    StartLength {
356        /// start of range
357        begin: u64,
358        /// length of range
359        length: u64,
360    },
361}
362
363impl<T: ReaderOffset> RawRngListEntry<T> {
364    /// Parse a range entry from `.debug_rnglists`
365    fn parse<R: Reader<Offset = T>>(
366        input: &mut R,
367        encoding: Encoding,
368        format: RangeListsFormat,
369    ) -> Result<Option<Self>> {
370        Ok(match format {
371            RangeListsFormat::Bare => {
372                let range = RawRange::parse(input, encoding.address_size)?;
373                if range.is_end() {
374                    None
375                } else if range.is_base_address(encoding.address_size) {
376                    Some(RawRngListEntry::BaseAddress { addr: range.end })
377                } else {
378                    Some(RawRngListEntry::AddressOrOffsetPair {
379                        begin: range.begin,
380                        end: range.end,
381                    })
382                }
383            }
384            RangeListsFormat::Rle => match constants::DwRle(input.read_u8()?) {
385                constants::DW_RLE_end_of_list => None,
386                constants::DW_RLE_base_addressx => Some(RawRngListEntry::BaseAddressx {
387                    addr: DebugAddrIndex(input.read_uleb128().and_then(R::Offset::from_u64)?),
388                }),
389                constants::DW_RLE_startx_endx => Some(RawRngListEntry::StartxEndx {
390                    begin: DebugAddrIndex(input.read_uleb128().and_then(R::Offset::from_u64)?),
391                    end: DebugAddrIndex(input.read_uleb128().and_then(R::Offset::from_u64)?),
392                }),
393                constants::DW_RLE_startx_length => Some(RawRngListEntry::StartxLength {
394                    begin: DebugAddrIndex(input.read_uleb128().and_then(R::Offset::from_u64)?),
395                    length: input.read_uleb128()?,
396                }),
397                constants::DW_RLE_offset_pair => Some(RawRngListEntry::OffsetPair {
398                    begin: input.read_uleb128()?,
399                    end: input.read_uleb128()?,
400                }),
401                constants::DW_RLE_base_address => Some(RawRngListEntry::BaseAddress {
402                    addr: input.read_address(encoding.address_size)?,
403                }),
404                constants::DW_RLE_start_end => Some(RawRngListEntry::StartEnd {
405                    begin: input.read_address(encoding.address_size)?,
406                    end: input.read_address(encoding.address_size)?,
407                }),
408                constants::DW_RLE_start_length => Some(RawRngListEntry::StartLength {
409                    begin: input.read_address(encoding.address_size)?,
410                    length: input.read_uleb128()?,
411                }),
412                entry => {
413                    return Err(Error::UnknownRangeListsEntry(entry));
414                }
415            },
416        })
417    }
418}
419
420impl<R: Reader> RawRngListIter<R> {
421    /// Construct a `RawRngListIter`.
422    fn new(input: R, encoding: Encoding, format: RangeListsFormat) -> RawRngListIter<R> {
423        RawRngListIter {
424            input,
425            encoding,
426            format,
427        }
428    }
429
430    /// Advance the iterator to the next range.
431    pub fn next(&mut self) -> Result<Option<RawRngListEntry<R::Offset>>> {
432        if self.input.is_empty() {
433            return Ok(None);
434        }
435
436        match RawRngListEntry::parse(&mut self.input, self.encoding, self.format) {
437            Ok(range) => {
438                if range.is_none() {
439                    self.input.empty();
440                }
441                Ok(range)
442            }
443            Err(e) => {
444                self.input.empty();
445                Err(e)
446            }
447        }
448    }
449}
450
451#[cfg(feature = "fallible-iterator")]
452impl<R: Reader> fallible_iterator::FallibleIterator for RawRngListIter<R> {
453    type Item = RawRngListEntry<R::Offset>;
454    type Error = Error;
455
456    fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
457        RawRngListIter::next(self)
458    }
459}
460
461impl<R: Reader> Iterator for RawRngListIter<R> {
462    type Item = Result<RawRngListEntry<R::Offset>>;
463
464    fn next(&mut self) -> Option<Self::Item> {
465        RawRngListIter::next(self).transpose()
466    }
467}
468
469/// An iterator over an address range list.
470///
471/// This iterator internally handles processing of base addresses and different
472/// entry types.  Thus, it only returns range entries that are valid
473/// and already adjusted for the base address.
474#[derive(Debug)]
475pub struct RngListIter<R: Reader> {
476    raw: RawRngListIter<R>,
477    base_address: u64,
478    debug_addr: DebugAddr<R>,
479    debug_addr_base: DebugAddrBase<R::Offset>,
480}
481
482impl<R: Reader> RngListIter<R> {
483    /// Construct a `RngListIter`.
484    fn new(
485        raw: RawRngListIter<R>,
486        base_address: u64,
487        debug_addr: DebugAddr<R>,
488        debug_addr_base: DebugAddrBase<R::Offset>,
489    ) -> RngListIter<R> {
490        RngListIter {
491            raw,
492            base_address,
493            debug_addr,
494            debug_addr_base,
495        }
496    }
497
498    #[inline]
499    fn get_address(&self, index: DebugAddrIndex<R::Offset>) -> Result<u64> {
500        self.debug_addr
501            .get_address(self.raw.encoding.address_size, self.debug_addr_base, index)
502    }
503
504    /// Advance the iterator to the next range.
505    pub fn next(&mut self) -> Result<Option<Range>> {
506        loop {
507            let raw_range = match self.raw.next()? {
508                Some(range) => range,
509                None => return Ok(None),
510            };
511
512            let range = self.convert_raw(raw_range)?;
513            if range.is_some() {
514                return Ok(range);
515            }
516        }
517    }
518
519    /// Return the next raw range.
520    ///
521    /// The raw range should be passed to `convert_range`.
522    #[doc(hidden)]
523    pub fn next_raw(&mut self) -> Result<Option<RawRngListEntry<R::Offset>>> {
524        self.raw.next()
525    }
526
527    /// Convert a raw range into a range, and update the state of the iterator.
528    ///
529    /// The raw range should have been obtained from `next_raw`.
530    #[doc(hidden)]
531    pub fn convert_raw(&mut self, raw_range: RawRngListEntry<R::Offset>) -> Result<Option<Range>> {
532        let address_size = self.raw.encoding.address_size;
533
534        let range = match raw_range {
535            RawRngListEntry::BaseAddress { addr } => {
536                self.base_address = addr;
537                return Ok(None);
538            }
539            RawRngListEntry::BaseAddressx { addr } => {
540                self.base_address = self.get_address(addr)?;
541                return Ok(None);
542            }
543            RawRngListEntry::StartxEndx { begin, end } => {
544                let begin = self.get_address(begin)?;
545                let end = self.get_address(end)?;
546                Range { begin, end }
547            }
548            RawRngListEntry::StartxLength { begin, length } => {
549                let begin = self.get_address(begin)?;
550                let end = begin.wrapping_add_sized(length, address_size);
551                Range { begin, end }
552            }
553            RawRngListEntry::AddressOrOffsetPair { begin, end }
554            | RawRngListEntry::OffsetPair { begin, end } => {
555                // Skip tombstone entries (see below).
556                if self.base_address >= u64::min_tombstone(address_size) {
557                    return Ok(None);
558                }
559                let mut range = Range { begin, end };
560                range.add_base_address(self.base_address, address_size);
561                range
562            }
563            RawRngListEntry::StartEnd { begin, end } => Range { begin, end },
564            RawRngListEntry::StartLength { begin, length } => {
565                let end = begin.wrapping_add_sized(length, address_size);
566                Range { begin, end }
567            }
568        };
569
570        // Skip tombstone entries.
571        //
572        // DWARF specifies a tombstone value of -1 or -2, but many linkers use 0 or 1.
573        // However, 0/1 may be a valid address, so we can't always reliably skip them.
574        // One case where we can skip them is for address pairs, where both values are
575        // replaced by tombstones and thus `begin` equals `end`. Since these entries
576        // are empty, it's safe to skip them even if they aren't tombstones.
577        //
578        // In addition to skipping tombstone entries, we also skip invalid entries
579        // where `begin` is greater than `end`. This can occur due to compiler bugs.
580        if range.begin >= u64::min_tombstone(address_size) || range.begin >= range.end {
581            return Ok(None);
582        }
583
584        Ok(Some(range))
585    }
586}
587
588#[cfg(feature = "fallible-iterator")]
589impl<R: Reader> fallible_iterator::FallibleIterator for RngListIter<R> {
590    type Item = Range;
591    type Error = Error;
592
593    fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
594        RngListIter::next(self)
595    }
596}
597
598impl<R: Reader> Iterator for RngListIter<R> {
599    type Item = Result<Range>;
600
601    fn next(&mut self) -> Option<Self::Item> {
602        RngListIter::next(self).transpose()
603    }
604}
605
606/// A raw address range from the `.debug_ranges` section.
607#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
608pub(crate) struct RawRange {
609    /// The beginning address of the range.
610    pub begin: u64,
611
612    /// The first address past the end of the range.
613    pub end: u64,
614}
615
616impl RawRange {
617    /// Check if this is a range end entry.
618    #[inline]
619    pub fn is_end(&self) -> bool {
620        self.begin == 0 && self.end == 0
621    }
622
623    /// Check if this is a base address selection entry.
624    ///
625    /// A base address selection entry changes the base address that subsequent
626    /// range entries are relative to.
627    #[inline]
628    pub fn is_base_address(&self, address_size: u8) -> bool {
629        self.begin == !0 >> (64 - address_size * 8)
630    }
631
632    /// Parse an address range entry from `.debug_ranges` or `.debug_loc`.
633    #[inline]
634    pub fn parse<R: Reader>(input: &mut R, address_size: u8) -> Result<RawRange> {
635        let begin = input.read_address(address_size)?;
636        let end = input.read_address(address_size)?;
637        let range = RawRange { begin, end };
638        Ok(range)
639    }
640}
641
642/// An address range from the `.debug_ranges`, `.debug_rnglists`, or `.debug_aranges` sections.
643#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
644pub struct Range {
645    /// The beginning address of the range.
646    pub begin: u64,
647
648    /// The first address past the end of the range.
649    pub end: u64,
650}
651
652impl Range {
653    /// Add a base address to this range.
654    #[inline]
655    pub(crate) fn add_base_address(&mut self, base_address: u64, address_size: u8) {
656        self.begin = base_address.wrapping_add_sized(self.begin, address_size);
657        self.end = base_address.wrapping_add_sized(self.end, address_size);
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use super::*;
664    use crate::common::Format;
665    use crate::constants::*;
666    use crate::endianity::LittleEndian;
667    use crate::test_util::GimliSectionMethods;
668    use alloc::vec::Vec;
669    use test_assembler::{Endian, Label, LabelMaker, Section};
670
671    #[test]
672    fn test_rnglists() {
673        let format = Format::Dwarf32;
674        for size in [4, 8] {
675            let tombstone = u64::ones_sized(size);
676            let tombstone_0 = 0;
677            let encoding = Encoding {
678                format,
679                version: 5,
680                address_size: size,
681            };
682            let section = Section::with_endian(Endian::Little)
683                .word(size, 0x0300_0000)
684                .word(size, 0x0301_0300)
685                .word(size, 0x0301_0400)
686                .word(size, 0x0301_0500)
687                .word(size, tombstone)
688                .word(size, 0x0301_0600)
689                .word(size, tombstone_0);
690            let buf = section.get_contents().unwrap();
691            let debug_addr = &DebugAddr::from(EndianSlice::new(&buf, LittleEndian));
692            let debug_addr_base = DebugAddrBase(0);
693
694            let length = Label::new();
695            let start = Label::new();
696            let first = Label::new();
697            let end = Label::new();
698            let mut section = Section::with_endian(Endian::Little)
699                .initial_length(format, &length, &start)
700                .L16(encoding.version)
701                .L8(encoding.address_size)
702                .L8(0)
703                .L32(0)
704                .mark(&first);
705
706            let mut expected_ranges = Vec::new();
707            let mut expect_range = |begin, end| {
708                expected_ranges.push(Range { begin, end });
709            };
710
711            // An offset pair using the unit base address.
712            section = section.L8(DW_RLE_offset_pair.0).uleb(0x10200).uleb(0x10300);
713            expect_range(0x0101_0200, 0x0101_0300);
714
715            section = section.L8(DW_RLE_base_address.0).word(size, 0x0200_0000);
716            section = section.L8(DW_RLE_offset_pair.0).uleb(0x10400).uleb(0x10500);
717            expect_range(0x0201_0400, 0x0201_0500);
718
719            section = section
720                .L8(DW_RLE_start_end.0)
721                .word(size, 0x201_0a00)
722                .word(size, 0x201_0b00);
723            expect_range(0x0201_0a00, 0x0201_0b00);
724
725            section = section
726                .L8(DW_RLE_start_length.0)
727                .word(size, 0x201_0c00)
728                .uleb(0x100);
729            expect_range(0x0201_0c00, 0x0201_0d00);
730
731            // An offset pair that starts at 0.
732            section = section.L8(DW_RLE_base_address.0).word(size, 0);
733            section = section.L8(DW_RLE_offset_pair.0).uleb(0).uleb(1);
734            expect_range(0, 1);
735
736            // An offset pair that ends at -1.
737            section = section.L8(DW_RLE_base_address.0).word(size, 0);
738            section = section.L8(DW_RLE_offset_pair.0).uleb(0).uleb(tombstone);
739            expect_range(0, tombstone);
740
741            section = section.L8(DW_RLE_base_addressx.0).uleb(0);
742            section = section.L8(DW_RLE_offset_pair.0).uleb(0x10100).uleb(0x10200);
743            expect_range(0x0301_0100, 0x0301_0200);
744
745            section = section.L8(DW_RLE_startx_endx.0).uleb(1).uleb(2);
746            expect_range(0x0301_0300, 0x0301_0400);
747
748            section = section.L8(DW_RLE_startx_length.0).uleb(3).uleb(0x100);
749            expect_range(0x0301_0500, 0x0301_0600);
750
751            // Tombstone entries, all of which should be ignored.
752            section = section.L8(DW_RLE_base_addressx.0).uleb(4);
753            section = section.L8(DW_RLE_offset_pair.0).uleb(0x11100).uleb(0x11200);
754
755            section = section.L8(DW_RLE_base_address.0).word(size, tombstone);
756            section = section.L8(DW_RLE_offset_pair.0).uleb(0x11300).uleb(0x11400);
757
758            section = section.L8(DW_RLE_startx_endx.0).uleb(4).uleb(5);
759            section = section.L8(DW_RLE_startx_length.0).uleb(4).uleb(0x100);
760            section = section
761                .L8(DW_RLE_start_end.0)
762                .word(size, tombstone)
763                .word(size, 0x201_1500);
764            section = section
765                .L8(DW_RLE_start_length.0)
766                .word(size, tombstone)
767                .uleb(0x100);
768
769            // Ignore some instances of 0 for tombstone.
770            section = section.L8(DW_RLE_startx_endx.0).uleb(6).uleb(6);
771            section = section
772                .L8(DW_RLE_start_end.0)
773                .word(size, tombstone_0)
774                .word(size, tombstone_0);
775
776            // Ignore empty ranges.
777            section = section.L8(DW_RLE_base_address.0).word(size, 0);
778            section = section.L8(DW_RLE_offset_pair.0).uleb(0).uleb(0);
779            section = section.L8(DW_RLE_base_address.0).word(size, 0x10000);
780            section = section.L8(DW_RLE_offset_pair.0).uleb(0x1234).uleb(0x1234);
781
782            // A valid range after the tombstones.
783            section = section
784                .L8(DW_RLE_start_end.0)
785                .word(size, 0x201_1600)
786                .word(size, 0x201_1700);
787            expect_range(0x0201_1600, 0x0201_1700);
788
789            section = section.L8(DW_RLE_end_of_list.0);
790            section = section.mark(&end);
791            // Some extra data.
792            section = section.word(size, 0x1234_5678);
793            length.set_const((&end - &start) as u64);
794
795            let offset = RangeListsOffset((&first - &section.start()) as usize);
796            let buf = section.get_contents().unwrap();
797            let debug_ranges = DebugRanges::new(&[], LittleEndian);
798            let debug_rnglists = DebugRngLists::new(&buf, LittleEndian);
799            let rnglists = RangeLists::new(debug_ranges, debug_rnglists);
800            let mut ranges = rnglists
801                .ranges(offset, encoding, 0x0100_0000, debug_addr, debug_addr_base)
802                .unwrap();
803
804            for expected_range in expected_ranges {
805                let range = ranges.next();
806                assert_eq!(
807                    range,
808                    Ok(Some(expected_range)),
809                    "read {:x?}, expect {:x?}",
810                    range,
811                    expected_range
812                );
813            }
814            assert_eq!(ranges.next(), Ok(None));
815
816            // An offset at the end of buf.
817            let mut ranges = rnglists
818                .ranges(
819                    RangeListsOffset(buf.len()),
820                    encoding,
821                    0x0100_0000,
822                    debug_addr,
823                    debug_addr_base,
824                )
825                .unwrap();
826            assert_eq!(ranges.next(), Ok(None));
827        }
828    }
829
830    #[test]
831    fn test_raw_range() {
832        let range = RawRange {
833            begin: 0,
834            end: 0xffff_ffff,
835        };
836        assert!(!range.is_end());
837        assert!(!range.is_base_address(4));
838        assert!(!range.is_base_address(8));
839
840        let range = RawRange { begin: 0, end: 0 };
841        assert!(range.is_end());
842        assert!(!range.is_base_address(4));
843        assert!(!range.is_base_address(8));
844
845        let range = RawRange {
846            begin: 0xffff_ffff,
847            end: 0,
848        };
849        assert!(!range.is_end());
850        assert!(range.is_base_address(4));
851        assert!(!range.is_base_address(8));
852
853        let range = RawRange {
854            begin: 0xffff_ffff_ffff_ffff,
855            end: 0,
856        };
857        assert!(!range.is_end());
858        assert!(!range.is_base_address(4));
859        assert!(range.is_base_address(8));
860    }
861
862    #[test]
863    fn test_ranges() {
864        for size in [4, 8] {
865            let base = u64::ones_sized(size);
866            let tombstone = u64::ones_sized(size) - 1;
867            let start = Label::new();
868            let first = Label::new();
869            let mut section = Section::with_endian(Endian::Little)
870                // A range before the offset.
871                .mark(&start)
872                .word(size, 0x10000)
873                .word(size, 0x10100)
874                .mark(&first);
875
876            let mut expected_ranges = Vec::new();
877            let mut expect_range = |begin, end| {
878                expected_ranges.push(Range { begin, end });
879            };
880
881            // A normal range.
882            section = section.word(size, 0x10200).word(size, 0x10300);
883            expect_range(0x0101_0200, 0x0101_0300);
884            // A base address selection followed by a normal range.
885            section = section.word(size, base).word(size, 0x0200_0000);
886            section = section.word(size, 0x10400).word(size, 0x10500);
887            expect_range(0x0201_0400, 0x0201_0500);
888            // An empty range followed by a normal range.
889            section = section.word(size, 0x10600).word(size, 0x10600);
890            section = section.word(size, 0x10800).word(size, 0x10900);
891            expect_range(0x0201_0800, 0x0201_0900);
892            // A range that starts at 0.
893            section = section.word(size, base).word(size, 0);
894            section = section.word(size, 0).word(size, 1);
895            expect_range(0, 1);
896            // A range that ends at -1.
897            section = section.word(size, base).word(size, 0);
898            section = section.word(size, 0).word(size, base);
899            expect_range(0, base);
900            // A normal range with tombstone.
901            section = section.word(size, tombstone).word(size, tombstone);
902            // A base address selection with tombstone followed by a normal range.
903            section = section.word(size, base).word(size, tombstone);
904            section = section.word(size, 0x10a00).word(size, 0x10b00);
905            // A range end.
906            section = section.word(size, 0).word(size, 0);
907            // Some extra data.
908            section = section.word(size, 0x1234_5678);
909
910            let buf = section.get_contents().unwrap();
911            let debug_ranges = DebugRanges::new(&buf, LittleEndian);
912            let debug_rnglists = DebugRngLists::new(&[], LittleEndian);
913            let rnglists = RangeLists::new(debug_ranges, debug_rnglists);
914            let offset = RangeListsOffset((&first - &start) as usize);
915            let debug_addr = &DebugAddr::from(EndianSlice::new(&[], LittleEndian));
916            let debug_addr_base = DebugAddrBase(0);
917            let encoding = Encoding {
918                format: Format::Dwarf32,
919                version: 4,
920                address_size: size,
921            };
922            let mut ranges = rnglists
923                .ranges(offset, encoding, 0x0100_0000, debug_addr, debug_addr_base)
924                .unwrap();
925
926            for expected_range in expected_ranges {
927                let range = ranges.next();
928                assert_eq!(
929                    range,
930                    Ok(Some(expected_range)),
931                    "read {:x?}, expect {:x?}",
932                    range,
933                    expected_range
934                );
935            }
936            assert_eq!(ranges.next(), Ok(None));
937
938            // An offset at the end of buf.
939            let mut ranges = rnglists
940                .ranges(
941                    RangeListsOffset(buf.len()),
942                    encoding,
943                    0x0100_0000,
944                    debug_addr,
945                    debug_addr_base,
946                )
947                .unwrap();
948            assert_eq!(ranges.next(), Ok(None));
949        }
950    }
951
952    #[test]
953    fn test_ranges_invalid() {
954        #[rustfmt::skip]
955        let section = Section::with_endian(Endian::Little)
956            // An invalid range.
957            .L32(0x20000).L32(0x10000)
958            // An invalid range after wrapping.
959            .L32(0x20000).L32(0xff01_0000);
960
961        let buf = section.get_contents().unwrap();
962        let debug_ranges = DebugRanges::new(&buf, LittleEndian);
963        let debug_rnglists = DebugRngLists::new(&[], LittleEndian);
964        let rnglists = RangeLists::new(debug_ranges, debug_rnglists);
965        let debug_addr = &DebugAddr::from(EndianSlice::new(&[], LittleEndian));
966        let debug_addr_base = DebugAddrBase(0);
967        let encoding = Encoding {
968            format: Format::Dwarf32,
969            version: 4,
970            address_size: 4,
971        };
972
973        // An invalid range.
974        let mut ranges = rnglists
975            .ranges(
976                RangeListsOffset(0x0),
977                encoding,
978                0x0100_0000,
979                debug_addr,
980                debug_addr_base,
981            )
982            .unwrap();
983        assert_eq!(ranges.next(), Ok(None));
984
985        // An invalid range after wrapping.
986        let mut ranges = rnglists
987            .ranges(
988                RangeListsOffset(0x8),
989                encoding,
990                0x0100_0000,
991                debug_addr,
992                debug_addr_base,
993            )
994            .unwrap();
995        assert_eq!(ranges.next(), Ok(None));
996
997        // An invalid offset.
998        match rnglists.ranges(
999            RangeListsOffset(buf.len() + 1),
1000            encoding,
1001            0x0100_0000,
1002            debug_addr,
1003            debug_addr_base,
1004        ) {
1005            Err(Error::UnexpectedEof(_)) => {}
1006            otherwise => panic!("Unexpected result: {:?}", otherwise),
1007        }
1008    }
1009
1010    #[test]
1011    fn test_get_offset() {
1012        for format in [Format::Dwarf32, Format::Dwarf64] {
1013            let encoding = Encoding {
1014                format,
1015                version: 5,
1016                address_size: 4,
1017            };
1018
1019            let zero = Label::new();
1020            let length = Label::new();
1021            let start = Label::new();
1022            let first = Label::new();
1023            let end = Label::new();
1024            let mut section = Section::with_endian(Endian::Little)
1025                .mark(&zero)
1026                .initial_length(format, &length, &start)
1027                .D16(encoding.version)
1028                .D8(encoding.address_size)
1029                .D8(0)
1030                .D32(20)
1031                .mark(&first);
1032            for i in 0..20 {
1033                section = section.word(format.word_size(), 1000 + i);
1034            }
1035            section = section.mark(&end);
1036            length.set_const((&end - &start) as u64);
1037            let section = section.get_contents().unwrap();
1038
1039            let debug_ranges = DebugRanges::from(EndianSlice::new(&[], LittleEndian));
1040            let debug_rnglists = DebugRngLists::from(EndianSlice::new(&section, LittleEndian));
1041            let ranges = RangeLists::new(debug_ranges, debug_rnglists);
1042
1043            let base = DebugRngListsBase((&first - &zero) as usize);
1044            assert_eq!(
1045                ranges.get_offset(encoding, base, DebugRngListsIndex(0)),
1046                Ok(RangeListsOffset(base.0 + 1000))
1047            );
1048            assert_eq!(
1049                ranges.get_offset(encoding, base, DebugRngListsIndex(19)),
1050                Ok(RangeListsOffset(base.0 + 1019))
1051            );
1052        }
1053    }
1054}