~taiite/protodump

ref: 1e4c5978de0ec9adf763779e87165553a9f74cb7 protodump/src/dwarf.rs -rw-r--r-- 8.0 KiB
1e4c5978Hubert Hirtz Account for (void) argument lists 2 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
use crate::types;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::hash::Hash;

#[derive(Clone)]
pub struct Parameter<R> {
    pub name: Option<R>,
    pub type_: types::InstancePtr<R>,
}

impl<R> PartialEq for Parameter<R>
where
    R: PartialEq,
{
    fn eq(&self, other: &Parameter<R>) -> bool {
        self.type_.eq(&other.type_)
    }
}

#[derive(Clone, PartialEq)]
pub struct Subprogram<R> {
    pub return_type: types::InstancePtr<R>,
    pub parameters: Option<Vec<Parameter<R>>>,
}

/// Iterator over the children of an entry.
pub struct EntryChildren<'e, R>
where
    R: gimli::Reader,
{
    entries: Option<gimli::EntriesCursor<'e, 'e, R>>,

    /// Whether the first child has been iterated over.
    init: bool,
}

/// Iterate over the children of an entry.
///
/// The given entry must be in the given unit.
pub fn entry_children<'e, R>(
    unit: &'e gimli::Unit<R>,
    entry: &'e gimli::DebuggingInformationEntry<R>,
) -> gimli::Result<EntryChildren<'e, R>>
where
    R: gimli::Reader,
{
    let entries = if entry.has_children() {
        // TODO error should not happen since we give the correct unit for the entry.
        let mut cursor = unit.entries_at_offset(entry.offset())?;
        // somehow EntriesCursor behaves like this??
        let (delta, child) = cursor
            .next_dfs()?
            .expect("first call to EntriesCursor::next_dfs should always succeed");
        debug_assert_eq!(
            delta, 0,
            "first call to EntriesCursor::next_dfs should always return delta==0",
        );
        debug_assert_eq!(
            entry.tag(),
            child.tag(),
            "first call to EntriesCursor::next_dfs should return the original entry",
        );
        Some(cursor)
    } else {
        None
    };
    Ok(EntryChildren {
        entries,
        init: false,
    })
}

impl<'e, R> EntryChildren<'e, R>
where
    R: gimli::Reader,
{
    pub fn next(&mut self) -> gimli::Result<Option<&gimli::DebuggingInformationEntry<'e, 'e, R>>> {
        if let Some(entries) = &mut self.entries {
            if self.init {
                entries.next_sibling()
            } else {
                self.init = true;
                let (delta, child) = entries
                    .next_dfs()?
                    // since we checked for children when creating the iterator...
                    .expect("second call to EntriesCursor::next_dfs should always succeed");
                debug_assert_eq!(
                    delta, 1,
                    "second call to EntriesCursor::next_dfs should always return delta==1"
                );
                Ok(Some(child))
            }
        } else {
            Ok(None)
        }
    }
}

pub fn entry_int_attr<R>(
    entry: &gimli::DebuggingInformationEntry<R>,
    attr: gimli::DwAt,
) -> gimli::Result<Option<u64>>
where
    R: gimli::Reader,
{
    let av = match entry.attr_value(attr)? {
        Some(av) => av,
        None => return Ok(None),
    };
    Ok(Some(match av {
        // TODO replace "as" with TryInto
        gimli::AttributeValue::Data1(n) => n as u64,
        gimli::AttributeValue::Data2(n) => n as u64,
        gimli::AttributeValue::Data4(n) => n as u64,
        gimli::AttributeValue::Data8(n) => n,
        gimli::AttributeValue::Sdata(n) => n as u64,
        gimli::AttributeValue::Udata(n) => n,
        av => panic!("unexpected attribute value for {}: {:?}", attr, av),
    }))
}

pub fn entry_byte_size<R>(entry: &gimli::DebuggingInformationEntry<R>) -> gimli::Result<Option<u64>>
where
    R: gimli::Reader,
{
    entry_int_attr(entry, gimli::DW_AT_byte_size)
}

