steroid 0.5.0

A lightweight framework for dynamic binary instrumentation
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! The mapping module provides convenient data types to manipulate the memory mapping of a process.
//!
//! ## Memory mapping
//!
//! The mapping of a process' memory can be visualized with the file `/proc/{pid}/maps` that lies in
//! the [`procfs(5)`] filesystem of Linux. This file looks like the following example obtained
//! running `/usr/bin/cat`:
//!
//! ```text
//! 5652a293f000-5652a2941000 r--p 00000000 fe:00 10486180                   /usr/bin/cat
//! 5652a2941000-5652a2945000 r-xp 00002000 fe:00 10486180                   /usr/bin/cat
//! 5652a2945000-5652a2947000 r--p 00006000 fe:00 10486180                   /usr/bin/cat
//! 5652a2947000-5652a2948000 r--p 00007000 fe:00 10486180                   /usr/bin/cat
//! 5652a2948000-5652a2949000 rw-p 00008000 fe:00 10486180                   /usr/bin/cat
//! 5652a42c6000-5652a42e7000 rw-p 00000000 00:00 0                          [heap]
//! 7fb5b9a92000-7fb5b9d7d000 r--p 00000000 fe:00 10496617                   /usr/lib/locale/locale-archive
//! 7fb5b9d7d000-7fb5b9d80000 rw-p 00000000 00:00 0
//! 7fb5b9d80000-7fb5b9da2000 r--p 00000000 fe:00 10495643                   /usr/lib/libc.so.6
//! 7fb5b9da2000-7fb5b9efc000 r-xp 00022000 fe:00 10495643                   /usr/lib/libc.so.6
//! 7fb5b9efc000-7fb5b9f54000 r--p 0017c000 fe:00 10495643                   /usr/lib/libc.so.6
//! 7fb5b9f54000-7fb5b9f58000 r--p 001d4000 fe:00 10495643                   /usr/lib/libc.so.6
//! 7fb5b9f58000-7fb5b9f5a000 rw-p 001d8000 fe:00 10495643                   /usr/lib/libc.so.6
//! 7fb5b9f5a000-7fb5b9f69000 rw-p 00000000 00:00 0
//! 7fb5b9f81000-7fb5b9fa3000 rw-p 00000000 00:00 0
//! 7fb5b9fa3000-7fb5b9fa4000 r--p 00000000 fe:00 10495632                   /usr/lib/ld-linux-x86-64.so.2
//! 7fb5b9fa4000-7fb5b9fca000 r-xp 00001000 fe:00 10495632                   /usr/lib/ld-linux-x86-64.so.2
//! 7fb5b9fca000-7fb5b9fd4000 r--p 00027000 fe:00 10495632                   /usr/lib/ld-linux-x86-64.so.2
//! 7fb5b9fd4000-7fb5b9fd6000 r--p 00031000 fe:00 10495632                   /usr/lib/ld-linux-x86-64.so.2
//! 7fb5b9fd6000-7fb5b9fd8000 rw-p 00033000 fe:00 10495632                   /usr/lib/ld-linux-x86-64.so.2
//! 7ffd2bb97000-7ffd2bbb9000 rw-p 00000000 00:00 0                          [stack]
//! 7ffd2bbe0000-7ffd2bbe4000 r--p 00000000 00:00 0                          [vvar]
//! 7ffd2bbe4000-7ffd2bbe6000 r-xp 00000000 00:00 0                          [vdso]
//! ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0                  [vsyscall]
//! ```
//!
//! The values of the first column correspond to the start and end addresses of the memory mapping,
//! which means the address range at which the memory is accessible in the process' address
//! space.
//!
//! The second column is the permissions of the memory mapping. For instance, one may not
//! want to make the program's code writable however it must be executable. It may be
//! private (the "p" in the permissions) or shared. If a mapping is private, it is copy-on-write and
//! modifies only the process' mapping of the memory. If it is shared, all the processes that map
//! this piece of memory will be affected.
//!
//! The third column is the offset in the source file at which the mapping starts.
//!
//! The fourth column is the device in which the file lives. It is given in the form of
//! `major:minor` pair of IDs.
//!
//! The fifth column is the inode of the file in the filesystem.
//!
//! Finally the last column is what is mapped. It may be a file (represented by its path), part of
//! the heap (represented by `[heap]`), the stack of one of the process' threads (represented by
//! `[stack:{tid}]` or `[stack]` for the main thread), the vdso (represented by `[vdso]`), the vvar
//! (represented by `[vvar]`), the legacy vsyscall (represented by `[vsyscall]`) or an anonymous
//! mapping. An anonymous mapping is a mapping of some memory allocated by the process to store
//! data.
//!
//! ## Convenient data types
//!
//! This module provides the user with a convenient API to manipulate this data. The structure
//! [`MemoryMapping`] gives a high-level representation of the memory mapping of the whole
//! process. It is a collection of [`Mapping`] that each represent one line of the maps file. It is
//! possible to get a [`MemoryMapping`] using the function [`memory_mapping`]:
//!
//! ```
//! # use anyhow::Error;
//! # use steroid::process::spawn_process;
//! # use steroid::run::Executing;
//! # use steroid::mapping::memory_mapping;
//! # let mut process = spawn_process("/bin/ls", ["-l"]).unwrap();
//! # let mut ctrl = process.wait()?.assume_alive()?;
//! let memory = memory_mapping(ctrl.process())?;
//! # Ok::<(), Error>(())
//! ```
//!
//! It is possible to get useful information using the API of types such as [`Mapping`]:
//!
//! ```
//! # use std::path::PathBuf;
//! # use anyhow::Error;
//! # use steroid::process::spawn_process;
//! # use steroid::run::{Executing};
//! # use steroid::breakpoint::{breakpoint, Mode};
//! # use steroid::mapping::{Type, memory_mapping};
//! # let mut path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! # path_buf.push("resources/test/say_hello_no_pie");
//! # let process = spawn_process::<_, _, &str>(path_buf, vec![])?;
//! # let mut ctrl_start = process.wait()?.assume_alive()?;
//! # breakpoint(&mut ctrl_start, 0x40113c, Mode::OneShot)?;
//! # let process = ctrl_start.resume()?;
//! # let mut ctrl = process.wait()?.assume_alive()?;
//! # let memory = memory_mapping(ctrl.process())?;
//! let c_lib_range = memory
//!     .find(|mapping| match &mapping.mapping_type {
//!         Type::File { path, .. } => {
//!             let filename = path.to_str().unwrap();
//!             mapping.permissions.executable && filename.contains("libc.so")
//!         }
//!         _ => false,
//!     })
//!     .map(|mapping| (mapping.start, mapping.end))
//!     .unwrap();
//! # Ok::<(), Error>(())
//! ```
//!
//! [`procfs(5)`]: https://man7.org/linux/man-pages/man5/proc.5.html
use std::fmt::Result as FmtResult;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::io::{Error as IOError, Lines};
use std::path::PathBuf;
use std::str::FromStr;

