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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Running a machine from your own program.
//!
//! [`Baryl::open`] takes an image and gives you back a handle; [`Options`]
//! builds everything else one open is told. The image may be a disk or a
//! checkpoint and you do not say which — that is read from the file, so
//! booting and restoring are the same call.
//!
//! Nothing here names an engine. `[baryl] engine` in the machine config does,
//! and a checkpoint carries the config it was taken under.
//!
//! # Examples
//!
//! ```ignore
//! use baryl::{Baryl, Options, RunEnd};
//!
//! let image = Path::new("disk.qcow2");
//! let cfg = MachineConfig::read(&MachineConfig::path_beside(image))?;
//!
//! let options = Options::default()
//!     .machine(Some(cfg))
//!     .seed(0x1234)
//!     .state_dir(Some(Path::new("./run")))?
//!     .components(&[(PathBuf::from("./libhello.so"), vec!["--who=world".into()])])?;
//!
//! let mut baryl = Baryl::open(image, &options)?;
//!
//! // Read the machine without running it.
//! let isa = baryl.control().subs.arch_id();
//!
//! match baryl.run()? {
//!     RunEnd::Component { message: Some(why), .. } => println!("stopped: {why}"),
//!     end => std::process::exit(i32::from(end.exit_status())),
//! }
//! ```

use std::ffi::{CStr, CString, c_char, c_int, c_void};
use std::fmt;
use std::mem::MaybeUninit;
use std::path::{Path, PathBuf};

use crate::config::MachineConfig;
use crate::control::Control;
use anyhow::Context;
use log::LevelFilter;

use crate::loader::BarylCore;

/// How a run ended — which is a separate question from whether it ran.
///
/// [`Baryl::run`] answers `Err` when the machine never got going, and `Ok` with
/// one of these when it did. So a guest that exited with status 1 is `Ok`, and
/// this is never an error itself: the run did exactly what it was asked.
///
/// Match on the variant, not only on [`code`](Self::code). A component that
/// stopped the run — the checkpoint was taken, there was nothing left to do —
/// and a guest that exited on its own can both answer 0.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunEnd {
    /// The guest ended itself; `code` is its own exit status.
    Engine { code: i32 },
    /// A component called `request_exit`, with that code and whatever reason it
    /// chose to give.
    Component { code: i32, message: Option<String> },
}

impl RunEnd {
    /// Whichever party ended the run, its status verbatim — full width, sign
    /// intact, no truncation. Only you know whether it is about to become a
    /// process status.
    pub fn code(&self) -> i32 {
        match *self {
            RunEnd::Engine { code } | RunEnd::Component { code, .. } => code,
        }
    }

    /// [`code`](Self::code) as a POSIX wait status: the low eight bits.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// assert_eq!(RunEnd::Engine { code: 3 }.exit_status(), 3);
    /// assert_eq!(RunEnd::Engine { code: -1 }.exit_status(), 255);
    /// assert_eq!(RunEnd::Engine { code: 256 }.exit_status(), 0);
    ///
    /// // The unmasked status is still there when you want it.
    /// assert_eq!(RunEnd::Engine { code: -1 }.code(), -1);
    /// ```
    pub fn exit_status(&self) -> u8 {
        (self.code() & 0xff) as u8
    }

    /// Raw outcome to this. A `kind` this build does not recognize reads as an
    /// engine exit, so a newer runtime adding a third one does not cost an
    /// older caller the status it does understand.
    ///
    /// # Safety
    /// `raw` must be a `BarylOutcome` the runtime wrote, and its `message` must
    /// still be live — the runtime promises it points into a library that is
    /// never unloaded.
    unsafe fn from_raw(raw: &crate::sys::BarylOutcome) -> RunEnd {
        if raw.kind == BARYL_EXIT_COMPONENT {
            let message = (!raw.message.is_null()).then(|| {
                // SAFETY: non-null and NUL-terminated per the outcome contract;
                // copied to an owned String so no borrow of the `.so` escapes.
                unsafe { CStr::from_ptr(raw.message) }
                    .to_string_lossy()
                    .into_owned()
            });
            RunEnd::Component { code: raw.code, message: message }
        } else {
            RunEnd::Engine { code: raw.code }
        }
    }
}

impl fmt::Display for RunEnd {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RunEnd::Engine { code } => write!(f, "engine exited ({code})"),
            RunEnd::Component { code, message: None } => {
                write!(f, "component requested exit ({code})")
            },
            RunEnd::Component { code, message: Some(m) } => {
                write!(f, "component requested exit ({code}): {m}")
            },
        }
    }
}

