~taiite/protodump

ref: 941d9dbf3bea58512a6a434ec32ef27f4fed0f0f protodump/src/main.rs -rw-r--r-- 14.5 KiB
941d9dbfSimon Ser Make prototypes names bold 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
use anyhow::Context;
use anyhow::Result;
use object::read::Object as _;
use object::read::ObjectSection as _;
use object::read::ObjectSymbol as _;
use std::borrow;
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::process;

// key=symbol name
type Sources = HashMap<String, Prototype>;
type SortedSources = Vec<(String, Prototype)>;

#[derive(Clone, PartialEq, Eq)]
struct Prototype {
    return_type: String,
    parameters: Vec<Parameter>,
}

#[derive(Clone, Eq)]
struct Parameter {
    name: String,
    typ: String,
}

impl PartialEq for Parameter {
    fn eq(&self, other: &Parameter) -> bool {
        self.typ.eq(&other.typ)
    }
}

fn entry_type<R>(
    dwarf: &gimli::Dwarf<R>,
    unit: &gimli::Unit<R>,
    entry: &gimli::DebuggingInformationEntry<R>,
) -> gimli::Result<Option<String>>
where
    R: gimli::Reader,
{
    entry
        .attr(gimli::DW_AT_type)?
        .map(|attr| resolve_type(dwarf, unit, attr))
        .transpose()
}

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

fn resolve_type<R>(
    dwarf: &gimli::Dwarf<R>,
    unit: &gimli::Unit<R>,
    mut attr: gimli::Attribute<R>,
) -> gimli::Result<String>
where
    R: gimli::Reader,
{
    let mut buf = String::new();
    let mut tags = Vec::new();
    loop {
        let entry = match attr.value() {
            gimli::AttributeValue::UnitRef(offset) => unit.entry(offset)?,
            av => panic!("unexpected attribute value: {:?}", av),
        };
        if let Some(next_attr) = entry.attr(gimli::DW_AT_type)? {
            attr = next_attr;
            tags.push(entry.tag());
            continue;
        }
        if let Some(name_attr) = entry.attr(gimli::DW_AT_name)? {
            if entry.tag() == gimli::DW_TAG_structure_type {
                buf.push_str("struct ");
            }
            buf.push_str(
                &dwarf
                    .attr_string(unit, name_attr.value())?
                    .to_string_lossy()?,
            );
            buf.push(' ');
            break;
        }
        tags.push(entry.tag());
        buf.push_str("void ");
        break;
    }

    for tag in tags.into_iter().rev() {
        match tag {
            gimli::DW_TAG_const_type => buf.push_str("const "),
            gimli::DW_TAG_pointer_type => buf.push('*'),
            gimli::DW_TAG_reference_type => buf.push('&'),
            gimli::DW_TAG_enumeration_type => buf.push_str("enum "),
            gimli::DW_TAG_subroutine_type => buf.push_str("fn "),
            gimli::DW_TAG_restrict_type => buf.push_str("restrict "),
            gimli::DW_TAG_array_type => buf.push_str("[]"),
            gimli::DW_TAG_structure_type => {}
            gimli::DW_TAG_typedef => {}
            tag => panic!("unexpected tag: {}", tag),
        }
    }

    Ok(buf)
}

fn read_prototypes(obj: &object::File<'_>) -> Result<Sources> {
    let endian = if obj.is_little_endian() {
        gimli::RunTimeEndian::Little
    } else {
        gimli::RunTimeEndian::Big
    };

    let load_section = |section_id: gimli::SectionId| -> gimli::Result<borrow::Cow<[u8]>> {
        let section_data = obj
            .section_by_name(section_id.name())
            .and_then(|section| section.uncompressed_data().ok())
            .unwrap_or(borrow::Cow::Borrowed(&[]));
        Ok(section_data)
    };
    let dwarf_cow = gimli::Dwarf::load(&load_section)?;
    let dwarf = dwarf_cow.borrow(|section| gimli::EndianSlice::new(section, endian));

    let mut prototypes = Sources::new();

    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(&dwarf, &unit, entry)?;
            if name.is_none() || typ.is_none() {
                continue;
            }
            let name = name.unwrap();
            let typ = typ.unwrap();
            let mut parameters = Vec::new();

            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)?.unwrap_or_else(|| String::new());
                    let typ = entry_type(&dwarf, &unit, entry)?;
                    if let Some(typ) = typ {
                        parameters.push(Parameter { name, typ });
                    }

                    entries.next_sibling()?;
                }
            }

            prototypes.insert(
                name,
                Prototype {
                    return_type: typ,
                    parameters,
                },
            );
        }
    }

    Ok(prototypes)
}

