baryl 0.0.4

Public SDK for Baryl, a full-system emulation and introspection engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! The guest's own view of itself: processes, threads, loaded images, symbols
//! and crashes.
//!
//! Reached as `ctl.subs.enlighten`. Everything below is the guest OS's
//! knowledge read out of guest memory — the answer to "which process is this
//! CR3", "what is at this address", "is this fault a bug".
//!
//! Every call here is safe to make at any time. A run with no enlighten
//! implementation — no support for the guest's OS, or none loaded — answers an
//! empty list, a `None`, or a row of sentinels. So [`EnlRef::ready`] is
//! something to report on rather than a gate you have to check first, and a
//! component that only reads through this handle need not require the
//! subsystem at all.
//!
//! Answers are a snapshot taken when you asked. A process list read at one exit
//! describes the guest at that exit and nothing later.

use core::{ffi::CStr, ops::Deref};
use std::vec::Vec;

use crate::abi::{FlatCStr, inline_cstr, pack_cstr};
use crate::arch::{CpuExceptionContext, GuestAddr};

// Bindgen output cannot satisfy the workspace lints; the allow stops here.
mod generated {
    #![allow(non_camel_case_types, non_upper_case_globals, dead_code)]
    include!("generated.rs");
}
pub use generated::*;

/// One guest operating system, as a value you can store and compare.
///
/// Holds any `u32`, including one this build has no constant for. The four it
/// does name are [`ANY`](Self::ANY), [`WINDOWS`](Self::WINDOWS),
/// [`LINUX`](Self::LINUX) and [`MACOS`](Self::MACOS); compare against those,
/// and treat anything else as an OS you do not handle.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct GuestOs(pub u32);

impl GuestOs {
    /// No particular OS — 0, so a zeroed field reads as neutral.
    pub const ANY: Self = Self(BARYL_OS_ANY);
    /// Windows.
    pub const WINDOWS: Self = Self(BARYL_OS_WINDOWS);
    /// Linux.
    pub const LINUX: Self = Self(BARYL_OS_LINUX);
    /// macOS.
    pub const MACOS: Self = Self(BARYL_OS_MACOS);
}

impl EnlightenVtable {
    /// A table with no calls in it. Start from this when filling one in, so a
    /// call you did not implement reads as absent rather than as garbage.
    pub const ABSENT: EnlightenVtable = EnlightenVtable {
        ready: None,
        processes: None,
        process_by_cr3: None,
        process_by_name: None,
        threads: None,
        current_thread: None,
        kernel_modules: None,
        user_modules: None,
        module_at: None,
        resolve_symbol: None,
        free_modules: None,
        symbolize: None,
        classify_fault: None,
        record_crash: None,
    };
}

// Every string is inline, so one of these may be stored in the pool.
crate::abi::impl_sandbox_safe!(SymbolizedBlock);

/// A guest code address with a name on it: which process, which image, and how
/// far into it.
///
/// All three strings are stored inline, so this owns nothing, needs no lifetime
/// and can go straight into a checkpoint or a queue. Long names are truncated
/// rather than allocated.
impl SymbolizedBlock {
    /// A block a module claimed, at `offset` into it.
    pub fn resolved(process: &CStr, module: &CStr, offset: u64) -> SymbolizedBlock {
        SymbolizedBlock {
            process: pack_cstr(process),
            module: pack_cstr(module),
            offset: offset,
        }
    }

    /// A block no module claimed: the module reads `"unresolved"` and
    /// [`module_offset`](Self::module_offset) answers `None`.
    pub fn unresolved(process: &CStr) -> SymbolizedBlock {
        // `as u64`: bindgen renders the all-ones `#define` as `i32 = -1`.
        SymbolizedBlock::resolved(process, c"unresolved", BARYL_OFFSET_NONE as u64)
    }

    /// The process the block ran in, or `"unknown"` when the guest view is not
    /// up.
    pub fn process(&self) -> &CStr {
        inline_cstr(&self.process)
    }

    /// The image the block belongs to, or `"unresolved"` when none claimed it.
    pub fn module(&self) -> &CStr {
        inline_cstr(&self.module)
    }

    /// How far into the image the block sits.
    ///
    /// `None` when no module claimed it — read this rather than testing the
    /// raw field against 0, which is a perfectly real offset.
    pub fn module_offset(&self) -> Option<u64> {
        (self.offset != BARYL_OFFSET_NONE as u64).then_some(self.offset)
    }
}

