~taiite/protodump

ref: d31d7df84aff952cd06147d47a8abad0b0410516 protodump/src/main.rs -rw-r--r-- 10.6 KiB
d31d7df8Hubert Hirtz Handle DW_AT_class_type 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
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
#![feature(arc_new_cyclic)]

use anyhow::Context;
use anyhow::Result;
use object::read::Object as _;
use object::read::ObjectSection as _;
use object::read::ObjectSymbol as _;
use std::borrow::Cow;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::process;

mod dwarf;
mod types;

type Reader<'a> = gimli::EndianSlice<'a, gimli::RunTimeEndian>;
type Sources<'a> = dwarf::Sources<'a, Reader<'a>>;

fn read_dwarf<'a>(obj: &object::File<'a>) -> gimli::Result<gimli::Dwarf<Cow<'a, [u8]>>> {
    let load_section = |section_id: gimli::SectionId| -> gimli::Result<Cow<[u8]>> {
        let section_data = obj
            .section_by_name(section_id.name())
            .and_then(|section| section.uncompressed_data().ok())
            .unwrap_or(Cow::Borrowed(&[]));
        Ok(section_data)
    };
    gimli::Dwarf::load(&load_section)
}

#[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<'a> {
    Added,
    Removed,
    Changed(dwarf::Subprogram<Reader<'a>>),
}

fn diff_sources<'a>(
    prev: Sources<'a>,
    mut next: Sources<'a>,
) -> Vec<(Reader<'a>, dwarf::Subprogram<Reader<'a>>, Diff<'a>)> {
    let mut res: Vec<_> = prev
        .subprograms
        .into_iter()
        .filter_map(|(prev_func, prev_prototype)| {
            let next_prototype = if let Some(p) = next.subprograms.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
        .subprograms
        .into_iter()
        .map(|(func, prototype)| (func, prototype, Diff::Added));
    res.extend(added);

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

    res
}

fn show_source_diff(d: &[(Reader<'_>, dwarf::Subprogram<Reader<'_>>, 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 show_prototype(name: Reader<'_>, prototype: &dwarf::Subprogram<Reader<'_>>, color: bool) {
    let return_type = prototype.return_type.borrow();
    print!("{}{}", return_type, return_type.display_padding());
    if color {
        print!(
            "{}(",
            ansi_term::Style::new().bold().paint(name.to_string_lossy())
        );
    } else {
        print!("{}(", name.to_string_lossy());
    }
    let mut first = true;
    for param in &prototype.parameters {
        if first {
            first = false;
        } else {
            print!(", ");
        }
        let type_ = param.type_.borrow();
        print!("{}", type_);
        if let Some(name) = param.name {
            print!("{}{}", type_.display_padding(), name.to_string_lossy());
        }
    }
    println!(");");
}

fn show_prototypes(sources: Sources<'_>) {
    let color = atty::is(atty::Stream::Stdout);
    // TODO show types
    let mut prototypes: Vec<_> = sources.subprograms.into_iter().collect();
    prototypes.sort_unstable_by(|(func1, _), (func2, _)| func1.slice().cmp(func2.slice()));
    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 dwarf = read_dwarf(&obj).context("failed to extract DWARF information")?;
    let endian = if obj.is_little_endian() {
        gimli::RunTimeEndian::Little
    } else {
        gimli::RunTimeEndian::Big
    };
    let dwarf = dwarf.borrow(|section| gimli::EndianSlice::new(section, endian));
    let mut sources = Sources::parse(&dwarf)?;
    let object_info = read_object_info(&obj, symbol_filter)?;

    sources.subprograms.retain(|func, _| {
        object_info
            .symbol_whitelist
            .contains(func.to_string_lossy().as_ref())
    });

    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 baseline_dwarf =
            read_dwarf(&baseline_obj).context("failed to extract DWARF information")?;
        let baseline_endian = if baseline_obj.is_little_endian() {
            gimli::RunTimeEndian::Little
        } else {
            gimli::RunTimeEndian::Big
        };
        let baseline_dwarf =
            baseline_dwarf.borrow(|section| gimli::EndianSlice::new(section, baseline_endian));
        let mut baseline_sources = Sources::parse(&baseline_dwarf)?;
        let baseline_object_info = read_object_info(&baseline_obj, symbol_filter)?;

        baseline_sources.subprograms.retain(|func, _| {
            baseline_object_info
                .symbol_whitelist
                .contains(func.to_string_lossy().as_ref())
        });

        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.subprograms.is_empty() {
            println!();
            show_prototypes(sources);
        }
    }

    Ok(())
}