hermit-detcore 0.5.0

Detcore: the deterministic scheduler and syscall determinization core of the Hermit execution 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
495
496
497
498
499
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! Which system-wide `/proc` names exist at each `--proc` level.
//!
//! A system-wide or `/proc/sys` name exists only if this table lists it, or
//! lists a name below it; so does a name in a process's directory
//! (`/proc/<pid>`, `/proc/self`) or a thread's (`/proc/<pid>/task/<tid>`,
//! `/proc/thread-self`). Every other name is ENOENT and missing from
//! listings, on every backend. Still not decided here, so still answered by
//! the kernel or the KVM executor: whether a process or thread directory
//! exists, the entries of `fd`, `fdinfo`, `ns` and `net`, what the `cwd`,
//! `root` and `exe` links reach, and the few names Hermit's own tests and
//! tools still need the kernel to answer ([`PROCESS_KERNEL`]). The table is the checklist in the
//! dev-hermit design note `ai_docs/proc-virtualization-design.md` (section
//! 5): its V and F entries, split into the two levels of its section 1b.

use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::Component;
use std::path::Path;

use detcore_model::config::ProcLevel;

/// The names at the `minimal` level, relative to `/proc`. Each directory on
/// the way to a name exists too.
const MINIMAL: &[&str] = &[
    "cmdline",
    "cpuinfo",
    "filesystems",
    "loadavg",
    "meminfo",
    "modules",
    "mounts",
    "net",
    "stat",
    "sys/kernel/cap_last_cap",
    "sys/kernel/domainname",
    "sys/kernel/hostname",
    "sys/kernel/osrelease",
    "sys/kernel/ostype",
    "sys/kernel/overflowgid",
    "sys/kernel/overflowuid",
    "sys/kernel/pid_max",
    "sys/kernel/random/boot_id",
    "sys/kernel/random/uuid",
    "sys/kernel/version",
    "sys/vm/max_map_count",
    "sys/vm/mmap_min_addr",
    "sys/vm/overcommit_memory",
    "uptime",
    "version",
];

/// The names `standard` adds. `sys/net/core/somaxconn` and
/// `sys/net/ipv4/ip_local_port_range` are still the kernel's: they are per
/// network namespace, and Detcore's port allocator reads the host's range,
/// so the two change together (design note, slice B2a).
///
/// `sys/crypto/fips_enabled`, planned for `standard`, is not here yet: its
/// directory `sys/crypto` exists only on a kernel built with it (not on
/// every development host's), and a file in a directory the guest cannot
/// see or list is not one view. It comes with Detcore's own directory nodes (slice B3a's
/// placeholder directories). Until then it is ENOENT on every host, which
/// is what a host without the directory answers.
const STANDARD: &[&str] = &[
    "buddyinfo",
    "cgroups",
    "diskstats",
    "driver/rtc",
    "interrupts",
    "key-users",
    "locks",
    "pressure/cpu",
    "pressure/io",
    "pressure/memory",
    "schedstat",
    "softirqs",
    "swaps",
    "sys/fs/aio-max-nr",
    "sys/fs/aio-nr",
    "sys/fs/dentry-state",
    "sys/fs/file-max",
    "sys/fs/file-nr",
    "sys/fs/inode-nr",
    "sys/fs/inode-state",
    "sys/fs/pipe-max-size",
    "sys/kernel/pty/nr",
    "sys/kernel/random/entropy_avail",
    "sys/net/core/somaxconn",
    "sys/net/ipv4/ip_local_port_range",
    "tty/drivers",
    "vmstat",
    "zoneinfo",
];

/// The names in a process's directory at the `minimal` level. A thread's
/// directory has the same names, except that Linux gives it no `task` (and
/// gives `children` only to it), which the kernel then refuses itself.
const PROCESS_MINIMAL: &[&str] = &[
    "auxv",
    "cgroup",
    "cmdline",
    "comm",
    "cwd",
    "environ",
    "exe",
    "fd",
    "fdinfo",
    "maps",
    "mountinfo",
    "mounts",
    "net",
    "ns",
    "root",
    "smaps",
    "stat",
    "statm",
    "status",
    "task",
];

/// The names `standard` adds to a process's or a thread's directory.
const PROCESS_STANDARD: &[&str] = &[
    "arch_status",
    "children",
    "io",
    "numa_maps",
    "sched",
    "schedstat",
    "smaps_rollup",
    "timerslack_ns",
];

/// The names in a process's directory below which this table decides
/// nothing: links that leave `/proc` (`cwd`, `root`, `exe`), the directories
/// whose entries are a process's descriptors (`fd`, `fdinfo`), and `ns` and
/// `net`, whose entries are not decided yet (design note, slices B3a and B3b).
const PROCESS_UNDECIDED_BELOW: &[&str] = &["cwd", "exe", "fd", "fdinfo", "net", "ns", "root"];

