Skip to content

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

32.1 KB
Raw Blame
//! Local diagnostics: a log file, panic reports and (on Windows) native crash
//! reports. Nothing leaves the machine. Never log tokens or message content.

use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};

static LOG_PATH: OnceLock<PathBuf> = OnceLock::new();
static STARTED: OnceLock<std::time::Instant> = OnceLock::new();

/// Milliseconds since RustCord started (for the start-up timings in the log).
pub fn ms_since_start() -> u128 {
    STARTED.get().map_or(0, |t| t.elapsed().as_millis())
}

pub fn log_path() -> Option<&'static PathBuf> {
    LOG_PATH.get()
}

/// Writes every log line to stderr and to the log file.
struct Tee {
    file: Option<Mutex<File>>,
}

impl Write for Tee {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let _ = std::io::stderr().write_all(buf);
        if let Some(f) = &self.file {
            if let Ok(mut f) = f.lock() {
                let _ = f.write_all(buf);
            }
        }
        Ok(buf.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        if let Some(f) = &self.file {
            if let Ok(mut f) = f.lock() {
                let _ = f.flush();
            }
        }
        Ok(())
    }
}

/// Developer hooks (`RUSTCORD_DEV_VIEW`, `RUSTCORD_DEV_INPUT`, `RUSTCORD_DUMP_API`…)
/// work in debug builds, or a release built with `--features dev-hooks`. In a
/// normal release build they are ignored: some of them can act as you (replay
/// clicks and typing from a file) or write account data to disk.
const DEV_HOOKS: bool = cfg!(any(debug_assertions, feature = "dev-hooks"));

/// A developer hook's environment variable (see [`DEV_HOOKS`]).
pub fn dev_var(name: &str) -> Result<String, std::env::VarError> {
    if DEV_HOOKS {
        std::env::var(name)
    } else {
        Err(std::env::VarError::NotPresent)
    }
}

/// [`dev_var`], as an OS string (for "is it set at all").
pub fn dev_var_os(name: &str) -> Option<std::ffi::OsString> {
    if DEV_HOOKS {
        std::env::var_os(name)
    } else {
        None
    }
}

/// Debug logging on or off (off: info and above, the default). `RUST_LOG`, when set,
/// decides instead.
pub fn set_debug(on: bool) {
    if std::env::var_os("RUST_LOG").is_none() {
        log::set_max_level(if on { log::LevelFilter::Debug } else { log::LevelFilter::Info });
    }
}

/// Set up logging (stderr + `<config>/rustcord.log`, fresh each run), the panic
/// hook and the Windows crash handler.
pub fn init() {
    STARTED.get_or_init(std::time::Instant::now);
    let dir = directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.config_dir().to_path_buf());
    // A side-by-side test instance (`RUSTCORD_KEEP_OTHERS`) keeps its own file, so it never
    // wipes or blocks the log of the RustCord being used. If the usual file cannot be
    // replaced (left behind by another account or a sandbox), a second name is used.
    let names: &[&str] =
        if std::env::var_os("RUSTCORD_KEEP_OTHERS").is_some() { &["rustcord-test.log"] } else { &["rustcord.log", "rustcord-2.log"] };
    let file = dir.and_then(|d| {
        let _ = std::fs::create_dir_all(&d);
        names.iter().find_map(|name| {
            let path = d.join(name);
            // The last run's log is kept once (`rustcord-previous.log`): a call that
            // misbehaved yesterday can still be read after a restart.
            if *name == "rustcord.log" && std::fs::metadata(&path).is_ok_and(|m| m.len() > 0) {
                let _ = std::fs::rename(&path, d.join("rustcord-previous.log"));
            }
            let f = File::create(&path).ok()?;
            let _ = LOG_PATH.set(path);
            Some(f)
        })
    });
    // (RustCord's own crates are let through at debug, for Settings → Voice & Video →
    // Debug logging; `set_debug` holds everything at info until that is switched on.)
    let mut builder = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info,rustcord=debug,discord=debug,voice=debug,rencord=debug,wgpu=warn,naga=warn"));
    // The network libraries never log below info, whatever RUST_LOG says: at
    // trace they write whole frames and requests, and the gateway's IDENTIFY
    // and RESUME carry the login token.
    for module in ["tungstenite", "tokio_tungstenite", "hyper", "hyper_util", "reqwest", "h2", "rustls", "native_tls"] {
        builder.filter_module(module, log::LevelFilter::Info);
    }
    builder
        .target(env_logger::Target::Pipe(Box::new(Tee { file: file.map(Mutex::new) })))
        .format_timestamp_millis()
        .init();
    log::info!("RustCord {} starting (pid {})", env!("CARGO_PKG_VERSION"), std::process::id());

    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let thread = std::thread::current().name().unwrap_or("unnamed").to_string();
        log::error!("PANIC on thread '{thread}': {info}\n{}", std::backtrace::Backtrace::force_capture());
        default_hook(info);
    }));

    #[cfg(windows)]
    windows_crash::install();
}

