ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
//! Kernel Event Logger for Visualization
//!
//! Provides a ring buffer of structured events (process, memory, filesystem)
//! that can be drained to serial as JSON for the host-side viz-bridge.

use alloc::collections::vec_deque::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use spin::Mutex;

pub const MAX_EVENTS: usize = 256;
pub const EVENT_SCHEMA_VERSION: u16 = 1;
pub const EVENT_SCHEMA_VERSION_FIELD: &str = "schema_version";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventKind {
    ProcessCreate,
    ProcessExit,
    ProcessStateChange,
    MemoryAlloc,
    MemoryFree,
    ThreadCreate,
    ThreadExit,
    FsCreate,
    FsWrite,
    FsRead,
    FsDelete,
    FsMount,
    Boot,
    Info,
}

#[derive(Debug, Clone)]
pub enum KernelEventValue {
    Str(String),
    U64(u64),
    I64(i64),
    Bool(bool),
}

#[derive(Debug, Clone)]
pub struct KernelEventField {
    pub key: String,
    pub value: KernelEventValue,
}

impl KernelEventField {
    pub fn str(key: &str, value: &str) -> Self {
        Self {
            key: String::from(key),
            value: KernelEventValue::Str(String::from(value)),
        }
    }

    pub fn u64(key: &str, value: u64) -> Self {
        Self {
            key: String::from(key),
            value: KernelEventValue::U64(value),
        }
    }

    pub fn i64(key: &str, value: i64) -> Self {
        Self {
            key: String::from(key),
            value: KernelEventValue::I64(value),
        }
    }

    pub fn bool(key: &str, value: bool) -> Self {
        Self {
            key: String::from(key),
            value: KernelEventValue::Bool(value),
        }
    }
}

#[derive(Debug, Clone)]
pub struct KernelEvent {
    pub schema_version: u16,
    pub kind: EventKind,
    pub detail: String,
    pub fields: Vec<KernelEventField>,
}

impl KernelEvent {
    pub fn new(kind: EventKind, detail: String) -> Self {
        Self {
            schema_version: EVENT_SCHEMA_VERSION,
            kind,
            detail,
            fields: Vec::new(),
        }
    }

    pub fn new_with_fields(kind: EventKind, detail: String, fields: Vec<KernelEventField>) -> Self {
        Self {
            schema_version: EVENT_SCHEMA_VERSION,
            kind,
            detail,
            fields,
        }
    }

    fn kind_str(&self) -> &str {
        match self.kind {
            EventKind::ProcessCreate => "proc_create",
            EventKind::ProcessExit => "proc_exit",
            EventKind::ProcessStateChange => "proc_state",
            EventKind::MemoryAlloc => "mem_alloc",
            EventKind::MemoryFree => "mem_free",
            EventKind::ThreadCreate => "thread_create",
            EventKind::ThreadExit => "thread_exit",
            EventKind::FsCreate => "fs_create",
            EventKind::FsWrite => "fs_write",
            EventKind::FsRead => "fs_read",
            EventKind::FsDelete => "fs_delete",
            EventKind::FsMount => "fs_mount",
            EventKind::Boot => "boot",
            EventKind::Info => "info",
        }
    }

    pub fn to_json(&self) -> String {
        let mut s = String::new();
        s.push_str("{\"type\":\"");
        s.push_str(self.kind_str());
        s.push_str("\",\"");
        s.push_str(EVENT_SCHEMA_VERSION_FIELD);
        s.push_str("\":");
        push_u64(&mut s, u64::from(self.schema_version));
        s.push_str(",\"detail\":\"");
        push_json_escaped_string(&mut s, &self.detail);
        s.push('"');
        for field in &self.fields {
            s.push(',');
            s.push('"');
            push_event_field_key(&mut s, &field.key);
            s.push_str("\":");
            match &field.value {
                KernelEventValue::Str(value) => {
                    s.push('"');
                    push_json_escaped_string(&mut s, value);
                    s.push('"');
                }
                KernelEventValue::U64(value) => push_u64(&mut s, *value),
                KernelEventValue::I64(value) => push_i64(&mut s, *value),
                KernelEventValue::Bool(value) => s.push_str(if *value { "true" } else { "false" }),
            }
        }
        s.push('}');
        s
    }
}

fn push_event_field_key(out: &mut String, key: &str) {
    if matches!(key, "type" | "detail" | EVENT_SCHEMA_VERSION_FIELD) {
        out.push_str("field_");
    }
    push_json_escaped_string(out, key);
}

fn push_json_escaped_string(out: &mut String, value: &str) {
    const HEX: &[u8; 16] = b"0123456789abcdef";

    for ch in value.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0c}' => out.push_str("\\f"),
            '\u{00}'..='\u{1f}' => {
                let code = ch as usize;
                out.push_str("\\u00");
                out.push(HEX[(code >> 4) & 0x0f] as char);
                out.push(HEX[code & 0x0f] as char);
            }
            _ => out.push(ch),
        }
    }
}

fn push_u64(out: &mut String, mut value: u64) {
    if value == 0 {
        out.push('0');
        return;
    }
    let mut digits = [0u8; 20];
    let mut len = 0;
    while value > 0 {
        digits[len] = b'0' + (value % 10) as u8;
        value /= 10;
        len += 1;
    }
    while len > 0 {
        len -= 1;
        out.push(digits[len] as char);
    }
}

fn push_i64(out: &mut String, value: i64) {
    if value < 0 {
        out.push('-');
        push_u64(out, value.unsigned_abs());
    } else {
        push_u64(out, value as u64);
    }
}

lazy_static! {
    pub static ref EVENT_LOG: Mutex<VecDeque<KernelEvent>> =
        Mutex::new(VecDeque::with_capacity(MAX_EVENTS));
}

/// Emit a kernel event into the ring buffer.
/// Drops oldest events if buffer is full.
pub fn emit(kind: EventKind, detail: &str) {
    push_event(KernelEvent::new(kind, String::from(detail)));
}

/// Emit a structured event using typed fields so JSON stays valid even when
/// string values contain quotes, control characters, or non-ASCII text.
pub fn emit_structured(kind: EventKind, detail: &str, fields: Vec<KernelEventField>) {
    push_event(KernelEvent::new_with_fields(
        kind,
        String::from(detail),
        fields,
    ));
}

fn push_event(event: KernelEvent) {
    crate::interrupts::without_interrupts(|| {
        let mut log = EVENT_LOG.lock();
        if log.len() >= MAX_EVENTS {
            log.pop_front();
        }
        log.push_back(event);
    });
}

/// Drain all pending events as newline-delimited JSON lines to serial.
pub fn drain_to_serial() {
    crate::interrupts::without_interrupts(|| {
        let mut log = EVENT_LOG.lock();
        if log.is_empty() {
            return;
        }
        crate::serial_println!("__EVENTS_BEGIN__");
        while let Some(event) = log.pop_front() {
            crate::serial_println!("{}", event.to_json());
        }
        crate::serial_println!("__EVENTS_END__");
    });
}

/// Drain events, returning them as a Vec (for host-side testing).
pub fn drain() -> Vec<KernelEvent> {
    let mut result = Vec::new();
    crate::interrupts::without_interrupts(|| {
        let mut log = EVENT_LOG.lock();
        while let Some(event) = log.pop_front() {
            result.push(event);
        }
    });
    result
}

/// Number of pending events
pub fn pending_count() -> usize {
    crate::interrupts::without_interrupts(|| EVENT_LOG.lock().len())
}