impl Process {
    /// The short name the kernel keeps: `comm` on Linux, the image name on
    /// Windows. Sixteen bytes including the terminator, so a longer name
    /// arrives truncated.
    pub fn name(&self) -> &CStr {
        inline_cstr(&self.name)
    }
}

impl Thread {
    /// The thread's name, where the guest OS keeps one.
    pub fn name(&self) -> &CStr {
        inline_cstr(&self.name)
    }
}

impl Module {
    /// The basename the guest knows this image by — `libc.so.6`, `ntdll.dll`.
    pub fn name(&self) -> &CStr {
        // SAFETY: callee-allocated, NUL-terminated, alive until `free_modules`.
        unsafe { CStr::from_ptr(self.name) }
    }

    /// The absolute path the image was loaded from, or `None` for one with no
    /// backing file — an anonymous mapping, or a module the guest built in
    /// memory.
    pub fn file(&self) -> Option<&CStr> {
        // SAFETY: as `name`; NULL is the ABI's spelling of "no backing file".
        (!self.file.is_null()).then(|| unsafe { CStr::from_ptr(self.file) })
    }

    /// Whether `va` falls inside this image's mapped range.
    pub fn covers(&self, va: u64) -> bool {
        va >= self.base_va && va - self.base_va < self.size
    }
}

/// One [`Module`], holding its strings alive.
///
/// `Module::name` and `Module::file` point at memory the subsystem allocated,
/// so the module has to be handed back when you are done with it. This does
/// that on drop; derefs to `Module`, so use it exactly as one. Copy anything
/// you want to keep out of it before it goes.
pub struct OwnedModule {
    raw: Module,
    enl: EnlRef,
}

impl Drop for OwnedModule {
    fn drop(&mut self) {
        let Some(f) = self.enl.table().and_then(|v| v.free_modules) else {
            return;
        };
        // SAFETY: this `Module` came from the same handle's own fill call.
        unsafe { f(self.enl, &raw mut self.raw, 1) }
    }
}

impl Deref for OwnedModule {
    type Target = Module;

    fn deref(&self) -> &Module {
        &self.raw
    }
}

/// A list of [`Module`]s, holding their strings alive.
///
/// [`OwnedModule`] over a whole list: derefs to `&[Module]`, so it iterates and
/// indexes like a slice, and frees every module's strings on drop.
///
/// # Examples
///
/// ```ignore
/// for m in t.subs.enlighten.kernel_modules().iter() {
///     baryl::logging::info!(
///         "{:?} at {:#x} +{:#x}",
///         m.name(), m.base_va, m.size,
///     );
/// }
/// ```
pub struct OwnedModules {
    raw: Vec<Module>,
    enl: EnlRef,
}

impl Drop for OwnedModules {
    fn drop(&mut self) {
        let Some(f) = self.enl.table().and_then(|v| v.free_modules) else {
            return;
        };
        // SAFETY: as `OwnedModule`; `raw` is exactly what that fill wrote.
        unsafe { f(self.enl, self.raw.as_mut_ptr(), self.raw.len() as u64) }
    }
}

impl Deref for OwnedModules {
    type Target = [Module];

    fn deref(&self) -> &[Module] {
        &self.raw
    }
}

/// Size, then fill: the first call reports the total, the second takes what the
/// first said would fit.
fn collect<T>(mut f: impl FnMut(*mut T, u64) -> u64) -> Vec<T> {
    let total = f(core::ptr::null_mut(), 0) as usize;
    let mut out: Vec<T> = Vec::with_capacity(total);
    let n = f(out.as_mut_ptr(), total as u64) as usize;
    // SAFETY: the ABI filled `min(total, cap)` entries, and `cap` is `total`.
    unsafe { out.set_len(n.min(total)) };
    out
}

impl EnlRef {
    /// The vtable, or `None` when nothing is bound to this handle.
    fn table(&self) -> Option<&EnlightenVtable> {
        // SAFETY: `vtable` is the enlighten `.so`'s static table, valid for the process.
        unsafe { self.vtable.as_ref() }
    }

    /// Whether the guest view is up and the reads below will find anything.
    ///
    /// `false` early in a boot, before the kernel structures exist to walk, and
    /// on a run with no support for the guest's OS. Not a gate — every read is
    /// safe to make regardless and answers empty — so use it to report why a
    /// component is finding nothing, rather than to decide whether to ask.
    pub fn ready(&self) -> bool {
        self.table()
            .and_then(|v| v.ready)
            .is_some_and(|f| unsafe { f(*self) } == 0)
    }

