Skip to main content

os/
event_log.rs

1//! Kernel Event Logger for Visualization
2//!
3//! Provides a ring buffer of structured events (process, memory, filesystem)
4//! that can be drained to serial as JSON for the host-side viz-bridge.
5
6use alloc::collections::vec_deque::VecDeque;
7use alloc::string::String;
8use alloc::vec::Vec;
9use lazy_static::lazy_static;
10use spin::Mutex;
11
12pub const MAX_EVENTS: usize = 256;
13pub const EVENT_SCHEMA_VERSION: u16 = 1;
14pub const EVENT_SCHEMA_VERSION_FIELD: &str = "schema_version";
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum EventKind {
18    ProcessCreate,
19    ProcessExit,
20    ProcessStateChange,
21    MemoryAlloc,
22    MemoryFree,
23    ThreadCreate,
24    ThreadExit,
25    FsCreate,
26    FsWrite,
27    FsRead,
28    FsDelete,
29    FsMount,
30    Boot,
31    Info,
32}
33
34#[derive(Debug, Clone)]
35pub enum KernelEventValue {
36    Str(String),
37    U64(u64),
38    I64(i64),
39    Bool(bool),
40}
41
42#[derive(Debug, Clone)]
43pub struct KernelEventField {
44    pub key: String,
45    pub value: KernelEventValue,
46}
47
48impl KernelEventField {
49    pub fn str(key: &str, value: &str) -> Self {
50        Self {
51            key: String::from(key),
52            value: KernelEventValue::Str(String::from(value)),
53        }
54    }
55
56    pub fn u64(key: &str, value: u64) -> Self {
57        Self {
58            key: String::from(key),
59            value: KernelEventValue::U64(value),
60        }
61    }
62
63    pub fn i64(key: &str, value: i64) -> Self {
64        Self {
65            key: String::from(key),
66            value: KernelEventValue::I64(value),
67        }
68    }
69
70    pub fn bool(key: &str, value: bool) -> Self {
71        Self {
72            key: String::from(key),
73            value: KernelEventValue::Bool(value),
74        }
75    }
76}
77
78#[derive(Debug, Clone)]
79pub struct KernelEvent {
80    pub schema_version: u16,
81    pub kind: EventKind,
82    pub detail: String,
83    pub fields: Vec<KernelEventField>,
84}
85
86impl KernelEvent {
87    pub fn new(kind: EventKind, detail: String) -> Self {
88        Self {
89            schema_version: EVENT_SCHEMA_VERSION,
90            kind,
91            detail,
92            fields: Vec::new(),
93        }
94    }
95
96    pub fn new_with_fields(kind: EventKind, detail: String, fields: Vec<KernelEventField>) -> Self {
97        Self {
98            schema_version: EVENT_SCHEMA_VERSION,
99            kind,
100            detail,
101            fields,
102        }
103    }
104
105    fn kind_str(&self) -> &str {
106        match self.kind {
107            EventKind::ProcessCreate => "proc_create",
108            EventKind::ProcessExit => "proc_exit",
109            EventKind::ProcessStateChange => "proc_state",
110            EventKind::MemoryAlloc => "mem_alloc",
111            EventKind::MemoryFree => "mem_free",
112            EventKind::ThreadCreate => "thread_create",
113            EventKind::ThreadExit => "thread_exit",
114            EventKind::FsCreate => "fs_create",
115            EventKind::FsWrite => "fs_write",
116            EventKind::FsRead => "fs_read",
117            EventKind::FsDelete => "fs_delete",
118            EventKind::FsMount => "fs_mount",
119            EventKind::Boot => "boot",
120            EventKind::Info => "info",
121        }
122    }
123
124    pub fn to_json(&self) -> String {
125        let mut s = String::new();
126        s.push_str("{\"type\":\"");
127        s.push_str(self.kind_str());
128        s.push_str("\",\"");
129        s.push_str(EVENT_SCHEMA_VERSION_FIELD);
130        s.push_str("\":");
131        push_u64(&mut s, u64::from(self.schema_version));
132        s.push_str(",\"detail\":\"");
133        push_json_escaped_string(&mut s, &self.detail);
134        s.push('"');
135        for field in &self.fields {
136            s.push(',');
137            s.push('"');
138            push_event_field_key(&mut s, &field.key);
139            s.push_str("\":");
140            match &field.value {
141                KernelEventValue::Str(value) => {
142                    s.push('"');
143                    push_json_escaped_string(&mut s, value);
144                    s.push('"');
145                }
146                KernelEventValue::U64(value) => push_u64(&mut s, *value),
147                KernelEventValue::I64(value) => push_i64(&mut s, *value),
148                KernelEventValue::Bool(value) => s.push_str(if *value { "true" } else { "false" }),
149            }
150        }
151        s.push('}');
152        s
153    }
154}
155
156fn push_event_field_key(out: &mut String, key: &str) {
157    if matches!(key, "type" | "detail" | EVENT_SCHEMA_VERSION_FIELD) {
158        out.push_str("field_");
159    }
160    push_json_escaped_string(out, key);
161}
162
163fn push_json_escaped_string(out: &mut String, value: &str) {
164    const HEX: &[u8; 16] = b"0123456789abcdef";
165
166    for ch in value.chars() {
167        match ch {
168            '"' => out.push_str("\\\""),
169            '\\' => out.push_str("\\\\"),
170            '\n' => out.push_str("\\n"),
171            '\r' => out.push_str("\\r"),
172            '\t' => out.push_str("\\t"),
173            '\u{08}' => out.push_str("\\b"),
174            '\u{0c}' => out.push_str("\\f"),
175            '\u{00}'..='\u{1f}' => {
176                let code = ch as usize;
177                out.push_str("\\u00");
178                out.push(HEX[(code >> 4) & 0x0f] as char);
179                out.push(HEX[code & 0x0f] as char);
180            }
181            _ => out.push(ch),
182        }
183    }
184}
185
186fn push_u64(out: &mut String, mut value: u64) {
187    if value == 0 {
188        out.push('0');
189        return;
190    }
191    let mut digits = [0u8; 20];
192    let mut len = 0;
193    while value > 0 {
194        digits[len] = b'0' + (value % 10) as u8;
195        value /= 10;
196        len += 1;
197    }
198    while len > 0 {
199        len -= 1;
200        out.push(digits[len] as char);
201    }
202}
203
204fn push_i64(out: &mut String, value: i64) {
205    if value < 0 {
206        out.push('-');
207        push_u64(out, value.unsigned_abs());
208    } else {
209        push_u64(out, value as u64);
210    }
211}
212
213lazy_static! {
214    pub static ref EVENT_LOG: Mutex<VecDeque<KernelEvent>> =
215        Mutex::new(VecDeque::with_capacity(MAX_EVENTS));
216}
217
218/// Emit a kernel event into the ring buffer.
219/// Drops oldest events if buffer is full.
220pub fn emit(kind: EventKind, detail: &str) {
221    push_event(KernelEvent::new(kind, String::from(detail)));
222}
223
224/// Emit a structured event using typed fields so JSON stays valid even when
225/// string values contain quotes, control characters, or non-ASCII text.
226pub fn emit_structured(kind: EventKind, detail: &str, fields: Vec<KernelEventField>) {
227    push_event(KernelEvent::new_with_fields(
228        kind,
229        String::from(detail),
230        fields,
231    ));
232}
233
234fn push_event(event: KernelEvent) {
235    crate::interrupts::without_interrupts(|| {
236        let mut log = EVENT_LOG.lock();
237        if log.len() >= MAX_EVENTS {
238            log.pop_front();
239        }
240        log.push_back(event);
241    });
242}
243
244/// Drain all pending events as newline-delimited JSON lines to serial.
245pub fn drain_to_serial() {
246    crate::interrupts::without_interrupts(|| {
247        let mut log = EVENT_LOG.lock();
248        if log.is_empty() {
249            return;
250        }
251        crate::serial_println!("__EVENTS_BEGIN__");
252        while let Some(event) = log.pop_front() {
253            crate::serial_println!("{}", event.to_json());
254        }
255        crate::serial_println!("__EVENTS_END__");
256    });
257}
258
259/// Drain events, returning them as a Vec (for host-side testing).
260pub fn drain() -> Vec<KernelEvent> {
261    let mut result = Vec::new();
262    crate::interrupts::without_interrupts(|| {
263        let mut log = EVENT_LOG.lock();
264        while let Some(event) = log.pop_front() {
265            result.push(event);
266        }
267    });
268    result
269}
270
271/// Number of pending events
272pub fn pending_count() -> usize {
273    crate::interrupts::without_interrupts(|| EVENT_LOG.lock().len())
274}