~taiite/protodump

ref: a6c68980abe12cd53fe4a0ddb8a9b29e439f3906 protodump/src/types.rs -rw-r--r-- 16.0 KiB
a6c68980Hubert Hirtz Add doc comments 3 months ago
                                                                                
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
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::hash_map;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::rc::Rc;
use std::rc::Weak;

/// Description of how base types are encoded.
///
/// Enumeration version of `DW_AT_encoding` (see section 7.8).
#[derive(PartialEq)]
pub enum Encoding {
    Address,
    Boolean,
    ComplexFloat,
    Float,
    Signed,
    SignedChar,
    Unsigned,
    UnsignedChar,
    ImaginaryFloat,
    PackedDecimal,
    NumericString,
    Edited,
    SignedFixed,
    UnsignedFixed,
    DecimalFloat,
    Utf,
    User(gimli::DwAte),
}

impl TryFrom<gimli::DwAte> for Encoding {
    type Error = ();

    fn try_from(ate: gimli::DwAte) -> Result<Encoding, ()> {
        Ok(match ate.0 {
            0x01 => Encoding::Address,
            0x02 => Encoding::Boolean,
            0x03 => Encoding::ComplexFloat,
            0x04 => Encoding::Float,
            0x05 => Encoding::Signed,
            0x06 => Encoding::SignedChar,
            0x07 => Encoding::Unsigned,
            0x08 => Encoding::UnsignedChar,
            0x09 => Encoding::ImaginaryFloat,
            0x0a => Encoding::PackedDecimal,
            0x0b => Encoding::NumericString,
            0x0c => Encoding::Edited,
            0x0d => Encoding::SignedFixed,
            0x0e => Encoding::UnsignedFixed,
            0x0f => Encoding::DecimalFloat,
            0x10 => Encoding::Utf,
            0x80..=0xff => Encoding::User(ate),
            _ => return Err(()),
        })
    }
}

/// Member/field of a structure or an union.
#[derive(PartialEq)]
pub struct Member<R> {
    /// The name of the field, or [None] if the field is an anonymous/unamed
    /// structure or union.
    name: Option<R>,

    /// Location of the member in bytes starting from the beginning of the
    /// structure.
    ///
    /// The location of union fields is always zero.
    location: u64,

    type_: InstancePtr<R>,
}

/// Variant of an enumeration.
#[derive(PartialEq)]
pub struct Enumerator<R> {
    name: R,
    value: u64,
}

/// Definition of a type.
#[derive(PartialEq)]
pub enum Definition<R> {
    /// A primitive type.
    Base {
        byte_size: u64,
        encoding: Encoding,
    },

    Enumeration {
        byte_size: u64,
        encoding: Encoding,
        enumerators: Vec<Enumerator<R>>,
    },

    /// A callback or function type.
    Subroutine {
        return_type: Option<InstancePtr<R>>,
        parameters: Vec<InstancePtr<R>>,
    },

    Structure {
        members: Vec<Member<R>>,
    },

    Union {
        members: Vec<Member<R>>,
    },
}

impl<R> Definition<R> {
    /// Convenience function to use when you want a value of type [Definition]
    /// but don't care about it.
    fn dummy() -> Definition<R> {
        Definition::Base {
            byte_size: 0,
            encoding: Encoding::Address,
        }
    }
}

/// The information of a definition and its name.
///
/// The name might be [None] if the type is anonymous (e.g. defined where used)
pub struct Type<R> {
    name: Option<R>,
    definition: Definition<R>,
}

/// Pointer type for [Type] used through protodump in order to avoid copies.
pub type TypePtr<R> = Rc<RefCell<Type<R>>>;

/// Type modifier used in type [Instance]s.
// TODO add fields like pointer size, array count, etc.
#[derive(Copy, Clone, PartialEq)]
enum Modifier {
    Array,
    Const,
    Pointer,
    Reference,
    Restrict,
    Volatile,
}