/// The `BarylExitKind` value for a component-requested exit, restated under a
/// spellable name. `kind_values_match_the_header` below pins the two together.
const BARYL_EXIT_COMPONENT: u32 = 1;

/// One opened machine.
///
/// Open it, read it, run it, drop it. Reading through [`control`](Self::control)
/// executes no guest instructions, so a program may open an image, inspect it
/// and close it without the machine ever running.
///
/// One run per open: [`run`](Self::run) takes `&mut self`, and `control`
/// borrows, so the borrow checker keeps a reader and a run from overlapping.
/// Dropping this closes the machine.
///
/// Neither `Send` nor `Sync`: the thread that opens one is the thread that runs
/// it.
pub struct Baryl {
    core: &'static BarylCore,
    ctx: *mut c_void,
}

impl Baryl {
    /// Open `image` — a disk to boot or a checkpoint to restore, decided from
    /// the file rather than from you.
    ///
    /// The runtime is located and version-checked on the way through, the first
    /// time this is called in a process; later calls reuse it.
    ///
    /// # Errors
    ///
    /// No runtime installed (the message says where it looked and what to run);
    /// an installed runtime outside this build's ABI window; `image` is not
    /// UTF-8 or holds an interior NUL; or the runtime refused to open it, in
    /// which case its own reason is the message. Nothing has run in any case.
    pub fn open(image: &Path, options: &Options) -> anyhow::Result<Baryl> {
        let core = BarylCore::load()?;
        let path = cstr(image)?;
        let abi = options.as_abi();
        // SAFETY: a live path, and an options struct borrowing `options`, which
        // outlives the call; the core keeps nothing out of either.
        let mut err = [0u8; crate::sys::BARYL_ERROR_LEN as usize];
        let ctx = unsafe {
            (core.open)(path.as_ptr(), &raw const abi, err.as_mut_ptr().cast(), err.len())
        };
        if ctx.is_null() {
            return Err(match open_error_message_read(&err) {
                Some(why) => anyhow::anyhow!("{why}"),
                None => anyhow::anyhow!("{} could not open {}", core.name(), image.display()),
            });
        }
        Ok(Baryl { core: core, ctx: ctx })
    }

    /// The same [`Control`] a component is handed: every subsystem, reachable
    /// from your own program.
    ///
    /// This is how a host inspects a machine — walk page tables through
    /// `.subs.arch`, list processes through `.subs.enlighten`, read physical
    /// memory through `.subs.engine`. Reading through it runs no guest
    /// instructions.
    ///
    /// The returned borrow lasts as long as you hold it, and
    /// [`run`](Self::run) takes `&mut self`, so nothing can enter the guest
    /// while you are looking at its state.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Open a checkpoint and list its processes without running it.
    /// let baryl = Baryl::open(Path::new("boot.ck"), &Options::default())?;
    /// for p in baryl.control().subs.enlighten.processes() {
    ///     println!("{} {:?}", p.pid, p.name());
    /// }
    /// ```
    pub fn control(&self) -> &Control {
        // SAFETY: the ctx one `open` answered, whose `Control` the core promises
        // is live until `close`; `Drop` is the only caller of that, and it takes
        // `self` by value, so no borrow from here is outstanding then.
        unsafe { &*(self.core.control)(self.abi()).cast() }
    }

    /// Start the machine, and return when it stops.
    ///
    /// Blocks for as long as the guest runs — which, for a fuzzing run with no
    /// case limit, is until something stops it. One run per open.
    ///
    /// `Ok` means the machine ran; [`RunEnd`] says how it ended, and an
    /// ordinary non-zero guest status is still `Ok`.
    ///
    /// # Errors
    ///
    /// The run did not complete. The reason is in the run's own log under the
    /// state directory, so the error points there rather than restating
    /// something this side never saw.
    pub fn run(&mut self) -> anyhow::Result<RunEnd> {
        let mut outcome = MaybeUninit::<crate::sys::BarylOutcome>::uninit();
        // SAFETY: the ctx one `open` answered, and an outcome writable for one.
        let rc = unsafe { (self.core.run)(self.abi(), outcome.as_mut_ptr()) };
        // SAFETY: rc == 0 is the core's promise that it wrote `outcome`.
        unsafe { run_end(rc, outcome) }
    }

    /// The handle every runtime call takes: this machine, under the runtime
    /// that opened it.
    fn abi(&self) -> crate::sys::BarylRef {
        crate::sys::BarylRef {
            ctx: self.ctx,
            descriptor: self.core.descriptor,
        }
    }
}

impl Drop for Baryl {
    fn drop(&mut self) {
        // SAFETY: the ctx one `open` answered, closed exactly once -- `Baryl` is
        // not `Copy`, and nothing else holds it.
        unsafe { (self.core.close)(self.abi()) };
    }
}

