blazesym 0.2.3

blazesym is a library for address symbolization and related tasks.
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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Definitions of supported symbolization sources.

use std::cmp::min;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::path::PathBuf;

use crate::MaybeDefault;
use crate::Pid;

#[cfg(doc)]
use super::Symbolizer;


cfg_apk! {
/// A single APK file.
///
/// This type is used in the [`Source::Apk`] variant.
#[derive(Clone)]
pub struct Apk {
    /// The path to an APK file.
    pub path: PathBuf,
    /// Whether or not to consult debug symbols to satisfy the request
    /// (if present).
    ///
    /// On top of this runtime configuration, the crate needs to be
    /// built with the `dwarf` feature to actually consult debug
    /// symbols. If neither is satisfied, ELF symbols will be used.
    pub debug_syms: bool,
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl Apk {
    /// Create a new [`Apk`] object, referencing the provided path.
    ///
    /// `debug_syms` defaults to `true` when using this constructor.
    #[inline]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            debug_syms: true,
            _non_exhaustive: (),
        }
    }
}

impl From<Apk> for Source<'static> {
    #[inline]
    fn from(apk: Apk) -> Self {
        Self::Apk(apk)
    }
}

impl Debug for Apk {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self {
            path,
            debug_syms: _,
            _non_exhaustive: (),
        } = self;

        f.debug_tuple(stringify!(Apk)).field(path).finish()
    }
}
}


cfg_breakpad! {
/// A single Breakpad file.
///
/// This type is used in the [`Source::Breakpad`] variant.
#[derive(Clone)]
pub struct Breakpad {
    /// The path to a Breakpad file.
    pub path: PathBuf,
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl Breakpad {
    /// Create a new [`Breakpad`] object, referencing the provided path.
    #[inline]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            _non_exhaustive: (),
        }
    }
}

impl From<Breakpad> for Source<'static> {
    #[inline]
    fn from(breakpad: Breakpad) -> Self {
        Self::Breakpad(breakpad)
    }
}

impl Debug for Breakpad {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self {
            path,
            _non_exhaustive: (),
        } = self;

        f.debug_tuple(stringify!(Breakpad)).field(path).finish()
    }
}
}


/// A single ELF file.
///
/// This type is used in the [`Source::Elf`] variant.
#[derive(Clone)]
pub struct Elf {
    /// The path to an ELF file.
    pub path: PathBuf,
    /// Whether or not to consult debug symbols to satisfy the request
    /// (if present).
    ///
    /// On top of this runtime configuration, the crate needs to be
    /// built with the `dwarf` feature to actually consult debug
    /// symbols. If neither is satisfied, ELF symbols will be used.
    ///
    /// Debug symbols are anything DWARF related. This can be DWARF data
    /// directly embedded in the ELF file, separate DWARF packages
    /// discovered by adding the `.dwp` extension to `path`, as well as
    /// data referenced via debug links inside the binary. For the
    /// latter, the directories that are searched for candidate files
    /// can be configured via [`Builder::set_debug_dirs`][debug_dirs].
    ///
    /// [debug_dirs]: crate::symbolize::Builder::set_debug_dirs
    pub debug_syms: bool,
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl Elf {
    /// Create a new [`Elf`] object, referencing the provided path.
    ///
    /// `debug_syms` defaults to `true` when using this constructor.
    #[inline]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            debug_syms: true,
            _non_exhaustive: (),
        }
    }
}

impl From<Elf> for Source<'static> {
    #[inline]
    fn from(elf: Elf) -> Self {
        Self::Elf(elf)
    }
}

impl Debug for Elf {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self {
            path,
            debug_syms: _,
            _non_exhaustive: (),
        } = self;

        f.debug_tuple(stringify!(Elf)).field(path).finish()
    }
}


