gimli 0.34.0

A library for reading and writing the DWARF debugging format.
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
use crate::common::{DebugInfoOffset, Format, SectionId};
use crate::constants::GdbIndexSymbolKind;
use crate::endianity::Endianity;
use crate::read::lookup::{DebugPubSet, PubSet, PubSetEntry, PubSetEntryIter, PubSetIter};
use crate::read::{EndianSlice, Reader, Result, Section, UnitOffset};

/// The `DebugPubNames` struct represents the DWARF public names information
/// found in the `.debug_pubnames` section.
#[derive(Debug, Clone)]
pub struct DebugPubNames<R: Reader>(DebugPubSet<R>);

impl<'input, Endian> DebugPubNames<EndianSlice<'input, Endian>>
where
    Endian: Endianity,
{
    /// Construct a new `DebugPubNames` instance from the data in the `.debug_pubnames`
    /// section.
    ///
    /// It is the caller's responsibility to read the `.debug_pubnames` section and
    /// present it as a `&[u8]` slice. That means using some ELF loader on
    /// Linux, a Mach-O loader on macOS, etc.
    ///
    /// ```
    /// use gimli::{DebugPubNames, LittleEndian};
    ///
    /// # let buf = [];
    /// # let read_debug_pubnames_section_somehow = || &buf;
    /// let debug_pubnames =
    ///     DebugPubNames::new(read_debug_pubnames_section_somehow(), LittleEndian);
    /// ```
    pub fn new(section: &'input [u8], endian: Endian) -> Self {
        Self::from(EndianSlice::new(section, endian))
    }
}

impl<R: Reader> DebugPubNames<R> {
    /// Iterate the pubnames in the `.debug_pubnames` section.
    ///
    /// ```
    /// use gimli::{DebugPubNames, EndianSlice, LittleEndian};
    ///
    /// # let buf = [];
    /// # let read_debug_pubnames_section_somehow = || &buf;
    /// let debug_pubnames =
    ///     DebugPubNames::new(read_debug_pubnames_section_somehow(), LittleEndian);
    ///
    /// let mut iter = debug_pubnames.items();
    /// while let Some(pubname) = iter.next().unwrap() {
    ///   println!("pubname {} found!", pubname.name().to_string_lossy());
    /// }
    /// ```
    pub fn items(&self) -> PubNamesEntryIter<R> {
        PubNamesEntryIter(self.0.items(false))
    }

    /// Iterate the sets of entries in the `.debug_pubnames` section.
    ///
    /// Each set corresponds to a single unit, and contains the header for that
    /// unit followed by its entries.
    pub fn sets(&self) -> PubNamesSetIter<R> {
        PubNamesSetIter(self.0.sets(false))
    }
}

impl<R: Reader> Section<R> for DebugPubNames<R> {
    fn id() -> SectionId {
        SectionId::DebugPubNames
    }

    fn reader(&self) -> &R {
        &self.0.section
    }
}

impl<R: Reader> From<R> for DebugPubNames<R> {
    fn from(section: R) -> Self {
        DebugPubNames(DebugPubSet { section })
    }
}

/// The `DebugGnuPubNames` struct represents the DWARF public names information
/// found in the `.debug_gnu_pubnames` section.
#[derive(Debug, Clone)]
pub struct DebugGnuPubNames<R: Reader>(DebugPubSet<R>);

impl<'input, Endian> DebugGnuPubNames<EndianSlice<'input, Endian>>
where
    Endian: Endianity,
{
    /// Construct a new `DebugGnuPubNames` instance from the data in the `.debug_gnu_pubnames`
    /// section.
    ///
    /// It is the caller's responsibility to read the `.debug_gnu_pubnames` section and
    /// present it as a `&[u8]` slice. That means using some ELF loader on
    /// Linux, a Mach-O loader on macOS, etc.
    ///
    /// ```
    /// use gimli::{DebugGnuPubNames, LittleEndian};
    ///
    /// # let buf = [];
    /// # let read_debug_gnu_pubnames_section_somehow = || &buf;
    /// let debug_gnu_pubnames =
    ///     DebugGnuPubNames::new(read_debug_gnu_pubnames_section_somehow(), LittleEndian);
    /// ```
    pub fn new(section: &'input [u8], endian: Endian) -> Self {
        Self::from(EndianSlice::new(section, endian))
    }
}