#[cfg(windows)]
mod windows_crash {
    use std::io::Write;
    use windows_sys::Win32::Foundation::HMODULE;
    /// Let Windows carry on with its normal crash handling after RustCord has logged.
    const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
    use windows_sys::Win32::System::Diagnostics::Debug::{SetUnhandledExceptionFilter, EXCEPTION_POINTERS};
    use windows_sys::Win32::System::LibraryLoader::{
        GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
        GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
    };

    pub fn install() {
        unsafe {
            SetUnhandledExceptionFilter(Some(filter));
        }
    }

    /// Best effort: record the exception code and which DLL it happened in.
    unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 {
        let (code, address) = if info.is_null() || (*info).ExceptionRecord.is_null() {
            (0u32, std::ptr::null_mut())
        } else {
            let rec = &*(*info).ExceptionRecord;
            (rec.ExceptionCode as u32, rec.ExceptionAddress)
        };
        let mut module: HMODULE = std::ptr::null_mut();
        let mut name = [0u16; 260];
        let mut module_name = String::from("unknown");
        if GetModuleHandleExW(
            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
            address as *const u16,
            &mut module,
        ) != 0
        {
            let len = GetModuleFileNameW(module, name.as_mut_ptr(), name.len() as u32) as usize;
            module_name = String::from_utf16_lossy(&name[..len]);
        }
        let line = format!(
            "NATIVE CRASH: exception 0x{code:08X} at {address:?} in {module_name} (module base {module:?})\n"
        );
        if let Some(path) = super::log_path() {
            if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(path) {
                let _ = f.write_all(line.as_bytes());
            }
        }
        let _ = std::io::stderr().write_all(line.as_bytes());
        EXCEPTION_CONTINUE_SEARCH
    }
}

/// Close other running RustCord windows (asked politely first, then forced).
/// Skipped when `RUSTCORD_KEEP_OTHERS` is set (used for side-by-side testing).
pub fn close_other_instances() {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        if std::env::var_os("RUSTCORD_KEEP_OTHERS").is_some() {
            return;
        }
        // Through their tray icon first: the one polite close that makes a
        // RustCord quit rather than go to the tray (see `tray::ask_others_to_quit`).
        let quitting = crate::tray::ask_others_to_quit();
        if quitting > 0 {
            log::info!("asked {quitting} older RustCord window(s) to close");
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
            while crate::tray::others_running() && std::time::Instant::now() < deadline {
                std::thread::sleep(std::time::Duration::from_millis(100));
            }
        }
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        let me = std::process::id().to_string();
        let run = |force: bool| {
            // Exactly this program: not its setup, uninstaller or anything
            // else whose name starts the same.
            let mut args = vec!["/FI", "IMAGENAME eq rustcord.exe"];
            let pid_filter = format!("PID ne {me}");
            args.push("/FI");
            args.push(&pid_filter);
            if force {
                args.push("/F");
            }
            // taskkill exits 0 even when nothing matched ("INFO: No tasks
            // running…"), so only a SUCCESS line means a window was asked to
            // close; otherwise there's nothing to wait for.
            // Windows' own taskkill, by its full path (not whatever PATH finds).
            let system = std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into());
            std::process::Command::new(std::path::Path::new(&system).join(r"System32\taskkill.exe"))
                .args(&args)
                .creation_flags(CREATE_NO_WINDOW)
                .stderr(std::process::Stdio::null())
                .output()
                .map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("SUCCESS"))
                .unwrap_or(false)
        };
        // Then taskkill for any left (versions before 0.4.41): a polite close
        // (WM_CLOSE) so settings get saved, then forced.
        if run(false) {
            log::info!("asked older RustCord windows to close");
            std::thread::sleep(std::time::Duration::from_millis(1500));
            run(true);
        }
    }
}