impl Modifier {
    /// Whether a space must be added after the string representation of the
    /// modifier.
    pub fn needs_padding(self) -> bool {
        match self {
            Modifier::Array | Modifier::Pointer | Modifier::Reference => false,
            Modifier::Const | Modifier::Restrict | Modifier::Volatile => true,
        }
    }
}

/// An instance, appearance of a type with some modifiers.
pub struct Instance<R> {
    modifiers: Vec<Modifier>,
    underlying: Option<TypePtr<R>>,
    self_weak: Weak<RefCell<Instance<R>>>,
}

/// Pointer type for [Instance] used through protodump in order to avoid copies.
pub type InstancePtr<R> = Rc<RefCell<Instance<R>>>;

impl<R> PartialEq for Instance<R>
where
    R: PartialEq,
{
    fn eq(&self, other: &Instance<R>) -> bool {
        use std::collections::hash_map::Entry;

        thread_local! {
            static CACHE: RefCell<HashMap<(usize, usize), bool>> = RefCell::new(HashMap::new());
        }

        CACHE.with(|cache| {
            let self_addr = Weak::as_ptr(&self.self_weak) as usize;
            let other_addr = Weak::as_ptr(&other.self_weak) as usize;

            match cache.borrow_mut().entry((self_addr, other_addr)) {
                Entry::Vacant(entry) => entry.insert(true),
                Entry::Occupied(entry) => return *entry.get(),
            };

            let modifiers_eq = self.modifiers == other.modifiers;
            let underlying_eq = match (&self.underlying, &other.underlying) {
                (None, None) => true,
                (Some(_), None) | (None, Some(_)) => false,
                (Some(s), Some(o)) => s.borrow().name == o.borrow().name,
            };
            let is_eq = modifiers_eq && underlying_eq;

            cache.borrow_mut().insert((self_addr, other_addr), is_eq);
            is_eq
        })
    }
}

impl<R> fmt::Display for Instance<R>
where
    R: gimli::Reader,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.underlying {
            Some(underlying) => {
                let underlying = underlying.borrow();
                let name = match &underlying.name {
                    Some(raw_name) => raw_name.to_string_lossy().map_err(|_| fmt::Error)?,
                    None => Cow::Borrowed("_UNAMED_"),
                };
                match &underlying.definition {
                    Definition::Base { .. } => write!(f, "{}", name)?,
                    Definition::Enumeration { .. } => write!(f, "enum {}", name)?,
                    Definition::Subroutine {
                        return_type,
                        parameters,
                    } => {
                        if let Some(type_) = return_type {
                            let type_ = type_.borrow();
                            write!(f, "{}{}fn(", type_, type_.display_padding())?;
                        } else {
                            write!(f, "void fn(")?;
                        }
                        if let Some(param) = parameters.first() {
                            write!(f, "{}", param.borrow())?;
                            for param in &parameters[1..] {
                                write!(f, ", {}", param.borrow())?;
                            }
                        }
                        write!(f, ")")?;
                    }
                    Definition::Structure { .. } => write!(f, "struct {}", name)?,
                    Definition::Union { .. } => write!(f, "union {}", name)?,
                }
            }
            None => write!(f, "void")?,
        }
        // TODO don't put space on both end of pointers and refs
        let mut needs_padding = true;
        for modifier in self.modifiers.iter().rev() {
            if needs_padding {
                write!(f, " ")?;
            }
            match modifier {
                Modifier::Array => write!(f, "[]")?,
                Modifier::Const => write!(f, "const")?,
                Modifier::Pointer => write!(f, "*")?,
                Modifier::Reference => write!(f, "&")?,
                Modifier::Restrict => write!(f, "restrict")?,
                Modifier::Volatile => write!(f, "volatile")?,
            }
            needs_padding = modifier.needs_padding();
        }
        Ok(())
    }
}

impl<R> Instance<R> {
    /// Padding needed after the string representation of the instance.
    pub fn display_padding(&self) -> &'static str {
        let needs_padding = match self.modifiers.first() {
            Some(modifier) => modifier.needs_padding(),
            None => true,
        };
        if needs_padding {
            " "
        } else {
            ""
        }
    }
}