/// The names in a process's directory that the checklist omits but that
/// stay the kernel's for now, because something Hermit runs needs the
/// kernel's answer and Detcore does not serve one yet:
/// - `mem`: Detcore's guard on writes through it, and its test
///   (`verify_claim_names_its_limit`), rr's suite and debuggers;
/// - `uid_map`: the DBT isolation test reads it in the guest
///   (`run_dbt_binds_in_a_user_namespace_of_its_own`);
/// - `gid_map`, `setgroups`: kept with `uid_map`, the files a user-namespace
///   setup writes together, until Detcore models user namespaces. Their
///   writers in this repository run before Hermit or stop at Detcore's
///   refusal of `unshare` before writing, so nothing intercepted needs them
///   yet (https://github.com/rrnewton/hermit/issues/4263).
const PROCESS_KERNEL: &[&str] = &["gid_map", "mem", "setgroups", "uid_map"];

/// What the table says about a path under `/proc`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProcfsName {
    /// A per-process name, or one reached through a link the table does not
    /// follow: not decided here.
    Undecided,
    /// A name that exists from this level up.
    From(ProcLevel),
    /// A name in no level.
    Omitted,
}

impl ProcfsName {
    /// Whether the name is absent at `level`.
    pub(crate) fn absent_at(self, level: ProcLevel) -> bool {
        match self {
            Self::Undecided => false,
            Self::From(from) => from > level,
            Self::Omitted => true,
        }
    }
}

/// The level from which the procfs name `path` exists, for an absolute path
/// with no `..` component; `None` for a path outside `/proc`. `path` is the
/// spelling the guest gave, so a link elsewhere into `/proc` is not followed.
pub(crate) fn procfs_name(path: &Path) -> Option<ProcfsName> {
    let mut components = path.components().filter(|c| *c != Component::CurDir);
    if components.next() != Some(Component::RootDir) {
        return None;
    }
    match components.next() {
        Some(Component::Normal(name)) if name == "proc" => {}
        _ => return None,
    }
    let mut names = Vec::new();
    for component in components {
        match component {
            Component::Normal(name) => names.push(name.as_bytes()),
            // A `..` is the kernel's to resolve (see the callers).
            _ => return Some(ProcfsName::Undecided),
        }
    }
    let Some(first) = names.first() else {
        return Some(ProcfsName::From(ProcLevel::Minimal));
    };
    if *first == b"self" || *first == b"thread-self" || first.iter().all(u8::is_ascii_digit) {
        return Some(process_name(&names[1..]));
    }
    // Below the `net` and `mounts` links is the process's own directory.
    if names.len() > 1 && (*first == b"net" || *first == b"mounts") {
        return Some(ProcfsName::Undecided);
    }
    // The name, a directory on the way to it, or a name below a file (which
    // the kernel refuses with ENOTDIR, as Linux does).
    let listed = |table: &[&str]| {
        table.iter().any(|entry| {
            names
                .iter()
                .zip(entry.split('/'))
                .all(|(name, part)| *name == part.as_bytes())
        })
    };
    Some(if listed(MINIMAL) {
        ProcfsName::From(ProcLevel::Minimal)
    } else if listed(STANDARD) {
        ProcfsName::From(ProcLevel::Standard)
    } else {
        ProcfsName::Omitted
    })
}

/// What the table says about the names below a process's or a thread's
/// directory.
fn process_name(names: &[&[u8]]) -> ProcfsName {
    let Some((first, rest)) = names.split_first() else {
        // Whether the process or thread exists is the kernel's.
        return ProcfsName::Undecided;
    };
    let is = |table: &[&str]| table.iter().any(|entry| entry.as_bytes() == *first);
    if *first == b"task" {
        return match rest.split_first() {
            None => ProcfsName::From(ProcLevel::Minimal),
            // A thread's directory and the names below it.
            Some((tid, below)) if tid.iter().all(u8::is_ascii_digit) => process_name(below),
            // `task` holds only threads.
            Some(_) => ProcfsName::Omitted,
        };
    }
    if (!rest.is_empty() && is(PROCESS_UNDECIDED_BELOW)) || is(PROCESS_KERNEL) {
        return ProcfsName::Undecided;
    }
    // A name below a file stays the file's (the kernel's ENOTDIR).
    if is(PROCESS_MINIMAL) {
        ProcfsName::From(ProcLevel::Minimal)
    } else if is(PROCESS_STANDARD) {
        ProcfsName::From(ProcLevel::Standard)
    } else {
        ProcfsName::Omitted
    }
}