/// The allocator's own view of memory, for the perf log: what is committed
/// now and at its peak.
pub fn heap_summary() -> String {
    let (mut rss, mut peak_rss, mut commit, mut peak_commit) = (0usize, 0usize, 0usize, 0usize);
    let (mut a, mut b, mut c, mut d) = (0usize, 0usize, 0usize, 0usize);
    unsafe { libmimalloc_sys::mi_process_info(&mut a, &mut b, &mut c, &mut rss, &mut peak_rss, &mut commit, &mut peak_commit, &mut d) };
    let mb = |v: usize| v as f64 / (1024.0 * 1024.0);
    format!("process: rss {:.0} MB (peak {:.0}), commit {:.0} MB (peak {:.0})", mb(rss), mb(peak_rss), mb(commit), mb(peak_commit))
}

/// Hand memory the allocator is holding but not using back to the system.
/// Cheap when there is nothing to return; called while the app is idle.
pub fn release_unused_memory() {
    unsafe { libmimalloc_sys::mi_collect(true) };
    // On Linux the C libraries (GTK, the graphics driver, fontconfig) allocate
    // with glibc's malloc, which keeps what they free for reuse rather than
    // returning it; this hands those pages back too.
    // SAFETY: malloc_trim only releases free memory; any thread may call it.
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    unsafe {
        libc::malloc_trim(0);
    }
}

/// How much of RustCord is in RAM right now (its working set), in MB.
pub fn working_set_mb() -> u64 {
    #[cfg(windows)]
    {
        let mut c = win_mem::Counters { cb: std::mem::size_of::<win_mem::Counters>() as u32, ..Default::default() };
        // SAFETY: `c` is a correctly sized PROCESS_MEMORY_COUNTERS for this call.
        if unsafe { win_mem::K32GetProcessMemoryInfo(win_mem::GetCurrentProcess(), &mut c, c.cb) } != 0 {
            return (c.working_set / (1024 * 1024)) as u64;
        }
    }
    #[cfg(target_os = "linux")]
    if let Some(p) = linux_proc::read(std::process::id()) {
        return p.working_set / (1024 * 1024);
    }
    #[cfg(target_os = "macos")]
    if let Some(p) = mac_proc::read_self() {
        return p.working_set / (1024 * 1024);
    }
    0
}

/// Let Windows take back the RAM pages RustCord isn't using. What is in
/// use comes straight back as it is touched (the pages stay cached), so
/// only what nothing touches stays out: font files, spell-check
/// dictionaries and program code that other software read in (a virus
/// scanner's sweep of the process pages all of it in at start-up, about
/// 150 MB that RustCord itself never looks at), and memory from start-up.
pub fn trim_working_set() {
    #[cfg(windows)]
    // SAFETY: (-1, -1) is the documented "empty the working set" request
    // for the calling process; it changes no limits.
    unsafe {
        win_mem::SetProcessWorkingSetSize(win_mem::GetCurrentProcess(), usize::MAX, usize::MAX);
    }
}