/// Configuration for kernel address symbolization.
///
/// This type is used in the [`Source::Kernel`] variant.
#[derive(Clone, Debug, PartialEq)]
pub struct Kernel {
    /// The path of a `kallsyms` file to use.
    ///
    /// By default, this will refer to `kallsyms` of the running kernel.
    /// If set to [`None`][MaybeDefault::None] usage of `kallsyms` will
    /// be disabled. Otherwise the copy at the given path will be used.
    ///
    /// If both a `vmlinux` as well as a `kallsyms` file are found,
    /// `vmlinux` will generally be given preference and `kallsyms` acts
    /// as a fallback.
    pub kallsyms: MaybeDefault<PathBuf>,
    /// The path of the `vmlinux` file to use.
    ///
    /// `vmlinux` is generally an uncompressed and unstripped object
    /// file that is typically used in debugging, profiling, and
    /// similar use cases.
    ///
    /// By default, the library will search for candidates in various
    /// locations, taking into account the currently running kernel
    /// version. If set to [`None`][MaybeDefault::None] discovery and
    /// usage of a vmlinux file will be disabled. Otherwise the copy at
    /// the given path will be used.
    ///
    /// If both a `vmlinux` as well as a `kallsyms` file are found,
    /// `vmlinux` will generally be given preference and `kallsyms` acts
    /// as a fallback.
    pub vmlinux: MaybeDefault<PathBuf>,
    /// The KASLR offset to use.
    ///
    /// Given a value of `None`, the library will attempt to deduce the
    /// offset itself. Note that this value only has relevance when a
    /// kernel image is used for symbolization, because `kallsyms` based
    /// data already include randomization adjusted addresses.
    pub kaslr_offset: Option<u64>,
    /// Whether or not to consult debug symbols from `vmlinux` to
    /// satisfy the request (if present).
    ///
    /// On top of this runtime configuration, the crate needs to be
    /// built with the `dwarf` feature to actually consult debug
    /// symbols. If either is not satisfied, only ELF symbols will be
    /// used.
    pub debug_syms: bool,
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl Default for Kernel {
    fn default() -> Self {
        Self {
            kallsyms: MaybeDefault::Default,
            vmlinux: MaybeDefault::Default,
            kaslr_offset: None,
            debug_syms: true,
            _non_exhaustive: (),
        }
    }
}

impl From<Kernel> for Source<'static> {
    #[inline]
    fn from(kernel: Kernel) -> Self {
        Self::Kernel(kernel)
    }
}


/// Configuration for process based address symbolization.
///
/// This type is used in the [`Source::Process`] variant.
///
/// The corresponding addresses supplied to [`Symbolizer::symbolize`] are
/// expected to be absolute addresses
/// ([`Input::AbsAddr`][crate::symbolize::Input::AbsAddr]) as valid within the
/// process identified by the [`pid`][Process::pid] member.
///
/// # Notes
/// Please note that process symbolization is generally a privileged operation
/// and may require the granting of additional capabilities compared to other
/// symbolization sources.
#[derive(Clone)]
pub struct Process {
    /// The referenced process' ID.
    pub pid: Pid,
    /// Whether or not to consult debug symbols to satisfy the request
    /// (if present).
    ///
    /// On top of this runtime configuration, the crate needs to be
    /// built with the `dwarf` feature to actually consult debug
    /// symbols. If neither is satisfied, ELF symbols will be used.
    pub debug_syms: bool,
    /// Whether to incorporate a process' [perf map] file into the
    /// symbolization procedure.
    ///
    /// Perf map files mostly have relevance in just-in-time compiled languages,
    /// where they provide an interface for the runtime to expose addresses of
    /// dynamic symbols to profiling tools.
    ///
    /// [perf map]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/perf/Documentation/jit-interface.txt
    pub perf_map: bool,
    /// Whether to work with `/proc/<pid>/map_files/` entries or with
    /// symbolic paths mentioned in `/proc/<pid>/maps` instead.
    ///
    /// `map_files` usage is generally strongly encouraged, as symbolic
    /// path usage is unlikely to work reliably in mount namespace
    /// contexts or when files have been deleted from the file system.
    /// However, by using symbolic paths the need for requiring the
    /// `SYS_ADMIN` capability is eliminated.
    pub map_files: bool,
    /// Whether or not to symbolize addresses in a vDSO (virtual dynamic
    /// shared object).
    pub vdso: bool,
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl Process {
    /// Create a new [`Process`] object using the provided `pid`.
    ///
    /// `debug_syms`, `perf_map`, `map_files`, and `vdso` default to
    /// `true` when using this constructor.
    #[inline]
    pub fn new(pid: Pid) -> Self {
        Self {
            pid,
            debug_syms: true,
            perf_map: true,
            map_files: true,
            vdso: true,
            _non_exhaustive: (),
        }
    }
}

impl Debug for Process {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self {
            pid,
            debug_syms: _,
            perf_map: _,
            map_files: _,
            vdso: _,
            _non_exhaustive: (),
        } = self;