    /// Every process the guest is running, as of now. Empty when the guest view
    /// is not up.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// for p in t.subs.enlighten.processes() {
    ///     baryl::logging::info!("{} {:?} cr3 {:#x}", p.pid, p.name(), p.dtb);
    /// }
    /// ```
    pub fn processes(&self) -> Vec<Process> {
        let Some(f) = self.table().and_then(|v| v.processes) else {
            return Vec::new();
        };
        collect(|out, cap| unsafe { f(*self, out, cap) })
    }

    /// The process whose page tables `cr3` names — how you turn "the address
    /// space the guest is in right now" into a process.
    ///
    /// `None` when no process matches, and when the guest view is not up.
    pub fn process_by_cr3(&self, cr3: u64) -> Option<Process> {
        let f = self.table().and_then(|v| v.process_by_cr3)?;
        let mut out = Process::default();
        (unsafe { f(*self, cr3, &raw mut out) } == 0).then_some(out)
    }

    /// The first process with this name.
    ///
    /// The *first*: a guest may well be running four of them, and which one you
    /// get is not defined. Walk [`processes`](Self::processes) when that
    /// matters.
    ///
    /// `None` when nothing matches, when the guest view is not up, and for a
    /// `name` over 255 bytes — a name that cannot be carried is a name nothing
    /// could have matched.
    ///
    /// # Panics
    ///
    /// If `name` holds a NUL byte.
    pub fn process_by_name(&self, name: &str) -> Option<Process> {
        let f = self.table().and_then(|v| v.process_by_name)?;
        let name: FlatCStr<MAX_NAME_BYTES> = FlatCStr::try_new(name)?;
        let mut out = Process::default();
        (unsafe { f(*self, name.as_ptr(), &raw mut out) } == 0).then_some(out)
    }

    /// Every thread of one process. Empty when the guest view is not up.
    pub fn threads(&self, proc: &Process) -> Vec<Thread> {
        let Some(f) = self.table().and_then(|v| v.threads) else {
            return Vec::new();
        };
        collect(|out, cap| unsafe { f(*self, core::ptr::from_ref(proc), out, cap) })
    }

    /// The thread that was running when this exit stopped the guest — who is
    /// doing the thing you were called about.
    pub fn current_thread(&self) -> Option<Thread> {
        let f = self.table().and_then(|v| v.current_thread)?;
        let mut out = Thread::default();
        (unsafe { f(*self, &raw mut out) } == 0).then_some(out)
    }

    /// The kernel image and every module loaded into it. Empty when the guest
    /// view is not up.
    pub fn kernel_modules(&self) -> OwnedModules {
        let Some(f) = self.table().and_then(|v| v.kernel_modules) else {
            return OwnedModules { raw: Vec::new(), enl: *self };
        };
        OwnedModules {
            raw: collect(|out, cap| unsafe { f(*self, out, cap) }),
            enl: *self,
        }
    }

    /// The images mapped into one process — its executable and every shared
    /// library it loaded.
    pub fn user_modules(&self, proc: &Process) -> OwnedModules {
        let Some(f) = self.table().and_then(|v| v.user_modules) else {
            return OwnedModules { raw: Vec::new(), enl: *self };
        };
        OwnedModules {
            raw: collect(|out, cap| unsafe { f(*self, core::ptr::from_ref(proc), out, cap) }),
            enl: *self,
        }
    }

    /// The image covering `va`, and how far into it the address sits — turning
    /// a raw address into `libc.so.6+0x8a3f0`.
    ///
    /// `proc` of `None` means kernel space; pass a process to search its own
    /// mappings instead.
    ///
    /// `None` when no image covers `va`, and when the guest view is not up.
    pub fn module_at(&self, proc: Option<&Process>, va: u64) -> Option<(OwnedModule, u64)> {
        let f = self.table().and_then(|v| v.module_at)?;
        let (mut out, mut off) = (Module::default(), 0u64);
        let rc = unsafe { f(*self, opt_ptr(proc), va, &raw mut out, &raw mut off) };
        (rc == 0).then_some((OwnedModule { raw: out, enl: *self }, off))
    }

