isr-dwarf 0.5.0

DWARF parser for ISR
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! DWARF type extraction.

use gimli::{
    Attribute, DebuggingInformationEntry, EntriesTree, EntriesTreeNode, Error, Reader as _, UnitRef,
};
use indexmap::map::Entry;
use isr_core::schema::{
    Array, Base, Bitfield, Enum, EnumRef, Field, Pointer, Profile, Struct, StructKind, StructRef,
    Type, Variant,
};

use super::_gimli::{DebuggingInformationEntryExt as _, Reader};

fn type_name<'data>(
    unit: &UnitRef<Reader<'data>>,
    entry: &DebuggingInformationEntry<Reader<'data>>,
) -> Result<String, Error> {
    match entry.name(unit)? {
        Some(name) => Ok(name),
        None => {
            let offset = entry.offset().to_unit_section_offset(unit).0;
            Ok(format!("__unnamed_{:x}", offset))
        }
    }
}

/// Deduplication cache keyed by `(name, byte_size, encoding)` for base types.
pub type DwarfCache = std::collections::HashSet<(String, u64, u64)>;

/// Populates a [`Profile`] with types extracted from DWARF units.
pub trait DwarfTypes<'data>
where
    Self: Sized,
{
    /// Walks a compilation unit and adds all type DIEs into `self`.
    fn add(&mut self, unit: &UnitRef<Reader<'data>>, cache: &mut DwarfCache) -> Result<(), Error>;

    /// Adds an enumeration DIE and its variants.
    fn add_enum(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error>;

    /// Adds a struct/union/class DIE and its fields.
    fn add_struct(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
        kind: StructKind,
    ) -> Result<(), Error>;
}

trait DwarfStruct<'data> {
    fn add_fields(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error>;

    fn add_field(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error>;
}

trait DwarfEnum<'data> {
    fn add_fields(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error>;

    fn add_field(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error>;
}

trait DwarfType<'data>
where
    Self: Sized,
{
    fn new(
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<Self, Error>;

    fn from_type(
        unit: &UnitRef<Reader<'data>>,
        type_: EntriesTree<Reader<'data>>,
    ) -> Result<Self, Error>;
}

impl<'data> DwarfTypes<'data> for Profile {
    fn add(&mut self, unit: &UnitRef<Reader<'data>>, cache: &mut DwarfCache) -> Result<(), Error> {
        let mut tree = unit.entries_tree(None)?;
        let mut children = tree.root()?.children();

        while let Some(child) = children.next()? {
            if !matches!(
                child.entry().tag(),
                gimli::DW_TAG_enumeration_type
                    | gimli::DW_TAG_structure_type
                    | gimli::DW_TAG_union_type
            ) {
                continue;
            }

            if child.entry().declaration()?.unwrap_or(false) {
                continue;
            }

            let decl_file = child.entry().decl_file(unit)?;
            let decl_line = child.entry().decl_line()?;
            let decl_column = child.entry().decl_column()?;

            match (decl_file, decl_line, decl_column) {
                (Some(decl_file), Some(decl_line), Some(decl_column)) => {
                    if !cache.insert((decl_file, decl_line, decl_column)) {
                        continue;
                    }
                }
                _ => {
                    let name = type_name(unit, child.entry())?;
                    tracing::warn!(%name, "missing declaration information");
                }
            }

            match child.entry().tag() {
                gimli::DW_TAG_enumeration_type => self.add_enum(unit, child)?,
                gimli::DW_TAG_structure_type => self.add_struct(unit, child, StructKind::Struct)?,
                gimli::DW_TAG_union_type => self.add_struct(unit, child, StructKind::Union)?,

                // Skip other tags.
                _ => (),
            }
        }

        Ok(())
    }

    #[tracing::instrument(skip_all, err, fields(name))]
    fn add_enum(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error> {
        let name = type_name(unit, node.entry())?;
        tracing::Span::current().record("name", &*name);

        let type_ = match node.entry().type_(unit)? {
            Some(type_) => type_,
            None => {
                tracing::warn!("enum doesn't have a type");
                return Ok(());
            }
        };

        let mut new_enum = Enum {
            subtype: Type::from_type(unit, type_)?,
            fields: Default::default(),
        };

        new_enum.add_fields(unit, node)?;

        let new_enum_fields = new_enum.fields.len();

        match self.enums.entry(name.clone()) {
            Entry::Vacant(entry) => {
                entry.insert(new_enum);
            }
            Entry::Occupied(mut entry) => {
                let previous_udt = entry.get_mut();
                let previous_enum_fields = previous_udt.fields.len();

                if new_enum_fields > previous_enum_fields {
                    tracing::warn!(
                        %name,
                        new_enum_fields,
                        previous_enum_fields,
                        "duplicate enum name; overwriting"
                    );

                    *previous_udt = new_enum;
                }
            }
        }

        Ok(())
    }

    #[tracing::instrument(skip_all, err, fields(name))]
    fn add_struct(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
        kind: StructKind,
    ) -> Result<(), Error> {
        let name = type_name(unit, node.entry())?;
        tracing::Span::current().record("name", &*name);

        let mut new_udt = Struct {
            kind,
            size: node.entry().byte_size()?.unwrap_or(0),
            fields: Default::default(),
        };

        new_udt.add_fields(unit, node)?;

        let new_udt_fields = new_udt.fields.len();

        match self.structs.entry(name.clone()) {
            Entry::Vacant(entry) => {
                entry.insert(new_udt);
            }
            Entry::Occupied(mut entry) => {
                let previous_udt = entry.get_mut();
                let previous_udt_fields = previous_udt.fields.len();

                if new_udt_fields > previous_udt_fields {
                    tracing::warn!(
                        %name,
                        new_udt_fields,
                        previous_udt_fields,
                        "duplicate UDT name; overwriting"
                    );

                    *previous_udt = new_udt;
                }
            }
        }

        Ok(())
    }
}

impl<'data> DwarfStruct<'data> for Struct {
    fn add_fields(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error> {
        let mut children = node.children();

        while let Some(child) = children.next()? {
            if child.entry().tag() != gimli::DW_TAG_member {
                tracing::warn!(
                    tag = ?child.entry().tag(),
                    "unexpected tag (expected DW_TAG_member)"
                );

                continue;
            }

            self.add_field(unit, child)?;
        }

        Ok(())
    }

    #[tracing::instrument(skip_all, err, fields(name))]
    fn add_field(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error> {
        debug_assert_eq!(node.entry().tag(), gimli::DW_TAG_member);

        let name = match node.entry().name(unit)? {
            Some(name) => name,
            None => format!("__unnamed_field_{:x}", self.fields.len()),
        };
        tracing::Span::current().record("name", &name);

        let offset = match node.entry().data_member_location()? {
            Some(offset) => offset,
            None => match node.entry().data_bit_offset()? {
                Some(bit_offset) => bit_offset / 8,
                // Assume zero offset if no offset is found.
                None => 0,
            },
        };

        self.fields.insert(
            name,
            Field {
                offset,
                ty: Type::new(unit, node)?,
            },
        );

        Ok(())
    }
}

impl<'data> DwarfEnum<'data> for Enum {
    fn add_fields(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error> {
        let mut children = node.children();

        while let Some(child) = children.next()? {
            if child.entry().tag() != gimli::DW_TAG_enumerator {
                tracing::warn!(
                    tag = ?child.entry().tag(),
                    "unexpected tag (expected DW_TAG_enumerator)"
                );

                continue;
            }

            self.add_field(unit, child)?;
        }

        Ok(())
    }

    #[tracing::instrument(skip_all, err, fields(name))]
    fn add_field(
        &mut self,
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<(), Error> {
        debug_assert_eq!(node.entry().tag(), gimli::DW_TAG_enumerator);

        let name = match node.entry().name(unit)? {
            Some(name) => name,
            None => format!("__unnamed_{:x}", self.fields.len()),
        };
        tracing::Span::current().record("name", &name);

        let value = match node
            .entry()
            .attr(gimli::DW_AT_const_value)
            .map(Attribute::value)
        {
            Some(value) => {
                // TODO: assign correct type to variant.
                if let Some(value) = value.udata_value() {
                    Variant::U64(value)
                }
                else if let Some(value) = value.sdata_value() {
                    Variant::I64(value)
                }
                else {
                    tracing::warn!(?value, "enumerator has invalid value");
                    return Ok(());
                }
            }
            None => {
                tracing::warn!("enumerator doesn't have a value");
                return Ok(());
            }
        };

        self.fields.insert(name, value);

        Ok(())
    }
}

impl<'data> DwarfType<'data> for Type {
    fn new(
        unit: &UnitRef<Reader<'data>>,
        node: EntriesTreeNode<Reader<'data>>,
    ) -> Result<Self, Error> {
        let type_ = match node.entry().type_(unit)? {
            Some(type_) => type_,
            None => {
                // If the type is not found, it's probably a void type.
                return Ok(Self::Base(Base::Void));
            }
        };

        if let Some(bit_length) = node.entry().bit_size()? {
            let bit_position = node.entry().data_bit_offset()?.unwrap_or(0) % 8;

            return Ok(Self::Bitfield(Bitfield {
                bit_length,
                bit_position,
                subtype: Box::new(Self::from_type(unit, type_)?),
            }));
        }

        Self::from_type(unit, type_)
    }

    fn from_type(
        unit: &UnitRef<Reader<'data>>,
        mut type_: EntriesTree<Reader<'data>>,
    ) -> Result<Self, Error> {
        let node = type_.root()?;

        let result = match node.entry().tag() {
            gimli::DW_TAG_base_type => Self::Base(__type_from_base_type(unit, node)?),

            gimli::DW_TAG_enumeration_type => Self::Enum(EnumRef {
                name: type_name(unit, node.entry())?,
            }),

            gimli::DW_TAG_structure_type | gimli::DW_TAG_union_type => Self::Struct(StructRef {
                name: type_name(unit, node.entry())?,
            }),

            gimli::DW_TAG_array_type => Self::Array(__type_from_array_type(unit, type_)?),

            gimli::DW_TAG_pointer_type => {
                let size = node.entry().byte_size()?.unwrap_or(0);
                Self::Pointer(Pointer {
                    subtype: Box::new(Self::new(unit, node)?),
                    size,
                })
            }

            gimli::DW_TAG_subroutine_type => Self::Function,

            gimli::DW_TAG_typedef | gimli::DW_TAG_const_type | gimli::DW_TAG_volatile_type => {
                Self::new(unit, node)?
            }

            tag => {
                // dump_attrs(unit, node.entry())?;

                tracing::error!(?tag, "unexpected tag");
                Self::Base(Base::Void)
            }
        };

        Ok(result)
    }
}

#[tracing::instrument(skip_all, err, fields(name))]
fn __type_from_base_type<'data>(
    unit: &UnitRef<Reader<'data>>,
    node: EntriesTreeNode<Reader<'data>>,
) -> Result<Base, Error> {
    debug_assert_eq!(node.entry().tag(), gimli::DW_TAG_base_type);

    let name = type_name(unit, node.entry())?;
    tracing::Span::current().record("name", &*name);

    let byte_size = match node.entry().byte_size()? {
        Some(byte_size) => byte_size,
        None => {
            tracing::warn!("base type doesn't have a byte size");
            return Ok(Base::Void);
        }
    };

    if byte_size == 0 {
        return Ok(Base::Void);
    }

    let encoding = match node.entry().encoding()? {
        Some(encoding) => encoding,
        None => {
            tracing::warn!("base type doesn't have an encoding");
            return Ok(match byte_size {
                1 => Base::U8,
                2 => Base::U16,
                4 => Base::U32,
                8 => Base::U64,
                16 => Base::U128,
                _ => {
                    tracing::error!(byte_size, "unsupported base type");
                    Base::Void
                }
            });
        }
    };

    let result = match encoding {
        gimli::DW_ATE_boolean => match byte_size {
            1 => Base::Bool,
            _ => {
                tracing::error!(byte_size, "unsupported boolean base type");
                Base::Void
            }
        },
        gimli::DW_ATE_signed | gimli::DW_ATE_signed_char => match byte_size {
            1 => Base::I8,
            2 => Base::I16,
            4 => Base::I32,
            8 => Base::I64,
            16 => Base::I128,
            _ => {
                tracing::error!(byte_size, "unsupported signed base type");
                Base::Void
            }
        },
        gimli::DW_ATE_unsigned | gimli::DW_ATE_unsigned_char => match byte_size {
            1 => Base::U8,
            2 => Base::U16,
            4 => Base::U32,
            8 => Base::U64,
            16 => Base::U128,
            _ => {
                tracing::error!(byte_size, "unsupported unsigned base type");
                Base::Void
            }
        },
        gimli::DW_ATE_float => match byte_size {
            4 => Base::F32,
            8 => Base::F64,
            _ => {
                tracing::error!(byte_size, "unsupported float base type");
                Base::Void
            }
        },
        _ => match byte_size {
            1 => Base::U8,
            2 => Base::U16,
            4 => Base::U32,
            8 => Base::U64,
            16 => Base::U128,
            _ => {
                tracing::error!(?encoding, byte_size, "unsupported base type");
                Base::Void
            }
        },
    };

    Ok(result)
}

fn __type_from_array_type<'data>(
    unit: &UnitRef<Reader<'data>>,
    mut type_: EntriesTree<Reader<'data>>,
) -> Result<Array, Error> {
    let node = type_.root()?;
    debug_assert_eq!(node.entry().tag(), gimli::DW_TAG_array_type);

    let mut dims = Vec::new();
    let mut children = node.children();

    // Parse array dimensions.
    while let Some(child) = children.next()? {
        if child.entry().tag() != gimli::DW_TAG_subrange_type {
            continue;
        }

        let count = match child.entry().count()? {
            Some(count) => Some(count),

            // Old binaries may have an upper bound instead.
            None => child
                .entry()
                .upper_bound()?
                .map(|upper_bound| upper_bound + 1),
        };

        dims.push(count.unwrap_or(0));
    }

    // Parse the type again, since the node.children() iterator consumed the node.
    let node = type_.root()?;

    Ok(Array {
        subtype: Box::new(Type::new(unit, node)?),
        dims,
    })
}

fn __dump_attrs<'data>(
    unit: &UnitRef<Reader<'data>>,
    entry: &DebuggingInformationEntry<Reader<'data>>,
) -> Result<(), Error> {
    for attr in entry.attrs() {
        print!("   {}: {:?}", attr.name(), attr.value());
        if let Ok(s) = unit.attr_string(attr.value()) {
            print!(" '{}'", s.to_string_lossy()?);
        }
        println!();
    }

    Ok(())
}