garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /xtask/src/profile.rs

raw

//! `cargo xtask profile <log> <elf>...`: the kernel's sampling profiler's
//! reports (`profile: <count> <address>` lines, `kernel/src/profile.rs`)
//! in a console log, named from the ELFs' symbol tables and added up per
//! function, the commonest first.

use std::collections::HashMap;
use std::path::Path;

/// A function: where it starts, its length, its name.
struct Symbol {
    start: u64,
    size: u64,
    name: String,
}

pub fn run(log: &Path, elfs: &[&str]) -> Result<(), String> {
    let mut symbols = Vec::new();
    for elf in elfs {
        let bytes = std::fs::read(elf).map_err(|e| format!("{elf}: {e}"))?;
        symbols.extend(functions(&bytes).ok_or(format!("{elf}: no symbol table"))?);
    }
    symbols.sort_by_key(|s| s.start);
    let text = std::fs::read_to_string(log).map_err(|e| format!("{}: {e}", log.display()))?;
    println!("Where the cores were:");
    rank(&text, "profile: ", &symbols);
    println!("\nWhat they would return to (x30: a leaf function's caller):");
    rank(&text, "profile-caller: ", &symbols);
    // "profile-syscall: <number> <calls> calls <us> us": the time programs
    // spent in each system call, which the samples count to the caller.
    let mut calls: HashMap<u64, (u64, u64)> = HashMap::new();
    for line in text.lines() {
        let Some(rest) = line.split("profile-syscall: ").nth(1) else {
            continue;
        };
        let words: Vec<u64> = rest.split_whitespace().filter_map(|w| w.parse().ok()).collect();
        if let [number, count, us] = words[..] {
            let entry = calls.entry(number).or_default();
            entry.0 += count;
            entry.1 += us;
        }
    }
    let mut calls: Vec<_> = calls.into_iter().collect();
    calls.sort_by_key(|a| std::cmp::Reverse(a.1.1));
    println!("\nSystem calls, by the time spent in them:");
    for (number, (count, us)) in calls.iter().take(15) {
        println!("{number:3}: {count:8} calls {:8} ms", us / 1000);
    }
    Ok(())
}

/// The `prefix` lines of `text` added up per function and said, the
/// commonest first.
fn rank(text: &str, prefix: &str, symbols: &[Symbol]) {
    let mut per_function: HashMap<String, u64> = HashMap::new();
    let mut total = 0;
    for line in text.lines() {
        let Some(rest) = line.split(prefix).nth(1) else {
            continue;
        };
        let mut words = rest.split_whitespace();
        let (Some(count), Some(address)) = (words.next(), words.next()) else {
            continue;
        };
        let (Ok(count), Some(Ok(address))) = (
            count.parse::<u64>(),
            address.strip_prefix("0x").map(|a| u64::from_str_radix(a, 16)),
        ) else {
            continue;
        };
        let at = symbols.partition_point(|s| s.start <= address);
        let name = at
            .checked_sub(1)
            .map(|i| &symbols[i])
            .filter(|s| address < s.start + s.size.max(1))
            .map_or_else(|| format!("{address:#x}"), |s| s.name.clone());
        *per_function.entry(name).or_default() += count;
        total += count;
    }
    let mut ranked: Vec<_> = per_function.into_iter().collect();
    ranked.sort_by_key(|a| std::cmp::Reverse(a.1));
    println!("{total} samples");
    for (name, count) in ranked.iter().take(30) {
        println!(
            "{count:7} {:5.1}%  {name}",
            *count as f64 * 100.0 / total.max(1) as f64
        );
    }
}

/// The functions an ELF64 (little-endian) names in its symbol table.
fn functions(elf: &[u8]) -> Option<Vec<Symbol>> {
    let u16_at = |at: usize| Some(u16::from_le_bytes(elf.get(at..at + 2)?.try_into().ok()?));
    let u32_at = |at: usize| Some(u32::from_le_bytes(elf.get(at..at + 4)?.try_into().ok()?));
    let u64_at = |at: usize| Some(u64::from_le_bytes(elf.get(at..at + 8)?.try_into().ok()?));
    if elf.get(..4)? != b"\x7fELF" {
        return None;
    }
    let sections = u64_at(0x28)? as usize;
    let entry = u16_at(0x3a)? as usize;
    let count = u16_at(0x3c)? as usize;
    let section = |i: usize| sections + i * entry;
    let symtab = (0..count).find(|&i| u32_at(section(i) + 4) == Some(2))?;
    let (offset, size) = (
        u64_at(section(symtab) + 24)? as usize,
        u64_at(section(symtab) + 32)? as usize,
    );
    let strtab = u32_at(section(symtab) + 40)? as usize;
    let strings = u64_at(section(strtab) + 24)? as usize;
    let mut found = Vec::new();
    for at in (offset..offset + size).step_by(24) {
        // A function (STT_FUNC) with an address.
        if elf.get(at + 4)? & 0xf != 2 {
            continue;
        }
        let (start, length) = (u64_at(at + 8)?, u64_at(at + 16)?);
        if start == 0 {
            continue;
        }
        let name_at = strings + u32_at(at)? as usize;
        let end = elf[name_at..].iter().position(|&b| b == 0)?;
        let name = String::from_utf8_lossy(&elf[name_at..name_at + end]);
        found.push(Symbol {
            start,
            size: length,
            name: demangle(&name),
        });
    }
    Some(found)
}

/// A Rust legacy-mangled name (`_ZN…E`) as a path, its hash left off;
/// any other name as it is.
fn demangle(name: &str) -> String {
    let Some(mut rest) = name.strip_prefix("_ZN") else {
        return name.to_string();
    };
    let mut parts = Vec::new();
    while let Some(digits) = rest.find(|c: char| !c.is_ascii_digit()).filter(|&d| d > 0) {
        let Ok(len) = rest[..digits].parse::<usize>() else {
            break;
        };
        let Some(part) = rest.get(digits..digits + len) else {
            break;
        };
        parts.push(part);
        rest = &rest[digits + len..];
    }
    if parts.last().is_some_and(|p| p.len() == 17 && p.starts_with('h')) {
        parts.pop();
    }
    let mut path = parts.join("::");
    for (from, to) in [
        ("$LT$", "<"),
        ("$GT$", ">"),
        ("$RF$", "&"),
        ("$BP$", "*"),
        ("$C$", ","),
        ("$u20$", " "),
        ("$u7b$", "{"),
        ("$u7d$", "}"),
        ("$u5b$", "["),
        ("$u5d$", "]"),
        ("$u27$", "'"),
        ("$u3b$", ";"),
        ("..", "::"),
    ] {
        path = path.replace(from, to);
    }
    path
}