/// Hand RAM back to Windows whenever RustCord sits idle, from a thread of its
/// own: a minimised or tray-hidden window may draw no frames at all, so the
/// UI thread can't be the one to notice. The UI thread only reports each
/// frame (`note`) whether there was input, whether RustCord is the window in
/// front, whether something short-lived is busy (playing sound, an open
/// picker) and whether a call or stream is on.
///
/// A call or stream keeps touching its own memory, but leaves behind what
/// joining and decoding set up once (watching a stream took a 200 MB working
/// set down to 85 MB). Those pages are released too, on a slower clock: a
/// minute in, then only after a real regrowth. What the call still uses comes
/// straight back from Windows' standby list (a soft fault, microseconds), so
/// audio and video carry on undisturbed.
pub mod idle {
    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
    use std::time::Duration;

    /// Idle this long in the background (another window in front,
    /// minimised, in the tray) / in front but untouched.
    const BACKGROUND_SECS: u64 = 60;
    const FOREGROUND_SECS: u64 = 300;
    /// While still idle, again only after it has grown this much since.
    const REGROW_MB: u64 = 64;
    const REGROW_SECS: u64 = 300;
    /// In a call: the first release this long after it started (joining and
    /// the first decoded pictures have settled by then), and again after a
    /// regrowth once this long has passed. A watched 1080p stream keeps about
    /// 100 MB in use; what comes back beyond that is mostly pages something
    /// else read in (a virus scanner sweeps the whole process, ~200 MB at
    /// once), which nothing in RustCord touches again.
    const CALL_SETTLE_SECS: u64 = 60;
    const CALL_REGROW_SECS: u64 = 60;

    static LAST_INPUT: AtomicU64 = AtomicU64::new(0);
    static FOREGROUND: AtomicBool = AtomicBool::new(true);
    static BUSY: AtomicBool = AtomicBool::new(false);
    static IN_CALL: AtomicBool = AtomicBool::new(false);

    fn now() -> u64 {
        (super::ms_since_start() / 1000) as u64
    }

    /// From the UI thread, every frame.
    pub fn note(input: bool, foreground: bool, busy: bool, in_call: bool) {
        if input {
            LAST_INPUT.store(now(), Relaxed);
        }
        FOREGROUND.store(foreground, Relaxed);
        BUSY.store(busy, Relaxed);
        IN_CALL.store(in_call, Relaxed);
    }

    /// Releases during one call or stream: a minute in, then again whenever it
    /// has regrown well past where it settled after the last release.
    #[derive(Default)]
    struct CallReleases {
        /// When the call started, the last release, and the size soon after
        /// it (seconds since start; 0: not yet).
        started: u64,
        released: u64,
        settled: u64,
    }

    impl CallReleases {
        /// Whether to release now, with `size` MB in RAM.
        fn due(&mut self, now: u64, size: u64) -> bool {
            if self.started == 0 {
                self.started = now;
            }
            if now < self.started + CALL_SETTLE_SECS {
                return false;
            }
            if self.released == 0 {
                return true;
            }
            if self.settled == 0 {
                self.settled = size;
            }
            size >= self.settled + REGROW_MB && now >= self.released + CALL_REGROW_SECS
        }

        fn released(&mut self, now: u64) {
            (self.released, self.settled) = (now, 0);
        }
    }

    #[cfg(test)]
    #[test]
    fn call_releases_settle_then_wait_for_regrowth() {
        let mut call = CallReleases::default();
        assert!(!call.due(100, 200), "not while joining");
        assert!(!call.due(150, 200));
        assert!(call.due(160, 200), "a minute in");
        call.released(160);
        assert!(!call.due(170, 90), "settles at 90 MB");
        assert!(!call.due(300, 140), "50 MB regrowth is not enough");
        assert!(!call.due(210, 160), "nor before a minute has passed");
        assert!(call.due(220, 160));
    }

