ghostscope-dwarf 0.1.5

DWARF parser and symbolizer used by GhostScope to resolve variables and types at runtime.
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
//! C type semantics derived from DWARF type information.
//!
//! This module keeps language-level type classification close to the DWARF
//! semantic layer so compiler backends do not need to duplicate C rules.

use crate::TypeInfo;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CIntegerComparisonType {
    pub size: u64,
    pub is_unsigned: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CIntegerComparisonPlan {
    pub size: u64,
    pub is_unsigned: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub struct MemberLayout {
    pub offset: u64,
    pub member_type: TypeInfo,
}

#[derive(Clone, Debug, PartialEq)]
pub struct IndexableElementLayout {
    pub element_type: TypeInfo,
    pub stride: u64,
}

#[derive(Debug, thiserror::Error)]
pub enum TypeLayoutError {
    #[error("Unknown member '{field}' in {kind} '{type_name}' (known members: {members})")]
    UnknownMember {
        kind: &'static str,
        type_name: String,
        field: String,
        members: String,
    },

    #[error("member access requires struct or union type, got '{type_name}'")]
    InvalidMemberBase { type_name: String },
}

impl CIntegerComparisonType {
    pub fn promoted(self) -> Self {
        if self.size < 4 {
            Self {
                size: 4,
                is_unsigned: false,
            }
        } else {
            self
        }
    }

    pub fn signed_i64() -> Self {
        Self {
            size: 8,
            is_unsigned: false,
        }
    }
}

pub fn strip_type_aliases(mut ty: &TypeInfo) -> &TypeInfo {
    while let TypeInfo::TypedefType {
        underlying_type, ..
    }
    | TypeInfo::QualifiedType {
        underlying_type, ..
    } = ty
    {
        ty = underlying_type.as_ref();
    }
    ty
}

pub fn is_c_aggregate_type(ty: &TypeInfo) -> bool {
    matches!(
        strip_type_aliases(ty),
        TypeInfo::StructType { .. } | TypeInfo::UnionType { .. } | TypeInfo::ArrayType { .. }
    )
}

pub fn is_c_pointer_or_array_type(ty: &TypeInfo) -> bool {
    matches!(
        strip_type_aliases(ty),
        TypeInfo::PointerType { .. } | TypeInfo::ArrayType { .. }
    )
}

pub fn member_layout(ty: &TypeInfo, field: &str) -> Result<MemberLayout, TypeLayoutError> {
    match strip_type_aliases(ty) {
        TypeInfo::StructType { name, members, .. } => members
            .iter()
            .find(|member| member.name == field)
            .map(|member| MemberLayout {
                offset: member.offset,
                member_type: member.member_type.clone(),
            })
            .ok_or_else(|| unknown_member_error("struct", name, field, members)),
        TypeInfo::UnionType { name, members, .. } => members
            .iter()
            .find(|member| member.name == field)
            .map(|member| MemberLayout {
                offset: member.offset,
                member_type: member.member_type.clone(),
            })
            .ok_or_else(|| unknown_member_error("union", name, field, members)),
        other => Err(TypeLayoutError::InvalidMemberBase {
            type_name: other.type_name(),
        }),
    }
}

pub fn indexable_element_layout(ty: &TypeInfo) -> Option<IndexableElementLayout> {
    match strip_type_aliases(ty) {
        TypeInfo::ArrayType { element_type, .. } => Some(IndexableElementLayout {
            element_type: element_type.as_ref().clone(),
            stride: element_type.size().max(1),
        }),
        TypeInfo::PointerType { target_type, .. } => Some(IndexableElementLayout {
            element_type: target_type.as_ref().clone(),
            stride: target_type.size().max(1),
        }),
        _ => None,
    }
}

pub fn c_integer_comparison_type(ty: &TypeInfo) -> Option<CIntegerComparisonType> {
    match ty {
        TypeInfo::BaseType { encoding, size, .. } => {
            let is_unsigned = *encoding == crate::constants::DW_ATE_unsigned.0 as u16
                || *encoding == crate::constants::DW_ATE_unsigned_char.0 as u16;
            let is_signed = *encoding == crate::constants::DW_ATE_signed.0 as u16
                || *encoding == crate::constants::DW_ATE_signed_char.0 as u16
                || *encoding == crate::constants::DW_ATE_boolean.0 as u16;
            if is_unsigned || is_signed {
                Some(CIntegerComparisonType {
                    size: *size,
                    is_unsigned,
                })
            } else {
                None
            }
        }
        TypeInfo::EnumType {
            base_type, size, ..
        } => c_integer_comparison_type(base_type).map(|mut ty| {
            if ty.size == 0 {
                ty.size = *size;
            }
            ty
        }),
        TypeInfo::BitfieldType {
            underlying_type,
            bit_size,
            ..
        } => c_integer_comparison_type(underlying_type).map(|mut ty| {
            ty.size = (*bit_size as u64).max(1).div_ceil(8);
            ty
        }),
        TypeInfo::TypedefType {
            underlying_type, ..
        }
        | TypeInfo::QualifiedType {
            underlying_type, ..
        } => c_integer_comparison_type(underlying_type),
        _ => None,
    }
}

pub fn is_c_signed_integer_type(ty: &TypeInfo) -> bool {
    match ty {
        TypeInfo::BaseType { encoding, .. } => {
            *encoding == crate::constants::DW_ATE_signed.0 as u16
                || *encoding == crate::constants::DW_ATE_signed_char.0 as u16
        }
        TypeInfo::EnumType { base_type, .. } => is_c_signed_integer_type(base_type),
        TypeInfo::BitfieldType {
            underlying_type, ..
        } => is_c_signed_integer_type(underlying_type),
        TypeInfo::TypedefType {
            underlying_type, ..
        }
        | TypeInfo::QualifiedType {
            underlying_type, ..
        } => is_c_signed_integer_type(underlying_type),
        _ => false,
    }
}

pub fn usual_c_arithmetic_comparison_plan(
    left: CIntegerComparisonType,
    right: CIntegerComparisonType,
) -> CIntegerComparisonPlan {
    let left = left.promoted();
    let right = right.promoted();
    if left.is_unsigned == right.is_unsigned {
        return CIntegerComparisonPlan {
            size: left.size.max(right.size),
            is_unsigned: left.is_unsigned,
        };
    }

    let unsigned = if left.is_unsigned { left } else { right };
    let signed = if left.is_unsigned { right } else { left };
    if unsigned.size >= signed.size {
        CIntegerComparisonPlan {
            size: unsigned.size,
            is_unsigned: true,
        }
    } else {
        CIntegerComparisonPlan {
            size: signed.size,
            is_unsigned: false,
        }
    }
}

fn unknown_member_error(
    kind: &'static str,
    type_name: &str,
    field: &str,
    members: &[crate::StructMember],
) -> TypeLayoutError {
    let mut member_names = members
        .iter()
        .map(|member| member.name.clone())
        .collect::<Vec<_>>();
    member_names.sort();
    member_names.dedup();
    let list = if member_names.is_empty() {
        "<none>".to_string()
    } else {
        member_names.join(", ")
    };

    TypeLayoutError::UnknownMember {
        kind,
        type_name: type_name.to_string(),
        field: field.to_string(),
        members: list,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::StructMember;

    fn int_type(name: &str, size: u64, encoding: u16) -> TypeInfo {
        TypeInfo::BaseType {
            name: name.to_string(),
            size,
            encoding,
        }
    }

    fn signed_int() -> TypeInfo {
        int_type("int", 4, crate::constants::DW_ATE_signed.0 as u16)
    }

    #[test]
    fn aggregate_classification_strips_aliases() {
        let struct_type = TypeInfo::StructType {
            name: "Request".to_string(),
            size: 4,
            members: vec![StructMember {
                name: "fd".to_string(),
                member_type: signed_int(),
                offset: 0,
                bit_offset: None,
                bit_size: None,
            }],
        };
        let typedef = TypeInfo::TypedefType {
            name: "request_t".to_string(),
            underlying_type: Box::new(TypeInfo::QualifiedType {
                qualifier: crate::TypeQualifier::Const,
                underlying_type: Box::new(struct_type),
            }),
        };

        assert!(is_c_aggregate_type(&typedef));
    }

    #[test]
    fn pointer_or_array_classification_strips_aliases() {
        let array_type = TypeInfo::ArrayType {
            element_type: Box::new(signed_int()),
            element_count: Some(4),
            total_size: Some(16),
        };
        let typedef = TypeInfo::TypedefType {
            name: "int_array_t".to_string(),
            underlying_type: Box::new(array_type),
        };

        assert!(is_c_pointer_or_array_type(&typedef));
    }

    #[test]
    fn member_and_index_layout_strip_aliases() {
        let signed_int = signed_int();
        let struct_type = TypeInfo::StructType {
            name: "Request".to_string(),
            size: 16,
            members: vec![StructMember {
                name: "fd".to_string(),
                member_type: signed_int.clone(),
                offset: 8,
                bit_offset: None,
                bit_size: None,
            }],
        };
        let qualified_struct = TypeInfo::QualifiedType {
            qualifier: crate::TypeQualifier::Const,
            underlying_type: Box::new(struct_type),
        };

        let layout = member_layout(&qualified_struct, "fd").expect("member layout");
        assert_eq!(layout.offset, 8);
        assert_eq!(layout.member_type, signed_int.clone());

        let pointer_type = TypeInfo::PointerType {
            target_type: Box::new(signed_int),
            size: 8,
        };
        let element = indexable_element_layout(&pointer_type).expect("pointer element layout");
        assert_eq!(element.stride, 4);
    }

    #[test]
    fn integer_comparison_type_handles_enums_and_bitfields() {
        let enum_type = TypeInfo::EnumType {
            name: "Mode".to_string(),
            size: 4,
            variants: vec![],
            base_type: Box::new(int_type(
                "unsigned int",
                0,
                crate::constants::DW_ATE_unsigned.0 as u16,
            )),
        };
        assert_eq!(
            c_integer_comparison_type(&enum_type),
            Some(CIntegerComparisonType {
                size: 4,
                is_unsigned: true,
            })
        );

        let bitfield_type = TypeInfo::BitfieldType {
            underlying_type: Box::new(signed_int()),
            bit_offset: 0,
            bit_size: 9,
        };
        assert_eq!(
            c_integer_comparison_type(&bitfield_type),
            Some(CIntegerComparisonType {
                size: 2,
                is_unsigned: false,
            })
        );
    }

    #[test]
    fn signed_integer_classification_excludes_boolean() {
        let bool_type = int_type("bool", 1, crate::constants::DW_ATE_boolean.0 as u16);
        assert_eq!(
            c_integer_comparison_type(&bool_type),
            Some(CIntegerComparisonType {
                size: 1,
                is_unsigned: false,
            })
        );
        assert!(!is_c_signed_integer_type(&bool_type));
        assert!(is_c_signed_integer_type(&signed_int()));
    }

    #[test]
    fn usual_comparison_plan_applies_integer_promotions() {
        let u8_type = CIntegerComparisonType {
            size: 1,
            is_unsigned: true,
        };
        let i8_type = CIntegerComparisonType {
            size: 1,
            is_unsigned: false,
        };

        assert_eq!(
            usual_c_arithmetic_comparison_plan(u8_type, i8_type),
            CIntegerComparisonPlan {
                size: 4,
                is_unsigned: false,
            }
        );
    }

    #[test]
    fn usual_comparison_plan_respects_unsigned_rank() {
        let u64_type = CIntegerComparisonType {
            size: 8,
            is_unsigned: true,
        };
        let i32_type = CIntegerComparisonType {
            size: 4,
            is_unsigned: false,
        };

        assert_eq!(
            usual_c_arithmetic_comparison_plan(u64_type, i32_type),
            CIntegerComparisonPlan {
                size: 8,
                is_unsigned: true,
            }
        );
    }
}