        f.debug_tuple(stringify!(Process))
            // We use the `Display` representation here.
            .field(&format_args!("{pid}"))
            .finish()
    }
}

impl From<Process> for Source<'static> {
    #[inline]
    fn from(process: Process) -> Self {
        Self::Process(process)
    }
}


cfg_gsym! {
/// Enumeration of supported Gsym sources.
///
/// This type is used in the [`Source::Gsym`] variant.
#[derive(Clone)]
pub enum Gsym<'dat> {
    /// "Raw" Gsym data.
    Data(GsymData<'dat>),
    /// A Gsym file.
    File(GsymFile),
}

impl Debug for Gsym<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            Self::Data(data) => Debug::fmt(data, f),
            Self::File(file) => Debug::fmt(file, f),
        }
    }
}

impl<'dat> From<Gsym<'dat>> for Source<'dat> {
    #[inline]
    fn from(gsym: Gsym<'dat>) -> Self {
        Self::Gsym(gsym)
    }
}


/// Gsym data.
#[derive(Clone)]
pub struct GsymData<'dat> {
    /// The "raw" Gsym data.
    pub data: &'dat [u8],
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl<'dat> GsymData<'dat> {
    /// Create a new [`GsymData`] object, referencing the provided path.
    #[inline]
    pub fn new(data: &'dat [u8]) -> Self {
        Self {
            data,
            _non_exhaustive: (),
        }
    }
}

impl Debug for GsymData<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self {
            data,
            _non_exhaustive: (),
        } = self;

        f.debug_tuple(stringify!(GsymData))
            .field(&data.get(0..(min(data.len(), 32))).unwrap_or_default())
            .finish()
    }
}

impl<'dat> From<GsymData<'dat>> for Source<'dat> {
    #[inline]
    fn from(gsym: GsymData<'dat>) -> Self {
        Self::Gsym(Gsym::Data(gsym))
    }
}


/// A Gsym file.
#[derive(Clone)]
pub struct GsymFile {
    /// The path to the Gsym file.
    pub path: PathBuf,
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl GsymFile {
    /// Create a new [`GsymFile`] object, referencing the provided path.
    #[inline]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            _non_exhaustive: (),
        }
    }
}

impl Debug for GsymFile {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self {
            path,
            _non_exhaustive: (),
        } = self;

        f.debug_tuple(stringify!(GsymFile)).field(path).finish()
    }
}

impl From<GsymFile> for Source<'static> {
    #[inline]
    fn from(gsym: GsymFile) -> Self {
        Self::Gsym(Gsym::File(gsym))
    }
}
}