impl<R: Reader> DebugGnuPubNames<R> {
    /// Iterate the pubnames in the `.debug_gnu_pubnames` section.
    ///
    /// ```
    /// use gimli::{DebugGnuPubNames, EndianSlice, LittleEndian};
    ///
    /// # let buf = [];
    /// # let read_debug_gnu_pubnames_section_somehow = || &buf;
    /// let debug_gnu_pubnames =
    ///     DebugGnuPubNames::new(read_debug_gnu_pubnames_section_somehow(), LittleEndian);
    ///
    /// let mut iter = debug_gnu_pubnames.items();
    /// while let Some(pubname) = iter.next().unwrap() {
    ///   println!("pubname {} found!", pubname.name().to_string_lossy());
    /// }
    /// ```
    pub fn items(&self) -> PubNamesEntryIter<R> {
        PubNamesEntryIter(self.0.items(true))
    }

    /// Iterate the sets of entries in the `.debug_gnu_pubnames` section.
    ///
    /// Each set corresponds to a single unit, and contains the header for that
    /// unit followed by its entries.
    pub fn sets(&self) -> PubNamesSetIter<R> {
        PubNamesSetIter(self.0.sets(true))
    }
}

impl<R: Reader> Section<R> for DebugGnuPubNames<R> {
    fn id() -> SectionId {
        SectionId::DebugGnuPubNames
    }

    fn reader(&self) -> &R {
        &self.0.section
    }
}

impl<R: Reader> From<R> for DebugGnuPubNames<R> {
    fn from(section: R) -> Self {
        DebugGnuPubNames(DebugPubSet { section })
    }
}

/// An iterator over the pubnames from a `.debug_pubnames` or `.debug_gnu_pubnames` section.
#[derive(Debug, Clone)]
pub struct PubNamesSetIter<R: Reader>(PubSetIter<R>);

impl<R: Reader> PubNamesSetIter<R> {
    /// Advance the iterator and return the next set.
    ///
    /// Returns the newly parsed set as `Ok(Some(set))`. Returns `Ok(None)` when
    /// iteration is complete. If an error occurs while parsing the next header,
    /// then this error is returned as `Err(e)`, and all subsequent calls return
    /// `Ok(None)`.
    pub fn next(&mut self) -> Result<Option<PubNamesSet<R>>> {
        self.0.next().map(|x| x.map(PubNamesSet))
    }
}

#[cfg(feature = "fallible-iterator")]
impl<R: Reader> fallible_iterator::FallibleIterator for PubNamesSetIter<R> {
    type Item = PubNamesSet<R>;
    type Error = crate::read::Error;

    fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
        self.next()
    }
}

impl<R: Reader> Iterator for PubNamesSetIter<R> {
    type Item = Result<PubNamesSet<R>>;

    fn next(&mut self) -> Option<Self::Item> {
        self.next().transpose()
    }
}

/// A set of entries that share a header in a `.debug_pubnames` or `.debug_gnu_pubnames` section.
///
/// These entries all belong to a single unit.
#[derive(Debug, Clone)]
pub struct PubNamesSet<R: Reader>(PubSet<R>);

impl<R: Reader> PubNamesSet<R> {
    /// Returns the offset into the `.debug_info` section for the header of the
    /// compilation unit which contains these names.
    pub fn unit_header_offset(&self) -> DebugInfoOffset<R::Offset> {
        self.0.header.unit_offset
    }

    /// Returns the length of the compilation unit in the `.debug_info` section
    /// which contains these names.
    pub fn unit_length(&self) -> R::Offset {
        self.0.header.unit_length
    }

    /// Returns the version of the set.
    pub fn version(&self) -> u16 {
        self.0.header.version
    }

    /// Returns the DWARF format of the set.
    pub fn format(&self) -> Format {
        self.0.header.format
    }

    /// Returns the length of the set, including the header.
    pub fn length(&self) -> R::Offset {
        self.0.header.length
    }