    /// Start watching (once, at start-up).
    pub fn start() {
        let _ = std::thread::Builder::new().name("idle-memory".into()).spawn(|| {
            // (Seconds since start of the last release, and its size soon after.)
            let (mut released_at, mut settled) = (0u64, 0u64);
            let mut call: Option<CallReleases> = None;
            loop {
                std::thread::sleep(Duration::from_secs(10));
                let now = now();
                if !IN_CALL.load(Relaxed) {
                    call = None;
                } else if !BUSY.load(Relaxed) {
                    let size = super::working_set_mb();
                    let call = call.get_or_insert_default();
                    if call.due(now, size) {
                        super::release_unused_memory();
                        super::trim_working_set();
                        log::info!("memory: in a call with {size} MB in RAM, unused pages handed back to the system");
                        call.released(now);
                    }
                    continue;
                }
                let last_input = LAST_INPUT.load(Relaxed);
                if released_at > 0 && last_input > released_at {
                    // Used again since: the next idle stretch gets its own release.
                    released_at = 0;
                }
                let wait = if FOREGROUND.load(Relaxed) { FOREGROUND_SECS } else { BACKGROUND_SECS };
                if now < 30 || BUSY.load(Relaxed) || IN_CALL.load(Relaxed) || now < last_input + wait {
                    continue;
                }
                let size = super::working_set_mb();
                if released_at > 0 {
                    if settled == 0 {
                        settled = size;
                    }
                    if size < settled + REGROW_MB || now < released_at + REGROW_SECS {
                        continue;
                    }
                }
                super::release_unused_memory();
                super::trim_working_set();
                log::info!("memory: idle {} s with {size} MB in RAM, unused pages handed back to the system", now - last_input);
                (released_at, settled) = (now, 0);
            }
        });
    }
}

/// One process in the Process Viewer: RustCord itself or a helper it started.
#[derive(Clone, Debug, Default)]
pub struct ProcessInfo {
    pub pid: u32,
    pub parent: u32,
    pub name: String,
    pub threads: u32,
    /// In RAM right now (working set) and its highest so far, in bytes.
    pub working_set: u64,
    pub peak_working_set: u64,
    /// The part of that only this process uses: Task Manager's "Memory".
    /// None when Windows wouldn't say.
    pub private_working_set: Option<u64>,
    /// Memory reserved for it, in RAM or not (commit).
    pub committed: u64,
    pub handles: u32,
    /// Processor time used since it started, in seconds.
    pub cpu_seconds: f64,
}

/// RustCord's process and every process under it (the embedded browser
/// behind the login page and embed players runs as helpers), RustCord first.
pub fn process_tree() -> Vec<ProcessInfo> {
    #[cfg(windows)]
    {
        win_mem::process_tree()
    }
    #[cfg(target_os = "linux")]
    {
        linux_proc::process_tree()
    }
    #[cfg(target_os = "macos")]
    {
        mac_proc::read_self().into_iter().collect()
    }
    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        Vec::new()
    }
}

/// The Process Viewer's numbers on macOS. RustCord alone: the WebKit
/// processes behind its web pages are started by the system, not by RustCord.
#[cfg(target_os = "macos")]
mod mac_proc {
    use super::ProcessInfo;