use nix::libc::{PROT_EXEC, PROT_READ, PROT_WRITE};

use crate::error::{CouldNotParseMappingFile, MappingError};
use crate::process::{Pid, TargetProcess};

/// Base generic type to express memory mapping permissions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PermissionsType<T> {
    pub readable: T,
    pub writable: T,
    pub executable: T,
    /// A private mapping means that it is copy-on-write, the mapped file is not modified by the
    /// process, only its copy mapped in memory. A "non-private" mapping is a shared mapping. See
    /// [`mmap(2)`].
    ///
    /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    pub private: T,
}

/// Permissions of a memory mapping.
pub type Permissions = PermissionsType<bool>;

impl FromStr for Permissions {
    type Err = CouldNotParseMappingFile;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() == 4 {
            let chars: Vec<char> = s.chars().collect();

            let readable = chars[0] == 'r';
            let writable = chars[1] == 'w';
            let executable = chars[2] == 'x';
            let private = chars[3] == 'p';

            Ok(Self {
                readable,
                writable,
                executable,
                private,
            })
        } else {
            Err(Self::Err::Permissions)
        }
    }
}

impl Display for Permissions {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
        let mut positives = Vec::with_capacity(4);
        if self.readable {
            positives.push("readable");
        }
        if self.writable {
            positives.push("writable");
        }
        if self.executable {
            positives.push("executable");
        }
        if self.private {
            positives.push("private");
        }

        write!(fmt, "{}", positives.join(", "))
    }
}

impl Permissions {
    #[must_use]
    pub const fn to_i32(&self) -> i32 {
        let mut res = 0;
        if self.readable {
            res |= PROT_READ;
        }
        if self.writable {
            res |= PROT_WRITE;
        }
        if self.executable {
            res |= PROT_EXEC;
        }

        res
    }

