symbolizer-rs 0.4.0

A fast execution trace symbolizer for Windows that runs on all major platforms and doesn't depend on any Microsoft libraries.
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
// Axel '0vercl0k' Souchet - February 19 2024
#![doc = include_str!("../README.md")]
#![allow(clippy::missing_panics_doc)]
use std::fmt::Display;
use std::fs::File;
use std::io::{BufReader, BufWriter, Write, stdout};
use std::path::{Path, PathBuf};
use std::time::Instant;
use std::{env, fs, io};

use addr_symbolizer::{AddrSpace, Module, PdbLookupConfig, Symbolizer};
use anyhow::{Context, Result, anyhow, bail};
use clap::{ArgAction, Parser, ValueEnum};
use kdmp_parser::parse::KernelDumpParser;

mod hex_addrs_iter;
mod human;

use hex_addrs_iter::HexAddressesIterator;
use human::ToHuman;
use kdmp_parser::virt;

#[derive(Debug)]
struct StatsBuilder {
    start: Instant,
    n_files: u64,
}

impl Default for StatsBuilder {
    fn default() -> Self {
        Self {
            start: Instant::now(),
            n_files: 0,
        }
    }
}

impl StatsBuilder {
    pub fn done_file(&mut self) {
        self.n_files += 1;
    }

    pub fn stop(self, symbolizer: Symbolizer) -> Stats {
        let stats = Stats {
            time: self.start.elapsed().as_secs(),
            n_files: self.n_files,
            symbolizer_stats: symbolizer.stats().clone(),
        };

        drop(symbolizer);

        stats
    }
}

struct Stats {
    time: u64,
    n_files: u64,
    #[expect(clippy::struct_field_names)]
    symbolizer_stats: addr_symbolizer::Stats,
}

impl Display for Stats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "✓ Successfully symbolized {} lines across {} files in {} ({}% cache hits",
            self.symbolizer_stats.n_addrs.human_number(),
            self.n_files.human_number(),
            self.time.human_time(),
            percentage(
                self.symbolizer_stats.cache_hit,
                self.symbolizer_stats.n_addrs
            )
        )?;

        let size_downloaded = self.symbolizer_stats.amount_downloaded();
        if size_downloaded > 0 {
            write!(
                f,
                ", downloaded {} / {} PDBs)",
                size_downloaded.human_bytes(),
                self.symbolizer_stats.pdb_download_count().human_number()
            )
        } else {
            write!(f, ")")
        }
    }
}

#[derive(Debug)]
struct AddrSpaceWrapper {
    parser: KernelDumpParser,
}

impl AddrSpaceWrapper {
    fn new(parser: KernelDumpParser) -> Self {
        Self { parser }
    }
}

impl AddrSpace for AddrSpaceWrapper {
    fn read_at(&mut self, addr: u64, buf: &mut [u8]) -> io::Result<usize> {
        virt::Reader::new(&self.parser)
            .read(addr.into(), buf)
            .map_err(|e| io::Error::new(io::ErrorKind::Unsupported, e))
    }
}

/// The style of the symbols.
#[derive(Default, Debug, Clone, ValueEnum)]
enum SymbolStyle {
    /// Module + offset style like `foo.dll+0x11`.
    Modoff,
    /// Full symbol style like `foo.dll!func+0x11`.
    #[default]
    Full,
}

/// The default maximum amount of lines to process per file.
const DEFAULT_LIMIT: usize = 20_000_000;