/// Everything one [`Baryl::open`] is told besides the image itself.
///
/// A builder: start from `Options::default()` and chain the parts you care
/// about. The defaults are a restore (no machine config), `<image>.state` for
/// artifacts, log level 0, seed 0, and no components.
///
/// Nothing here is retained past the open — the runtime reads it during the
/// call — so these `Options` may be dropped the moment
/// [`Baryl::open`] returns.
///
/// # Examples
///
/// ```ignore
/// // Boot a disk with one component and a fixed seed.
/// let options = Options::default()
///     .machine(Some(cfg))
///     .seed(0xfeed)
///     .log_level(LevelFilter::Debug)
///     .state_dir(Some(Path::new("./run")))?
///     .components(&[(PathBuf::from("./libhello.so"), vec!["--who=world".into()])])?;
///
/// // Restore a checkpoint and read it: no machine, no components.
/// let inspect = Options::default();
/// ```
#[derive(Default)]
pub struct Options {
    machine: Option<Box<MachineConfig>>,
    state_dir: Option<CString>,
    log_level: c_int,
    seed: u64,
    /// Owns every string `rows` points at; `rows` is the array the ABI reads.
    owned: Vec<OwnedComponent>,
    rows: Vec<crate::sys::BarylComponent>,
}

impl Options {
    /// The machine to boot.
    ///
    /// `None` — the default — means restore, which uses the config the
    /// checkpoint carries. Passing one alongside a checkpoint image is not how
    /// you change a restored machine's shape.
    pub fn machine(mut self, machine: Option<MachineConfig>) -> Options {
        self.machine = machine.map(Box::new);
        self
    }

    /// Where this run writes its logs, checkpoints and crash files.
    ///
    /// `None` — the default — puts them in `<image>.state`.
    ///
    /// # Errors
    ///
    /// `path` is not UTF-8 or holds an interior NUL.
    pub fn state_dir(mut self, path: Option<&Path>) -> anyhow::Result<Options> {
        self.state_dir = path.map(cstr).transpose()?;
        Ok(self)
    }

    /// How loud every library in the run is. `LevelFilter::Off` by default.
    ///
    /// Each library files its own `<state_dir>/<name>.log` at this level.
    pub fn log_level(mut self, level: LevelFilter) -> Options {
        self.log_level = level as c_int;
        self
    }

    /// This run's entropy, and the whole of what makes it reproducible.
    ///
    /// Every random stream any subsystem draws from descends from this one
    /// word, so two runs of one image with the same seed take the same path and
    /// find the same crash. 0 is a seed like any other, not "pick one for me".
    pub fn seed(mut self, seed: u64) -> Options {
        self.seed = seed;
        self
    }

    /// The components to load, each with the argv its own parser will read.
    ///
    /// Replaces any previous list rather than adding to it.
    ///
    /// # Errors
    ///
    /// A path is not UTF-8, or a path or argument holds an interior NUL.
    pub fn components(mut self, components: &[(PathBuf, Vec<String>)]) -> anyhow::Result<Options> {
        self.owned = components
            .iter()
            .map(OwnedComponent::new)
            .collect::<anyhow::Result<_>>()?;
        self.rows = self.owned.iter().map(OwnedComponent::as_abi).collect();
        Ok(self)
    }

    /// Borrows `self` for the length of one call; nothing in it is retained.
    fn as_abi(&self) -> crate::sys::BarylOptions {
        crate::sys::BarylOptions {
            machine: self
                .machine
                .as_deref()
                .map_or(std::ptr::null(), |m| std::ptr::from_ref(m).cast()),
            components: self.rows.as_ptr(),
            ncomponents: self.rows.len() as u32,
            state_dir: or_null(&self.state_dir),
            log_level: self.log_level,
            seed: self.seed,
        }
    }
}

/// One component's owned strings, plus the row the ABI reads them through.
struct OwnedComponent {
    path: CString,
    argv: Vec<CString>,
    argv_ptrs: Vec<*const c_char>,
}

impl OwnedComponent {
    fn new((path, argv): &(PathBuf, Vec<String>)) -> anyhow::Result<OwnedComponent> {
        let path = cstr(path)?;
        let argv: Vec<CString> = argv
            .iter()
            .map(|s| CString::new(s.as_str()))
            .collect::<Result<_, _>>()
            .context("a component argument contains an interior NUL")?;
        let argv_ptrs: Vec<*const c_char> = argv.iter().map(|a| a.as_ptr()).collect();
        Ok(OwnedComponent {
            path: path,
            argv: argv,
            argv_ptrs: argv_ptrs,
        })
    }

