gimli/read/
loclists.rs

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