app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
+28
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "procwatch"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "A native app's own memory and CPU, watched from inside: footprint, per-thread CPU (exited threads too), open files, a counting allocator, byte gauges for native buffers, warnings in the log, and a loopback JSON endpoint."
|
||||
autotests = false
|
||||
|
||||
[features]
|
||||
# Count `Gauge` bytes in builds without debug assertions too. Off by default, so a release
|
||||
# build's gauges compile to nothing.
|
||||
release-gauges = []
|
||||
# Live heap by allocation site, sampled, written out on request (`alloc::sites`): for measuring
|
||||
# builds only. Windows.
|
||||
alloc-sites = []
|
||||
|
||||
[dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[[test]]
|
||||
name = "no_allocator"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
//! A counting global allocator: live and peak heap bytes, the largest single request, and the
|
||||
//! bytes held in big blocks, plus net bytes per thread tag. A few relaxed atomics per call.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! #[cfg(debug_assertions)]
|
||||
//! #[global_allocator]
|
||||
//! static ALLOC: procwatch::alloc::Counting = procwatch::alloc::Counting::system();
|
||||
//! ```
|
||||
//!
|
||||
//! Tags attribute heap to threads: `procwatch::alloc::tag_thread("audio")` at a thread's start
|
||||
//! counts what that thread allocates minus what it frees. A producer whose buffer is freed
|
||||
//! elsewhere still shows; that's the point.
|
||||
//!
|
||||
//! [`thread_allocations`] counts this thread's allocations, so a test can assert a hot path
|
||||
//! allocates nothing while other tests run in parallel. [`thread_allocated_bytes`] counts the
|
||||
//! bytes they asked for, for a per-frame allocation figure.
|
||||
|
||||
#[cfg(feature = "alloc-sites")]
|
||||
pub mod sites;
|
||||
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::Cell;
|
||||
use std::sync::atomic::{AtomicI64, AtomicPtr, AtomicU64, AtomicUsize, Ordering::{Acquire, Relaxed, Release}};
|
||||
|
||||
/// A block at least this big counts as "big": a buffer worth naming in a warning.
|
||||
pub const BIG: usize = 64 << 20;
|
||||
/// Thread tags there's room for; more fall into tag 0, "untagged".
|
||||
pub const TAGS: usize = 16;
|
||||
|
||||
static INSTALLED: AtomicU64 = AtomicU64::new(0);
|
||||
static LIVE: AtomicI64 = AtomicI64::new(0);
|
||||
static PEAK: AtomicI64 = AtomicI64::new(0);
|
||||
static ALLOCS: AtomicU64 = AtomicU64::new(0);
|
||||
static LARGEST: AtomicUsize = AtomicUsize::new(0);
|
||||
static BIG_LIVE: AtomicI64 = AtomicI64::new(0);
|
||||
static BIG_BLOCKS: AtomicI64 = AtomicI64::new(0);
|
||||
static TAG_NET: [AtomicI64; TAGS] = [const { AtomicI64::new(0) }; TAGS];
|
||||
static TAG_NAMES: [AtomicPtr<&'static str>; TAGS] = [const { AtomicPtr::new(std::ptr::null_mut()) }; TAGS];
|
||||
|
||||
thread_local! {
|
||||
static TAG: Cell<u8> = const { Cell::new(0) };
|
||||
static THREAD_ALLOCS: Cell<u64> = const { Cell::new(0) };
|
||||
static THREAD_BYTES: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
fn counted(size: usize) {
|
||||
ALLOCS.fetch_add(1, Relaxed);
|
||||
THREAD_ALLOCS.try_with(|c| c.set(c.get() + 1)).ok();
|
||||
THREAD_BYTES.try_with(|c| c.set(c.get().wrapping_add(size as u64))).ok();
|
||||
}
|
||||
|
||||
/// Allocations (and reallocations) made on this thread so far; 0 unless [`Counting`] is the
|
||||
/// global allocator.
|
||||
pub fn thread_allocations() -> u64 {
|
||||
THREAD_ALLOCS.try_with(Cell::get).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Bytes this thread has asked for so far: every successful alloc, alloc_zeroed and realloc
|
||||
/// (a realloc counts its whole new size), frees not subtracted. Traffic, not live heap.
|
||||
/// `None` until [`Counting`] has served a request, so a missing allocator never reads as zero.
|
||||
pub fn thread_allocated_bytes() -> Option<u64> {
|
||||
if INSTALLED.load(Relaxed) == 0 {
|
||||
return None;
|
||||
}
|
||||
THREAD_BYTES.try_with(Cell::get).ok()
|
||||
}
|
||||
|
||||
pub struct Counting<A = System> {
|
||||
inner: A,
|
||||
}
|
||||
|
||||
impl Counting<System> {
|
||||
pub const fn system() -> Self {
|
||||
Counting { inner: System }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A> Counting<A> {
|
||||
pub const fn new(inner: A) -> Self {
|
||||
Counting { inner }
|
||||
}
|
||||
}
|
||||
|
||||
fn grew(size: usize) {
|
||||
let live = LIVE.fetch_add(size as i64, Relaxed) + size as i64;
|
||||
// A plain read first: the peak and the largest rarely move, and `fetch_max` is a locked
|
||||
// compare-and-swap loop on every call.
|
||||
if live > PEAK.load(Relaxed) {
|
||||
PEAK.fetch_max(live, Relaxed);
|
||||
}
|
||||
if size > LARGEST.load(Relaxed) {
|
||||
LARGEST.fetch_max(size, Relaxed);
|
||||
}
|
||||
if size >= BIG {
|
||||
BIG_LIVE.fetch_add(size as i64, Relaxed);
|
||||
BIG_BLOCKS.fetch_add(1, Relaxed);
|
||||
}
|
||||
// `try_with`: a thread's last frees run after its locals are gone.
|
||||
let tag = TAG.try_with(Cell::get).unwrap_or(0) as usize;
|
||||
TAG_NET[tag].fetch_add(size as i64, Relaxed);
|
||||
}
|
||||
|
||||
/// Notes that [`Counting`] serves requests; after the first, a read that keeps the flag's cache
|
||||
/// line shared rather than a store to it on every call.
|
||||
fn installed() {
|
||||
if INSTALLED.load(Relaxed) == 0 {
|
||||
INSTALLED.store(1, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn shrank(size: usize) {
|
||||
LIVE.fetch_sub(size as i64, Relaxed);
|
||||
if size >= BIG {
|
||||
BIG_LIVE.fetch_sub(size as i64, Relaxed);
|
||||
BIG_BLOCKS.fetch_sub(1, Relaxed);
|
||||
}
|
||||
let tag = TAG.try_with(Cell::get).unwrap_or(0) as usize;
|
||||
TAG_NET[tag].fetch_sub(size as i64, Relaxed);
|
||||
}
|
||||
|
||||
// SAFETY: every call goes straight to `inner`; the counters never touch the heap.
|
||||
#[allow(unsafe_code)]
|
||||
unsafe impl<A: GlobalAlloc> GlobalAlloc for Counting<A> {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
installed();
|
||||
// SAFETY: forwards the caller's `GlobalAlloc::alloc` contract and valid `layout` to `inner`.
|
||||
let p = unsafe { self.inner.alloc(layout) };
|
||||
if !p.is_null() {
|
||||
counted(layout.size());
|
||||
grew(layout.size());
|
||||
#[cfg(feature = "alloc-sites")]
|
||||
sites::allocated(p, layout.size());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
||||
installed();
|
||||
// SAFETY: forwards the caller's `GlobalAlloc::alloc_zeroed` contract and valid `layout` to `inner`.
|
||||
let p = unsafe { self.inner.alloc_zeroed(layout) };
|
||||
if !p.is_null() {
|
||||
counted(layout.size());
|
||||
grew(layout.size());
|
||||
#[cfg(feature = "alloc-sites")]
|
||||
sites::allocated(p, layout.size());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
#[cfg(feature = "alloc-sites")]
|
||||
sites::freed(ptr);
|
||||
// SAFETY: caller guarantees `ptr` was allocated by `inner` with `layout` and is no longer used.
|
||||
unsafe { self.inner.dealloc(ptr, layout) };
|
||||
shrank(layout.size());
|
||||
}
|
||||
|
||||
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
||||
#[cfg(feature = "alloc-sites")]
|
||||
sites::freed(ptr);
|
||||
// SAFETY: caller guarantees `ptr` was allocated by `inner` with `layout` and `new_size` meets `GlobalAlloc::realloc`.
|
||||
let p = unsafe { self.inner.realloc(ptr, layout, new_size) };
|
||||
if !p.is_null() {
|
||||
counted(new_size);
|
||||
shrank(layout.size());
|
||||
grew(new_size);
|
||||
#[cfg(feature = "alloc-sites")]
|
||||
sites::allocated(p, new_size);
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts this thread's heap under `name` from now on (net bytes: allocated minus freed here).
|
||||
#[allow(unsafe_code)]
|
||||
pub fn tag_thread(name: &'static str) {
|
||||
let index = (1..TAGS)
|
||||
.find(|&i| {
|
||||
let seen = TAG_NAMES[i].load(Acquire);
|
||||
if !seen.is_null() {
|
||||
// SAFETY: only ever set from a leaked `&'static str` box below.
|
||||
return unsafe { *seen } == name;
|
||||
}
|
||||
let fresh = Box::into_raw(Box::new(name));
|
||||
match TAG_NAMES[i].compare_exchange(std::ptr::null_mut(), fresh, Release, Acquire) {
|
||||
Ok(_) => true,
|
||||
Err(other) => {
|
||||
// SAFETY: `fresh` was never shared.
|
||||
drop(unsafe { Box::from_raw(fresh) });
|
||||
// SAFETY: `other` was loaded with Acquire from `TAG_NAMES[i]`, which only stores leaked `&'static str` boxes.
|
||||
unsafe { *other == name }
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap_or(0);
|
||||
TAG.with(|t| t.set(index as u8));
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Heap {
|
||||
pub live: i64,
|
||||
pub peak: i64,
|
||||
pub allocations: u64,
|
||||
pub largest: usize,
|
||||
/// Bytes, and blocks, held in allocations of at least [`BIG`].
|
||||
pub big_live: i64,
|
||||
pub big_blocks: i64,
|
||||
/// Net bytes per thread tag, biggest first; "untagged" is everything else.
|
||||
pub tags: Vec<(&'static str, i64)>,
|
||||
}
|
||||
|
||||
/// The counters, or `None` when [`Counting`] isn't the global allocator.
|
||||
#[allow(unsafe_code)]
|
||||
pub fn heap() -> Option<Heap> {
|
||||
if INSTALLED.load(Relaxed) == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut tags: Vec<(&'static str, i64)> = (0..TAGS)
|
||||
.filter_map(|i| {
|
||||
let name = match i {
|
||||
0 => "untagged",
|
||||
_ => {
|
||||
let p = TAG_NAMES[i].load(Acquire);
|
||||
if p.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as in `tag_thread`.
|
||||
unsafe { *p }
|
||||
}
|
||||
};
|
||||
Some((name, TAG_NET[i].load(Relaxed)))
|
||||
})
|
||||
.collect();
|
||||
tags.sort_by_key(|(_, bytes)| -bytes);
|
||||
Some(Heap {
|
||||
live: LIVE.load(Relaxed),
|
||||
peak: PEAK.load(Relaxed),
|
||||
allocations: ALLOCS.load(Relaxed),
|
||||
largest: LARGEST.load(Relaxed),
|
||||
big_live: BIG_LIVE.load(Relaxed),
|
||||
big_blocks: BIG_BLOCKS.load(Relaxed),
|
||||
tags,
|
||||
})
|
||||
}
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
//! Live heap by allocation site, sampled (the `alloc-sites` feature, for measuring builds).
|
||||
//!
|
||||
//! [`Counting`](super::Counting) hands every request here. One in every [`INTERVAL`] bytes a
|
||||
//! thread asks for is sampled (a request of [`INTERVAL`] or more always is): its call stack is
|
||||
//! captured and the block is remembered until it's freed, so a site's live bytes are its live
|
||||
//! samples times their weight. Everything sits in fixed tables made on the first sample; nothing
|
||||
//! here allocates through the global allocator.
|
||||
//!
|
||||
//! With `PROCWATCH_ALLOC_SITES=<folder>` in the environment, a thread waits on the event
|
||||
//! `Local\procwatch-alloc-sites-<pid>`; each time it's set, the live sites are written to
|
||||
//! `<folder>\alloc-sites-<pid>-<n>.txt` beside the modules loaded, for a symbolizer to name
|
||||
//! (`harness\perf\memory` in the workspace that measures OpenCode). Windows only; elsewhere the
|
||||
//! feature records nothing.
|
||||
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::cell::{Cell, UnsafeCell};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering::{Acquire, Relaxed, Release}};
|
||||
|
||||
/// One sample per this many bytes asked for.
|
||||
pub const INTERVAL: usize = 32 << 10;
|
||||
const FRAMES: usize = 28;
|
||||
const SITES: usize = 1 << 13;
|
||||
const LIVE: usize = 1 << 16;
|
||||
const FILTER_BITS: usize = 1 << 22;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Site {
|
||||
hash: u64,
|
||||
frames: [usize; FRAMES],
|
||||
depth: u8,
|
||||
live_bytes: i64,
|
||||
live_blocks: i64,
|
||||
sampled_bytes: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Live {
|
||||
/// 0 empty, 1 removed, else the block's address.
|
||||
ptr: usize,
|
||||
site: u32,
|
||||
weight: usize,
|
||||
}
|
||||
|
||||
struct Tables {
|
||||
sites: *mut Site,
|
||||
live: *mut Live,
|
||||
used_sites: usize,
|
||||
}
|
||||
|
||||
struct SyncTables(UnsafeCell<Tables>);
|
||||
|
||||
// SAFETY: every access to the inner `Tables` is synchronized under `LOCK` (`GlobalAlloc` cannot
|
||||
// use `std::sync::Mutex`, which may allocate or re-enter the allocator).
|
||||
unsafe impl Sync for SyncTables {}
|
||||
|
||||
static LOCK: AtomicBool = AtomicBool::new(false);
|
||||
static READY: AtomicUsize = AtomicUsize::new(0);
|
||||
static TABLES: SyncTables = SyncTables(UnsafeCell::new(Tables {
|
||||
sites: std::ptr::null_mut(),
|
||||
live: std::ptr::null_mut(),
|
||||
used_sites: 0,
|
||||
}));
|
||||
/// A bit per address hash: set while some sampled block may hash there, so most frees skip the lock.
|
||||
static FILTER: [AtomicU64; FILTER_BITS / 64] = [const { AtomicU64::new(0) }; FILTER_BITS / 64];
|
||||
static DROPPED: AtomicU64 = AtomicU64::new(0);
|
||||
/// Other reports written beside the sites (a GPU allocator's, from the framework that owns it).
|
||||
type Section = (&'static str, Box<dyn Fn() -> String + Send>);
|
||||
static SECTIONS: std::sync::Mutex<Vec<Section>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// Adds `report`'s text to every dump, under `section <name>`: memory this allocator never sees
|
||||
/// (GPU heaps), named by whoever made it.
|
||||
pub fn contribute(name: &'static str, report: impl Fn() -> String + Send + 'static) {
|
||||
SECTIONS.lock().unwrap_or_else(|e| e.into_inner()).push((name, Box::new(report)));
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static UNTIL: Cell<isize> = const { Cell::new(INTERVAL as isize) };
|
||||
static INSIDE: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
fn lock() {
|
||||
while LOCK.compare_exchange_weak(false, true, Acquire, Relaxed).is_err() {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
}
|
||||
|
||||
fn unlock() {
|
||||
LOCK.store(false, Release);
|
||||
}
|
||||
|
||||
fn filter_bit(ptr: usize) -> (usize, u64) {
|
||||
let h = (ptr >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> (64 - 22);
|
||||
(h / 64, 1 << (h % 64))
|
||||
}
|
||||
|
||||
/// The block at `ptr` of `size` bytes was just made.
|
||||
pub(super) fn allocated(ptr: *mut u8, size: usize) {
|
||||
let weight = if size >= INTERVAL {
|
||||
size
|
||||
} else {
|
||||
let Ok(due) = UNTIL.try_with(|u| {
|
||||
let left = u.get() - size as isize;
|
||||
if left > 0 {
|
||||
u.set(left);
|
||||
false
|
||||
} else {
|
||||
u.set(left + INTERVAL as isize);
|
||||
true
|
||||
}
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
if !due {
|
||||
return;
|
||||
}
|
||||
INTERVAL
|
||||
};
|
||||
if INSIDE.try_with(Cell::get).unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let mut frames = [0usize; FRAMES];
|
||||
let depth = capture(&mut frames);
|
||||
lock();
|
||||
// SAFETY: the tables are only touched under LOCK.
|
||||
unsafe { record(ptr as usize, weight, &frames[..depth]) };
|
||||
unlock();
|
||||
}
|
||||
|
||||
/// The block at `ptr` is going.
|
||||
pub(super) fn freed(ptr: *mut u8) {
|
||||
let (word, bit) = filter_bit(ptr as usize);
|
||||
if FILTER[word].load(Relaxed) & bit == 0 || INSIDE.try_with(Cell::get).unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
lock();
|
||||
// SAFETY: under LOCK.
|
||||
unsafe { forget(ptr as usize) };
|
||||
unlock();
|
||||
}
|
||||
|
||||
unsafe fn record(ptr: usize, weight: usize, frames: &[usize]) {
|
||||
// SAFETY: the caller holds LOCK; `TABLES` is only reached through this module.
|
||||
let t = unsafe { &mut *TABLES.0.get() };
|
||||
if t.sites.is_null() {
|
||||
let (sites, live) = (os::zeroed(SITES * size_of::<Site>()), os::zeroed(LIVE * size_of::<Live>()));
|
||||
if sites.is_null() || live.is_null() {
|
||||
return;
|
||||
}
|
||||
(t.sites, t.live) = (sites.cast(), live.cast());
|
||||
READY.store(1, Release);
|
||||
os::start_dumper();
|
||||
}
|
||||
let hash = frames.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &f| (h ^ f as u64).wrapping_mul(0x100_0000_01b3)) | 1;
|
||||
let mut i = hash as usize & (SITES - 1);
|
||||
let site = loop {
|
||||
// SAFETY: `i < SITES`, inside the table made above.
|
||||
let s = unsafe { &mut *t.sites.add(i) };
|
||||
if s.hash == hash {
|
||||
break i;
|
||||
}
|
||||
if s.hash == 0 {
|
||||
if t.used_sites * 4 > SITES * 3 {
|
||||
DROPPED.fetch_add(1, Relaxed);
|
||||
return;
|
||||
}
|
||||
t.used_sites += 1;
|
||||
s.hash = hash;
|
||||
s.depth = frames.len() as u8;
|
||||
s.frames[..frames.len()].copy_from_slice(frames);
|
||||
break i;
|
||||
}
|
||||
i = (i + 1) & (SITES - 1);
|
||||
};
|
||||
let mut j = (ptr >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) & (LIVE - 1);
|
||||
for _ in 0..LIVE {
|
||||
// SAFETY: `j < LIVE`.
|
||||
let l = unsafe { &mut *t.live.add(j) };
|
||||
if l.ptr <= 1 {
|
||||
*l = Live { ptr, site: site as u32, weight };
|
||||
// SAFETY: `site < SITES`.
|
||||
let s = unsafe { &mut *t.sites.add(site) };
|
||||
s.live_bytes += weight as i64;
|
||||
s.live_blocks += 1;
|
||||
s.sampled_bytes += weight as u64;
|
||||
let (word, bit) = filter_bit(ptr);
|
||||
FILTER[word].fetch_or(bit, Relaxed);
|
||||
return;
|
||||
}
|
||||
j = (j + 1) & (LIVE - 1);
|
||||
}
|
||||
DROPPED.fetch_add(1, Relaxed);
|
||||
}
|
||||
|
||||
unsafe fn forget(ptr: usize) {
|
||||
// SAFETY: the caller holds LOCK.
|
||||
let t = unsafe { &mut *TABLES.0.get() };
|
||||
if t.live.is_null() {
|
||||
return;
|
||||
}
|
||||
let mut j = (ptr >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) & (LIVE - 1);
|
||||
for _ in 0..LIVE {
|
||||
// SAFETY: `j < LIVE`.
|
||||
let l = unsafe { &mut *t.live.add(j) };
|
||||
if l.ptr == 0 {
|
||||
return;
|
||||
}
|
||||
if l.ptr == ptr {
|
||||
// SAFETY: a recorded site index.
|
||||
let s = unsafe { &mut *t.sites.add(l.site as usize) };
|
||||
s.live_bytes -= l.weight as i64;
|
||||
s.live_blocks -= 1;
|
||||
l.ptr = 1;
|
||||
return;
|
||||
}
|
||||
j = (j + 1) & (LIVE - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// The live sites as text: a `module <base> <size> <path>` line per loaded module, then a
|
||||
/// `site <live bytes> <live samples> <sampled bytes ever> <frame>...` line per site with live bytes.
|
||||
fn report() -> String {
|
||||
use std::fmt::Write;
|
||||
let mut out = String::new();
|
||||
writeln!(out, "interval {INTERVAL}").ok();
|
||||
writeln!(out, "dropped {}", DROPPED.load(Relaxed)).ok();
|
||||
writeln!(out, "heap {} {}", super::LIVE.load(Relaxed), super::PEAK.load(Relaxed)).ok();
|
||||
for (base, size, path) in os::modules() {
|
||||
writeln!(out, "module {base:x} {size:x} {path}").ok();
|
||||
}
|
||||
if READY.load(Acquire) == 0 {
|
||||
return out;
|
||||
}
|
||||
lock();
|
||||
// SAFETY: under LOCK; READY says the tables exist.
|
||||
let t = unsafe { &*TABLES.0.get() };
|
||||
let mut lines = Vec::new();
|
||||
for i in 0..SITES {
|
||||
// SAFETY: `i < SITES`.
|
||||
let s = unsafe { *t.sites.add(i) };
|
||||
if s.hash != 0 && s.live_bytes != 0 {
|
||||
lines.push(s);
|
||||
}
|
||||
}
|
||||
unlock();
|
||||
for s in lines {
|
||||
write!(out, "site {} {} {}", s.live_bytes, s.live_blocks, s.sampled_bytes).ok();
|
||||
for f in &s.frames[..s.depth as usize] {
|
||||
write!(out, " {f:x}").ok();
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str("section nt-heaps\n");
|
||||
for (heap, regions, busy, blocks, big) in os::nt_heaps() {
|
||||
writeln!(out, "ntheap {heap:x} busy {busy} blocks {blocks}").ok();
|
||||
for (base, committed, uncommitted) in regions {
|
||||
writeln!(out, "region {base:x} {committed} {uncommitted}").ok();
|
||||
}
|
||||
for (at, size) in big {
|
||||
writeln!(out, "big {at:x} {size}").ok();
|
||||
}
|
||||
}
|
||||
for (name, section) in SECTIONS.lock().unwrap_or_else(|e| e.into_inner()).iter() {
|
||||
writeln!(out, "section {name}").ok();
|
||||
out.push_str(§ion());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs `f` on this thread without sampling what it allocates or frees (the dump's own work).
|
||||
fn unsampled<T>(f: impl FnOnce() -> T) -> T {
|
||||
INSIDE.try_with(|i| i.set(true)).ok();
|
||||
let v = f();
|
||||
INSIDE.try_with(|i| i.set(false)).ok();
|
||||
v
|
||||
}
|
||||
|
||||
fn capture(frames: &mut [usize; FRAMES]) -> usize {
|
||||
os::capture(frames)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod os {
|
||||
use std::ffi::c_void;
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn RtlCaptureStackBackTrace(skip: u32, count: u32, frames: *mut *mut c_void, hash: *mut u32) -> u16;
|
||||
fn VirtualAlloc(addr: *mut c_void, size: usize, kind: u32, protect: u32) -> *mut c_void;
|
||||
fn CreateThread(attrs: *mut c_void, stack: usize, start: unsafe extern "system" fn(*mut c_void) -> u32, param: *mut c_void, flags: u32, id: *mut u32) -> *mut c_void;
|
||||
fn CreateEventW(attrs: *mut c_void, manual: i32, initial: i32, name: *const u16) -> *mut c_void;
|
||||
fn WaitForSingleObject(h: *mut c_void, ms: u32) -> u32;
|
||||
fn GetCurrentProcess() -> *mut c_void;
|
||||
fn GetCurrentProcessId() -> u32;
|
||||
fn K32EnumProcessModules(p: *mut c_void, mods: *mut *mut c_void, cb: u32, needed: *mut u32) -> i32;
|
||||
fn K32GetModuleInformation(p: *mut c_void, m: *mut c_void, info: *mut [usize; 3], cb: u32) -> i32;
|
||||
fn K32GetModuleFileNameExW(p: *mut c_void, m: *mut c_void, name: *mut u16, n: u32) -> u32;
|
||||
fn GetProcessHeaps(n: u32, heaps: *mut *mut c_void) -> u32;
|
||||
fn HeapLock(h: *mut c_void) -> i32;
|
||||
fn HeapUnlock(h: *mut c_void) -> i32;
|
||||
fn HeapWalk(h: *mut c_void, entry: *mut [u8; 40]) -> i32;
|
||||
}
|
||||
|
||||
/// A heap's regions, the bytes and blocks in use, and blocks of 256 KiB or more (which the
|
||||
/// heap makes with VirtualAlloc of their own), per heap of the process (the C runtime's, the
|
||||
/// GPU driver's and the system DLLs' heaps).
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(super) fn nt_heaps() -> Vec<(usize, Vec<(usize, u32, u32)>, u64, u64, Vec<(usize, usize)>)> {
|
||||
let mut heaps = vec![std::ptr::null_mut(); 256];
|
||||
// SAFETY: the buffer holds as many handles as passed.
|
||||
let n = unsafe { GetProcessHeaps(heaps.len() as u32, heaps.as_mut_ptr()) } as usize;
|
||||
heaps.truncate(n.min(256));
|
||||
heaps
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let (mut regions, mut busy, mut blocks, mut big) = (Vec::new(), 0u64, 0u64, Vec::new());
|
||||
let mut e = [0u8; 40];
|
||||
// SAFETY: a heap of this process, locked while it's walked; `e` is a PROCESS_HEAP_ENTRY.
|
||||
unsafe {
|
||||
HeapLock(h);
|
||||
while HeapWalk(h, &mut e) != 0 {
|
||||
let data = usize::from_le_bytes(e[0..8].try_into().unwrap_or_default());
|
||||
let size = u32::from_le_bytes(e[8..12].try_into().unwrap_or_default()) as usize;
|
||||
let flags = u16::from_le_bytes([e[14], e[15]]);
|
||||
if flags & 1 != 0 {
|
||||
regions.push((data, u32::from_le_bytes(e[16..20].try_into().unwrap_or_default()), u32::from_le_bytes(e[20..24].try_into().unwrap_or_default())));
|
||||
} else if flags & 4 != 0 {
|
||||
busy += size as u64;
|
||||
blocks += 1;
|
||||
if size >= 256 << 10 {
|
||||
big.push((data, size));
|
||||
}
|
||||
}
|
||||
}
|
||||
HeapUnlock(h);
|
||||
}
|
||||
(h as usize, regions, busy, blocks, big)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn capture(frames: &mut [usize; super::FRAMES]) -> usize {
|
||||
// From the caller of this frame; the symbolizer drops procwatch's and the allocator's own.
|
||||
// SAFETY: `frames` has room for `FRAMES` pointers.
|
||||
unsafe { RtlCaptureStackBackTrace(1, super::FRAMES as u32, frames.as_mut_ptr().cast(), std::ptr::null_mut()) as usize }
|
||||
}
|
||||
|
||||
pub(super) fn zeroed(size: usize) -> *mut u8 {
|
||||
// SAFETY: a fresh committed, zeroed read-write region, or null.
|
||||
unsafe { VirtualAlloc(std::ptr::null_mut(), size, 0x3000, 0x04).cast() }
|
||||
}
|
||||
|
||||
pub(super) fn modules() -> Vec<(usize, usize, String)> {
|
||||
let mut mods = vec![std::ptr::null_mut(); 1024];
|
||||
let mut needed = 0u32;
|
||||
// SAFETY: the buffer's size in bytes is passed; the pseudo-handle needs no closing.
|
||||
let ok = unsafe { K32EnumProcessModules(GetCurrentProcess(), mods.as_mut_ptr(), (mods.len() * 8) as u32, &mut needed) };
|
||||
if ok == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
mods.truncate((needed as usize / 8).min(mods.len()));
|
||||
mods.into_iter()
|
||||
.map(|m| {
|
||||
let mut info = [0usize; 3];
|
||||
let mut name = [0u16; 520];
|
||||
// SAFETY: `m` is a module of this process; buffers sized as passed.
|
||||
let n = unsafe {
|
||||
K32GetModuleInformation(GetCurrentProcess(), m, &mut info, 24);
|
||||
K32GetModuleFileNameExW(GetCurrentProcess(), m, name.as_mut_ptr(), name.len() as u32)
|
||||
};
|
||||
(info[0], info[1] as u32 as usize, String::from_utf16_lossy(&name[..n as usize]))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn start_dumper() {
|
||||
// A raw thread: `std::thread` would allocate here, inside the allocator.
|
||||
// SAFETY: `dumper` takes no parameter and runs for the life of the process.
|
||||
unsafe { CreateThread(std::ptr::null_mut(), 0, dumper, std::ptr::null_mut(), 0, std::ptr::null_mut()) };
|
||||
}
|
||||
|
||||
unsafe extern "system" fn dumper(_: *mut c_void) -> u32 {
|
||||
super::unsampled(|| {
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
let Some(dir) = std::env::var_os("PROCWATCH_ALLOC_SITES") else { return };
|
||||
// SAFETY: plain Win32 calls.
|
||||
let pid = unsafe { GetCurrentProcessId() };
|
||||
let name: Vec<u16> = format!("Local\\procwatch-alloc-sites-{pid}").encode_utf16().chain([0]).collect();
|
||||
// SAFETY: an auto-reset event named for this process.
|
||||
let event = unsafe { CreateEventW(std::ptr::null_mut(), 0, 0, name.as_ptr()) };
|
||||
if event.is_null() {
|
||||
return;
|
||||
}
|
||||
for n in 0u64..=u64::MAX {
|
||||
// SAFETY: a valid event handle, kept for the life of the process.
|
||||
unsafe { WaitForSingleObject(event, u32::MAX) };
|
||||
let path = std::path::Path::new(&dir).join(format!("alloc-sites-{pid}-{n}.txt"));
|
||||
std::fs::write(path, super::report()).ok();
|
||||
}
|
||||
});
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod os {
|
||||
pub(super) fn capture(_frames: &mut [usize; super::FRAMES]) -> usize {
|
||||
0
|
||||
}
|
||||
pub(super) fn zeroed(_size: usize) -> *mut u8 {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
pub(super) fn modules() -> Vec<(usize, usize, String)> {
|
||||
Vec::new()
|
||||
}
|
||||
pub(super) fn start_dumper() {}
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(super) fn nt_heaps() -> Vec<(usize, Vec<(usize, u32, u32)>, u64, u64, Vec<(usize, usize)>)> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
//! Byte gauges for memory the Rust allocator never sees: pixel buffers, IOSurfaces, GPU
|
||||
//! textures, model weights mapped by a C library, or a queue you want named in a warning.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! static FRAMES: procwatch::Gauge = procwatch::Gauge::new("video.frames");
|
||||
//!
|
||||
//! let lease = FRAMES.track(width * height * 4); // subtracted again when `lease` drops
|
||||
//! FRAMES.set(cache.bytes()); // or report a total you measure yourself
|
||||
//! ```
|
||||
//!
|
||||
//! A snapshot subtracts the counted heap and every gauge from the footprint; what's left
|
||||
//! ([`crate::Snapshot::unaccounted`]) is memory nothing claims, which is where a leaked native
|
||||
//! handle shows up.
|
||||
//!
|
||||
//! Gauges count in builds with debug assertions, or with the `release-gauges` feature;
|
||||
//! otherwise every call compiles to nothing and [`gauges`] is empty.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicPtr, Ordering::Relaxed};
|
||||
|
||||
/// Gauges there's room for; more still count but aren't listed.
|
||||
pub const GAUGES: usize = 64;
|
||||
|
||||
const ON: bool = cfg!(any(debug_assertions, feature = "release-gauges"));
|
||||
|
||||
static REGISTRY: [AtomicPtr<Gauge>; GAUGES] = [const { AtomicPtr::new(std::ptr::null_mut()) }; GAUGES];
|
||||
|
||||
pub struct Gauge {
|
||||
name: &'static str,
|
||||
bytes: AtomicI64,
|
||||
registered: AtomicBool,
|
||||
}
|
||||
|
||||
impl Gauge {
|
||||
pub const fn new(name: &'static str) -> Gauge {
|
||||
Gauge { name, bytes: AtomicI64::new(0), registered: AtomicBool::new(false) }
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &'static str {
|
||||
self.name
|
||||
}
|
||||
|
||||
/// Current bytes (0 when gauges are compiled out).
|
||||
pub fn get(&self) -> i64 {
|
||||
self.bytes.load(Relaxed)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn add(&'static self, bytes: usize) {
|
||||
if ON {
|
||||
self.register();
|
||||
self.bytes.fetch_add(bytes as i64, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn sub(&'static self, bytes: usize) {
|
||||
if ON {
|
||||
self.bytes.fetch_sub(bytes as i64, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the total, for a size you measure rather than count.
|
||||
#[inline]
|
||||
pub fn set(&'static self, bytes: usize) {
|
||||
if ON {
|
||||
self.register();
|
||||
self.bytes.store(bytes as i64, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `bytes` now and subtracts them when the lease drops.
|
||||
#[inline]
|
||||
#[must_use = "the bytes are subtracted again when the lease drops"]
|
||||
pub fn track(&'static self, bytes: usize) -> Lease {
|
||||
self.add(bytes);
|
||||
Lease { gauge: self, bytes }
|
||||
}
|
||||
|
||||
fn register(&'static self) {
|
||||
if self.registered.load(Relaxed) || self.registered.swap(true, Relaxed) {
|
||||
return;
|
||||
}
|
||||
let me = self as *const Gauge as *mut Gauge;
|
||||
for slot in ®ISTRY {
|
||||
if slot.compare_exchange(std::ptr::null_mut(), me, Relaxed, Relaxed).is_ok() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes counted against a [`Gauge`] until dropped.
|
||||
pub struct Lease {
|
||||
gauge: &'static Gauge,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Lease {
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
self.gauge.sub(self.bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every gauge used so far, biggest first.
|
||||
#[allow(unsafe_code)]
|
||||
pub fn gauges() -> Vec<(&'static str, i64)> {
|
||||
let mut out: Vec<(&'static str, i64)> = REGISTRY
|
||||
.iter()
|
||||
.map(|slot| slot.load(Relaxed))
|
||||
.take_while(|p| !p.is_null())
|
||||
// SAFETY: only `&'static Gauge`s are ever stored.
|
||||
.map(|p| unsafe { &*p })
|
||||
.map(|g| (g.name, g.get()))
|
||||
.collect();
|
||||
out.sort_by_key(|(_, bytes)| -bytes);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
static A: Gauge = Gauge::new("test.a");
|
||||
static B: Gauge = Gauge::new("test.b");
|
||||
|
||||
#[test]
|
||||
fn leases_add_and_give_back() {
|
||||
if !ON {
|
||||
A.add(1000);
|
||||
assert_eq!((A.get(), gauges().len()), (0, 0), "compiled out");
|
||||
return;
|
||||
}
|
||||
let lease = A.track(1000);
|
||||
A.add(24);
|
||||
B.set(5);
|
||||
let listed = gauges();
|
||||
assert_eq!(listed.iter().find(|(n, _)| *n == "test.a").map(|g| g.1), Some(1024));
|
||||
assert_eq!(listed.iter().find(|(n, _)| *n == "test.b").map(|g| g.1), Some(5));
|
||||
drop(lease);
|
||||
A.sub(24);
|
||||
assert_eq!(A.get(), 0);
|
||||
// Registered once, however often it's used.
|
||||
A.add(1);
|
||||
A.sub(1);
|
||||
assert_eq!(gauges().iter().filter(|(n, _)| *n == "test.a").count(), 1);
|
||||
}
|
||||
}
|
||||
+591
@@ -0,0 +1,591 @@
|
||||
//! A native app's own memory and CPU, watched from inside.
|
||||
//!
|
||||
//! - [`snapshot`]: physical footprint (what Activity Monitor and jetsam count), its lifetime
|
||||
//! peak, resident size, total CPU including threads that have exited, open file descriptors,
|
||||
//! and each live thread's name and CPU. [`snapshot_of`] reads the same of another process of
|
||||
//! this user, with no task port, so it works on a hardened release build.
|
||||
//! - [`usage`]: just the footprint, its peak, resident size and open files, without walking
|
||||
//! threads or touching the heap counters: cheap enough for a recorder to sample every second.
|
||||
//! - [`alloc::Counting`]: an optional counting global allocator for dev builds and tests.
|
||||
//! - [`Gauge`]: named byte counts for memory the allocator never sees (pixel buffers,
|
||||
//! IOSurfaces, GPU textures). With both, [`Snapshot::unaccounted`] is the footprint nothing
|
||||
//! claims, which is where leaked native handles show up.
|
||||
//! - [`watch`]: a thread that samples every few seconds, keeps the latest for [`latest`], and
|
||||
//! writes a line to stderr when the footprint passes a threshold, keeps growing, or the
|
||||
//! process burns CPU, naming the busy threads (or "exited threads"). [`watch_with`] also
|
||||
//! hands each warning to a callback.
|
||||
//! - [`serve`]: a fresh snapshot as JSON on a loopback port, for a dev panel or `curl`.
|
||||
//!
|
||||
//! macOS only for now; elsewhere [`snapshot`] returns `None`, [`usage`] has every field `None`,
|
||||
//! and [`watch`] does nothing.
|
||||
|
||||
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
|
||||
pub mod alloc;
|
||||
pub mod gauge;
|
||||
|
||||
pub use gauge::Gauge;
|
||||
pub use gauge::Lease;
|
||||
pub use gauge::gauges;
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::Instant;
|
||||
|
||||
// procwatch has no Rune dependencies and runs natively.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[inline]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn now() -> Instant { Instant::now() }
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Thread {
|
||||
/// The kernel's id for the thread, stable for its life.
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// CPU seconds since the thread started.
|
||||
pub cpu_s: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Snapshot {
|
||||
pub pid: i32,
|
||||
/// Physical footprint: dirty memory, compressed and swapped included.
|
||||
pub footprint: u64,
|
||||
pub footprint_peak: u64,
|
||||
pub resident: u64,
|
||||
/// User plus system CPU seconds over the process's life, exited threads included.
|
||||
pub cpu_s: f64,
|
||||
/// Open file descriptors, sockets and pipes included.
|
||||
pub fds: u32,
|
||||
pub threads: Vec<Thread>,
|
||||
pub heap: Option<alloc::Heap>,
|
||||
/// Every [`Gauge`] used so far, biggest first.
|
||||
pub gauges: Vec<(&'static str, i64)>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// CPU seconds spent by threads that have since exited.
|
||||
pub fn exited_cpu_s(&self) -> f64 {
|
||||
(self.cpu_s - self.threads.iter().map(|t| t.cpu_s).sum::<f64>()).max(0.0)
|
||||
}
|
||||
|
||||
/// Footprint minus the counted Rust heap and every gauge; `None` without
|
||||
/// [`alloc::Counting`]. It has a floor (code, stacks, allocator overhead, system
|
||||
/// libraries), so watch it grow rather than reading it alone.
|
||||
pub fn unaccounted(&self) -> Option<i64> {
|
||||
let heap = self.heap.as_ref()?;
|
||||
Some(self.footprint as i64 - heap.live.max(0) - self.gauges.iter().map(|(_, b)| b).sum::<i64>())
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> String {
|
||||
let mut s = String::new();
|
||||
write!(
|
||||
s,
|
||||
"{{\"pid\":{},\"footprint\":{},\"footprint_peak\":{},\"resident\":{},\"cpu_s\":{:.3},\"exited_cpu_s\":{:.3},\"fds\":{},\"threads\":[",
|
||||
self.pid,
|
||||
self.footprint,
|
||||
self.footprint_peak,
|
||||
self.resident,
|
||||
self.cpu_s,
|
||||
self.exited_cpu_s(),
|
||||
self.fds,
|
||||
).ok();
|
||||
for (i, t) in self.threads.iter().enumerate() {
|
||||
write!(s, "{}{{\"name\":\"{}\",\"cpu_s\":{:.3}}}", if i > 0 { "," } else { "" }, clean(&t.name), t.cpu_s).ok();
|
||||
}
|
||||
s.push(']');
|
||||
if let Some(h) = &self.heap {
|
||||
write!(
|
||||
s,
|
||||
",\"heap\":{{\"live\":{},\"peak\":{},\"allocations\":{},\"largest\":{},\"big_live\":{},\"big_blocks\":{},\"tags\":",
|
||||
h.live, h.peak, h.allocations, h.largest, h.big_live, h.big_blocks
|
||||
).ok();
|
||||
json_map(&mut s, &h.tags);
|
||||
s.push('}');
|
||||
}
|
||||
s.push_str(",\"gauges\":");
|
||||
json_map(&mut s, &self.gauges);
|
||||
if let Some(bytes) = self.unaccounted() {
|
||||
write!(s, ",\"unaccounted\":{bytes}").ok();
|
||||
}
|
||||
s.push('}');
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
fn clean(name: &str) -> String {
|
||||
name.chars().filter(|c| !c.is_control() && *c != '"' && *c != '\\').collect()
|
||||
}
|
||||
|
||||
fn json_map(s: &mut String, entries: &[(&'static str, i64)]) {
|
||||
s.push('{');
|
||||
for (i, (name, bytes)) in entries.iter().enumerate() {
|
||||
write!(s, "{}\"{}\":{bytes}", if i > 0 { "," } else { "" }, clean(name)).ok();
|
||||
}
|
||||
s.push('}');
|
||||
}
|
||||
|
||||
/// This process now.
|
||||
pub fn snapshot() -> Option<Snapshot> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
None
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let mut s = snapshot_of(std::process::id() as i32)?;
|
||||
s.heap = alloc::heap();
|
||||
s.gauges = gauges();
|
||||
Some(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Another process of this user (or this one), read through `proc_pid_rusage` and
|
||||
/// `proc_pidinfo`: no task port, so hardened apps can be read too.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[allow(unsafe_code)]
|
||||
pub fn snapshot_of(pid: i32) -> Option<Snapshot> {
|
||||
use std::mem::{MaybeUninit, size_of};
|
||||
let usage = rusage(pid)?;
|
||||
// SAFETY: plain libproc and mach calls into buffers sized for them.
|
||||
unsafe {
|
||||
let ticks = ticks_to_seconds();
|
||||
const PROC_PIDLISTTHREADS: i32 = 6;
|
||||
let mut ids = vec![0u64; 512];
|
||||
let bytes = libc::proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, ids.as_mut_ptr().cast(), (ids.len() * 8) as i32);
|
||||
ids.truncate(bytes.max(0) as usize / 8);
|
||||
let threads = ids
|
||||
.iter()
|
||||
.filter_map(|&id| {
|
||||
let mut info = MaybeUninit::<libc::proc_threadinfo>::zeroed();
|
||||
let size = size_of::<libc::proc_threadinfo>() as i32;
|
||||
if libc::proc_pidinfo(pid, libc::PROC_PIDTHREADINFO, id, info.as_mut_ptr().cast(), size) != size {
|
||||
return None;
|
||||
}
|
||||
let info = info.assume_init();
|
||||
let name = std::ffi::CStr::from_ptr(info.pth_name.as_ptr()).to_string_lossy().into_owned();
|
||||
Some(Thread { id, name, cpu_s: (info.pth_user_time + info.pth_system_time) as f64 / 1e9 })
|
||||
})
|
||||
.collect();
|
||||
Some(Snapshot {
|
||||
pid,
|
||||
footprint: usage.ri_phys_footprint,
|
||||
footprint_peak: usage.ri_lifetime_max_phys_footprint,
|
||||
resident: usage.ri_resident_size,
|
||||
cpu_s: (usage.ri_user_time + usage.ri_system_time) as f64 * ticks,
|
||||
fds: open_fds(pid).unwrap_or(0),
|
||||
threads,
|
||||
heap: None,
|
||||
gauges: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn snapshot_of(_pid: i32) -> Option<Snapshot> {
|
||||
None
|
||||
}
|
||||
|
||||
/// This process's memory and open files, each `None` where it can't be read.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Usage {
|
||||
/// Physical footprint, as in [`Snapshot::footprint`].
|
||||
pub footprint: Option<u64>,
|
||||
pub footprint_peak: Option<u64>,
|
||||
pub resident: Option<u64>,
|
||||
pub fds: Option<u32>,
|
||||
}
|
||||
|
||||
/// [`snapshot`]'s memory and file counts without its thread walk or heap counters: two
|
||||
/// libproc calls for memory and two for files. A failed read leaves its fields `None`.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn usage() -> Usage {
|
||||
let pid = std::process::id() as i32;
|
||||
let mut out = Usage { fds: open_fds(pid), ..Usage::default() };
|
||||
if let Some(u) = rusage(pid) {
|
||||
out.footprint = Some(u.ri_phys_footprint);
|
||||
out.footprint_peak = Some(u.ri_lifetime_max_phys_footprint);
|
||||
out.resident = Some(u.ri_resident_size);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn usage() -> Usage {
|
||||
Usage::default()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[allow(unsafe_code)]
|
||||
fn rusage(pid: i32) -> Option<libc::rusage_info_v4> {
|
||||
let mut usage = std::mem::MaybeUninit::<libc::rusage_info_v4>::zeroed();
|
||||
// SAFETY: a zeroed buffer of the size RUSAGE_INFO_V4 fills; read only on success.
|
||||
unsafe {
|
||||
if libc::proc_pid_rusage(pid, libc::RUSAGE_INFO_V4, usage.as_mut_ptr().cast()) != 0 {
|
||||
return None;
|
||||
}
|
||||
Some(usage.assume_init())
|
||||
}
|
||||
}
|
||||
|
||||
/// `PROC_PIDLISTFDS` fills one 8-byte `proc_fdinfo` per descriptor. Asking with no buffer
|
||||
/// returns a size with headroom; the second call returns what it filled. Either call
|
||||
/// returns 0 on failure, so 0 is `None`.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[allow(unsafe_code)]
|
||||
fn open_fds(pid: i32) -> Option<u32> {
|
||||
const PROC_PIDLISTFDS: i32 = 1;
|
||||
const FDINFO: usize = 8;
|
||||
// SAFETY: the first call writes nothing; the second writes at most `buf`'s length.
|
||||
unsafe {
|
||||
let want = libc::proc_pidinfo(pid, PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0);
|
||||
if want <= 0 {
|
||||
return None;
|
||||
}
|
||||
let mut buf = vec![0u64; want as usize / FDINFO + 1];
|
||||
let got = libc::proc_pidinfo(pid, PROC_PIDLISTFDS, 0, buf.as_mut_ptr().cast(), (buf.len() * FDINFO) as i32);
|
||||
(got > 0).then(|| (got as usize / FDINFO) as u32)
|
||||
}
|
||||
}
|
||||
|
||||
/// `rusage_info` times are mach ticks (nanoseconds on Intel, 125/3 ns on Apple silicon).
|
||||
#[cfg(target_os = "macos")]
|
||||
#[allow(unsafe_code)]
|
||||
fn ticks_to_seconds() -> f64 {
|
||||
#[repr(C)]
|
||||
struct Timebase {
|
||||
numer: u32,
|
||||
denom: u32,
|
||||
}
|
||||
unsafe extern "C" {
|
||||
fn mach_timebase_info(info: *mut Timebase) -> i32;
|
||||
}
|
||||
let mut base = Timebase { numer: 0, denom: 0 };
|
||||
// SAFETY: fills `base`.
|
||||
unsafe { mach_timebase_info(&mut base) };
|
||||
if base.denom == 0 { 1e-9 } else { base.numer as f64 / base.denom as f64 / 1e9 }
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
/// How often to sample.
|
||||
pub every: Duration,
|
||||
/// A status line this often even when all is well; `None`: only warnings.
|
||||
pub report: Option<Duration>,
|
||||
/// Warn when the footprint passes this, then again at each doubling.
|
||||
pub warn_footprint: u64,
|
||||
/// Warn when the footprint grew by this much over `growth_window`, every sample of it up.
|
||||
pub warn_growth: u64,
|
||||
pub growth_window: Duration,
|
||||
/// Warn when the process averaged more than this many cores over `cpu_window`.
|
||||
pub warn_cpu_cores: f64,
|
||||
pub cpu_window: Duration,
|
||||
/// Prefix for log lines.
|
||||
pub name: &'static str,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Quiet in a release build: one line an hour, and warnings.
|
||||
pub fn release(name: &'static str) -> Config {
|
||||
Config {
|
||||
every: Duration::from_secs(10),
|
||||
report: Some(Duration::from_secs(3600)),
|
||||
warn_footprint: 1 << 30,
|
||||
warn_growth: 256 << 20,
|
||||
growth_window: Duration::from_secs(60),
|
||||
warn_cpu_cores: 0.8,
|
||||
cpu_window: Duration::from_secs(60),
|
||||
name,
|
||||
}
|
||||
}
|
||||
|
||||
/// Chatty in a dev build: a line a minute, lower thresholds.
|
||||
pub fn dev(name: &'static str) -> Config {
|
||||
Config {
|
||||
every: Duration::from_secs(2),
|
||||
report: Some(Duration::from_secs(60)),
|
||||
warn_footprint: 512 << 20,
|
||||
warn_growth: 64 << 20,
|
||||
growth_window: Duration::from_secs(20),
|
||||
warn_cpu_cores: 0.5,
|
||||
cpu_window: Duration::from_secs(20),
|
||||
..Config::release(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`Watcher`] noticed in a sample.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// The footprint passed `warn_footprint`, or doubled since the last such warning.
|
||||
Footprint,
|
||||
/// The footprint rose every sample for `growth_window`, by at least `warn_growth`.
|
||||
Growth,
|
||||
/// The process averaged at least `warn_cpu_cores` over `cpu_window`.
|
||||
Cpu,
|
||||
/// The periodic status line.
|
||||
Report,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Event {
|
||||
pub kind: Kind,
|
||||
pub line: String,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn is_warning(&self) -> bool {
|
||||
self.kind != Kind::Report
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Event {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.line)
|
||||
}
|
||||
}
|
||||
|
||||
static LATEST: Mutex<Option<Snapshot>> = Mutex::new(None);
|
||||
|
||||
/// The watcher's last sample, if it runs.
|
||||
pub fn latest() -> Option<Snapshot> {
|
||||
LATEST.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
/// Samples on a `procwatch` thread for the life of the process, logging to stderr.
|
||||
pub fn watch(config: Config) {
|
||||
watch_with(config, |_, _| {});
|
||||
}
|
||||
|
||||
/// [`watch`], and calls `on_warning` on the watcher thread for every warning (not the
|
||||
/// periodic report): to drop a cache, write a capture, or post the numbers somewhere.
|
||||
pub fn watch_with(config: Config, on_warning: impl Fn(&Event, &Snapshot) + Send + 'static) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (config, on_warning);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if snapshot().is_none() {
|
||||
return;
|
||||
}
|
||||
std::thread::Builder::new().name("procwatch".into()).spawn(move || {
|
||||
let mut watcher = Watcher::new(config);
|
||||
loop {
|
||||
if let Some(s) = snapshot() {
|
||||
for event in watcher.observe(now(), &s) {
|
||||
eprintln!("{event}");
|
||||
if event.is_warning() {
|
||||
on_warning(&event, &s);
|
||||
}
|
||||
}
|
||||
*LATEST.lock().unwrap_or_else(|e| e.into_inner()) = Some(s);
|
||||
}
|
||||
std::thread::sleep(watcher.config.every);
|
||||
}
|
||||
}).ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// The judging half of [`watch`], fed samples so tests can drive it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub struct Watcher {
|
||||
pub config: Config,
|
||||
history: Vec<(Instant, Snapshot)>,
|
||||
/// The footprint last warned about (0: none yet); the next warning needs twice it.
|
||||
warned_footprint: u64,
|
||||
growth: Gate,
|
||||
cpu: Gate,
|
||||
report: Gate,
|
||||
}
|
||||
|
||||
/// One message of a kind per window: the first goes out at once, the next a window after it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Gate {
|
||||
last: Option<Instant>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Gate {
|
||||
/// Whether a message may go out at `now`, `window` after the last; if so, it counts as sent.
|
||||
fn pass(&mut self, now: Instant, window: Duration) -> bool {
|
||||
let open = self.last.is_none_or(|at| now.duration_since(at) >= window);
|
||||
if open {
|
||||
self.last = Some(now);
|
||||
}
|
||||
open
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Watcher {
|
||||
pub fn new(config: Config) -> Watcher {
|
||||
Watcher { config, history: Vec::new(), warned_footprint: 0, growth: Gate::default(), cpu: Gate::default(), report: Gate::default() }
|
||||
}
|
||||
|
||||
/// Takes a sample; returns what to log.
|
||||
pub fn observe(&mut self, now: Instant, s: &Snapshot) -> Vec<Event> {
|
||||
let c = &self.config;
|
||||
let mut out = Vec::new();
|
||||
// Keep one sample at or past the longest window, so a window always has a start even
|
||||
// when sleeps run a little long.
|
||||
let keep = c.growth_window.max(c.cpu_window);
|
||||
if let Some(edge) = self.history.iter().rposition(|(at, _)| now.duration_since(*at) >= keep) {
|
||||
self.history.drain(..edge);
|
||||
}
|
||||
self.history.push((now, s.clone()));
|
||||
let history = &self.history;
|
||||
// The samples from the last one at or past `window` ago up to now.
|
||||
let since = |window: Duration| {
|
||||
let start = history.iter().rposition(|(at, _)| now.duration_since(*at) >= window).unwrap_or(0);
|
||||
&history[start..]
|
||||
};
|
||||
let event = |kind, line| Event { kind, line };
|
||||
|
||||
if s.footprint >= c.warn_footprint && s.footprint >= self.warned_footprint.saturating_mul(2) {
|
||||
self.warned_footprint = s.footprint;
|
||||
out.push(event(
|
||||
Kind::Footprint,
|
||||
format!("{}: warning: footprint {} (peak {}){}", c.name, mb(s.footprint), mb(s.footprint_peak), memory_note(s)),
|
||||
));
|
||||
}
|
||||
let window = since(c.growth_window);
|
||||
if let Some((then, first)) = window.first()
|
||||
&& now.duration_since(*then) >= c.growth_window.mul_f64(0.9)
|
||||
{
|
||||
let rising = window.windows(2).all(|w| w[1].1.footprint >= w[0].1.footprint);
|
||||
let grew = s.footprint.saturating_sub(first.footprint);
|
||||
if rising && grew >= c.warn_growth && self.growth.pass(now, c.growth_window) {
|
||||
out.push(event(
|
||||
Kind::Growth,
|
||||
format!(
|
||||
"{}: warning: footprint grew {} in {:.0}s to {}{}",
|
||||
c.name,
|
||||
mb(grew),
|
||||
c.growth_window.as_secs_f64(),
|
||||
mb(s.footprint),
|
||||
memory_note(s)
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some((then, old)) = since(c.cpu_window).first() {
|
||||
let span = now.duration_since(*then).as_secs_f64();
|
||||
let cores = (s.cpu_s - old.cpu_s) / span.max(1e-9);
|
||||
if span >= c.cpu_window.as_secs_f64() * 0.9 && cores >= c.warn_cpu_cores && self.cpu.pass(now, c.cpu_window) {
|
||||
out.push(event(Kind::Cpu, format!("{}: warning: {:.0}% CPU over {:.0}s: {}", c.name, cores * 100.0, span, busiest(old, s, span))));
|
||||
}
|
||||
}
|
||||
if let Some(every) = c.report
|
||||
&& self.report.pass(now, every)
|
||||
{
|
||||
out.push(event(
|
||||
Kind::Report,
|
||||
format!(
|
||||
"{}: footprint {} (peak {}), resident {}, CPU {:.1}s ({:.1}s in exited threads), {} threads, {} fds{}",
|
||||
c.name,
|
||||
mb(s.footprint),
|
||||
mb(s.footprint_peak),
|
||||
mb(s.resident),
|
||||
s.cpu_s,
|
||||
s.exited_cpu_s(),
|
||||
s.threads.len(),
|
||||
s.fds,
|
||||
memory_note(s)
|
||||
),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The threads that used the most CPU between two samples, as percentages of one core.
|
||||
fn busiest(old: &Snapshot, new: &Snapshot, span: f64) -> String {
|
||||
let mut used: Vec<(String, f64)> = new
|
||||
.threads
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let before = old.threads.iter().find(|o| o.id == t.id).map_or(0.0, |o| o.cpu_s);
|
||||
let name = if t.name.is_empty() { "unnamed".to_owned() } else { t.name.clone() };
|
||||
(name, (t.cpu_s - before).max(0.0))
|
||||
})
|
||||
.collect();
|
||||
// Whatever the live threads don't account for went to threads that exited in between,
|
||||
// counting only their CPU since `old`, not their whole lives.
|
||||
let exited = (new.cpu_s - old.cpu_s) - used.iter().map(|(_, s)| s).sum::<f64>();
|
||||
if exited > 0.01 * span {
|
||||
used.push(("exited threads".into(), exited));
|
||||
}
|
||||
used.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
used.iter()
|
||||
.take(4)
|
||||
.filter(|(_, s)| *s > 0.0)
|
||||
.map(|(n, s)| format!("{n} {:.0}%", 100.0 * s / span.max(1e-9)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// Where the footprint sits: the counted heap, the biggest gauges, and what nothing claims.
|
||||
fn memory_note(s: &Snapshot) -> String {
|
||||
let mut note = match &s.heap {
|
||||
Some(h) if h.big_blocks > 0 => format!(
|
||||
"; heap {} live, {} in {} big blocks, largest request {}",
|
||||
mb(h.live.max(0) as u64),
|
||||
mb(h.big_live.max(0) as u64),
|
||||
h.big_blocks,
|
||||
mb(h.largest as u64)
|
||||
),
|
||||
Some(h) => format!("; heap {} live (peak {})", mb(h.live.max(0) as u64), mb(h.peak.max(0) as u64)),
|
||||
None => String::new(),
|
||||
};
|
||||
let top: Vec<String> = s.gauges.iter().filter(|(_, b)| *b > 0).take(3).map(|(n, b)| format!("{n} {}", mb(*b as u64))).collect();
|
||||
if !top.is_empty() {
|
||||
write!(note, "; {}", top.join(", ")).ok();
|
||||
}
|
||||
if let Some(bytes) = s.unaccounted() {
|
||||
write!(note, "; unaccounted {}", mb(bytes.max(0) as u64)).ok();
|
||||
}
|
||||
note
|
||||
}
|
||||
|
||||
pub fn mb(bytes: u64) -> String {
|
||||
if bytes >= 10 << 30 {
|
||||
format!("{:.0} GB", bytes as f64 / (1u64 << 30) as f64)
|
||||
} else if bytes >= 1 << 30 {
|
||||
format!("{:.1} GB", bytes as f64 / (1u64 << 30) as f64)
|
||||
} else {
|
||||
format!("{:.0} MB", bytes as f64 / (1u64 << 20) as f64)
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers every request on `addr` (keep it loopback) with a fresh [`snapshot`] as JSON.
|
||||
pub fn serve(addr: std::net::SocketAddr) -> std::io::Result<std::net::SocketAddr> {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind(addr)?;
|
||||
let bound = listener.local_addr()?;
|
||||
std::thread::Builder::new().name("procwatch-http".into()).spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut stream) = stream else { continue };
|
||||
if !stream.peer_addr().is_ok_and(|p| p.ip().is_loopback()) {
|
||||
continue;
|
||||
}
|
||||
stream.set_read_timeout(Some(Duration::from_secs(1))).ok();
|
||||
let _bytes = stream.read(&mut [0; 1024]).unwrap_or(0);
|
||||
let body = snapshot().map_or_else(|| "null".to_owned(), |s| s.to_json());
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
).ok();
|
||||
}
|
||||
})?;
|
||||
Ok(bound)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
use super::*;
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOC: alloc::Counting = alloc::Counting::system();
|
||||
|
||||
#[test]
|
||||
fn counts_this_threads_allocations_and_live_heap() {
|
||||
let live = alloc::heap().unwrap().live;
|
||||
let before = alloc::thread_allocations();
|
||||
let held = std::hint::black_box(vec![0u8; 1 << 20]);
|
||||
assert_eq!(alloc::thread_allocations() - before, 1);
|
||||
// Other tests allocate in parallel, so allow slack.
|
||||
assert!(alloc::heap().unwrap().live - live >= (1 << 20) - (256 << 10));
|
||||
drop(held);
|
||||
let quiet = alloc::thread_allocations();
|
||||
let _ = std::hint::black_box(1 + 1);
|
||||
assert_eq!(alloc::thread_allocations(), quiet);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(unsafe_code)]
|
||||
fn thread_bytes_count_requests_not_frees_on_this_thread_only() {
|
||||
use std::alloc::{GlobalAlloc, Layout};
|
||||
let allocator = alloc::Counting::system();
|
||||
let before = alloc::thread_allocated_bytes().unwrap();
|
||||
// SAFETY: valid layouts, checked allocations, each freed once with its layout.
|
||||
unsafe {
|
||||
let layout = Layout::from_size_align(128, 8).unwrap();
|
||||
let p = allocator.alloc_zeroed(layout);
|
||||
assert!(!p.is_null());
|
||||
let p = allocator.realloc(p, layout, 256);
|
||||
assert!(!p.is_null());
|
||||
allocator.dealloc(p, Layout::from_size_align(256, 8).unwrap());
|
||||
}
|
||||
assert_eq!(alloc::thread_allocated_bytes().unwrap() - before, 384);
|
||||
let threads: Vec<_> = (0..8)
|
||||
.map(|_| {
|
||||
std::thread::spawn(|| {
|
||||
let start = alloc::thread_allocated_bytes().unwrap();
|
||||
for _ in 0..10_000 {
|
||||
drop(std::hint::black_box(vec![42u8; 128]));
|
||||
}
|
||||
alloc::thread_allocated_bytes().unwrap() - start
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for thread in threads {
|
||||
assert_eq!(thread.join().unwrap(), 1_280_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn usage_reads_memory_and_files_without_threads() {
|
||||
let u = usage();
|
||||
let footprint = u.footprint.unwrap();
|
||||
assert!(footprint > 0 && u.footprint_peak.unwrap() >= footprint, "{u:?}");
|
||||
assert!(u.resident.unwrap() > 0 && u.fds.unwrap() >= 3, "{u:?}");
|
||||
let opened: Vec<_> = (0..8).map(|_| std::fs::File::open("Cargo.toml").unwrap()).collect();
|
||||
assert!(usage().fds.unwrap() >= u.fds.unwrap() + 4);
|
||||
drop(opened);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn usage_is_unknown_off_macos() {
|
||||
assert_eq!(usage(), Usage::default());
|
||||
}
|
||||
|
||||
fn at(footprint: u64, cpu_s: f64) -> Snapshot {
|
||||
Snapshot {
|
||||
footprint,
|
||||
footprint_peak: footprint,
|
||||
cpu_s,
|
||||
threads: vec![Thread { id: 1, name: "main".into(), cpu_s: 1.0 }],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn lines(events: &[Event]) -> String {
|
||||
events.iter().map(|e| e.line.as_str()).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[allow(unsafe_code)]
|
||||
fn thread_cpu_s() -> f64 {
|
||||
let mut t = libc::timespec { tv_sec: 0, tv_nsec: 0 };
|
||||
// SAFETY: fills `t`.
|
||||
unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) };
|
||||
t.tv_sec as f64 + t.tv_nsec as f64 / 1e9
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn reads_this_process() {
|
||||
let s = snapshot().unwrap();
|
||||
assert!(s.footprint > 0 && s.footprint_peak >= s.footprint, "{s:?}");
|
||||
assert!(!s.threads.is_empty());
|
||||
assert_eq!(s.pid, std::process::id() as i32);
|
||||
// stdin, stdout and stderr at least.
|
||||
assert!(s.fds >= 3, "{s:?}");
|
||||
let opened: Vec<_> = (0..8).map(|_| std::fs::File::open("Cargo.toml").unwrap()).collect();
|
||||
assert!(snapshot().unwrap().fds >= s.fds + 4, "{s:?}");
|
||||
drop(opened);
|
||||
// A thread that burns CPU and exits still counts.
|
||||
let before = snapshot().unwrap();
|
||||
std::thread::spawn(|| {
|
||||
// Spin on the thread's own CPU clock: on a loaded machine 300 ms of wall time can
|
||||
// be well under 200 ms of CPU.
|
||||
let t = now();
|
||||
let mut x = 0u64;
|
||||
while thread_cpu_s() < 0.3 && t.elapsed() < Duration::from_secs(10) {
|
||||
x = std::hint::black_box(x.wrapping_add(1));
|
||||
}
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
let after = snapshot().unwrap();
|
||||
assert!(after.exited_cpu_s() - before.exited_cpu_s() > 0.2, "{before:?} {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_parses_and_subtracts_heap_and_gauges() {
|
||||
let s = Snapshot {
|
||||
pid: 7,
|
||||
footprint: 1000,
|
||||
threads: vec![Thread { id: 1, name: "a\"b\\c\n".into(), cpu_s: 0.5 }],
|
||||
heap: Some(alloc::Heap { live: 300, tags: vec![("untagged", 300)], ..Default::default() }),
|
||||
gauges: vec![("video.frames", 200), ("gpu.textures", 100)],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s.unaccounted(), Some(400));
|
||||
let v: serde_json::Value = serde_json::from_str(&s.to_json()).unwrap();
|
||||
assert_eq!(v["pid"], 7);
|
||||
assert_eq!(v["threads"][0]["name"], "abc");
|
||||
assert_eq!(v["heap"]["tags"]["untagged"], 300);
|
||||
assert_eq!(v["gauges"]["video.frames"], 200);
|
||||
assert_eq!(v["unaccounted"], 400);
|
||||
// Without the counting allocator there's no honest unaccounted figure.
|
||||
let bare = Snapshot { heap: None, ..s };
|
||||
assert_eq!(bare.unaccounted(), None);
|
||||
let v: serde_json::Value = serde_json::from_str(&bare.to_json()).unwrap();
|
||||
assert!(v.get("unaccounted").is_none() && v.get("heap").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warnings_name_where_the_memory_is() {
|
||||
let mut w = Watcher::new(Config { report: None, ..Config::release("t") });
|
||||
let s = Snapshot {
|
||||
footprint: 2 << 30,
|
||||
heap: Some(alloc::Heap { live: 100 << 20, ..Default::default() }),
|
||||
gauges: vec![("video.frames", 300 << 20)],
|
||||
..at(2 << 30, 0.0)
|
||||
};
|
||||
let events = w.observe(now(), &s);
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].kind, Kind::Footprint);
|
||||
assert!(events[0].line.contains("heap 100 MB live") && events[0].line.ends_with("; video.frames 300 MB; unaccounted 1.6 GB"), "{}", events[0].line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warns_on_size_growth_and_cpu_once_per_window() {
|
||||
let mut w = Watcher::new(Config { report: None, ..Config::release("t") });
|
||||
let t0 = now();
|
||||
let mut events = Vec::new();
|
||||
for i in 0..=12u64 {
|
||||
// 100 MB every 10 s, and a full core.
|
||||
events.extend(w.observe(t0 + Duration::from_secs(i * 10), &at((50 + 100 * i) << 20, i as f64 * 10.0)));
|
||||
}
|
||||
let joined = lines(&events);
|
||||
assert!(joined.contains("footprint grew"), "{joined}");
|
||||
assert!(joined.contains("% CPU over 60s: exited threads 100%"), "{joined}");
|
||||
assert!(joined.contains("warning: footprint 1.0 GB") || joined.contains("warning: footprint 1.1 GB"), "{joined}");
|
||||
assert_eq!(events.iter().filter(|e| e.kind == Kind::Growth).count(), 2, "{joined}");
|
||||
assert!(events.iter().all(Event::is_warning));
|
||||
// Flat and idle: nothing.
|
||||
let mut w = Watcher::new(Config { report: None, ..Config::release("t") });
|
||||
for i in 0..=12u64 {
|
||||
assert!(w.observe(t0 + Duration::from_secs(i * 10), &at(50 << 20, 1.0)).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gate_passes_once_per_window() {
|
||||
let (mut g, t0, window) = (Gate::default(), now(), Duration::from_secs(60));
|
||||
assert!(g.pass(t0, window), "the first goes out at once");
|
||||
assert!(!g.pass(t0 + Duration::from_secs(59), window));
|
||||
assert!(g.pass(t0 + Duration::from_secs(60), window));
|
||||
assert!(!g.pass(t0 + Duration::from_secs(61), window), "a window from the last one that went out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_once_per_period() {
|
||||
let mut w = Watcher::new(Config { report: Some(Duration::from_secs(30)), ..Config::release("t") });
|
||||
let t0 = now();
|
||||
let reported: Vec<u64> = (0..=9u64)
|
||||
.filter(|i| w.observe(t0 + Duration::from_secs(i * 10), &at(50 << 20, 1.0)).iter().any(|e| e.kind == Kind::Report))
|
||||
.collect();
|
||||
assert_eq!(reported, [0, 3, 6, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_samples_still_fill_the_window() {
|
||||
// Sleeps that run 10 ms long leave no sample exactly 60 s back.
|
||||
let mut w = Watcher::new(Config { report: None, ..Config::release("t") });
|
||||
let t0 = now();
|
||||
let mut events = Vec::new();
|
||||
for i in 0..=12u32 {
|
||||
let t = Duration::from_millis(10_010) * i;
|
||||
events.extend(w.observe(t0 + t, &at(50 << 20, t.as_secs_f64())));
|
||||
}
|
||||
assert_eq!(events.iter().filter(|e| e.kind == Kind::Cpu).count(), 2, "{}", lines(&events));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exited_thread_counts_only_its_last_stretch() {
|
||||
let thread = |id, name: &str, cpu_s| Thread { id, name: name.into(), cpu_s };
|
||||
let old = Snapshot { cpu_s: 101.0, threads: vec![thread(1, "main", 1.0), thread(2, "worker", 100.0)], ..Default::default() };
|
||||
// The worker ran 6 more seconds and exited; main ran 54.
|
||||
let new = Snapshot { cpu_s: 161.0, threads: vec![thread(1, "main", 55.0)], ..Default::default() };
|
||||
assert_eq!(busiest(&old, &new, 60.0), "main 90%, exited threads 10%");
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! A binary without `procwatch::alloc::Counting` installed.
|
||||
|
||||
#[test]
|
||||
fn counters_are_unknown_without_the_allocator() {
|
||||
drop(std::hint::black_box(vec![0u8; 64]));
|
||||
assert_eq!(procwatch::alloc::thread_allocated_bytes(), None);
|
||||
assert_eq!(procwatch::alloc::heap(), None);
|
||||
}
|
||||
Reference in new issue
Block a user