    #[must_use]
    pub fn matches(&self, matcher: &PermissionMatcher) -> bool {
        matcher.readable.map_or(true, |v| self.readable == v)
            && matcher.writable.map_or(true, |v| self.writable == v)
            && matcher.executable.map_or(true, |v| self.executable == v)
            && matcher.private.map_or(true, |v| self.private == v)
    }
}

/// Type used in errors to represent subsets of permissions that were expected.
///
/// For instance, if a mapping was expected to be readable but not writable, the corresponding
/// matcher would be:
///
/// ```
/// # use steroid::mapping::PermissionMatcher;
/// #
/// PermissionMatcher {
///     readable: Some(true),
///     writable: Some(false),
///     executable: None,
///     private: None,
/// }
/// # ; ()
/// ```
pub type PermissionMatcher = PermissionsType<Option<bool>>;

impl Display for PermissionMatcher {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
        fn dispatch<'a>(
            positive: &mut Vec<&'a str>,
            negative: &mut Vec<&'a str>,
            value: Option<bool>,
            disp: &'a str,
        ) {
            if value == Some(true) {
                positive.push(disp);
            } else if value == Some(false) {
                negative.push(disp);
            }
        }

        let mut positive = Vec::with_capacity(4);
        let mut negative = Vec::with_capacity(4);

        dispatch(&mut positive, &mut negative, self.readable, "readable");
        dispatch(&mut positive, &mut negative, self.writable, "writable");
        dispatch(&mut positive, &mut negative, self.executable, "executable");
        dispatch(&mut positive, &mut negative, self.private, "private");

        let positive_msg = positive.join(", ");
        let negative_msg = if negative.is_empty() {
            String::new()
        } else {
            format!(" but not {}", negative.join(", "))
        };

        write!(fmt, "{positive_msg}{negative_msg}")
    }
}

/// Device on which the mapped file is stored, in major:minor form.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Device {
    pub major: u8,
    pub minor: u8,
}

impl FromStr for Device {
    type Err = CouldNotParseMappingFile;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (major, minor) =
            s.split_once(':')
                .ok_or(Self::Err::Device)
                .and_then(|(maj, min)| {
                    let major = u8::from_str_radix(maj, 16).or(Err(Self::Err::Device))?;
                    let minor = u8::from_str_radix(min, 16).or(Err(Self::Err::Device))?;

                    Ok((major, minor))
                })?;

        Ok(Self { major, minor })
    }
}

#[derive(Debug, PartialEq)]
enum Pathname {
    Stack { tid: usize },
    Vdso,
    Vvar,
    Vsyscall,
    Heap,
    File(PathBuf),
    Anonymous,
}

impl FromStr for Pathname {
    type Err = CouldNotParseMappingFile;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(if s.starts_with("[stack") {
            if !s.ends_with(']') {
                Self::File(PathBuf::from(s))
            } else if s.len() == 7 {
                Self::Stack { tid: 0 }
            } else {
                let slice = &s[7..s.len() - 1];
                let tid = slice.parse::<usize>().or(Err(Self::Err::StackTID))?;
                Self::Stack { tid }
            }
        } else {
            match s {
                "[stack]" => Self::Stack { tid: 0 },
                "" => Self::Anonymous,
                "[vdso]" => Self::Vdso,
                "[vvar]" => Self::Vvar,
                "[vsyscall]" => Self::Vsyscall,
                "[heap]" => Self::Heap,
                s => Self::File(PathBuf::from(s)),
            }
        })
    }
}

/// Type of a memory mapping.
#[derive(Debug, PartialEq, Eq)]
#[allow(clippy::module_name_repetitions)]
pub enum Type {
    /// Anonymous mapping of memory, typically performed by the process via [`mmap(2)`]
    ///
    /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    Anonymous,
    /// Mapping of the [`vdso(7)`]
    ///
    /// [`vdso(7)`]: https://man7.org/linux/man-pages/man7/vdso.7.html
    Vdso,
    /// Mirror mapping of kernel variables required by system calls exported by the kernel. See
    /// [`this article`] for further information
    ///
    /// [`this article`]: https://lwn.net/Articles/615809/
    Vvar,
    /// Defunct mapping of some kernel code for specific system calls that did not require elevated
    /// privileges
    Vsyscall,
    /// Mapping of a part of the heap of the process
    Heap,
    /// Mapping of a stack of the process, the TID is the thread ID in the process
    Stack { tid: usize },
    /// Mapping of a file in the process' address space
    File {
        device: Device,
        inode: usize,
        offset: usize,
        path: PathBuf,
    },
}