    /// A name to the guest virtual address it stands for.
    ///
    /// `spec` is one of three forms: `symbol`, `module!symbol`, or
    /// `module+0xNN`. `proc` of `None` resolves against kernel space; pass a
    /// process to resolve inside it.
    ///
    /// `None` when the name resolves to nothing, when the guest view is not up,
    /// and for a `spec` over 255 bytes.
    ///
    /// # Panics
    ///
    /// If `spec` holds a NUL byte.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Arm a breakpoint on a kernel entry point by name.
    /// let enl = &t.subs.enlighten;
    /// if let Some(va) = enl.resolve_symbol(None, "do_sys_openat2") {
    ///     baryl::logging::info!("openat2 at {va:#x}");
    /// }
    ///
    /// // Or somewhere inside one process's libc.
    /// let sshd = enl.process_by_name("sshd")?;
    /// let malloc = enl.resolve_symbol(Some(&sshd), "libc.so.6!malloc")?;
    /// ```
    pub fn resolve_symbol(&self, proc: Option<&Process>, spec: &str) -> Option<u64> {
        let f = self.table().and_then(|v| v.resolve_symbol)?;
        let spec: FlatCStr<MAX_NAME_BYTES> = FlatCStr::try_new(spec)?;
        let mut out = 0u64;
        let rc = unsafe { f(*self, opt_ptr(proc), spec.as_ptr(), &raw mut out) };
        (rc == 0).then_some(out)
    }

    /// Put a name on the block `key` identifies: process, image, offset.
    ///
    /// The one read here that always answers. A guest view that is not up gives
    /// you a row of sentinels — process `"unknown"`, module `"unresolved"`,
    /// [`module_offset`](SymbolizedBlock::module_offset) `None` — rather than
    /// nothing, so this can go straight into a log line or a coverage row with
    /// no branch in front of it.
    pub fn symbolize(&self, key: &GuestAddr) -> SymbolizedBlock {
        let Some(f) = self.table().and_then(|v| v.symbolize) else {
            return SymbolizedBlock::unresolved(c"unknown");
        };
        let mut out = SymbolizedBlock::default();
        unsafe { f(*self, core::ptr::from_ref(key), &raw mut out) };
        out
    }
}

/// Longest name or spec these calls will carry, terminator included.
const MAX_NAME_BYTES: usize = 256;

/// `None` becomes NULL, which is how "kernel space" is spelled.
fn opt_ptr(proc: Option<&Process>) -> *const Process {
    proc.map_or(core::ptr::null(), core::ptr::from_ref)
}

/// Telling a bug in the guest from an ordinary fault, and keeping one copy of
/// each distinct one.
///
/// Only the guest OS can tell the two apart — a page fault on a page the kernel
/// is about to fill in looks exactly like one on a wild pointer — so both of
/// these live here, and a harness built on them names no OS of its own.
impl EnlRef {
    /// Whether this fault is a bug in the guest, and if so what and where.
    ///
    /// `None` means the guest OS handles this fault itself, which is the great
    /// majority of faults a running system takes — demand paging,
    /// copy-on-write, stack growth. It is also what a run with no guest view
    /// answers, so a harness sees no crashes rather than false ones.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// #[arch(cpu_exception)]
    /// fn on_fault(&mut self, t: &mut Control, ctx: &CpuExceptionContext) {
    ///     let Some(crash) = t.subs.enlighten.classify_fault(ctx) else { return };
    ///     if t.subs.enlighten.record_crash(&crash, c"./crashes") {
    ///         baryl::logging::warn!("new crash {:#x} at {:?}", crash.hash, crash.site.module());
    ///     }
    ///     t.core.request_reset(BARYL_RESET_CRASH);
    /// }
    /// ```
    pub fn classify_fault(&self, ctx: &CpuExceptionContext) -> Option<GuestCrash> {
        let f = self.table().and_then(|v| v.classify_fault)?;
        let mut out = GuestCrash::default();
        (unsafe { f(*self, core::ptr::from_ref(ctx), &raw mut out) } == 1).then_some(out)
    }

    /// Keep one copy of each distinct crash under `dir`, and say whether this
    /// one was new.
    ///
    /// Deduplicated on `crash.hash`, which covers the kind, the faulting image
    /// and the offset into it — so the same bug reached by a thousand different
    /// inputs is written once. `true` means it had not been seen and a file was
    /// written; `false` means it had, and nothing was.
    ///
    /// `false` is also what a run with no guest view answers.
    pub fn record_crash(&self, crash: &GuestCrash, dir: &CStr) -> bool {
        let Some(f) = self.table().and_then(|v| v.record_crash) else {
            return false;
        };
        unsafe { f(*self, core::ptr::from_ref(crash), dir.as_ptr()) == 1 }
    }
}