/// The description of a source of symbols and debug information that the
/// library will consult to satisfy an address symbolization request.
///
/// Objects of this type are used first and foremost with the
/// [`Symbolizer::symbolize`] method.
#[derive(Clone)]
#[non_exhaustive]
pub enum Source<'dat> {
    /// A single APK file.
    #[cfg(feature = "apk")]
    #[cfg_attr(docsrs, doc(cfg(feature = "apk")))]
    Apk(Apk),
    /// A single Breakpad file.
    #[cfg(feature = "breakpad")]
    #[cfg_attr(docsrs, doc(cfg(feature = "breakpad")))]
    Breakpad(Breakpad),
    /// A single ELF file.
    Elf(Elf),
    /// Information about the Linux kernel.
    Kernel(Kernel),
    /// Information about a process.
    Process(Process),
    /// A Gsym file.
    #[cfg(feature = "gsym")]
    #[cfg_attr(docsrs, doc(cfg(feature = "gsym")))]
    Gsym(Gsym<'dat>),
    #[doc(hidden)]
    Phantom(&'dat ()),
}

impl Debug for Source<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            #[cfg(feature = "apk")]
            Self::Apk(apk) => Debug::fmt(apk, f),
            #[cfg(feature = "breakpad")]
            Self::Breakpad(breakpad) => Debug::fmt(breakpad, f),
            Self::Elf(elf) => Debug::fmt(elf, f),
            Self::Kernel(kernel) => Debug::fmt(kernel, f),
            Self::Process(process) => Debug::fmt(process, f),
            #[cfg(feature = "gsym")]
            Self::Gsym(gsym) => Debug::fmt(gsym, f),
            Self::Phantom(()) => unreachable!(),
        }
    }
}


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


    /// Exercise the `Debug` representation of various types.
    #[test]
    fn debug_repr() {
        let apk = Apk::new("/a-path/with/components.apk");
        assert_eq!(format!("{apk:?}"), "Apk(\"/a-path/with/components.apk\")");
        let src = Source::from(apk);
        assert_eq!(format!("{src:?}"), "Apk(\"/a-path/with/components.apk\")");

        let breakpad = Breakpad::new("/a-path/with/components.sym");
        assert_eq!(
            format!("{breakpad:?}"),
            "Breakpad(\"/a-path/with/components.sym\")"
        );
        let src = Source::from(breakpad);
        assert_eq!(
            format!("{src:?}"),
            "Breakpad(\"/a-path/with/components.sym\")"
        );

        let elf = Elf::new("/a-path/with/components.elf");
        assert_eq!(format!("{elf:?}"), "Elf(\"/a-path/with/components.elf\")");
        let src = Source::from(elf);
        assert_eq!(format!("{src:?}"), "Elf(\"/a-path/with/components.elf\")");

        let gsym_data = GsymData::new(b"12345");
        assert_eq!(format!("{gsym_data:?}"), "GsymData([49, 50, 51, 52, 53])");
        let gsym = Gsym::Data(gsym_data.clone());
        assert_eq!(format!("{gsym:?}"), "GsymData([49, 50, 51, 52, 53])");

        let gsym_file = GsymFile::new("/a-path/gsym");
        assert_eq!(format!("{gsym_file:?}"), "GsymFile(\"/a-path/gsym\")");
        let gsym = Gsym::File(gsym_file);
        assert_eq!(format!("{gsym:?}"), "GsymFile(\"/a-path/gsym\")");
        let src = Source::from(gsym);
        assert_eq!(format!("{src:?}"), "GsymFile(\"/a-path/gsym\")");
        let src = Source::from(Gsym::Data(gsym_data));
        assert_eq!(format!("{src:?}"), "GsymData([49, 50, 51, 52, 53])");

        let kernel = Kernel::default();
        assert_ne!(format!("{kernel:?}"), "");
        let src = Source::from(kernel);
        assert_ne!(format!("{src:?}"), "");

        let process = Process::new(Pid::Slf);
        assert_eq!(format!("{process:?}"), "Process(self)");
        let process = Process::new(Pid::from(1234));
        assert_eq!(format!("{process:?}"), "Process(1234)");
        let src = Source::from(process);
        assert_eq!(format!("{src:?}"), "Process(1234)");
    }
}