    pub fn read_self() -> Option<ProcessInfo> {
        let pid = std::process::id();
        // SAFETY (the three zeroed structs): plain C structs of integers, for
        // which all zeroes is a valid value.
        let mut usage: libc::rusage_info_v4 = unsafe { std::mem::zeroed() };
        // SAFETY: `usage` is the rusage_info_v4 that RUSAGE_INFO_V4 fills.
        if unsafe { libc::proc_pid_rusage(pid as i32, libc::RUSAGE_INFO_V4, (&mut usage as *mut libc::rusage_info_v4).cast()) } != 0 {
            return None;
        }
        let mut task: libc::proc_taskinfo = unsafe { std::mem::zeroed() };
        let size = std::mem::size_of::<libc::proc_taskinfo>() as i32;
        // SAFETY: `task` is a proc_taskinfo of the size passed.
        let filled = unsafe { libc::proc_pidinfo(pid as i32, libc::PROC_PIDTASKINFO, 0, (&mut task as *mut libc::proc_taskinfo).cast(), size) };
        let mut own: libc::rusage = unsafe { std::mem::zeroed() };
        // SAFETY: `own` is the rusage getrusage fills.
        unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut own) };
        let seconds = |t: libc::timeval| t.tv_sec as f64 + t.tv_usec as f64 / 1e6;
        Some(ProcessInfo {
            pid,
            parent: std::os::unix::process::parent_id(),
            name: std::env::current_exe().ok().and_then(|p| Some(p.file_name()?.to_str()?.to_owned())).unwrap_or_else(|| "rustcord".into()),
            threads: if filled == size { task.pti_threadnum.max(0) as u32 } else { 0 },
            working_set: usage.ri_resident_size,
            // (Bytes on macOS, kilobytes on Linux.)
            peak_working_set: own.ru_maxrss.max(0) as u64,
            // The physical footprint: Activity Monitor's "Memory".
            private_working_set: Some(usage.ri_phys_footprint),
            committed: usage.ri_phys_footprint,
            handles: std::fs::read_dir("/dev/fd").map(|d| d.count() as u32).unwrap_or(0),
            cpu_seconds: seconds(own.ru_utime) + seconds(own.ru_stime),
        })
    }
}

#[cfg(all(test, any(windows, target_os = "linux", target_os = "macos")))]
mod process_tests {
    /// The Process Viewer finds RustCord's own process, with real figures.
    #[test]
    fn process_tree_starts_with_this_process() {
        let tree = super::process_tree();
        let me = tree.first().expect("this process");
        assert_eq!(me.pid, std::process::id());
        assert!(me.working_set > 0 && me.threads > 0, "{me:?}");
    }
}

/// The Process Viewer's numbers on Linux, from /proc.
#[cfg(target_os = "linux")]
mod linux_proc {
    use super::ProcessInfo;

    /// The kernel's clock ticks per second for /proc's processor times
    /// (USER_HZ, 100 on every Linux in use).
    const TICKS: f64 = 100.0;

    /// One process; None once it has gone.
    pub fn read(pid: u32) -> Option<ProcessInfo> {
        let dir = std::path::PathBuf::from(format!("/proc/{pid}"));
        let stat = std::fs::read_to_string(dir.join("stat")).ok()?;
        // The name sits in parentheses and may itself contain them: the
        // fields after it start past the last ')'.
        let fields: Vec<&str> = stat.get(stat.rfind(')')? + 2..)?.split_whitespace().collect();
        let field = |i: usize| fields.get(i).and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
        let status = std::fs::read_to_string(dir.join("status")).unwrap_or_default();
        let kb = |key: &str| {
            status.lines().find_map(|l| l.strip_prefix(key)?.trim().strip_suffix("kB")?.trim().parse::<u64>().ok()).map(|v| v * 1024)
        };
        Some(ProcessInfo {
            pid,
            // (state, ppid, …: fields 3 and 4 of `stat`, counted from 1.)
            parent: field(1) as u32,
            name: std::fs::read_to_string(dir.join("comm")).map(|s| s.trim().to_string()).unwrap_or_default(),
            threads: field(17) as u32,
            working_set: kb("VmRSS:").unwrap_or(0),
            peak_working_set: kb("VmHWM:").unwrap_or(0),
            private_working_set: kb("RssAnon:"),
            committed: kb("VmData:").unwrap_or(0),
            handles: std::fs::read_dir(dir.join("fd")).map(|d| d.count() as u32).unwrap_or(0),
            cpu_seconds: (field(11) + field(12)) as f64 / TICKS,
        })
    }

    /// RustCord and everything it started (the WebKit helpers behind its web
    /// pages), RustCord first.
    pub fn process_tree() -> Vec<ProcessInfo> {
        let me = std::process::id();
        let Some(first) = read(me) else { return Vec::new() };
        let all: Vec<ProcessInfo> = std::fs::read_dir("/proc")
            .map(|d| d.flatten().filter_map(|e| e.file_name().to_str()?.parse::<u32>().ok()).filter(|&p| p != me).filter_map(read).collect())
            .unwrap_or_default();
        let mut tree = vec![first];
        let mut i = 0;
        while i < tree.len() {
            let parent = tree[i].pid;
            tree.extend(all.iter().filter(|p| p.parent == parent).cloned());
            i += 1;
        }
        tree
    }
}

