| 1 |
// |
| 2 |
// Print the physical memory page with the most references |
| 3 |
// |
| 4 |
// Require CAP_SYS_ADMIN privilege, or root |
| 5 |
// |
| 6 |
// Sample output: |
| 7 |
// |
| 8 |
// Found RAM here: 0x1000-0x9fbff |
| 9 |
// Lots of references to this locations: addr=0x9d000, pfn=157, refs=0 |
| 10 |
// Found RAM here: 0x100000-0xdffeffff |
| 11 |
// Lots of references to this locations: addr=0x81ba3000, pfn=531363, refs=128 |
| 12 |
// Found RAM here: 0x100000000-0x11fffffff |
| 13 |
// Lots of references to this locations: addr=0x1b575000, pfn=111989, refs=134 |
| 14 |
// |
| 15 |
|
| 16 |
use procfs::prelude::*; |
| 17 |
|
| 18 |
fn main() { |
| 19 |
if !rustix::process::geteuid().is_root() { |
| 20 |
panic!("ERROR: Access to /proc/iomem requires root, re-run with sudo"); |
| 21 |
} |
| 22 |
|
| 23 |
let page_size = procfs::page_size(); |
| 24 |
|
| 25 |
// /proc/iomem contain a list of memory mapping, but we're only interested in RAM mapping |
| 26 |
let iomem = procfs::iomem().expect("Can't open /proc/iomem"); |
| 27 |
|
| 28 |
let ram = iomem |
| 29 |
.iter() |
| 30 |
.filter_map(|(_, map)| if map.name == "System RAM" { Some(map) } else { None }); |
| 31 |
let mut kpagecount = procfs::KPageCount::new().expect("Can't open /proc/kpagecount"); |
| 32 |
|
| 33 |
for map in ram { |
| 34 |
println!("Found RAM here: 0x{:x}-0x{:x}", map.address.0, map.address.1); |
| 35 |
|
| 36 |
// Physical memory is divided into pages of `page_size` bytes (usually 4kiB) |
| 37 |
// Each page is referenced by its Page Fram Number (PFN) |
| 38 |
let (start_pfn, end_pfn) = map.get_range().get(); |
| 39 |
|
| 40 |
let page_references = kpagecount |
| 41 |
.get_count_in_range(start_pfn, end_pfn) |
| 42 |
.expect("Can't read from /proc/kpagecount"); |
| 43 |
|
| 44 |
// find the page with most references |
| 45 |
let (pfn, refs) = page_references |
| 46 |
.iter() |
| 47 |
.enumerate() |
| 48 |
.max_by(|(_, a), (_, b)| a.cmp(b)) |
| 49 |
.unwrap(); |
| 50 |
|
| 51 |
println!( |
| 52 |
"Lots of references to this locations: addr=0x{:x}, pfn={}, refs={}", |
| 53 |
pfn * page_size as usize, |
| 54 |
pfn, |
| 55 |
refs |
| 56 |
); |
| 57 |
} |
| 58 |
} |