#[derive(Debug, PartialEq, Eq)]
enum ContainerType {
    Coff,
    Elf32,
    Elf64,
    MachO32,
    MachO64,
    Pe32,
    Pe64,
}

#[derive(Copy, Clone)]
struct SymbolFilter {
    /// Also show imported symbols.
    imports: bool,

    /// Also show non-exported global/weak symbols.
    globals: bool,

    /// Also show non-exported local symbols.
    locals: bool,
}

#[derive(Eq)]
struct ObjectInfo<'a> {
    container_type: ContainerType,
    is_little_endian: bool,
    symbol_whitelist: HashSet<&'a str>,
}

impl PartialEq for ObjectInfo<'_> {
    fn eq(&self, other: &ObjectInfo<'_>) -> bool {
        self.container_type == other.container_type
            && self.is_little_endian == other.is_little_endian
    }
}

fn show_object_info_diff(prev: &ObjectInfo<'_>, next: &ObjectInfo<'_>) {
    if prev.container_type != next.container_type {
        println!("-Container type: {:?}", prev.container_type);
        println!("+Container type: {:?}", next.container_type);
    }
    if prev.is_little_endian != next.is_little_endian {
        println!(
            "-Endianness: {}",
            if prev.is_little_endian {
                "little"
            } else {
                "big"
            }
        );
        println!(
            "+Endianness: {}",
            if next.is_little_endian {
                "little"
            } else {
                "big"
            }
        );
    }
    // TODO show symbol whitelist diff?
}

enum Diff {
    Added,
    Removed,
    Changed(Prototype),
}

fn diff_sources(prev: Sources, mut next: Sources) -> Vec<(String, Prototype, Diff)> {
    let mut res: Vec<_> = prev
        .into_iter()
        .filter_map(|(prev_func, prev_prototype)| {
            let next_prototype = if let Some(p) = next.remove(&prev_func) {
                p
            } else {
                return Some((prev_func, prev_prototype, Diff::Removed));
            };
            if prev_prototype == next_prototype {
                None
            } else {
                Some((prev_func, prev_prototype, Diff::Changed(next_prototype)))
            }
        })
        .collect();

    let added = next
        .into_iter()
        .map(|(func, prototype)| (func, prototype, Diff::Added));
    res.extend(added);

    res.sort_unstable_by(|(func1, _, _), (func2, _, _)| String::cmp(func1, func2));

    res
}

fn show_source_diff(d: &[(String, Prototype, Diff)]) {
    let color = atty::is(atty::Stream::Stdout);
    for (func, prototype, diff) in d {
        match diff {
            Diff::Added => {
                print!("add ");
                show_prototype(func, prototype, color);
            }
            Diff::Removed => {
                print!("del ");
                show_prototype(func, prototype, color);
            }
            Diff::Changed(new_prototype) => {
                print!("prv ");
                show_prototype(func, prototype, color);
                print!("nxt ");
                show_prototype(func, new_prototype, color);
            }
        }
    }
}

fn read_object_info<'a>(obj: &object::File<'a>, filter: SymbolFilter) -> Result<ObjectInfo<'a>> {
    let container_type = match obj.format() {
        object::BinaryFormat::Coff => ContainerType::Coff,
        object::BinaryFormat::Elf => {
            if obj.is_64() {
                ContainerType::Elf64
            } else {
                ContainerType::Elf32
            }
        }
        object::BinaryFormat::MachO => {
            if obj.is_64() {
                ContainerType::MachO64
            } else {
                ContainerType::MachO32
            }
        }
        object::BinaryFormat::Pe => {
            if obj.is_64() {
                ContainerType::Pe64
            } else {
                ContainerType::Pe32
            }
        }
        format => panic!("unsupported object format: {:?}", format),
    };

    let mut symbol_whitelist: HashSet<_> = obj
        .dynamic_symbols()
        .filter(|symbol| symbol.kind() == object::SymbolKind::Text)
        .filter(|symbol| filter.imports || !symbol.is_undefined())
        .filter_map(|symbol| symbol.name().ok())
        .collect();

    if filter.globals || filter.locals {
        for symbol in obj.symbols() {
            if symbol.kind() != object::SymbolKind::Text || symbol.is_undefined() {
                continue;
            }
            if !filter.globals && symbol.is_global() {
                // did not ask for global symbols.
                continue;
            }
            if !filter.locals && symbol.is_local() {
                // did not ask for local symbols.
                continue;
            }
            if let Ok(name) = symbol.name() {
                symbol_whitelist.insert(name);
            }
        }
    }

    Ok(ObjectInfo {
        container_type,
        is_little_endian: obj.is_little_endian(),
        symbol_whitelist,
    })
}

