#[cfg(not(target_os = "linux"))]
use std::alloc::System as ProcessAllocator;
use std::alloc::{GlobalAlloc, Layout};
use std::cell::Cell;
use std::marker::PhantomData;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, AtomicU64, Ordering};
use std::sync::Mutex;
#[cfg(target_os = "linux")]
use tikv_jemallocator::Jemalloc as ProcessAllocator;
mod capture;
mod report;
mod ring;
pub use report::{drain_now, set_line_sink, start_logger};
pub const LARGE_ALLOCATION_BYTES: usize = 64 << 20;
pub const LABEL_BURST_BYTES: isize = 512 << 20;
pub const FLUSH_QUANTUM_BYTES: isize = 1 << 20;
const MAX_LABELS: usize = 128;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Label(u8);
const FIXED_LABELS: [&str; 11] = [
"",
"index_build",
"callgraph_start",
"callgraph_refresh",
"segment_fold",
"meaning_fill",
"symbol_prewarm",
"remote_input_capture",
"frame_encode",
"census",
"tool:other",
];
static INTERNED: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
impl Label {
pub const NONE: Label = Label(0);
pub const INDEX_BUILD: Label = Label(1);
pub const CALLGRAPH_START: Label = Label(2);
pub const CALLGRAPH_REFRESH: Label = Label(3);
pub const SEGMENT_FOLD: Label = Label(4);
pub const MEANING_FILL: Label = Label(5);
pub const SYMBOL_PREWARM: Label = Label(6);
pub const REMOTE_INPUT_CAPTURE: Label = Label(7);
pub const FRAME_ENCODE: Label = Label(8);
pub const CENSUS: Label = Label(9);
pub const TOOL_OTHER: Label = Label(10);
pub fn tool(name: &str) -> Label {
let valid = !name.is_empty()
&& name.len() <= 48
&& name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'));
if !valid {
return Label::TOOL_OTHER;
}
Label::intern_with_prefix("tool:", name).unwrap_or(Label::TOOL_OTHER)
}
#[doc(hidden)]
pub fn custom(name: &str) -> Label {
Label::intern_with_prefix("", name).unwrap_or(Label::TOOL_OTHER)
}
fn intern_with_prefix(prefix: &str, name: &str) -> Option<Label> {
let matches = |entry: &str| entry.strip_prefix(prefix) == Some(name);
if let Some(index) = FIXED_LABELS.iter().position(|entry| matches(entry)) {
return Some(Label(index as u8));
}
let mut interned = INTERNED.lock().unwrap_or_else(|e| e.into_inner());
let offset = FIXED_LABELS.len();
if let Some(index) = interned.iter().position(|entry| matches(entry)) {
return Some(Label((offset + index) as u8));
}
if offset + interned.len() >= MAX_LABELS {
return None;
}
let leaked: &'static str = Box::leak(format!("{prefix}{name}").into_boxed_str());
interned.push(leaked);
Some(Label((offset + interned.len() - 1) as u8))
}
pub fn name(self) -> &'static str {
label_name(self.0)
}
}
fn label_name(id: u8) -> &'static str {
let id = usize::from(id);
if let Some(name) = FIXED_LABELS.get(id) {
return name;
}
INTERNED
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(id - FIXED_LABELS.len())
.copied()
.unwrap_or("unknown")
}
#[derive(Clone, Copy)]
pub struct RootName {
len: u8,
bytes: [u8; 47],
}
impl RootName {
pub const EMPTY: RootName = RootName {
len: 0,
bytes: [0; 47],
};
pub fn from_path(root: &Path) -> RootName {
let name = root
.file_name()
.map(|name| name.to_string_lossy())
.unwrap_or_else(|| root.to_string_lossy());
RootName::from_str(&name)
}
fn from_str(name: &str) -> RootName {
let mut end = name.len().min(47);
while !name.is_char_boundary(end) {
end -= 1;
}
let mut out = RootName::EMPTY;
out.bytes[..end].copy_from_slice(&name.as_bytes()[..end]);
out.len = end as u8;
out
}
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("")
}
}
struct LabelState {
live: AtomicIsize,
census_peak: AtomicIsize,
burst_peak: AtomicIsize,
active: AtomicU32,
crossed: AtomicBool,
crossed_at_ns: AtomicU64,
}
impl LabelState {
const fn new() -> Self {
Self {
live: AtomicIsize::new(0),
census_peak: AtomicIsize::new(0),
burst_peak: AtomicIsize::new(0),
active: AtomicU32::new(0),
crossed: AtomicBool::new(false),
crossed_at_ns: AtomicU64::new(0),
}
}
}
static LABELS: [LabelState; MAX_LABELS] = [const { LabelState::new() }; MAX_LABELS];
struct ThreadState {
label: Cell<u8>,
pending_label: Cell<u8>,
pending: Cell<isize>,
busy: Cell<bool>,
root: Cell<RootName>,
}
thread_local! {
static THREAD: ThreadState = const {
ThreadState {
label: Cell::new(0),
pending_label: Cell::new(0),
pending: Cell::new(0),
busy: Cell::new(false),
root: Cell::new(RootName::EMPTY),
}
};
}
pub struct TracingAllocator;
unsafe impl GlobalAlloc for TracingAllocator {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr = unsafe { ProcessAllocator.alloc(layout) };
if !ptr.is_null() {
on_alloc(layout.size());
}
ptr
}
#[inline]
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
let ptr = unsafe { ProcessAllocator.alloc_zeroed(layout) };
if !ptr.is_null() {
on_alloc(layout.size());
}
ptr
}
#[inline]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { ProcessAllocator.dealloc(ptr, layout) };
account(-(layout.size() as isize));
}
#[inline]
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let next = unsafe { ProcessAllocator.realloc(ptr, layout, new_size) };
if !next.is_null() {
if new_size >= LARGE_ALLOCATION_BYTES {
record_large(EventKind::Realloc, new_size, layout.size());
}
account(new_size as isize - layout.size() as isize);
}
next
}
}
#[inline(always)]
fn on_alloc(size: usize) {
if size >= LARGE_ALLOCATION_BYTES {
record_large(EventKind::Alloc, size, 0);
}
account(size as isize);
}
#[inline(always)]
fn account(delta: isize) {
THREAD.with(|thread| {
let label = thread.label.get();
if label != thread.pending_label.get() {
switch_pending(thread, label, delta);
return;
}
if label == 0 {
return;
}
let pending = thread.pending.get() + delta;
if pending >= FLUSH_QUANTUM_BYTES || pending <= -FLUSH_QUANTUM_BYTES {
thread.pending.set(0);
flush(thread, label, pending);
} else {
thread.pending.set(pending);
}
});
}
#[cold]
fn switch_pending(thread: &ThreadState, label: u8, delta: isize) {
let old = thread.pending_label.get();
let owed = thread.pending.replace(0);
if old != 0 && owed != 0 {
flush(thread, old, owed);
}
thread.pending_label.set(label);
if label == 0 {
return;
}
if delta >= FLUSH_QUANTUM_BYTES || delta <= -FLUSH_QUANTUM_BYTES {
flush(thread, label, delta);
} else {
thread.pending.set(delta);
}
}
#[cold]
fn flush(thread: &ThreadState, label: u8, delta: isize) {
let state = &LABELS[usize::from(label)];
let live = state.live.fetch_add(delta, Ordering::Relaxed) + delta;
if delta > 0 {
state.census_peak.fetch_max(live, Ordering::Relaxed);
if live >= LABEL_BURST_BYTES {
state.burst_peak.fetch_max(live, Ordering::Relaxed);
if !state.crossed.load(Ordering::Relaxed)
&& !state.crossed.swap(true, Ordering::Relaxed)
{
state.crossed_at_ns.store(monotonic_ns(), Ordering::Relaxed);
record_burst(thread, label, live);
}
}
} else if live < LABEL_BURST_BYTES / 2 && state.crossed.load(Ordering::Relaxed) {
end_burst(label, thread.root.get());
}
}
fn end_burst(label: u8, root: RootName) {
let state = &LABELS[usize::from(label)];
if !state.crossed.swap(false, Ordering::Relaxed) {
return;
}
let peak = state.burst_peak.swap(0, Ordering::Relaxed);
let started = state.crossed_at_ns.load(Ordering::Relaxed);
let mut event = ring::Event::new(EventKind::BurstEnded);
event.label = label;
event.root = root;
event.size = peak.max(0) as usize;
event.old_size = state.live.load(Ordering::Relaxed).max(0) as usize;
event.duration_ns = monotonic_ns().saturating_sub(started);
ring::push(&mut event);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EventKind {
Alloc,
Realloc,
BurstCrossed,
BurstEnded,
}
#[cold]
#[inline(never)]
fn record_large(kind: EventKind, size: usize, old_size: usize) {
THREAD.with(|thread| {
if thread.busy.replace(true) {
return;
}
let mut event = ring::Event::new(kind);
event.size = size;
event.old_size = old_size;
event.label = thread.label.get();
event.root = thread.root.get();
capture::fill(&mut event);
ring::push(&mut event);
thread.busy.set(false);
});
}
#[cold]
#[inline(never)]
fn record_burst(thread: &ThreadState, label: u8, live: isize) {
if thread.busy.replace(true) {
return;
}
let mut event = ring::Event::new(EventKind::BurstCrossed);
event.size = live.max(0) as usize;
event.label = label;
event.root = thread.root.get();
capture::fill(&mut event);
ring::push(&mut event);
thread.busy.set(false);
}
fn monotonic_ns() -> u64 {
static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
let epoch = *EPOCH.get_or_init(std::time::Instant::now);
u64::try_from(epoch.elapsed().as_nanos()).unwrap_or(u64::MAX)
}
#[must_use = "the label applies only while the guard lives"]
pub struct ScopeGuard {
previous_label: u8,
previous_root: RootName,
label: u8,
owner: bool,
_not_send: PhantomData<*const ()>,
}
pub fn scope(label: Label, root: Option<&Path>) -> ScopeGuard {
let root = root.map(RootName::from_path);
enter(label.0, root, true)
}
fn enter(label: u8, root: Option<RootName>, owner: bool) -> ScopeGuard {
if owner && label != 0 {
LABELS[usize::from(label)]
.active
.fetch_add(1, Ordering::Relaxed);
}
THREAD.with(|thread| {
let previous_label = thread.label.replace(label);
let previous_root = thread.root.get();
if let Some(root) = root {
thread.root.set(root);
}
ScopeGuard {
previous_label,
previous_root,
label,
owner,
_not_send: PhantomData,
}
})
}
impl Drop for ScopeGuard {
fn drop(&mut self) {
let root = THREAD.with(|thread| {
let root = thread.root.get();
if self.owner && thread.pending_label.get() == self.label {
let owed = thread.pending.replace(0);
if self.label != 0 && owed != 0 {
flush(thread, self.label, owed);
}
}
thread.label.set(self.previous_label);
thread.root.set(self.previous_root);
root
});
if !self.owner || self.label == 0 {
return;
}
close_scope(self.label, root);
}
}
#[derive(Clone, Copy)]
pub struct Carry {
label: u8,
root: RootName,
}
pub fn carry() -> Carry {
THREAD.with(|thread| Carry {
label: thread.label.get(),
root: thread.root.get(),
})
}
pub fn install<R: Send>(pool: &rayon::ThreadPool, op: impl FnOnce() -> R + Send) -> R {
pool.install(carry().wrap(op))
}
pub fn future<F: std::future::Future>(label: Label, root: Option<&Path>, inner: F) -> Labelled<F> {
Labelled {
inner,
carry: Carry {
label: label.0,
root: root.map_or_else(|| carry().root, RootName::from_path),
},
open: false,
}
}
pub struct Labelled<F> {
inner: F,
carry: Carry,
open: bool,
}
impl<F: std::future::Future> std::future::Future for Labelled<F> {
type Output = F::Output;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<F::Output> {
let this = unsafe { self.get_unchecked_mut() };
if !this.open && this.carry.label != 0 {
this.open = true;
LABELS[usize::from(this.carry.label)]
.active
.fetch_add(1, Ordering::Relaxed);
}
let _label = this.carry.enter();
unsafe { std::pin::Pin::new_unchecked(&mut this.inner) }.poll(cx)
}
}
impl<F> Drop for Labelled<F> {
fn drop(&mut self) {
if self.open {
close_scope(self.carry.label, self.carry.root);
}
}
}
fn close_scope(label: u8, root: RootName) {
let state = &LABELS[usize::from(label)];
if state.active.fetch_sub(1, Ordering::Relaxed) == 1 {
state.live.store(0, Ordering::Relaxed);
end_burst(label, root);
}
}
impl Carry {
pub fn enter(&self) -> ScopeGuard {
enter(self.label, Some(self.root), false)
}
pub fn wrap<R>(self, work: impl FnOnce() -> R) -> impl FnOnce() -> R {
move || {
let _label = self.enter();
work()
}
}
pub fn each<T, R>(self, work: impl Fn(T) -> R) -> impl Fn(T) -> R {
move |item| {
let _label = self.enter();
work(item)
}
}
pub fn label(&self) -> Label {
Label(self.label)
}
}
#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq)]
pub struct LabelPeak {
pub label: &'static str,
pub peak_bytes: u64,
pub live_bytes: u64,
}
pub fn take_census_peaks(limit: usize) -> Vec<LabelPeak> {
if !report::logger_started() {
return Vec::new();
}
collect_census_peaks(limit)
}
fn collect_census_peaks(limit: usize) -> Vec<LabelPeak> {
let mut peaks = Vec::new();
for (id, state) in LABELS.iter().enumerate().skip(1) {
let live = state.live.load(Ordering::Relaxed).max(0);
let peak = state.census_peak.swap(live, Ordering::Relaxed).max(live);
if peak > 0 {
peaks.push((id as u8, peak as u64, live as u64));
}
}
peaks.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
peaks.truncate(limit);
peaks
.into_iter()
.map(|(id, peak_bytes, live_bytes)| LabelPeak {
label: label_name(id),
peak_bytes,
live_bytes,
})
.collect()
}
#[doc(hidden)]
pub fn live_bytes(label: Label) -> isize {
let pending = THREAD.with(|thread| {
if thread.pending_label.get() == label.0 {
thread.pending.get()
} else {
0
}
});
LABELS[usize::from(label.0)].live.load(Ordering::Relaxed) + pending
}
#[cfg(test)]
mod tests;