/// The command line arguments.
#[derive(Debug, Default, Parser)]
#[command(about = "A fast execution trace symbolizer for Windows.")]
struct CliArgs {
    /// Directory path full of traces or single input trace file.
    #[arg(short, long)]
    trace: PathBuf,
    /// Output directory where to write symbolized traces, a path to an output
    /// file, or empty for the output to go on stdout.
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// Path to the crash-dump to load. If not specified, an attempt is made to
    /// find a 'state/mem.dmp' file in the same directory than the trace file.
    #[arg(short, long)]
    crash_dump: Option<PathBuf>,
    /// Skip a number of lines.
    #[arg(short, long, default_value_t = 0)]
    skip: usize,
    /// The maximum amount of lines to process per file (defaults to 20m, use
    /// `0` for no limit).
    #[arg(short, long)]
    limit: Option<usize>,
    /// The symbolization style (mod+offset or mod!f+offset).
    #[arg(long, default_value = "full")]
    style: SymbolStyle,
    /// Overwrite the output files if they exist.
    #[arg(long, default_value_t = false)]
    overwrite: bool,
    /// Include line numbers in the symbolized output.
    #[arg(long, default_value_t = false)]
    line_numbers: bool,
    /// Symbol servers to use to download PDBs; you can provide more than one.
    #[arg(long, default_value = "https://msdl.microsoft.com/download/symbols/", action = ArgAction::Append)]
    symsrvs: Vec<String>,
    /// Specify a symbol cache path. If not specified, `_NT_SYMBOL_PATH` will be
    /// parsed if present.
    #[arg(long)]
    symcache: Option<PathBuf>,
    /// Import PDBs found in the specified directories into the symbol cache.
    #[arg(long)]
    import_pdbs: Option<Vec<PathBuf>>,
    /// The size in bytes of the buffer used to write data into the output
    /// files.
    #[arg(long, default_value_t = 3 * 1_024 * 1_024)]
    out_buffer_size: usize,
    /// The size in bytes of the buffer used to read data from the input files.
    #[arg(long, default_value_t = 1_024 * 1_024)]
    in_buffer_size: usize,
    /// Don't try to download PDBs off the network.
    #[arg(long, default_value_t = false)]
    offline: bool,
}

/// Calculate a percentage value.
#[must_use]
pub fn percentage(how_many: u64, how_many_total: u64) -> u32 {
    assert!(
        how_many_total > 0,
        "{how_many_total} needs to be bigger than 0"
    );

    let p = (how_many * 1_00) / how_many_total;
    assert!(p <= 100);

    u32::try_from(p).unwrap()
}

/// Parse the `_NT_SYMBOL_PATH` environment variable to try the path of a symbol
/// cache.
fn sympath() -> Option<PathBuf> {
    let env = env::var("_NT_SYMBOL_PATH").ok()?;

    if !env.starts_with("srv*") {
        return None;
    }

    let sympath = env.strip_prefix("srv*").unwrap();
    let sympath = PathBuf::from(sympath.split('*').next().unwrap());

    if sympath.is_dir() {
        Some(sympath)
    } else {
        None
    }
}

/// Create the output file from an input.
///
/// This logic was moved into a function to be able to handle the `--overwrite`
/// logic and to handle the case when `output` is a directory path and not a
/// file path. In that case, we will create a file with the same input file
/// name, but with a specific suffix.
fn get_output_file(args: &CliArgs, input: &Path, output: &Path) -> Result<File> {
    let output_path = if output.is_dir() {
        // If the output is a directory, then we'll create a file that has the same file
        // name as the input, but with a suffix.
        let path = input.with_extension("symbolized.txt");
        let filename = path.file_name().ok_or_else(|| anyhow!("no file name"))?;

        output.join(filename)
    } else {
        // If the output path is already a file path, then we'll use it as is.
        output.into()
    };

    // If the output exists, we'll want the user to tell us to overwrite those
    // files.
    if output_path.exists() && !args.overwrite {
        // If they don't we will bail.
        bail!(
            "{} already exists, run with --overwrite",
            output_path.display()
        );
    }

    // We can now create the output file!
    File::create(output_path.clone())
        .with_context(|| format!("failed to create output file {}", output_path.display()))
}

/// Process an input file and symbolize every line.
fn symbolize_file(
    symbolizer: &mut Symbolizer,
    addr_space: &mut impl AddrSpace,
    trace_path: impl AsRef<Path>,
    args: &CliArgs,
) -> Result<usize> {
    let trace_path = trace_path.as_ref();
    let input = File::open(trace_path)
        .with_context(|| format!("failed to open {}", trace_path.display()))?;

    let writer: &mut dyn Write = match &args.output {
        Some(output) => &mut get_output_file(args, trace_path, output)?,
        None => &mut stdout(),
    };

    let mut output = BufWriter::with_capacity(args.out_buffer_size, writer);
    let mut lines_symbolized = 1;
    let limit = match args.limit.unwrap_or(DEFAULT_LIMIT) {
        // The `0` value is used as a way to say "there's no limit".
        0 => None,
        rest => Some(rest),
    };

    let reader = BufReader::with_capacity(args.in_buffer_size, input);
    for (line_number, addr) in
        (1 + args.skip..).zip(HexAddressesIterator::new(reader).skip(args.skip))
    {
        let addr = addr.with_context(|| {
            format!(
                "failed to get hex addr from l{line_number} of {}",
                trace_path.display()
            )
        })?;

        if args.line_numbers {
            let mut buffer = itoa::Buffer::new();
            output.write_all(b"l")?;
            output.write_all(buffer.format(line_number).as_bytes())?;
            output.write_all(b": ")?;
        }

        match args.style {
            SymbolStyle::Modoff => symbolizer.symbolize_modoff_into(addr, &mut output),
            SymbolStyle::Full => symbolizer.symbolize_full_into(addr_space, addr, &mut output),
        }
        .with_context(|| {
            format!(
                "failed to symbolize l{line_number} of {}",
                trace_path.display()
            )
        })?;

        output.write_all(b"\n")?;

        if let Some(limit) = limit
            && lines_symbolized >= limit
        {
            println!(
                "Hit maximum line limit {} for {}",
                limit,
                trace_path.display()
            );
            break;
        }

        lines_symbolized += 1;
    }

    Ok(lines_symbolized)
}

