summaryrefslogtreecommitdiff
path: root/plugins/dwarf/dwarf_import/src/die_handlers.rs
blob: a803afdac2ff3a34e6e134de05706486b3002831 (plain)
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
// Copyright 2021-2026 Vector 35 Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::dwarfdebuginfo::{DebugInfoBuilder, DebugInfoBuilderContext, TypeUID};
use crate::types::get_type;
use crate::{helpers::*, ReaderType};

use binaryninja::{
    rc::*,
    types::{EnumerationBuilder, FunctionParameter, ReferenceType, Type, TypeBuilder},
};

use gimli::Dwarf;
use gimli::{constants, AttributeValue::Encoding, DebuggingInformationEntry, Unit};

pub(crate) fn handle_base_type<R: ReaderType>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    entry: &DebuggingInformationEntry<R>,
    debug_info_builder_context: &DebugInfoBuilderContext<R>,
) -> Option<Ref<Type>> {
    // All base types have:
    //   DW_AT_encoding (our concept of type_class)
    //   DW_AT_byte_size and/or DW_AT_bit_size
    //   *DW_AT_name
    //   *DW_AT_endianity (assumed default for arch)
    //   *DW_AT_data_bit_offset (assumed 0)
    //   *Some indication of signedness?
    //   * = Optional

    let name = debug_info_builder_context.get_name(dwarf, unit, entry)?;
    let size = get_size_as_usize(entry)?;
    match entry.attr_value(constants::DW_AT_encoding) {
        Ok(Some(Encoding(encoding))) => {
            match encoding {
                constants::DW_ATE_address => None,
                constants::DW_ATE_boolean => Some(Type::bool()),
                constants::DW_ATE_complex_float => None,
                constants::DW_ATE_float => Some(Type::named_float(size, &name)),
                constants::DW_ATE_signed => Some(Type::named_int(size, true, &name)),
                constants::DW_ATE_signed_char => Some(Type::named_int(size, true, &name)),
                constants::DW_ATE_unsigned => Some(Type::named_int(size, false, &name)),
                constants::DW_ATE_unsigned_char => Some(Type::named_int(size, false, &name)),
                constants::DW_ATE_imaginary_float => None,
                constants::DW_ATE_packed_decimal => None,
                constants::DW_ATE_numeric_string => None,
                constants::DW_ATE_edited => None,
                constants::DW_ATE_signed_fixed => None,
                constants::DW_ATE_unsigned_fixed => None,
                constants::DW_ATE_decimal_float => Some(Type::named_float(size, &name)),
                constants::DW_ATE_UTF => Some(Type::named_int(size, false, &name)), // TODO : Verify
                constants::DW_ATE_UCS => None,
                constants::DW_ATE_ASCII => None, // Some sort of array?
                constants::DW_ATE_lo_user => None,
                constants::DW_ATE_hi_user => None,
                _ => None, // Anything else is invalid at time of writing (gimli v0.23.0)
            }
        }
        _ => None,
    }
}

pub(crate) fn handle_enum<R: ReaderType>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    entry: &DebuggingInformationEntry<R>,
    debug_info_builder_context: &DebugInfoBuilderContext<R>,
) -> Option<Ref<Type>> {
    // All base types have:
    //   DW_AT_byte_size
    //   *DW_AT_name
    //   *DW_AT_enum_class
    //   *DW_AT_type
    //   ?DW_AT_abstract_origin
    //   ?DW_AT_accessibility
    //   ?DW_AT_allocated
    //   ?DW_AT_associated
    //   ?DW_AT_bit_size
    //   ?DW_AT_bit_stride
    //   ?DW_AT_byte_stride
    //   ?DW_AT_data_location
    //   ?DW_AT_declaration
    //   ?DW_AT_description
    //   ?DW_AT_sibling
    //   ?DW_AT_signature
    //   ?DW_AT_specification
    //   ?DW_AT_start_scope
    //   ?DW_AT_visibility
    //   * = Optional

    // Children of enumeration_types are enumerators which contain:
    //  DW_AT_name
    //  DW_AT_const_value
    //  *DW_AT_description

    let mut enumeration_builder = EnumerationBuilder::new();

    let mut tree = match unit.entries_tree(Some(entry.offset())) {
        Ok(x) => x,
        Err(e) => {
            tracing::error!("Failed to get enum entry tree: {}", e);
            return None;
        }
    };

    let tree_root = match tree.root() {
        Ok(x) => x,
        Err(e) => {
            tracing::error!("Failed to get enum entry tree root: {}", e);
            return None;
        }
    };

    let mut children = tree_root.children();
    while let Ok(Some(child)) = children.next() {
        if child.entry().tag() == constants::DW_TAG_enumerator {
            let name = debug_info_builder_context.get_name(dwarf, unit, child.entry())?;
            match &child.entry().attr(constants::DW_AT_const_value) {
                Ok(Some(attr)) => {
                    if let Some(value) = get_attr_as_u64(attr) {
                        enumeration_builder.insert(&name, value);
                    } else {
                        // Somehow the child entry is not a const value.
                        tracing::error!("Unhandled enum member value type for `{}`", name);
                    }
                }
                Ok(None) => {
                    // Somehow the child entry does not have a const value.
                    tracing::error!("Enum member `{}` has no constant value attribute", name);
                }
                Err(e) => {
                    tracing::error!("Error parsing next attribute entry for `{}`: {}", name, e);
                    return None;
                }
            }
        }
    }

    let width = match get_size_as_usize(entry).unwrap_or(8) {
        0 => debug_info_builder_context.default_address_size(),
        x => x,
    };

    Some(Type::enumeration(
        &enumeration_builder.finalize(),
        // TODO: This looks bad, look at the comment in [`Type::width`].
        width.try_into().expect("Enum cannot be zero width"),
        false,
    ))
}