    /// Iterate the entries in this set.
    pub fn items(&self) -> PubNamesEntryIter<R> {
        PubNamesEntryIter(self.0.items())
    }
}

/// An iterator over the pubnames from a `.debug_pubnames` or `.debug_gnu_pubnames` section.
#[derive(Debug, Clone)]
pub struct PubNamesEntryIter<R: Reader>(PubSetEntryIter<R>);

impl<R: Reader> PubNamesEntryIter<R> {
    /// Advance the iterator and return the next pubname.
    ///
    /// Returns the newly parsed pubname as `Ok(Some(pubname))`. Returns
    /// `Ok(None)` when iteration is complete and all pubnames have already been
    /// parsed and yielded. If an error occurs while parsing the next pubname,
    /// then this error is returned as `Err(e)`, and all subsequent calls return
    /// `Ok(None)`.
    pub fn next(&mut self) -> Result<Option<PubNamesEntry<R>>> {
        self.0.next().map(|x| x.map(PubNamesEntry))
    }
}

#[cfg(feature = "fallible-iterator")]
impl<R: Reader> fallible_iterator::FallibleIterator for PubNamesEntryIter<R> {
    type Item = PubNamesEntry<R>;
    type Error = crate::read::Error;

    fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
        self.next()
    }
}

impl<R: Reader> Iterator for PubNamesEntryIter<R> {
    type Item = Result<PubNamesEntry<R>>;

    fn next(&mut self) -> Option<Self::Item> {
        self.next().transpose()
    }
}

/// A single parsed pubname.
#[derive(Debug, Clone)]
pub struct PubNamesEntry<R: Reader>(PubSetEntry<R>);

impl<R: Reader> PubNamesEntry<R> {
    /// Returns the name this entry refers to.
    pub fn name(&self) -> &R {
        &self.0.name
    }

    /// Returns the offset into the .debug_info section for the header of the compilation unit
    /// which contains this name.
    pub fn unit_header_offset(&self) -> DebugInfoOffset<R::Offset> {
        self.0.unit_header_offset
    }

    /// Returns the offset into the compilation unit for the debugging information entry which
    /// has this name.
    pub fn die_offset(&self) -> UnitOffset<R::Offset> {
        self.0.die_offset
    }

    /// Return the symbol kind.
    ///
    /// The compiler derives this from the tag of the DIE.
    ///
    /// Only .debug_gnu_pubnames entries contain this value.
    /// Always returns `GDB_INDEX_SYMBOL_KIND_NONE` for a .debug_pubnames entry.
    pub fn kind(&self) -> GdbIndexSymbolKind {
        self.0.kind()
    }

    /// Return true if the symbol is static.
    ///
    /// Always returns false for a .debug_pubnames entry.
    pub fn is_static(&self) -> bool {
        self.0.is_static()
    }