fn main() -> Result<()> {
    #[cfg(debug_assertions)]
    env_logger::init();

    // Parse the CLI arguments.
    let args = CliArgs::parse();

    // Figure out the path to the crash-dump we will use. We will use the one
    // specified by the user, or we will try to find one ourselves.
    let crash_dump_path = if let Some(dump_path) = &args.crash_dump {
        dump_path.clone()
    } else {
        let wtf_base_path = args.trace.parent().expect("parent");
        let wtf_crash_dump_path = wtf_base_path.join("state").join("mem.dmp");
        if !wtf_crash_dump_path.is_file() {
            bail!(
                "A dump file wasn't specified, and a wtf state directory wasn't found either in {}. Please use --crash-dump.",
                wtf_base_path.display()
            );
        }

        println!(
            "A dump file wasn't specified, but found {} so using it..",
            wtf_crash_dump_path.display()
        );

        wtf_crash_dump_path
    };

    // We need to parse the crash-dump to figure out where drivers / user-modules
    // are loaded at, and to read enough information out of the PE to download PDB
    // files ourselves.
    let parser = KernelDumpParser::new(crash_dump_path).context("failed to create dump parser")?;

    // Figure out what is the symbol path we should be using. We will use the one
    // specified by the user, or will try to find one in the `_NT_SYMBOL_PATH`
    // environment variable if it is defined.
    let Some(symcache) = (match args.symcache.clone() {
        Some(symcache) => Some(symcache),
        None => sympath(),
    }) else {
        bail!("no sympath");
    };

    let mut modules = Vec::new();
    for (at, name) in parser.user_modules().chain(parser.kernel_modules()) {
        let (_, filename) = name.rsplit_once('\\').unwrap_or((name, name));
        modules.push(Module::new(
            filename.to_string(),
            at.start.into(),
            at.end.into(),
        ));
    }

    // All right, ready to create the symbolizer.
    let mut wrapper = AddrSpaceWrapper::new(parser);
    let pdb_lookup = if args.offline {
        PdbLookupConfig::new(symcache)
    } else {
        PdbLookupConfig::with_symsrvs(symcache, args.symsrvs.clone())
    }?;
    let mut symbolizer = Symbolizer::new(pdb_lookup, modules);

    if let Some(import_pdbs) = &args.import_pdbs {
        symbolizer.import_pdbs(import_pdbs.iter())?;
    }

    let paths = if args.trace.is_dir() {
        // If we received a path to a directory as input, then we will try to symbolize
        // every file inside that directory..
        let entries = fs::read_dir(&args.trace)?;

        entries
            .map(|e| e.map(|e| e.path()).context(""))
            .collect::<Result<Vec<_>>>()?
    } else {
        // .. or the user specified a path to a file in which case this is the file
        // we'll symbolize.
        vec![args.trace.clone()]
    };

    let mut stats_builder = StatsBuilder::default();
    let total = paths.len();
    for (idx, path) in paths.into_iter().enumerate() {
        print!("\x1B[2K\r");
        symbolize_file(&mut symbolizer, &mut wrapper, &path, &args)?;
        stats_builder.done_file();
        print!("[{}/{total}] {} done", idx + 1, path.display());
        io::stdout().flush()?;
    }

    // Grab a few stats before exiting!
    let stats = stats_builder.stop(symbolizer);
    println!("\x1B[2K\r{stats}");

    Ok(())
}