fn sort_prototypes(prototypes: Sources) -> SortedSources {
    let mut sorted: Vec<_> = prototypes.into_iter().collect();
    sorted.sort_unstable_by(|(name1, _), (name2, _)| String::cmp(name1, name2));
    sorted
}

fn show_prototype(name: &str, prototype: &Prototype, color: bool) {
    print!("{}", prototype.return_type);
    if color {
        print!("{}(", ansi_term::Style::new().bold().paint(name));
    } else {
        print!("{}(", name);
    }
    let mut first = true;
    for param in &prototype.parameters {
        if first {
            first = false;
        } else {
            print!(", ");
        }
        let typ = if param.name.is_empty() {
            param.typ.trim_end()
        } else {
            &param.typ
        };
        print!("{}{}", typ, param.name);
    }
    println!(");");
}

fn show_prototypes(prototypes: SortedSources) {
    let color = atty::is(atty::Stream::Stdout);
    for (name, p) in prototypes {
        show_prototype(&name, &p, color);
    }
}

fn main() -> Result<()> {
    let mut options = getopts::Options::new();
    options.optflag("h", "help", "print this help menu");
    options.optflag("i", "imports", "also read imported symbols");
    options.optflag(
        "g",
        "globals",
        "also read non-exported, global/weak symbols",
    );
    options.optflag("l", "locals", "also read non-exported, local symbols");
    options.optopt("d", "diff", "show differences with FILE", "FILE");

    let matches = options.parse(env::args().skip(1))?;

    if matches.opt_present("h") || matches.free.is_empty() {
        eprintln!("{}", options.usage("Usage: protodump [options] FILE"));
        process::exit(0);
    }

    let path = &matches.free[0];

    let symbol_filter = SymbolFilter {
        imports: matches.opt_present("i"),
        globals: matches.opt_present("g"),
        locals: matches.opt_present("l"),
    };

    let file = fs::File::open(path).context("failed to open file")?;
    let file_contents = unsafe { memmap::Mmap::map(&file) }.context("failed to mmap file")?;
    let obj = object::File::parse(file_contents.as_ref()).context("failed to parse object")?;

    let mut sources = read_prototypes(&obj).context("failed to extract DWARF information")?;
    let object_info = read_object_info(&obj, symbol_filter)?;

    sources.retain(|func, _| object_info.symbol_whitelist.contains(func.as_str()));

    if let Some(baseline_path) = matches.opt_str("d") {
        let baseline = fs::File::open(baseline_path).context("failed to open diff baseline")?;
        let baseline_contents =
            unsafe { memmap::Mmap::map(&baseline).context("failed to mmap diff baseline")? };
        let baseline_obj = object::File::parse(baseline_contents.as_ref())
            .context("failed to parse diff baseline as an object")?;

        let mut baseline_sources = read_prototypes(&baseline_obj)
            .context("failed to extract DWARF information from diff baseline")?;
        let baseline_object_info = read_object_info(&baseline_obj, symbol_filter)?;

        baseline_sources.retain(|func, _| {
            baseline_object_info
                .symbol_whitelist
                .contains(func.as_str())
        });

        let mut is_match = true;

        if baseline_object_info != object_info {
            show_object_info_diff(&baseline_object_info, &object_info);
            is_match = false;
        }

        let d = diff_sources(baseline_sources, sources);
        show_source_diff(&d);
        is_match = is_match && d.is_empty();

        if is_match {
            process::exit(0);
        } else {
            process::exit(1);
        }
    } else {
        println!("OBJECT FILE {}", path);
        println!("Container type: {:?}", object_info.container_type);
        if object_info.is_little_endian {
            println!("Endianness: little");
        } else {
            println!("Endianness: big");
        }
        if !sources.is_empty() {
            println!();
            let sorted_sources = sort_prototypes(sources);
            show_prototypes(sorted_sources);
        }
    }

    Ok(())
}