pub(crate) fn handle_typedef(
    debug_info_builder: &mut DebugInfoBuilder,
    entry_type: Option<TypeUID>,
    typedef_name: &str,
) -> (Option<Ref<Type>>, bool) {
    // All base types have:
    //   DW_AT_name
    //   *DW_AT_type
    //   * = Optional

    // This will fail in the case where we have a typedef to a type that doesn't exist (failed to parse, incomplete, etc)
    if let Some(entry_type_offset) = entry_type {
        if let Some(t) = debug_info_builder.get_type(entry_type_offset) {
            let typedef_type = Type::named_type_from_type(typedef_name, &t.get_type());
            return (Some(typedef_type), typedef_name != t.name);
        }
    }

    // 5.3: "typedef represents a declaration of the type that is not also a definition"
    (None, false)
}

pub(crate) fn handle_pointer<R: ReaderType>(
    entry: &DebuggingInformationEntry<R>,
    debug_info_builder_context: &DebugInfoBuilderContext<R>,
    debug_info_builder: &mut DebugInfoBuilder,
    entry_type: Option<TypeUID>,
    reference_type: ReferenceType,
) -> Option<Ref<Type>> {
    // All pointer types have:
    //   DW_AT_type
    //   *DW_AT_byte_size
    //   ?DW_AT_name
    //   ?DW_AT_address
    //   ?DW_AT_allocated
    //   ?DW_AT_associated
    //   ?DW_AT_data_location
    //   * = Optional

    let pointer_size = match get_size_as_usize(entry) {
        Some(x) => x,
        None => debug_info_builder_context.default_address_size(),
    };

    let target_type = match entry_type {
        Some(entry_type_offset) => {
            let debug_target_type =
                debug_info_builder.get_type(entry_type_offset).or_else(|| {
                    tracing::error!(
                        "Failed to get pointer target type at entry offset {}",
                        entry_type_offset
                    );
                    None
                })?;

            debug_target_type.get_type()
        }
        None => Type::void(),
    };

    Some(Type::pointer_of_width(
        target_type.as_ref(),
        pointer_size,
        false,
        false,
        Some(reference_type),
    ))
}

pub(crate) fn handle_array<R: ReaderType>(
    unit: &Unit<R>,
    entry: &DebuggingInformationEntry<R>,
    debug_info_builder: &mut DebugInfoBuilder,
    entry_type: Option<TypeUID>,
) -> Option<Ref<Type>> {
    // All array types have:
    //    DW_AT_type
    //   *DW_AT_name
    //   *DW_AT_ordering
    //   *DW_AT_byte_stride or DW_AT_bit_stride
    //   *DW_AT_byte_size or DW_AT_bit_size
    //   *DW_AT_allocated
    //   *DW_AT_associated and
    //   *DW_AT_data_location
    //   * = Optional
    //   For multidimensional arrays, DW_TAG_subrange_type or DW_TAG_enumeration_type

    let entry_type_offset = entry_type?;
    let parent_type = debug_info_builder
        .get_type(entry_type_offset)
        .or_else(|| {
            tracing::error!(
                "Failed to get array member type at entry offset {}",
                entry_type_offset
            );
            None
        })?
        .get_type();

    let mut tree = match unit.entries_tree(Some(entry.offset())) {
        Ok(x) => x,
        Err(e) => {
            tracing::error!("Failed to get array entry tree: {}", e);
            return None;
        }
    };
    let tree_root = match tree.root() {
        Ok(x) => x,
        Err(e) => {
            tracing::error!("Failed to get array entry tree root: {}", e);
            return None;
        }
    };
    let mut children = tree_root.children();

    // TODO : This is currently applying the size in reverse order
    let mut result_type: Option<Ref<Type>> = None;
    while let Ok(Some(child)) = children.next() {
        if let Some(inner_type) = result_type {
            result_type = Some(Type::array(
                inner_type.as_ref(),
                get_subrange_size(child.entry()),
            ));
        } else {
            result_type = Some(Type::array(
                parent_type.as_ref(),
                get_subrange_size(child.entry()),
            ));
        }
    }

    result_type.map_or(Some(Type::array(parent_type.as_ref(), 0)), Some)
}

