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
use std::borrow::Cow;
use std::cell::OnceCell;
use std::fs::File;
use std::ops::Range;
use std::path::Path;
use std::path::PathBuf;

#[cfg(feature = "apk")]
use crate::apk::create_apk_elf_path;
use crate::elf::ElfParser;
use crate::elf::StaticMem;
use crate::file_cache::FileCache;
use crate::insert_map::InsertMap;
use crate::maps;
use crate::util;
#[cfg(feature = "tracing")]
use crate::util::Hexify;
use crate::util::OnceCellExt as _;
use crate::vdso::create_vdso_parser;
#[cfg(feature = "apk")]
use crate::zip;
use crate::Addr;
use crate::Error;
use crate::ErrorExt as _;
use crate::IntoError as _;
use crate::Mmap;
use crate::Pid;
use crate::Result;

use super::buildid::read_build_id;
use super::buildid::read_elf_build_id_from_mmap;
use super::buildid::BuildId;
use super::ioctl::query_procmap;
use super::user;
use super::user::normalize_sorted_user_addrs_with_entries;
use super::user::UserOutput;
use super::NormalizeOpts;


/// A type capturing normalized outputs along with captured meta data.
///
/// This type enables "remote" symbolization. That is to say, it represents the
/// input necessary for addresses to be symbolized on a system other than where
/// they were recorded.
#[derive(Clone, Debug)]
pub struct Output<M> {
    /// Outputs along with an index into `meta` for retrieval of the
    /// corresponding meta information.
    ///
    /// The output is a file offset when normalization was successful and the
    /// unnormalized input address otherwise. Normalization errors are indicated
    /// by an index referencing a [`Unknown`][crate::normalize::Unknown] object.
    ///
    /// A file offset is one as it would appear in a binary or debug symbol
    /// file, i.e., one excluding any relocations. The data reported here can be
    /// used with the
    /// [`symbolize::Input::FileOffset`][crate::symbolize::Input::FileOffset]
    /// variant.
    pub outputs: Vec<(u64, usize)>,
    /// Meta information about the normalized outputs.
    pub meta: Vec<M>,
}


/// A builder for configurable construction of [`Normalizer`] objects.
///
/// By default `/proc/<pid>/maps` contents are parsed to query available
/// VMA ranges (instead of using the `PROCMAP_QUERY` ioctl). Reading of
/// build IDs is enabled, but they are not being cached. The caching of
/// VMA ranges is also disabled.
#[derive(Clone, Debug)]
pub struct Builder {
    /// See [`Builder::enable_procmap_query`].
    use_procmap_query: bool,
    /// See [`Builder::enable_vma_caching`].
    cache_vmas: bool,
    /// See [`Builder::enable_build_ids`].
    build_ids: bool,
    /// See [`Builder::enable_build_id_caching`].
    cache_build_ids: bool,
}

impl Builder {
    /// Enable/disable the usage of the `PROCMAP_QUERY` ioctl instead of
    /// parsing `/proc/<pid>/maps` for getting available VMA ranges.
    ///
    /// Refer to
    /// [`helper::is_procmap_query_supported`][crate::helper::is_procmap_query_supported]
    /// as a way to check whether your system supports this
    /// functionality.
    ///
    /// # Notes
    /// Support for this ioctl is only present on kernels of version
    /// 6.11 or higher. See <https://lwn.net/Articles/979931/> for
    /// details.
    ///
    /// Furthermore, the ioctl will also be used for retrieving build
    /// IDs (if enabled). Build ID reading logic in the kernel is known
    /// to be incomplete in 6.11 and earlier, but a fix included with
    /// 6.12.
    pub fn enable_procmap_query(mut self, enable: bool) -> Builder {
        self.use_procmap_query = enable;
        self
    }

    /// Enable/disable caching VMA ranges and meta data (excluding build
    /// IDs).
    ///
    /// Setting this flag to `true` is not generally recommended, because it
    /// could result in addresses corresponding to mappings added after caching
    /// may not be normalized successfully, as there is no reasonable way of
    /// detecting staleness.
    ///
    /// Please note than if the `PROCMAP_QUERY` ioctl is being used, VMA
    /// caching implies build ID caching as well.
    pub fn enable_vma_caching(mut self, enable: bool) -> Builder {
        self.cache_vmas = enable;
        self
    }