    /// Borrows the strings above; every pointer stays live while `self` does.
    fn as_abi(&self) -> crate::sys::BarylComponent {
        crate::sys::BarylComponent {
            path: self.path.as_ptr(),
            argv: self.argv_ptrs.as_ptr(),
            argc: self.argv.len() as u32,
        }
    }
}

/// The runtime's own reason out of the buffer it filled; `None` when it left
/// none.
fn open_error_message_read(err: &[u8]) -> Option<String> {
    let end = err.iter().position(|b| *b == 0).unwrap_or(err.len());
    (end != 0).then(|| String::from_utf8_lossy(&err[..end]).into_owned())
}

/// `None` becomes NULL, which is how "take the documented default" is spelled.
fn or_null(s: &Option<CString>) -> *const c_char {
    s.as_ref().map_or(std::ptr::null(), |s| s.as_ptr())
}

/// `outcome` is written only on `rc == 0`, so it must not be read on anything
/// else.
///
/// # Safety
/// `outcome` must have been handed to the call that produced `rc`.
unsafe fn run_end(
    rc: c_int,
    outcome: MaybeUninit<crate::sys::BarylOutcome>,
) -> anyhow::Result<RunEnd> {
    // The runtime logs the actual reason, so point at that rather than
    // restating one this side never saw.
    anyhow::ensure!(rc == 0, "the run did not complete; the reason is in the run's log");
    // SAFETY: rc == 0, so the core wrote a complete `BarylOutcome`.
    Ok(unsafe { RunEnd::from_raw(outcome.assume_init_ref()) })
}

/// A path as the C string the runtime takes; an interior NUL is not a path
/// anything can open.
fn cstr(path: &Path) -> anyhow::Result<CString> {
    let s = path
        .to_str()
        .with_context(|| format!("path {} is not UTF-8", path.display()))?;
    CString::new(s).with_context(|| format!("path {} contains an interior NUL", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `BARYL_EXIT_COMPONENT` restates a generated value; pin the two together.
    #[test]
    fn kind_values_match_the_header() {
        assert_eq!(BARYL_EXIT_COMPONENT, crate::sys::BarylExitKind_BARYL_EXIT_COMPONENT);
        assert_ne!(BARYL_EXIT_COMPONENT, crate::sys::BarylExitKind_BARYL_EXIT_ENGINE);
    }

    /// A layout disagreement here shifts fields silently rather than failing to
    /// link.
    #[test]
    fn outcome_layout_matches_the_static_assert() {
        assert_eq!(size_of::<crate::sys::BarylOutcome>(), 0x10);
    }

    #[test]
    fn engine_and_component_ends_are_distinguished() {
        let engine = crate::sys::BarylOutcome {
            kind: crate::sys::BarylExitKind_BARYL_EXIT_ENGINE,
            code: 3,
            message: std::ptr::null(),
        };
        // SAFETY: locally built, null message.
        assert_eq!(unsafe { RunEnd::from_raw(&engine) }, RunEnd::Engine { code: 3 });

        let component = crate::sys::BarylOutcome {
            kind: BARYL_EXIT_COMPONENT,
            code: 0,
            message: c"took the checkpoint".as_ptr(),
        };
        // SAFETY: locally built; the message is a 'static CStr.
        assert_eq!(
            unsafe { RunEnd::from_raw(&component) },
            RunEnd::Component {
                code: 0,
                message: Some("took the checkpoint".into())
            }
        );
    }

    /// An unknown kind must not cost the caller the status it does understand.
    #[test]
    fn unknown_kind_degrades_to_an_engine_exit() {
        let future = crate::sys::BarylOutcome {
            kind: 99,
            code: 7,
            message: std::ptr::null(),
        };
        // SAFETY: locally built, null message.
        assert_eq!(unsafe { RunEnd::from_raw(&future) }, RunEnd::Engine { code: 7 });
    }

    /// POSIX truncation, and the unmasked status still available beside it.
    #[test]
    fn exit_status_is_the_low_byte() {
        assert_eq!(RunEnd::Engine { code: 0 }.exit_status(), 0);
        assert_eq!(RunEnd::Engine { code: 3 }.exit_status(), 3);
        assert_eq!(RunEnd::Engine { code: 255 }.exit_status(), 255);
        assert_eq!(RunEnd::Engine { code: -1 }.exit_status(), 255);
        assert_eq!(RunEnd::Engine { code: 256 }.exit_status(), 0);
        // The unmasked status stays available for callers that want it.
        assert_eq!(RunEnd::Engine { code: -1 }.code(), -1);
    }
}