pub(crate) fn handle_function<R: ReaderType>(
    dwarf: &Dwarf<R>,
    unit: &Unit<R>,
    entry: &DebuggingInformationEntry<R>,
    debug_info_builder_context: &DebugInfoBuilderContext<R>,
    debug_info_builder: &mut DebugInfoBuilder,
    entry_type: Option<TypeUID>,
) -> Option<Ref<Type>> {
    // All subroutine types have:
    //   *DW_AT_name
    //   *DW_AT_type (if not provided, void)
    //   *DW_AT_prototyped
    //   ?DW_AT_abstract_origin
    //   ?DW_AT_accessibility
    //   ?DW_AT_address_class
    //   ?DW_AT_allocated
    //   ?DW_AT_associated
    //   ?DW_AT_data_location
    //   ?DW_AT_declaration
    //   ?DW_AT_description
    //   ?DW_AT_sibling
    //   ?DW_AT_start_scope
    //   ?DW_AT_visibility
    //   * = Optional

    // May have children, including DW_TAG_formal_parameters, which all have:
    //   *DW_AT_type
    //   * = Optional
    // or is otherwise DW_TAG_unspecified_parameters

    let return_type = match entry_type {
        Some(entry_type_offset) => debug_info_builder
            .get_type(entry_type_offset)
            .expect("Subroutine return type was not processed")
            .get_type(),
        None => Type::void(),
    };

    // Alias function type in the case that it contains itself
    let name = debug_info_builder_context
        .get_name(dwarf, unit, entry)
        .unwrap_or("_unnamed_func".to_string());
    let ntr =
        Type::named_type_from_type(&name, &Type::function(return_type.as_ref(), vec![], false));
    debug_info_builder.add_type(get_uid(dwarf, unit, entry), name, ntr, false, None);

    let mut parameters: Vec<FunctionParameter> = vec![];
    let mut variable_arguments = false;

    // Get all the children and populate
    let mut tree = match unit.entries_tree(Some(entry.offset())) {
        Ok(x) => x,
        Err(e) => {
            tracing::error!("Failed to get function entry tree: {}", e);
            return None;
        }
    };

    let tree_root = match tree.root() {
        Ok(x) => x,
        Err(e) => {
            tracing::error!("Failed to get function entry tree root: {}", e);
            return None;
        }
    };

    let mut children = tree_root.children();
    while let Ok(Some(child)) = children.next() {
        if child.entry().tag() == constants::DW_TAG_formal_parameter {
            let Some(child_uid) = get_type(
                dwarf,
                unit,
                child.entry(),
                debug_info_builder_context,
                debug_info_builder,
            ) else {
                tracing::error!(
                    "Failed to get function parameter child type in unit {:?} at offset {:x}",
                    unit.header.offset(),
                    child.entry().offset().0,
                );
                continue;
            };
            let name = debug_info_builder_context.get_name(dwarf, unit, child.entry());

            let child_debug_type = debug_info_builder.get_type(child_uid).or_else(|| {
                tracing::error!(
                    "Failed to get function parameter type with uid {}",
                    child_uid
                );
                None
            })?;
            let child_type = child_debug_type.get_type();

            parameters.push(FunctionParameter::new(
                child_type,
                name.unwrap_or_default(),
                None,
            ));
        } else if child.entry().tag() == constants::DW_TAG_unspecified_parameters {
            variable_arguments = true;
        }
    }

    // Remove the aliased type from the builder.
    debug_info_builder.remove_type(get_uid(dwarf, unit, entry));

    Some(Type::function(
        return_type.as_ref(),
        parameters,
        variable_arguments,
    ))
}

pub(crate) fn handle_const(
    debug_info_builder: &mut DebugInfoBuilder,
    entry_type: Option<TypeUID>,
) -> Option<Ref<Type>> {
    // All const types have:
    //   ?DW_AT_allocated
    //   ?DW_AT_associated
    //   ?DW_AT_data_location
    //   ?DW_AT_name
    //   ?DW_AT_sibling
    //   ?DW_AT_type

    let target_type_builder = match entry_type {
        Some(entry_type_offset) => debug_info_builder
            .get_type(entry_type_offset)
            .or_else(|| {
                tracing::error!(
                    "Failed to get const type with entry offset {}",
                    entry_type_offset
                );
                None
            })?
            .get_type()
            .to_builder(),
        None => TypeBuilder::void(),
    };

    Some(target_type_builder.set_const(true).finalize())
}

pub(crate) fn handle_volatile(
    debug_info_builder: &mut DebugInfoBuilder,
    entry_type: Option<TypeUID>,
) -> Option<Ref<Type>> {
    // All const types have:
    //   ?DW_AT_allocated
    //   ?DW_AT_associated
    //   ?DW_AT_data_location
    //   ?DW_AT_name
    //   ?DW_AT_sibling
    //   ?DW_AT_type

    let target_type_builder = match entry_type {
        Some(entry_type_offset) => debug_info_builder
            .get_type(entry_type_offset)
            .or_else(|| {
                tracing::error!(
                    "Failed to get volatile type with entry offset {}",
                    entry_type_offset
                );
                None
            })?
            .get_type()
            .to_builder(),
        None => TypeBuilder::void(),
    };

    Some(target_type_builder.set_volatile(true).finalize())
}