    /// Enable/disable the reading of build IDs as appropriate.
    ///
    /// Note that build ID read failures will be swallowed without
    /// failing the normalization operation.
    pub fn enable_build_ids(mut self, enable: bool) -> Builder {
        self.build_ids = enable;
        self
    }

    /// Enable/disable the caching of build IDs.
    ///
    /// # Notes
    /// This property only has a meaning if reading of build IDs is
    /// enabled as well and it is not auto-enabled by this method.
    pub fn enable_build_id_caching(mut self, enable: bool) -> Builder {
        self.cache_build_ids = enable;
        self
    }

    /// Create the [`Normalizer`] object.
    pub fn build(self) -> Normalizer {
        let Builder {
            use_procmap_query,
            cache_vmas,
            build_ids,
            cache_build_ids,
        } = self;

        Normalizer {
            use_procmap_query,
            cache_vmas,
            build_ids,
            cache_build_ids: build_ids && cache_build_ids,
            #[cfg(feature = "apk")]
            apk_cache: FileCache::default(),
            vdso_parser: OnceCell::new(),
            entry_cache: InsertMap::new(),
            build_id_cache: FileCache::default(),
        }
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self {
            use_procmap_query: false,
            cache_vmas: false,
            build_ids: true,
            cache_build_ids: false,
        }
    }
}


/// A normalizer for addresses.
///
/// Address normalization is the process of taking virtual absolute
/// addresses as they are seen by, say, a process (which include
/// relocation and process specific layout randomizations, among other
/// things) and converting them to file offsets. This is typically a
/// very fast running operation. The file offsets can subsequently be
/// used as symbolization input.
///
/// If caching of data is enabled, an instance of this type is the unit
/// at which caching happens. If you are normalizing address in a large
/// number of processes or involving a larger number of binaries with
/// build IDs over time, you may want to consider creating a new
/// `Normalizer` instance regularly to free up cached data.
#[derive(Debug)]
pub struct Normalizer {
    /// See [`Builder::enable_procmap_query`].
    use_procmap_query: bool,
    /// See [`Builder::enable_vma_caching`].
    cache_vmas: bool,
    /// See [`Builder::enable_build_ids`].
    build_ids: bool,
    /// See [`Builder::enable_build_id_caching`].
    cache_build_ids: bool,
    /// Cache for APKs as well as build IDs of ELF files inside them.
    #[cfg(feature = "apk")]
    apk_cache: FileCache<(
        zip::Archive,
        InsertMap<Range<u64>, Option<BuildId<'static>>>,
    )>,
    /// The ELF parser used for the system-wide vDSO.
    vdso_parser: OnceCell<Box<ElfParser<StaticMem>>>,
    /// If `cache_vmas` is `true`, the cached parsed
    /// [`MapsEntry`][maps::MapsEntry] objects.
    entry_cache: InsertMap<Pid, Box<[maps::MapsEntry]>>,
    /// A cache of build IDs.
    build_id_cache: FileCache<Option<BuildId<'static>>>,
}

impl Normalizer {
    /// Create a new [`Normalizer`].
    ///
    /// This method is just a short hand for instantiating a `Normalizer` from
    /// the default [`Builder`].
    #[inline]
    pub fn new() -> Self {
        Builder::default().build()
    }

    /// Retrieve a [`Builder`] object for configurable construction of a
    /// [`Normalizer`].
    #[inline]
    pub fn builder() -> Builder {
        Builder::default()
    }