/// A type storage that holds all type instances and type definitions for a
/// single object file.
pub struct Cache<'a, R>
where
    R: gimli::Reader,
{
    dwarf: &'a gimli::Dwarf<R>,

    /// Map of type instances identified by where they appear in DWARF info.
    instances: HashMap<gimli::DebugInfoOffset<R::Offset>, InstancePtr<R>>,

    /// Map of type definitions identified by where they appear in DWARF info.
    definitions: HashMap<gimli::DebugInfoOffset<R::Offset>, TypePtr<R>>,
}

impl<'a, R> Cache<'a, R>
where
    R: gimli::Reader,
{
    pub fn new(dwarf: &'a gimli::Dwarf<R>) -> Cache<'a, R> {
        Cache {
            dwarf,
            instances: HashMap::new(),
            definitions: HashMap::new(),
        }
    }

    fn resolve_base_definition(
        &mut self,
        entry: &gimli::DebuggingInformationEntry<R>,
    ) -> gimli::Result<Definition<R>> {
        Ok(Definition::Base {
            byte_size: crate::dwarf::entry_byte_size(entry)?.unwrap(),
            encoding: crate::dwarf::entry_encoding(entry)?.unwrap(),
        })
    }

    fn resolve_enumeration_definition(
        &mut self,
        unit: &gimli::Unit<R>,
        entry: &gimli::DebuggingInformationEntry<R>,
    ) -> gimli::Result<Definition<R>> {
        let byte_size = crate::dwarf::entry_byte_size(entry)?.unwrap();
        let encoding = crate::dwarf::entry_encoding(entry)?.unwrap();

        // TODO also get underlying type?

        let mut enumerators = Vec::new();
        let mut children = crate::dwarf::entry_children(unit, entry)?;
        while let Some(child) = children.next()? {
            if child.tag() != gimli::DW_TAG_enumerator {
                continue;
            }
            let name = crate::dwarf::entry_name(self.dwarf, unit, child)?.unwrap();
            let value = crate::dwarf::entry_int_attr(child, gimli::DW_AT_const_value)?.unwrap();
            enumerators.push(Enumerator { name, value });
        }

        Ok(Definition::Enumeration {
            byte_size,
            encoding,
            enumerators,
        })
    }

    fn resolve_structure_definition(
        &mut self,
        unit: &gimli::Unit<R>,
        entry: &gimli::DebuggingInformationEntry<R>,
    ) -> gimli::Result<Definition<R>> {
        let mut members = Vec::new();
        let mut children = crate::dwarf::entry_children(unit, entry)?;
        while let Some(child) = children.next()? {
            if child.tag() != gimli::DW_TAG_member {
                continue;
            }
            let name = crate::dwarf::entry_name(self.dwarf, unit, child)?;
            let location =
                crate::dwarf::entry_int_attr(child, gimli::DW_AT_data_member_location)?.unwrap();
            let type_ = crate::dwarf::entry_type(self, unit, child)?.unwrap();
            members.push(Member {
                name,
                location,
                type_,
            })
        }
        Ok(Definition::Structure { members })
    }

    fn resolve_subroutine_definition(
        &mut self,
        unit: &gimli::Unit<R>,
        entry: &gimli::DebuggingInformationEntry<R>,
    ) -> gimli::Result<Definition<R>> {
        let return_type = crate::dwarf::entry_type(self, unit, entry)?;
        let mut parameters = Vec::new();
        let mut children = crate::dwarf::entry_children(unit, entry)?;
        while let Some(child) = children.next()? {
            if child.tag() != gimli::DW_TAG_formal_parameter {
                continue;
            }
            let type_ = crate::dwarf::entry_type(self, unit, child)?.unwrap();
            parameters.push(type_);
        }
        Ok(Definition::Subroutine {
            return_type,
            parameters,
        })
    }

    fn resolve_union_definition(
        &mut self,
        unit: &gimli::Unit<R>,
        entry: &gimli::DebuggingInformationEntry<R>,
    ) -> gimli::Result<Definition<R>> {
        let mut members = Vec::new();
        let mut children = crate::dwarf::entry_children(unit, entry)?;
        while let Some(child) = children.next()? {
            if child.tag() != gimli::DW_TAG_member {
                continue;
            }
            let name = crate::dwarf::entry_name(self.dwarf, unit, child)?;
            let type_ = crate::dwarf::entry_type(self, unit, child)?.unwrap();
            members.push(Member {
                name,
                location: 0,
                type_,
            })
        }
        Ok(Definition::Union { members })
    }

    fn resolve_definition(
        &mut self,
        unit: &gimli::Unit<R>,
        entry: &gimli::DebuggingInformationEntry<R>,
    ) -> gimli::Result<TypePtr<R>> {
        let entry_offset = entry.offset().to_debug_info_offset(&unit.header).unwrap();

        // Allocate the definition and store it in the map in case the type is
        // recursive.
        let definition_placeholder = match self.definitions.entry(entry_offset) {
            hash_map::Entry::Occupied(e) => return Ok(Rc::clone(e.get())),
            hash_map::Entry::Vacant(e) => {
                let dummy_definition = Rc::new(RefCell::new(Type {
                    name: None,
                    definition: Definition::dummy(),
                }));
                e.insert(dummy_definition.clone());
                dummy_definition
            }
        };

        let name = crate::dwarf::entry_name(self.dwarf, unit, entry)?;
        let definition = match entry.tag() {
            gimli::DW_TAG_base_type => self.resolve_base_definition(entry)?,
            gimli::DW_TAG_enumeration_type => self.resolve_enumeration_definition(unit, entry)?,
            gimli::DW_TAG_structure_type => self.resolve_structure_definition(unit, entry)?,
            gimli::DW_TAG_subroutine_type => self.resolve_subroutine_definition(unit, entry)?,
            gimli::DW_TAG_union_type => self.resolve_union_definition(unit, entry)?,
            _ => unreachable!(),
        };

        *definition_placeholder.borrow_mut() = Type { name, definition };

        Ok(definition_placeholder)
    }

    pub fn resolve(
        &mut self,
        unit: &gimli::Unit<R>,
        mut entry_offset: gimli::UnitOffset<R::Offset>,
    ) -> gimli::Result<InstancePtr<R>> {
        let absolute_offset = entry_offset.to_debug_info_offset(&unit.header).unwrap();
        if let Some(instance) = self.instances.get(&absolute_offset) {
            return Ok(Rc::clone(instance));
        }

        let mut underlying = None;
        let mut modifiers = Vec::new();
        loop {
            let entry = unit.entry(entry_offset)?;
            match entry.tag() {
                gimli::DW_TAG_base_type
                | gimli::DW_TAG_enumeration_type
                | gimli::DW_TAG_structure_type
                | gimli::DW_TAG_subroutine_type
                | gimli::DW_TAG_union_type => {
                    underlying = Some(self.resolve_definition(unit, &entry)?);
                    break;
                }
                gimli::DW_TAG_array_type => modifiers.push(Modifier::Array),
                gimli::DW_TAG_const_type => modifiers.push(Modifier::Const),
                gimli::DW_TAG_pointer_type => modifiers.push(Modifier::Pointer),
                gimli::DW_TAG_reference_type => modifiers.push(Modifier::Reference),
                gimli::DW_TAG_restrict_type => modifiers.push(Modifier::Restrict),
                gimli::DW_TAG_volatile_type => modifiers.push(Modifier::Volatile),
                gimli::DW_TAG_typedef => {}
                tag => panic!("unexpected tag: {}", tag),
            }

            if let Some(next_attr) = entry.attr_value(gimli::DW_AT_type)? {
                entry_offset = match next_attr {
                    gimli::AttributeValue::UnitRef(offset) => offset,
                    av => panic!("unexpected attribute value: {:?}", av),
                };
                continue;
            }

            break;
        }

        let instance = Rc::new_cyclic(move |self_weak| {
            RefCell::new(Instance {
                modifiers,
                underlying,
                self_weak: self_weak.clone(),
            })
        });
        self.instances.insert(absolute_offset, Rc::clone(&instance));

        Ok(instance)
    }
}