Debian Codegraph @

debian/rust-vendor/procfs/src/kpageflags.rs

raw
1 use crate::{process::Pfn, FileWrapper, ProcResult};
2
3 use std::{
4 io::{BufReader, Read, Seek, SeekFrom},
5 mem::size_of,
6 path::Path,
7 };
8
9 pub use procfs_core::PhysicalPageFlags;
10
11 /// Parse physical memory flags accessing `/proc/kpageflags`.
12 ///
13 /// Require root or CAP_SYS_ADMIN
14 pub struct KPageFlags {
15 reader: BufReader<FileWrapper>,
16 }
17
18 impl KPageFlags {
19 /// Get a parser from default `/proc/kpageflags`
20 ///
21 /// Return `Err` if process is not running as root or don't have CAP_SYS_ADMIN
22 pub fn new() -> ProcResult<Self> {
23 Self::from_custom_root("/proc")
24 }
25
26 /// Get a parser from custom `/proc`
27 ///
28 /// Return `Err` if process is not running as root or don't have CAP_SYS_ADMIN
29 pub fn from_custom_root<P: AsRef<Path>>(root: P) -> ProcResult<Self> {
30 let mut path = root.as_ref().to_path_buf();
31 path.push("kpageflags");
32
33 let reader = BufReader::new(FileWrapper::open(path)?);
34
35 Ok(Self { reader })
36 }
37
38 /// Retrieve information in the page table entry for the PFN (page frame number) at index `page_index`.
39 /// If you need to retrieve multiple PFNs, opt for [Self::get_range_info()] instead.
40 ///
41 /// Return Err if the PFN is not in RAM (see [crate::iomem()]):
42 /// Io(Error { kind: UnexpectedEof, message: "failed to fill whole buffer" }, None)
43 pub fn get_info(&mut self, pfn: Pfn) -> ProcResult<PhysicalPageFlags> {
44 self.get_range_info(pfn, Pfn(pfn.0 + 1))
45 .map(|mut vec| vec.pop().unwrap())
46 }
47
48 /// Retrieve information in the page table entry for the PFNs within range `start` (included) and `end` (excluded) PFNs.
49 ///
50 /// Return Err if any PFN is not in RAM (see [crate::iomem()]):
51 /// Io(Error { kind: UnexpectedEof, message: "failed to fill whole buffer" }, None)
52 pub fn get_range_info(&mut self, start: Pfn, end: Pfn) -> ProcResult<Vec<PhysicalPageFlags>> {
53 let start_position = start.0 * size_of::<PhysicalPageFlags>() as u64;
54 self.reader.seek(SeekFrom::Start(start_position))?;
55
56 let mut page_infos = Vec::with_capacity((end.0 - start.0) as usize);
57 for _ in start.0..end.0 {
58 let mut info_bytes = [0; size_of::<PhysicalPageFlags>()];
59 self.reader.read_exact(&mut info_bytes)?;
60 page_infos.push(PhysicalPageFlags::parse_info(u64::from_ne_bytes(info_bytes)));
61 }
62
63 Ok(page_infos)
64 }
65 }
66
67 #[cfg(test)]
68 mod tests {
69 use super::*;
70
71 #[test]
72 fn test_kpageflags_parsing() {
73 let pagemap_entry: u64 = 0b0000000000000000000000000000000000000000000000000000000000000001;
74 let info = PhysicalPageFlags::parse_info(pagemap_entry);
75 assert!(info == PhysicalPageFlags::LOCKED);
76 }
77 }