impl Type {
    #[allow(clippy::missing_const_for_fn)]
    fn from_pathname(pathname: Pathname, device: Device, inode: usize, offset: usize) -> Self {
        match pathname {
            Pathname::Anonymous => Self::Anonymous,
            Pathname::Heap => Self::Heap,
            Pathname::Stack { tid } => Self::Stack { tid },
            Pathname::Vdso => Self::Vdso,
            Pathname::Vvar => Self::Vvar,
            Pathname::Vsyscall => Self::Vsyscall,
            Pathname::File(buf) => Self::File {
                device,
                inode,
                offset,
                path: buf,
            },
        }
    }
}

/// One memory mapping in a process. A mapping has a start and end address in the process' address
/// space, it has permissions, so that the user cannot mess with the memory. The [`Type`] of a
/// mapping corresponds to the type of mapping, whether it is one of the process' stacks, heap, the
/// vdso, a file (like a library) or even an anonymous mapping.
#[derive(Debug, PartialEq, Eq)]
pub struct Mapping {
    pub start: usize,
    pub end: usize,
    pub permissions: Permissions,
    pub mapping_type: Type,
}

fn mapping_file_lines(pid: Pid) -> Result<Lines<BufReader<File>>, IOError> {
    let filename = format!("/proc/{pid}/maps");
    let file = BufReader::new(File::open(filename)?);

    Ok(file.lines())
}

impl FromStr for Mapping {
    type Err = CouldNotParseMappingFile;

    fn from_str(line: &str) -> Result<Self, Self::Err> {
        let mut words = line.split_whitespace();
        let range = Self::Err::from_option(words.next())?;
        let permissions = Permissions::from_str(Self::Err::from_option(words.next())?)?;
        let offset = usize::from_str_radix(Self::Err::from_option(words.next())?, 16)
            .or(Err(Self::Err::Offset))?;
        let device = Device::from_str(Self::Err::from_option(words.next())?)?;
        let inode = Self::Err::from_option(words.next())?
            .parse::<usize>()
            .or(Err(Self::Err::Inode))?;

        let pathname = Pathname::from_str(words.collect::<Vec<_>>().join(" ").as_str())?;

        let (start, end) = range
            .split_once('-')
            .ok_or(Self::Err::AddressRange)
            .and_then(|(s, e)| {
                let start = usize::from_str_radix(s, 16).or(Err(Self::Err::StartAddress))?;
                let end = usize::from_str_radix(e, 16).or(Err(Self::Err::StartAddress))?;
                Ok((start, end))
            })?;

        Ok(Self {
            start,
            end,
            permissions,
            mapping_type: Type::from_pathname(pathname, device, inode, offset),
        })
    }
}

impl Mapping {
    /// Check if the mapping is an anonymous mapping of memory, see [`mmap(2)`].
    ///
    /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    #[must_use]
    pub const fn is_anonymous(&self) -> bool {
        matches!(self.mapping_type, Type::Anonymous)
    }

    /// Check if the mapping corresponds to the VDSO, see [`vdso(7)`].
    ///
    /// [`vdso(7)`]: https://man7.org/linux/man-pages/man7/vdso.7.html
    #[must_use]
    pub const fn is_vdso(&self) -> bool {
        matches!(self.mapping_type, Type::Vdso)
    }

    /// Check if the mapping is the vvar.
    #[must_use]
    pub const fn is_vvar(&self) -> bool {
        matches!(self.mapping_type, Type::Vvar)
    }

    /// Check if the mapping is the vsyscall.
    #[must_use]
    pub const fn is_vsyscall(&self) -> bool {
        matches!(self.mapping_type, Type::Vsyscall)
    }

    /// Check if the mapping is part of the process heap.
    #[must_use]
    pub const fn is_heap(&self) -> bool {
        matches!(self.mapping_type, Type::Heap)
    }

    /// Check if the mapping is a stack of the process.
    #[must_use]
    pub const fn is_stack(&self) -> bool {
        matches!(self.mapping_type, Type::Stack { .. })
    }

    /// Check if the mapping is a mapping of a file.
    #[must_use]
    pub const fn is_file(&self) -> bool {
        matches!(self.mapping_type, Type::File { .. })
    }
}

/// Convienient structure over a [`Vec`] of [`Mapping`] that represents the whole memory mapping of a
/// process. This structure provides the user with some convienient methods to manipulate the memory
/// mapping more easily.
#[allow(clippy::module_name_repetitions)]
pub struct MemoryMapping(pub Vec<Mapping>);