#[cfg(windows)]
mod win_mem {
    use super::ProcessInfo;

    /// PROCESSENTRY32W.
    #[repr(C)]
    struct Entry {
        size: u32,
        usage: u32,
        pid: u32,
        default_heap: usize,
        module: u32,
        threads: u32,
        parent: u32,
        priority: i32,
        flags: u32,
        exe: [u16; 260],
    }

    /// PROCESS_MEMORY_COUNTERS_EX.
    #[repr(C)]
    #[derive(Default)]
    struct CountersEx {
        base: Counters,
        private_usage: usize,
    }

    #[link(name = "kernel32")]
    extern "system" {
        fn GetCurrentProcessId() -> u32;
        fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> isize;
        fn Process32FirstW(snapshot: isize, entry: *mut Entry) -> i32;
        fn Process32NextW(snapshot: isize, entry: *mut Entry) -> i32;
        fn OpenProcess(access: u32, inherit: i32, pid: u32) -> isize;
        fn CloseHandle(handle: isize) -> i32;
        fn GetProcessTimes(process: isize, created: *mut u64, exited: *mut u64, kernel: *mut u64, user: *mut u64) -> i32;
        fn GetProcessHandleCount(process: isize, count: *mut u32) -> i32;
        fn K32QueryWorkingSet(process: isize, info: *mut usize, cb: u32) -> i32;
    }

    /// Bytes of the working set no other process shares (what Task Manager
    /// lists as a process's memory): the pages not flagged Shared.
    fn private_working_set(process: isize, working_set: usize) -> Option<u64> {
        // One word per page, after a count; room to spare as it can grow.
        let mut buf = vec![0usize; working_set / 4096 + 4096];
        // SAFETY: the buffer is `buf.len()` words and Windows is told so.
        if unsafe { K32QueryWorkingSet(process, buf.as_mut_ptr(), (buf.len() * std::mem::size_of::<usize>()) as u32) } == 0 {
            return None;
        }
        let n = buf[0].min(buf.len() - 1);
        Some(buf[1..=n].iter().filter(|e| **e & 0x100 == 0).count() as u64 * 4096)
    }

    fn fill(info: &mut ProcessInfo, process: isize) {
        let mut c = CountersEx::default();
        c.base.cb = std::mem::size_of::<CountersEx>() as u32;
        let (mut created, mut exited, mut kernel, mut user) = (0u64, 0u64, 0u64, 0u64);
        // SAFETY: every out-pointer is a live local of the type the call fills.
        unsafe {
            if K32GetProcessMemoryInfo(process, &mut c as *mut CountersEx as *mut Counters, c.base.cb) != 0 {
                info.working_set = c.base.working_set as u64;
                info.peak_working_set = c.base.peak_working_set as u64;
                info.committed = c.private_usage as u64;
                info.private_working_set = private_working_set(process, c.base.working_set);
            }
            if GetProcessTimes(process, &mut created, &mut exited, &mut kernel, &mut user) != 0 {
                // (FILETIMEs: 100 ns units.)
                info.cpu_seconds = (kernel + user) as f64 / 1e7;
            }
            GetProcessHandleCount(process, &mut info.handles);
        }
    }

