Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

5.6 KB
Raw Blame
//! Developer aid (`--features memprof`): an allocator wrapper that counts
//! live bytes by size class and remembers who made each large allocation,
//! so "where does the idle memory go" has an answer. `dump()` writes the
//! picture to the log. Not compiled into normal builds.

use std::alloc::{GlobalAlloc, Layout};
use std::cell::Cell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicIsize, Ordering};
use std::sync::Mutex;

/// Allocations at least this big are tracked individually.
const BIG: usize = 128 * 1024;
const CLASSES: [(&str, usize); 5] = [("<1K", 1 << 10), ("1K-16K", 16 << 10), ("16K-128K", BIG), ("128K-4M", 4 << 20), (">=4M", usize::MAX)];

pub struct Prof;

static BYTES: [AtomicIsize; 5] = [const { AtomicIsize::new(0) }; 5];
static COUNT: [AtomicIsize; 5] = [const { AtomicIsize::new(0) }; 5];
static LIVE: Mutex<Option<HashMap<usize, (usize, String)>>> = Mutex::new(None);

thread_local! {
    /// Set while the profiler itself allocates (backtraces, its map).
    static BUSY: Cell<bool> = const { Cell::new(false) };
}

fn class(size: usize) -> usize {
    CLASSES.iter().position(|(_, max)| size < *max).unwrap_or(4)
}

fn track(ptr: *mut u8, size: usize) {
    let c = class(size);
    BYTES[c].fetch_add(size as isize, Ordering::Relaxed);
    COUNT[c].fetch_add(1, Ordering::Relaxed);
    if size < BIG || ptr.is_null() {
        return;
    }
    let _ = BUSY.try_with(|busy| {
        if busy.replace(true) {
            return;
        }
        // (Release builds have no symbols: the thread's name stands in for "who".)
        let thread = std::thread::current().name().unwrap_or("?").to_string();
        let trace = format!("{}
0: thread {thread}", std::backtrace::Backtrace::force_capture());
        if let Ok(mut live) = LIVE.lock() {
            live.get_or_insert_with(HashMap::new).insert(ptr as usize, (size, trace));
        }
        busy.set(false);
    });
}

fn untrack(ptr: *mut u8, size: usize) {
    let c = class(size);
    BYTES[c].fetch_sub(size as isize, Ordering::Relaxed);
    COUNT[c].fetch_sub(1, Ordering::Relaxed);
    if size < BIG {
        return;
    }
    let _ = BUSY.try_with(|busy| {
        if busy.replace(true) {
            return;
        }
        if let Ok(mut live) = LIVE.lock() {
            if let Some(map) = live.as_mut() {
                map.remove(&(ptr as usize));
            }
        }
        busy.set(false);
    });
}

unsafe impl GlobalAlloc for Prof {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let p = mimalloc::MiMalloc.alloc(layout);
        track(p, layout.size());
        p
    }

    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        let p = mimalloc::MiMalloc.alloc_zeroed(layout);
        track(p, layout.size());
        p
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        untrack(ptr, layout.size());
        mimalloc::MiMalloc.dealloc(ptr, layout)
    }

    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        untrack(ptr, layout.size());
        let p = mimalloc::MiMalloc.realloc(ptr, layout, new_size);
        track(p, new_size);
        p
    }
}

/// The frames of a backtrace that say something: RustCord's and its libraries',
/// without the allocator's and the runtime's own.
fn short(trace: &str) -> String {
    let skip = ["memprof", "alloc::", "core::", "std::", "__rust", "backtrace", "hashbrown", "BaseThreadInitThunk", "RtlUserThreadStart", "mimalloc"];
    let mut out = Vec::new();
    for line in trace.lines() {
        let line = line.trim();
        // Frame lines look like "12: crate::module::function"; skip "at file:line".
        let Some((n, name)) = line.split_once(": ") else { continue };
        if !n.chars().all(|c| c.is_ascii_digit()) || skip.iter().any(|s| name.contains(s)) {
            continue;
        }
        out.push(name.chars().take(90).collect::<String>());
        if out.len() >= 7 {
            break;
        }
    }
    out.join(" < ")
}

/// Write what is allocated right now to the log.
pub fn dump() {
    let mb = |b: isize| b as f64 / (1024.0 * 1024.0);
    let classes: Vec<String> = CLASSES.iter().enumerate().map(|(i, (name, _))| format!("{name}: {:.1} MB in {}", mb(BYTES[i].load(Ordering::Relaxed)), COUNT[i].load(Ordering::Relaxed))).collect();
    let total: isize = BYTES.iter().map(|b| b.load(Ordering::Relaxed)).sum();
    // Group the large ones by where they were made.
    let mut by_site: HashMap<String, (usize, usize)> = HashMap::new();
    BUSY.with(|b| b.set(true));
    if let Ok(live) = LIVE.lock() {
        for (size, trace) in live.iter().flat_map(|m| m.values()) {
            let e = by_site.entry(short(trace)).or_default();
            e.0 += size;
            e.1 += 1;
        }
    }
    let mut sites: Vec<(String, (usize, usize))> = by_site.into_iter().collect();
    sites.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));
    let mut lines: Vec<String> = sites.iter().take(28).map(|(site, (bytes, n))| format!("  {:.1} MB in {n}: {site}", mb(*bytes as isize))).collect();
    // The biggest single allocations, by size and thread.
    if let Ok(live) = LIVE.lock() {
        let mut big: Vec<(usize, String)> = live
            .iter()
            .flat_map(|m| m.values())
            .map(|(size, trace)| (*size, trace.rsplit("thread ").next().unwrap_or("?").to_string()))
            .collect();
        big.sort_by(|a, b| b.0.cmp(&a.0));
        lines.push(format!("  biggest: {}", big.iter().take(24).map(|(s, t)| format!("{:.2} MB ({t})", *s as f64 / 1048576.0)).collect::<Vec<_>>().join(", ")));
    }
    BUSY.with(|b| b.set(false));
    log::info!("memprof: live {:.1} MB; {}\n{}", mb(total), classes.join("; "), lines.join("\n"));
}