pub fn entry_encoding<R>(
    entry: &gimli::DebuggingInformationEntry<R>,
) -> gimli::Result<Option<crate::types::Encoding>>
where
    R: gimli::Reader,
{
    let encoding_attr = match entry.attr_value(gimli::DW_AT_encoding)? {
        Some(av) => av,
        None => return Ok(None),
    };
    Ok(Some(match encoding_attr {
        gimli::AttributeValue::Encoding(encoding) => crate::types::Encoding::try_from(encoding)
            .map_err(|()| gimli::Error::Io /* TODO */)?,
        av => panic!("unexpected attribute value for DW_AT_encoding: {:?}", av),
    }))
}

pub fn entry_name<R>(
    dwarf: &gimli::Dwarf<R>,
    unit: &gimli::Unit<R>,
    entry: &gimli::DebuggingInformationEntry<R>,
) -> gimli::Result<Option<R>>
where
    R: gimli::Reader,
{
    Ok(entry
        .attr_value(gimli::DW_AT_name)?
        .and_then(|attr| dwarf.attr_string(unit, attr).ok()))
}

pub fn entry_type<R>(
    cache: &mut types::Cache<R>,
    unit: &gimli::Unit<R>,
    entry: &gimli::DebuggingInformationEntry<R>,
) -> gimli::Result<Option<types::InstancePtr<R>>>
where
    R: gimli::Reader,
{
    let type_attr = match entry.attr_value(gimli::DW_AT_type)? {
        Some(av) => av,
        None => return Ok(None),
    };
    let type_offset = match type_attr {
        gimli::AttributeValue::UnitRef(offset) => offset,
        av => panic!("unexpected attribute value for DW_AT_type: {:?}", av),
    };
    let type_ = cache.resolve(unit, type_offset)?;
    Ok(Some(type_))
}

pub struct Sources<'a, R>
where
    R: gimli::Reader,
{
    pub subprograms: HashMap<R, Subprogram<R>>,
    pub type_cache: types::Cache<'a, R>,
}

impl<'a, R> Sources<'a, R>
where
    R: gimli::Reader + Eq + Hash,
{
    pub fn parse(dwarf: &'a gimli::Dwarf<R>) -> gimli::Result<Sources<'a, R>> {
        let mut subprograms = HashMap::new();
        let mut type_cache = types::Cache::new(dwarf);

        let mut it = dwarf.units();
        while let Some(header) = it.next()? {
            let unit = dwarf.unit(header)?;

            let mut entries = unit.entries();
            while let Some((_, entry)) = entries.next_dfs()? {
                if entry.tag() != gimli::DW_TAG_subprogram {
                    // This debug entry is not a function.
                    continue;
                }
                if let Some(gimli::AttributeValue::Flag(true)) =
                    entry.attr_value(gimli::DW_AT_declaration)?
                {
                    // This debug entry does not define the function.
                    continue;
                }

                let name = entry_name(&dwarf, &unit, entry)?;
                let typ = entry_type(&mut type_cache, &unit, entry)?;
                if name.is_none() || typ.is_none() {
                    continue;
                }
                let name = name.unwrap();
                let typ = typ.unwrap();
                let mut parameters = Vec::new();

                let prototyped = matches!(
                    entry.attr_value(gimli::DW_AT_prototyped)?,
                    Some(gimli::AttributeValue::Flag(true))
                );

                if entry.has_children() {
                    entries.next_dfs()?.unwrap();
                    loop {
                        let entry = match entries.current() {
                            Some(entry) => entry,
                            None => break,
                        };
                        if entry.tag() != gimli::DW_TAG_formal_parameter {
                            entries.next_sibling()?;
                            continue;
                        }
                        let name = entry_name(&dwarf, &unit, entry)?;
                        let type_ = entry_type(&mut type_cache, &unit, entry)?;
                        if let Some(type_) = type_ {
                            parameters.push(Parameter { name, type_ });
                        }

                        entries.next_sibling()?;
                    }
                }

                let parameters = if parameters.is_empty() {
                    if prototyped {
                        Some(parameters)
                    } else {
                        None
                    }
                } else {
                    Some(parameters)
                };

                subprograms.insert(
                    name,
                    Subprogram {
                        return_type: typ,
                        parameters,
                    },
                );
            }
        }

        Ok(Sources {
            subprograms,
            type_cache,
        })
    }
}