    pub fn process_tree() -> Vec<ProcessInfo> {
        let mut all: Vec<ProcessInfo> = Vec::new();
        // SAFETY: a process snapshot (TH32CS_SNAPPROCESS) walked with a
        // correctly sized entry, then closed.
        unsafe {
            let snap = CreateToolhelp32Snapshot(2, 0);
            if snap == -1 {
                return all;
            }
            let mut e: Entry = std::mem::zeroed();
            e.size = std::mem::size_of::<Entry>() as u32;
            let mut more = Process32FirstW(snap, &mut e);
            while more != 0 {
                let len = e.exe.iter().position(|c| *c == 0).unwrap_or(e.exe.len());
                all.push(ProcessInfo { pid: e.pid, parent: e.parent, name: String::from_utf16_lossy(&e.exe[..len]), threads: e.threads, ..Default::default() });
                more = Process32NextW(snap, &mut e);
            }
            CloseHandle(snap);
        }
        // RustCord's process, then whatever descends from it.
        let me = unsafe { GetCurrentProcessId() };
        let mut tree: Vec<ProcessInfo> = all.iter().filter(|p| p.pid == me).cloned().collect();
        let mut i = 0;
        while i < tree.len() {
            let parent = tree[i].pid;
            let known: Vec<u32> = tree.iter().map(|p| p.pid).collect();
            tree.extend(all.iter().filter(|p| p.parent == parent && p.pid != 0 && !known.contains(&p.pid)).cloned());
            i += 1;
        }
        for p in &mut tree {
            // SAFETY: the handle is checked, used for queries only, and closed.
            unsafe {
                if p.pid == me {
                    fill(p, GetCurrentProcess());
                    continue;
                }
                // PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, else the limited query right.
                let mut h = OpenProcess(0x0400 | 0x0010, 0, p.pid);
                if h == 0 {
                    h = OpenProcess(0x1000, 0, p.pid);
                }
                if h != 0 {
                    fill(p, h);
                    CloseHandle(h);
                }
            }
        }
        tree
    }

    /// PROCESS_MEMORY_COUNTERS.
    #[repr(C)]
    #[derive(Default)]
    pub struct Counters {
        pub cb: u32,
        pub page_fault_count: u32,
        pub peak_working_set: usize,
        pub working_set: usize,
        pub quota_peak_paged_pool: usize,
        pub quota_paged_pool: usize,
        pub quota_peak_non_paged_pool: usize,
        pub quota_non_paged_pool: usize,
        pub pagefile: usize,
        pub peak_pagefile: usize,
    }
    #[link(name = "kernel32")]
    extern "system" {
        pub fn GetCurrentProcess() -> isize;
        pub fn SetProcessWorkingSetSize(process: isize, min: usize, max: usize) -> i32;
        pub fn K32GetProcessMemoryInfo(process: isize, counters: *mut Counters, cb: u32) -> i32;
    }
}

/// The same, for the thread that calls it, at most every 15 seconds. The
/// allocator keeps a heap per thread and only that thread can tidy it: the
/// network and decoder threads build big short-lived things (the account as
/// JSON, pictures, clips) that the UI thread frees, and their emptied pages
/// then sat committed for good. Called by those threads when they go idle.
pub fn release_this_threads_memory() {
    use std::cell::Cell;
    use std::time::{Duration, Instant};
    thread_local! {
        static LAST: Cell<Option<Instant>> = const { Cell::new(None) };
    }
    let _ = LAST.try_with(|last| {
        if last.get().is_some_and(|t| t.elapsed() < Duration::from_secs(15)) {
            return;
        }
        last.set(Some(Instant::now()));
        unsafe { libmimalloc_sys::mi_collect(true) };
    });
}

/// Allocator settings for a small idle footprint, set before anything much
/// is allocated. Measured on a 132-server account (release, idle on Home):
/// private memory 263 MB -> ~200 MB.
///
/// * commit page memory when it is first touched, not a whole page run up
///   front (most of the saving: start-up touches many size classes once);
/// * return freed memory after 100 ms instead of a second.
pub fn tune_allocator() {
    // mimalloc v3 option numbers (mimalloc.h `mi_option_e`).
    const PURGE_DELAY: i32 = 15;
    const PAGE_COMMIT_ON_DEMAND: i32 = 40;
    unsafe {
        libmimalloc_sys::mi_option_set(PAGE_COMMIT_ON_DEMAND as _, 1);
        libmimalloc_sys::mi_option_set(PURGE_DELAY as _, 100);
    }
}