    fn normalize_user_addrs_impl<'slf, A, E, M>(
        &'slf self,
        pid: Pid,
        addrs: A,
        entries: E,
        opts: &NormalizeOpts,
    ) -> Result<UserOutput<'slf>>
    where
        A: ExactSizeIterator<Item = Addr> + Clone,
        E: FnMut(Addr) -> Option<Result<M>>,
        M: AsRef<maps::MapsEntry>,
    {
        let addrs_cnt = addrs.len();
        let mut handler = user::NormalizationHandler::new(self, opts, pid, addrs_cnt);
        let () = normalize_sorted_user_addrs_with_entries(addrs, entries, &mut handler)?;
        debug_assert_eq!(handler.normalized.outputs.len(), addrs_cnt);
        Ok(handler.normalized)
    }

    fn normalize_user_addrs_iter<A>(
        &self,
        addrs: A,
        pid: Pid,
        opts: &NormalizeOpts,
    ) -> Result<UserOutput<'_>>
    where
        A: ExactSizeIterator<Item = Addr> + Clone,
    {
        if self.use_procmap_query {
            let path = format!("/proc/{pid}/maps");
            let file = File::open(&path)
                .with_context(|| format!("failed to open `{path}` for reading"))?;

            if !self.cache_vmas {
                let entries =
                    move |addr| query_procmap(&file, pid, addr, self.build_ids).transpose();
                self.normalize_user_addrs_impl(pid, addrs, entries, opts)
            } else {
                let entries = self.entry_cache.get_or_try_insert(pid, || {
                    let mut entries = Vec::new();
                    let mut next_addr = 0;
                    while let Some(entry) = query_procmap(&file, pid, next_addr, self.build_ids)? {
                        next_addr = entry.range.end;
                        if maps::filter_relevant(&entry) {
                            let () = entries.push(entry);
                        }
                    }
                    Ok(entries.into_boxed_slice())
                })?;

                let mut entry_iter = entries.iter().map(Ok);
                let entries = |_addr| entry_iter.next();
                self.normalize_user_addrs_impl(pid, addrs, entries, opts)
            }
        } else {
            if !self.cache_vmas {
                let mut entry_iter = maps::parse_filtered(pid)?;
                let entries = |_addr| entry_iter.next();
                self.normalize_user_addrs_impl(pid, addrs, entries, opts)
            } else {
                let parsed = self.entry_cache.get_or_try_insert(pid, || {
                    // If we use the cached maps entries but don't have anything
                    // cached yet, then just parse the file eagerly and take it from
                    // there.
                    let parsed = maps::parse_filtered(pid)?.collect::<Result<Box<_>>>()?;
                    Ok(parsed)
                })?;

                let mut entry_iter = parsed.iter().map(Ok);
                let entries = |_addr| entry_iter.next();
                self.normalize_user_addrs_impl(pid, addrs, entries, opts)
            }
        }
    }

    /// Normalize addresses belonging to a process.
    ///
    /// Normalize all `addrs` in a given process to their corresponding
    /// file offsets, which are suitable for later symbolization.
    ///
    /// Unknown addresses are not normalized. They are reported as
    /// [`Unknown`][crate::normalize::Unknown] meta entries in the returned
    /// [`UserOutput`] object. The cause of an address to be unknown (and,
    /// hence, not normalized), could be manifold, including, but not limited
    /// to:
    /// - user error (if a bogus address was provided)
    /// - they belonged to an ELF object that has been unmapped since the
    ///   address was captured
    ///
    /// The process' ID should be provided in `pid`.
    ///
    /// Normalized outputs are reported in the exact same order (and in
    /// equal amount) in which the non-normalized ones were provided.
    #[cfg_attr(feature = "tracing", crate::log::instrument(skip_all, fields(pid = ?pid, addrs = ?Hexify(addrs)), err))]
    pub fn normalize_user_addrs_opts(
        &self,
        pid: Pid,
        addrs: &[Addr],
        opts: &NormalizeOpts,
    ) -> Result<UserOutput<'_>> {
        if opts.sorted_addrs {
            self.normalize_user_addrs_iter(addrs.iter().copied(), pid, opts)
        } else {
            util::with_ordered_elems(
                addrs,
                |normalized: &mut UserOutput| normalized.outputs.as_mut_slice(),
                |sorted_addrs| self.normalize_user_addrs_iter(sorted_addrs, pid, opts),
            )
        }
    }

    /// Normalize addresses belonging to a process.
    ///
    /// A convenience wrapper around [`Normalizer::normalize_user_addrs_opts`]
    /// that uses the default normalization options.
    pub fn normalize_user_addrs(&self, pid: Pid, addrs: &[Addr]) -> Result<UserOutput<'_>> {
        self.normalize_user_addrs_opts(pid, addrs, &NormalizeOpts::default())
    }

    /// Read the build ID of a file, honoring various settings.
    #[cfg_attr(feature = "tracing", crate::log::instrument(err, skip_all, fields(path = ?path)))]
    pub(crate) fn read_build_id(&self, path: &Path) -> Result<Option<BuildId<'static>>> {
        let build_id = if self.build_ids {
            if self.cache_build_ids {
                let (file, cell) = self.build_id_cache.entry(path)?;
                cell.get_or_try_init_(|| {
                    let parser = ElfParser::from_file(file, path.to_path_buf().into_os_string())?;
                    let build_id =
                        read_build_id(&parser)?.map(|build_id| Cow::Owned(build_id.to_vec()));
                    Result::<_, Error>::Ok(build_id)
                })?
                .clone()
            } else {
                let parser = ElfParser::open(path)?;
                read_build_id(&parser)?.map(|build_id| Cow::Owned(build_id.to_vec()))
            }
        } else {
            // Build ID caching always implies reading of build IDs to
            // begin with.
            debug_assert!(!self.cache_build_ids);
            None
        };
        Ok(build_id)
    }

    /// Translate a file offset inside an APK into a file offset inside
    /// an ELF member inside of it.
    #[cfg(feature = "apk")]
    pub(crate) fn translate_apk_to_elf(
        &self,
        apk_file_off: u64,
        apk_path: &Path,
    ) -> Result<Option<(u64, PathBuf, Option<BuildId<'static>>)>> {
        let (file, cell) = self.apk_cache.entry(apk_path)?;
        let (apk, elf_build_ids) = cell.get_or_try_init_(|| {
            let mmap = Mmap::builder()
                .map(file)
                .with_context(|| format!("failed to memory map `{}`", apk_path.display()))?;
            let apk = zip::Archive::with_mmap(mmap)
                .with_context(|| format!("failed to open zip file `{}`", apk_path.display()))?;
            let elf_build_ids = InsertMap::new();
            Result::<_, Error>::Ok((apk, elf_build_ids))
        })?;

        for apk_entry in apk.entries() {
            let apk_entry = apk_entry
                .with_context(|| format!("failed to iterate `{}` members", apk_path.display()))?;
            let bounds = apk_entry.data_offset..apk_entry.data_offset + apk_entry.data.len() as u64;
            if bounds.contains(&apk_file_off) {
                let elf_build_id = if self.build_ids {
                    let mmap = apk
                        .mmap()
                        .constrain(bounds.clone())
                        .ok_or_invalid_input(|| {
                            format!(
                                "invalid APK entry data bounds ({bounds:?}) in {}",
                                apk_path.display()
                            )
                        })?;

                    if self.cache_build_ids {
                        elf_build_ids
                            .get_or_try_insert(bounds.clone(), || {
                                read_elf_build_id_from_mmap(&mmap)
                            })?
                            .clone()
                    } else {
                        read_elf_build_id_from_mmap(&mmap)?
                    }
                } else {
                    None
                };

                let elf_off = apk_file_off - apk_entry.data_offset;
                let elf_path = create_apk_elf_path(apk_path, apk_entry.path);
                return Ok(Some((elf_off, elf_path, elf_build_id)))
            }
        }
        Ok(None)
    }

    pub(crate) fn vdso_parser<'slf>(
        &'slf self,
        pid: Pid,
        range: &Range<Addr>,
    ) -> Result<&'slf ElfParser<StaticMem>> {
        let parser = self.vdso_parser.get_or_try_init_(|| {
            let parser = create_vdso_parser(pid, range)?;
            Result::<_, Error>::Ok(Box::new(parser))
        })?;
        Ok(parser)
    }
}

impl Default for Normalizer {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}


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


    /// Exercise the `Default` impl for `Normalizer`.
    #[test]
    fn default_initialization() {
        let _normalizer = Normalizer::default();
    }
}