/// The names the table gives the system-wide directory `/proc/<names>` at
/// `level` (the root for no names), each with its `d_type`, in the table's
/// order; `None` when the table holds no directory there. A name with names
/// below it is a directory; the root's `mounts` and `net` are links into the
/// caller's own directory.
pub(crate) fn system_entries(names: &[&[u8]], level: ProcLevel) -> Option<Vec<(Vec<u8>, u8)>> {
    let tables: &[&[&str]] = match level {
        ProcLevel::Minimal => &[MINIMAL],
        ProcLevel::Standard => &[MINIMAL, STANDARD],
    };
    let mut entries: Vec<(Vec<u8>, u8)> = Vec::new();
    let mut found = names.is_empty();
    for entry in tables.iter().flat_map(|table| table.iter()) {
        let mut parts = entry.split('/');
        if !names
            .iter()
            .all(|name| parts.next().is_some_and(|part| part.as_bytes() == *name))
        {
            continue;
        }
        let Some(child) = parts.next() else {
            // `names` is this entry itself, a file.
            return None;
        };
        found = true;
        let ty = if parts.next().is_some() {
            libc::DT_DIR
        } else if names.is_empty() && (child == "mounts" || child == "net") {
            libc::DT_LNK
        } else {
            libc::DT_REG
        };
        match entries
            .iter_mut()
            .find(|(name, _)| name == child.as_bytes())
        {
            Some(existing) if ty == libc::DT_DIR => existing.1 = ty,
            Some(_) => {}
            None => entries.push((child.as_bytes().to_vec(), ty)),
        }
    }
    found.then_some(entries)
}

/// The names in a process's directory, or a thread's (`thread`), at
/// `level`, each with its `d_type`: the level's names and the kernel's
/// ([`PROCESS_KERNEL`]), less `task` and `timerslack_ns` in a thread's
/// directory and `children` in a process's, as on Linux
/// (`tgid_base_stuff`, `tid_base_stuff`).
pub(crate) fn process_entries(thread: bool, level: ProcLevel) -> Vec<(&'static str, u8)> {
    let mut names: Vec<&'static str> = PROCESS_MINIMAL.to_vec();
    if level >= ProcLevel::Standard {
        names.extend_from_slice(PROCESS_STANDARD);
    }
    names.extend_from_slice(PROCESS_KERNEL);
    names
        .into_iter()
        .filter(|name| match *name {
            "task" | "timerslack_ns" => !thread,
            "children" => thread,
            _ => true,
        })
        .map(|name| {
            let ty = match name {
                "fd" | "fdinfo" | "net" | "ns" | "task" => libc::DT_DIR,
                "cwd" | "exe" | "root" => libc::DT_LNK,
                _ => libc::DT_REG,
            };
            (name, ty)
        })
        .collect()
}

