use std::path::Path;
const ARENA_BYTES: u64 = 64 * 1024 * 1024;
#[derive(Debug, Clone, Copy, Default, serde::Serialize)]
pub struct HeapStats {
pub live_bytes: u64,
pub free_bytes: u64,
pub system_bytes: u64,
pub rss_anon_bytes: u64,
pub arena_mappings: usize,
}
impl HeapStats {
pub fn retained_fraction(&self) -> f64 {
if self.system_bytes == 0 {
return 0.0;
}
self.free_bytes as f64 / self.system_bytes as f64
}
}
#[cfg(target_env = "gnu")]
fn allocator_bytes() -> (u64, u64, u64) {
let info = unsafe { libc::mallinfo2() };
let arena = info.arena as u64;
let mmapped = info.hblkhd as u64;
let in_use = info.uordblks as u64;
let free = info.fordblks as u64;
(in_use + mmapped, free, arena + mmapped)
}
#[cfg(not(target_env = "gnu"))]
fn allocator_bytes() -> (u64, u64, u64) {
(0, 0, 0)
}
pub fn rss_anon_bytes(status_path: &Path) -> u64 {
let Ok(status) = std::fs::read_to_string(status_path) else {
return 0;
};
rss_anon_from_status(&status)
}
fn rss_anon_from_status(status: &str) -> u64 {
for line in status.lines() {
if let Some(rest) = line.strip_prefix("RssAnon:") {
let kb: u64 = rest
.trim()
.trim_end_matches("kB")
.trim()
.parse()
.unwrap_or(0);
return kb * 1024;
}
}
0
}
pub fn arena_mappings(maps_path: &Path) -> usize {
let Ok(maps) = std::fs::read_to_string(maps_path) else {
return 0;
};
arena_mappings_from_maps(&maps)
}
fn arena_mappings_from_maps(maps: &str) -> usize {
maps.lines()
.filter(|line| {
let mut fields = line.split_whitespace();
let Some(range) = fields.next() else {
return false;
};
if fields.clone().count() >= 5 {
return false;
}
let Some((start, end)) = range.split_once('-') else {
return false;
};
let (Ok(start), Ok(end)) =
(u64::from_str_radix(start, 16), u64::from_str_radix(end, 16))
else {
return false;
};
end - start == ARENA_BYTES && start % ARENA_BYTES == 0
})
.count()
}
pub fn heap_stats() -> HeapStats {
let (live_bytes, free_bytes, system_bytes) = allocator_bytes();
HeapStats {
live_bytes,
free_bytes,
system_bytes,
rss_anon_bytes: rss_anon_bytes(Path::new("/proc/self/status")),
arena_mappings: arena_mappings(Path::new("/proc/self/maps")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rss_anon_is_read_as_bytes() {
let status = "Name:\tsb\nVmRSS:\t 1653472 kB\nRssAnon:\t 1626960 kB\nThreads:\t24\n";
assert_eq!(rss_anon_from_status(status), 1_626_960 * 1024);
}
#[test]
fn rss_anon_missing_field_reads_zero() {
assert_eq!(rss_anon_from_status("Name:\tsb\nThreads:\t24\n"), 0);
}
#[test]
fn only_unnamed_64mib_aligned_mappings_count_as_arenas() {
let maps = concat!(
"7f0004000000-7f0008000000 rw-p 00000000 00:00 0\n",
"7f0010000000-7f0014000000 rw-p 00000000 08:01 1234 /lib/libc.so.6\n",
"7f0018100000-7f001c100000 rw-p 00000000 00:00 0\n",
"7f0020000000-7f0020200000 rw-p 00000000 00:00 0\n",
"555500000000-555500100000 rw-p 00000000 00:00 0 [heap]\n",
);
assert_eq!(arena_mappings_from_maps(maps), 1);
}
#[test]
fn retained_fraction_is_free_over_system_and_zero_when_empty() {
let stats = HeapStats {
free_bytes: 300,
system_bytes: 1200,
..Default::default()
};
assert!((stats.retained_fraction() - 0.25).abs() < 1e-9);
assert_eq!(HeapStats::default().retained_fraction(), 0.0);
}
}