    /// Return flags.
    ///
    /// Only .debug_gnu_pubnames entries contain this value.
    pub fn flags(&self) -> u8 {
        self.0.flags()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::DebugInfoOffset;
    use crate::constants::*;
    use crate::test_util::GimliSectionMethods;
    use crate::{Format, LittleEndian};
    use test_assembler::{Endian, Label, LabelMaker, Section};

    #[test]
    fn test_pubnames() {
        for format in [Format::Dwarf32, Format::Dwarf64] {
            let size = format.word_size();

            // Set 1, with two entries.
            let length = Label::new();
            let start = Label::new();
            let section = Section::with_endian(Endian::Little)
                .initial_length(format, &length, &start)
                .D16(2) // Version
                .word(size, 0x10) // Unit header offset
                .word(size, 0x20) // Unit length
                // Entry 1
                .word(size, 0x02) // DIE offset
                .append_bytes(b"foo\0")
                // Entry 2
                .word(size, 0x04) // DIE offset
                .append_bytes(b"bar\0")
                // Null entry
                .word(size, 0)
                .set_initial_length(&length, &start);

            // Set 2, with one entry.
            let length = Label::new();
            let start = Label::new();
            let section = section
                .initial_length(format, &length, &start)
                .D16(2) // Version
                .word(size, 0x40) // Unit header offset
                .word(size, 0x30) // Unit length
                // Entry 1
                .word(size, 0x06) // DIE offset
                .append_bytes(b"baz\0")
                // Null entry
                .word(size, 0)
                .set_initial_length(&length, &start);

            let section = section.get_contents().unwrap();
            let debug_pubnames = DebugPubNames::new(&section, LittleEndian);

            // Iterate all entries.
            let mut items = debug_pubnames.items();

            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"foo", LittleEndian));
            assert_eq!(entry.unit_header_offset(), DebugInfoOffset(0x10));
            assert_eq!(entry.die_offset(), UnitOffset(0x02));
            assert_eq!(entry.kind(), GDB_INDEX_SYMBOL_KIND_NONE);
            assert!(!entry.is_static());

            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"bar", LittleEndian));
            assert_eq!(entry.unit_header_offset(), DebugInfoOffset(0x10));
            assert_eq!(entry.die_offset(), UnitOffset(0x04));

            // Iteration continues into the next set.
            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"baz", LittleEndian));
            assert_eq!(entry.unit_header_offset(), DebugInfoOffset(0x40));
            assert_eq!(entry.die_offset(), UnitOffset(0x06));

            assert!(matches!(items.next(), Ok(None)));

            // Iterate entries within sets.
            let mut sets = debug_pubnames.sets();

            // Set 1.
            let set = sets.next().unwrap().unwrap();
            assert_eq!(set.version(), 2);
            assert_eq!(set.format(), format);
            assert_eq!(set.unit_header_offset(), DebugInfoOffset(0x10));
            assert_eq!(set.unit_length(), 0x20);

            let mut items = set.items();
            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"foo", LittleEndian));
            assert_eq!(entry.die_offset(), UnitOffset(0x02));
            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"bar", LittleEndian));
            assert_eq!(entry.die_offset(), UnitOffset(0x04));
            // Iteration stops at the end of this set.
            assert!(matches!(items.next(), Ok(None)));

            // Set 2.
            let set = sets.next().unwrap().unwrap();
            assert_eq!(set.unit_header_offset(), DebugInfoOffset(0x40));
            assert_eq!(set.unit_length(), 0x30);

            let mut items = set.items();
            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"baz", LittleEndian));
            assert_eq!(entry.die_offset(), UnitOffset(0x06));
            assert!(matches!(items.next(), Ok(None)));

            assert!(matches!(sets.next(), Ok(None)));
        }
    }

    #[test]
    fn test_gnu_pubnames() {
        for format in [Format::Dwarf32, Format::Dwarf64] {
            let size = format.word_size();

            let length = Label::new();
            let start = Label::new();
            let section = Section::with_endian(Endian::Little)
                .initial_length(format, &length, &start)
                .D16(2) // Version
                .word(size, 0x10) // Unit header offset
                .word(size, 0x20) // Unit length
                // Entry 1
                .word(size, 0x02)
                .D8(0xb0) // static (0x80) | function (3 << 4) = 0xb0.
                .append_bytes(b"foo\0")
                // Entry 2
                .word(size, 0x04)
                .D8(0x20) // global (0x00) | variable (2 << 4) = 0x20.
                .append_bytes(b"bar\0")
                // Null entry
                .word(size, 0)
                .set_initial_length(&length, &start);

            let section = section.get_contents().unwrap();
            let debug_gnu_pubnames = DebugGnuPubNames::new(&section, LittleEndian);
            let mut items = debug_gnu_pubnames.items();

            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"foo", LittleEndian));
            assert_eq!(entry.unit_header_offset(), DebugInfoOffset(0x10));
            assert_eq!(entry.die_offset(), UnitOffset(0x02));
            assert_eq!(entry.kind(), GDB_INDEX_SYMBOL_KIND_FUNCTION);
            assert!(entry.is_static());
            assert_eq!(entry.flags(), 0xb0);

            let entry = items.next().unwrap().unwrap();
            assert_eq!(entry.name(), &EndianSlice::new(b"bar", LittleEndian));
            assert_eq!(entry.kind(), GDB_INDEX_SYMBOL_KIND_VARIABLE);
            assert!(!entry.is_static());
            assert_eq!(entry.flags(), 0x20);

            assert!(matches!(items.next(), Ok(None)));
        }
    }
}