/// Whether the entry `name` of the directory at the canonical path
/// `directory` is absent at `level`.
pub(crate) fn absent_entry(directory: &Path, name: &[u8], level: ProcLevel) -> bool {
    if name == b"." || name == b".." {
        return false;
    }
    procfs_name(&directory.join(OsStr::from_bytes(name)))
        .is_some_and(|entry| entry.absent_at(level))
}

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

    fn name(path: &str) -> Option<ProcfsName> {
        procfs_name(Path::new(path))
    }

    #[test]
    fn levels_follow_the_checklist() {
        use ProcLevel::*;
        use ProcfsName::*;
        for (path, expected) in [
            ("/proc", From(Minimal)),
            ("/proc/", From(Minimal)),
            ("/proc/version", From(Minimal)),
            ("/proc/./version", From(Minimal)),
            ("/proc/sys", From(Minimal)),
            ("/proc/sys/kernel", From(Minimal)),
            ("/proc/sys/kernel/random", From(Minimal)),
            ("/proc/sys/kernel/random/uuid", From(Minimal)),
            ("/proc/sys/fs", From(Standard)),
            ("/proc/sys/fs/file-nr", From(Standard)),
            ("/proc/sys/kernel/random/entropy_avail", From(Standard)),
            ("/proc/sys/net", From(Standard)),
            ("/proc/interrupts", From(Standard)),
            ("/proc/tty", From(Standard)),
            ("/proc/tty/drivers", From(Standard)),
            ("/proc/version/x", From(Minimal)),
            ("/proc/kallsyms", Omitted),
            ("/proc/kcore", Omitted),
            ("/proc/sysvipc", Omitted),
            ("/proc/sysvipc/shm", Omitted),
            ("/proc/slabinfo", Omitted),
            ("/proc/bus/pci/devices", Omitted),
            ("/proc/tty/ldiscs", Omitted),
            ("/proc/sys/kernel/core_pattern", Omitted),
            ("/proc/sys/kernel/ngroups_max", Omitted),
            ("/proc/sys/kernel/random/poolsize", Omitted),
            ("/proc/sys/fs/binfmt_misc", Omitted),
            ("/proc/sys/crypto/fips_enabled", Omitted),
            ("/proc/sys/net/ipv4/tcp_rmem", Omitted),
            ("/proc/versionx", Omitted),
            ("/proc/self", Undecided),
            ("/proc/thread-self", Undecided),
            ("/proc/1", Undecided),
            ("/proc/1/stat", From(Minimal)),
            ("/proc/self/status", From(Minimal)),
            ("/proc/thread-self/status", From(Minimal)),
            ("/proc/self/task", From(Minimal)),
            ("/proc/self/task/7", Undecided),
            ("/proc/self/task/7/comm", From(Minimal)),
            ("/proc/self/task/7/children", From(Standard)),
            ("/proc/self/task/x", Omitted),
            ("/proc/self/io", From(Standard)),
            ("/proc/1/timerslack_ns", From(Standard)),
            ("/proc/self/limits", Omitted),
            ("/proc/self/mem", Undecided),
            ("/proc/1/task/1/mem", Undecided),
            ("/proc/thread-self/wchan", Omitted),
            ("/proc/self/uid_map", Undecided),
            ("/proc/self/setgroups", Undecided),
            ("/proc/self/oom_score_adj", Omitted),
            ("/proc/self/loginuid", Omitted),
            ("/proc/1/task/1/attr/current", Omitted),
            ("/proc/self/map_files", Omitted),
            ("/proc/self/status/x", From(Minimal)),
            ("/proc/self/fd", From(Minimal)),
            ("/proc/self/fd/3", Undecided),
            ("/proc/self/fdinfo/3", Undecided),
            ("/proc/self/ns/pid", Undecided),
            ("/proc/self/net/tcp", Undecided),
            ("/proc/self/root/proc/kallsyms", Undecided),
            ("/proc/self/cwd/x", Undecided),
            ("/proc/net/tcp", Undecided),
            ("/proc/mounts/x", Undecided),
            ("/proc/self/../kallsyms", Undecided),
        ] {
            assert_eq!(name(path), Some(expected), "{path}");
        }
        for path in [
            "/",
            "/procx/version",
            "/sys/kernel",
            "proc/version",
            "/tmp/proc/kcore",
        ] {
            assert_eq!(name(path), None, "{path}");
        }
        // A name that is not UTF-8 is in no level.
        assert_eq!(
            procfs_name(Path::new(OsStr::from_bytes(b"/proc/\xff"))),
            Some(Omitted)
        );
    }

    #[test]
    fn each_level_contains_the_one_before() {
        let interrupts = name("/proc/interrupts").unwrap();
        assert!(interrupts.absent_at(ProcLevel::Minimal));
        assert!(!interrupts.absent_at(ProcLevel::Standard));
        let version = name("/proc/version").unwrap();
        assert!(!version.absent_at(ProcLevel::Minimal));
        assert!(!version.absent_at(ProcLevel::Standard));
        let kallsyms = name("/proc/kallsyms").unwrap();
        assert!(kallsyms.absent_at(ProcLevel::Minimal));
        assert!(kallsyms.absent_at(ProcLevel::Standard));
        // Every rendered or fixed file is in a level.
        for path in super::super::fixed::FixedProcfsFile::ALL
            .iter()
            .map(|file| file.path())
        {
            assert!(
                !procfs_name(path).unwrap().absent_at(ProcLevel::Standard),
                "{path:?}"
            );
        }
    }

    #[test]
    fn listings_leave_out_what_lookups_refuse() {
        let proc = Path::new("/proc");
        let level = ProcLevel::Standard;
        assert!(absent_entry(proc, b"kallsyms", level));
        assert!(!absent_entry(proc, b"interrupts", level));
        assert!(absent_entry(proc, b"interrupts", ProcLevel::Minimal));
        assert!(!absent_entry(proc, b"self", level));
        assert!(!absent_entry(proc, b"42", level));
        assert!(!absent_entry(proc, b".", level));
        assert!(!absent_entry(proc, b"..", level));
        assert!(absent_entry(Path::new("/proc/sys"), b"crypto", level));
        assert!(!absent_entry(Path::new("/proc/sys"), b"fs", level));
        assert!(absent_entry(
            Path::new("/proc/sys"),
            b"fs",
            ProcLevel::Minimal
        ));
        assert!(absent_entry(
            Path::new("/proc/sys/kernel"),
            b"core_pattern",
            level
        ));
        assert!(absent_entry(Path::new("/proc/self"), b"limits", level));
        assert!(!absent_entry(Path::new("/proc/42"), b"status", level));
        assert!(absent_entry(
            Path::new("/proc/42"),
            b"io",
            ProcLevel::Minimal
        ));
        assert!(!absent_entry(Path::new("/proc/42/task"), b"43", level));
        assert!(!absent_entry(Path::new("/proc/42/fd"), b"3", level));
        assert!(!absent_entry(Path::new("/tmp"), b"kallsyms", level));
        assert!(absent_entry(proc, b"\xff", level));
    }
}