impl MemoryMapping {
    /// Look for a mapping in the memory mapping that accepts the given predicate.
    ///
    /// ```
    /// # use anyhow::Error;
    /// # use steroid::process::spawn_process;
    /// # use steroid::run::Executing;
    /// # use steroid::mapping::memory_mapping;
    /// # let mut process = spawn_process("/bin/ls", ["-l"])?;
    /// # let mut ctrl = process.wait()?.assume_alive()?;
    /// let memory = memory_mapping(ctrl.process())?;
    /// let mapping = memory.find(|m| m.is_stack());
    /// assert!(mapping.is_some());
    /// # Ok::<(), Error>(())
    /// ```
    pub fn find<P>(&self, predicate: P) -> Option<&Mapping>
    where
        P: Fn(&Mapping) -> bool,
    {
        self.0.iter().find(|mapping| predicate(mapping))
    }
}

/// Get the memory mapping of the given process. The memory mapping will tell the user what pages
/// are mapped, their permissions, the file they may be mapping, etc. This function is relatively
/// safe and only returns an error when the memory map file `/proc/{pid}/maps` is not accessible or
/// could not be parsed correctly, which in theory should never happen.
///
/// # Errors
///
/// If any error occurs during the parsing of the maps file, the function will fail and return a
/// [`MappingError`].
#[allow(clippy::module_name_repetitions)]
pub fn memory_mapping(process: &TargetProcess) -> Result<MemoryMapping, MappingError> {
    let vec = mapping_file_lines(process.pid())?
        .map(|line| Mapping::from_str(&line?).map_err(MappingError::from))
        .collect::<Result<Vec<Mapping>, _>>()?;
    Ok(MemoryMapping(vec))
}

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

    #[test]
    fn parse_permissions() {
        let perm = Permissions::from_str("");
        assert_eq!(perm, Err(CouldNotParseMappingFile::Permissions));

        let perm = Permissions::from_str("r---");
        assert_eq!(
            perm,
            Ok(Permissions {
                readable: true,
                writable: false,
                executable: false,
                private: false
            })
        );

        let perm = Permissions::from_str("-wx-");
        assert_eq!(
            perm,
            Ok(Permissions {
                readable: false,
                writable: true,
                executable: true,
                private: false
            })
        );

        let perm = Permissions::from_str("r-x-");
        assert_eq!(
            perm,
            Ok(Permissions {
                readable: true,
                writable: false,
                executable: true,
                private: false
            })
        );

        let perm = Permissions::from_str("r-xp");
        assert_eq!(
            perm,
            Ok(Permissions {
                readable: true,
                writable: false,
                executable: true,
                private: true
            })
        );
    }

    #[test]
    fn parse_pathname() {
        let stack = Pathname::from_str("[stack]");
        assert_eq!(stack, Ok(Pathname::Stack { tid: 0 }));
        let stack = Pathname::from_str("[stack");
        assert_eq!(stack, Ok(Pathname::File(PathBuf::from("[stack"))));
        let stack = Pathname::from_str("[stack:890]");
        assert_eq!(stack, Ok(Pathname::Stack { tid: 890 }));

        let vdso = Pathname::from_str("[vdso]");
        assert_eq!(vdso, Ok(Pathname::Vdso));

        let heap = Pathname::from_str("[heap]");
        assert_eq!(heap, Ok(Pathname::Heap));

        let anon = Pathname::from_str("");
        assert_eq!(anon, Ok(Pathname::Anonymous));

        let file = Pathname::from_str("/lib/somelib.so");
        assert_eq!(file, Ok(Pathname::File(PathBuf::from("/lib/somelib.so"))));
    }

    #[test]
    fn parse_device() {
        let device = Device::from_str("fd:04");
        assert_eq!(
            device,
            Ok(Device {
                major: 0xfd,
                minor: 0x04
            })
        );
    }

    #[test]
    fn parse_line() {
        let line = "7f7663254000-7f7663255000 r--p 00000000 fe:00 10495632                   /usr/lib/ld-linux-x86-64.so.2";
        let res = Mapping::from_str(line);
        assert_eq!(
            res,
            Ok(Mapping {
                start: 0x7f76_6325_4000,
                end: 0x7f76_6325_5000,
                permissions: Permissions {
                    readable: true,
                    writable: false,
                    executable: false,
                    private: true
                },
                mapping_type: Type::File {
                    offset: 0,
                    device: Device {
                        major: 0xfe,
                        minor: 0
                    },
                    inode: 10_495_632,
                    path: PathBuf::from("/usr/lib/ld-linux-x86-64.so.2"),
                }
            })
        );
    }
}