detcore_model/config.rs
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! Detcore configuration and widely used types.
10
11use std::collections::BTreeSet;
12use std::ffi::OsString;
13use std::fmt;
14use std::num::NonZeroU64;
15use std::path::PathBuf;
16use std::str::FromStr;
17use std::time::SystemTime;
18
19use chrono::DateTime;
20use chrono::Utc;
21use clap::Parser;
22use reverie::BackendCapabilities;
23use serde::Deserialize;
24use serde::Serialize;
25
26use crate::happens_before::HappensBeforeProgram;
27use crate::network_trace::NetworkTraceConfig;
28use crate::pid::DetTid;
29use crate::schedule::SigWrapper;
30use crate::time::NANOS_PER_RCB;
31use crate::time::NANOS_PER_SCHED;
32use crate::time::RcbTimeMultiplier;
33
34const fn default_backend_capabilities() -> BackendCapabilities {
35 DEFAULT_BACKEND_CAPABILITIES
36}
37
38/// The capabilities a [`Config`] has before the host prepares it for the
39/// backend that runs it: ptrace's, the backend Detcore's own tests use, except
40/// that four facts stay off (`supports_blocked_wait_signal_interruption`,
41/// `delivers_preemption_timer_events`, `runs_guest_code_between_injections`,
42/// `reports_sigreturns`). Until the first three became backend capabilities
43/// they were `Config` fields that only the host set, for the backend it had
44/// selected, and were false otherwise; a configuration nobody prepared keeps
45/// that behaviour. A configuration nobody prepared cannot know that sigreturns
46/// are reported, so the fourth is off too (the DBT runtime's standalone
47/// fallback starts from these). `reports_kernel_child_exit_signals` keeps
48/// ptrace's value, as `reports_child_exit_publication` does: it took over the
49/// child-exit ledger's gates from that field, so such a configuration behaves
50/// as before. The host copies the running backend's own answer over all of
51/// these before a run.
52pub const DEFAULT_BACKEND_CAPABILITIES: BackendCapabilities = {
53 let mut backend = BackendCapabilities::PTRACE;
54 backend.supports_blocked_wait_signal_interruption = false;
55 backend.delivers_preemption_timer_events = false;
56 backend.runs_guest_code_between_injections = false;
57 backend.reports_sigreturns = false;
58 backend
59};
60
61/// One mount row whose kernel-private root must be replaced before it becomes
62/// guest-visible.
63///
64/// The CLI populates this only after proving, with held file descriptors in the
65/// completed mount namespace, that the mount is one Hermit created. The raw
66/// mount ID is namespace-local, so these entries are valid only for the one
67/// container run whose configuration carries them.
68#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
69pub struct MountInfoRootRewrite {
70 /// Mount ID read from the held target descriptor's `/proc/self/fdinfo`.
71 pub raw_mount_id: u64,
72 /// Stable guest-visible replacement for the row's root field.
73 pub deterministic_root: Vec<u8>,
74 /// Exact encoded kernel root prefix used for descendant mount rows.
75 ///
76 /// This is present only for a proven private `/tmp`. Mounts installed below
77 /// that directory before it is bound over guest `/tmp` otherwise expose the
78 /// randomly named backing directory in mountinfo field 5.
79 #[serde(default)]
80 pub raw_root_prefix: Option<Vec<u8>>,
81 /// Guest-visible prefix replacing `raw_root_prefix`.
82 #[serde(default)]
83 pub deterministic_root_prefix: Option<Vec<u8>>,
84 /// Exact encoded host path prefix used for descendant mountpoints.
85 #[serde(default)]
86 pub raw_mountpoint_prefix: Option<Vec<u8>>,
87 /// Guest-visible prefix replacing `raw_mountpoint_prefix`.
88 #[serde(default)]
89 pub deterministic_mountpoint_prefix: Option<Vec<u8>>,
90}
91
92/// The seccomp state of the thread that starts the guest, which the guest
93/// inherits: every filter that thread has applies to the guest's system calls,
94/// and to the calls Detcore injects into it. Detcore refuses the guest's own
95/// `seccomp(2)` and `prctl(PR_SET_SECCOMP)`, so these and the backend's own
96/// filter are the only filters a guest has.
97#[derive(
98 Clone,
99 Copy,
100 Debug,
101 Default,
102 PartialEq,
103 Eq,
104 Hash,
105 Serialize,
106 Deserialize
107)]
108pub enum InheritedSeccomp {
109 /// Not measured, or not readable, so a filter may apply.
110 #[default]
111 Unknown,
112 /// No seccomp (`Seccomp: 0`).
113 Disabled,
114 /// Strict mode (`Seccomp: 1`).
115 Strict,
116 /// Filter mode (`Seccomp: 2`), with the number of filters when
117 /// `Seccomp_filters` gives it.
118 Filter(Option<u32>),
119}
120
121impl InheritedSeccomp {
122 /// The state of the calling thread, which a process it forks inherits,
123 /// from `/proc/thread-self/status`.
124 pub fn measure() -> Self {
125 std::fs::read_to_string("/proc/thread-self/status")
126 .map_or(Self::Unknown, |status| Self::parse(&status))
127 }
128
129 /// The state the `Seccomp` and `Seccomp_filters` lines of the text of a
130 /// `/proc/<pid>/status` file give. A missing or unexpected `Seccomp` line
131 /// is unknown.
132 pub fn parse(status: &str) -> Self {
133 let field = |name: &str| {
134 status
135 .lines()
136 .find_map(|line| line.strip_prefix(name)?.strip_prefix(':'))
137 .map(str::trim)
138 };
139 match field("Seccomp") {
140 Some("0") => Self::Disabled,
141 Some("1") => Self::Strict,
142 Some("2") => Self::Filter(field("Seccomp_filters").and_then(|n| n.parse().ok())),
143 _ => Self::Unknown,
144 }
145 }
146}
147
148/// What a launch tells Detcore about the guest's first image
149/// ([`Config::launch_image`]).
150#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
151pub struct LaunchImage {
152 /// The first image as its `/proc/self/exe` link names it: the program's
153 /// canonical path, or for a script the interpreter it runs
154 /// (`detcore::exec_record::ExecRecord::resolve`). `None` where the launch
155 /// could not resolve it, which leaves the first image without a record.
156 pub exe: Option<PathBuf>,
157 /// The image the kernel exec'd in the guest's place, where a launcher
158 /// loads the guest itself (SaBRe's loader, DynamoRIO's library), so that
159 /// the kernel's `/proc/<pid>/exe` names the launcher. Detcore keeps a recorded image
160 /// only where the kernel's link names that image or this one
161 /// (`detcore::exec_record`). `None` where the kernel execs the guest.
162 pub launcher: Option<PathBuf>,
163}
164
165/// One mount namespace, as `DetConfig::mountinfo_mount_namespace` names it.
166///
167/// `id` is the kernel's 64-bit namespace ID (`ioctl(NS_GET_MNTNS_ID)` on a
168/// `/proc/<pid>/ns/mnt` descriptor, on kernels that have it). Linux draws it from
169/// one counter that only increases (`__ns_tree_gen_id` in kernel/nstree.c), so
170/// it names one namespace for the life of the boot. `device` and `inode` are
171/// the descriptor's nsfs device and inode numbers, which Linux recycles once a
172/// namespace is gone; they alone identify the namespace only on a kernel
173/// without the ioctl, where `id` is `None`.
174#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
175pub struct MountNamespaceIdentity {
176 /// The kernel's namespace ID, where the kernel reports one.
177 pub id: Option<u64>,
178 /// The nsfs device number of the namespace's descriptor.
179 pub device: u64,
180 /// The nsfs inode number of the namespace's descriptor.
181 pub inode: u64,
182}
183
184/// Configuration options for detcore.
185#[derive(Debug, Serialize, Deserialize, Clone, Parser)]
186pub struct Config {
187 /// Disable virtual/logical time. Note that virtual time is required for virtual metadata.
188 #[clap(long = "no-virtualize-time", action = clap::ArgAction::SetFalse)]
189 pub virtualize_time: bool,
190
191 /// Disable virtual cpuid
192 #[clap(long = "no-virtualize-cpuid", action = clap::ArgAction::SetFalse)]
193 pub virtualize_cpuid: bool,
194
195 /// The CPU the guest sees: x86-64-v2 (the default) or x86-64-v3, offered
196 /// only on qualified ptrace hosts. The long help states what the
197 /// qualification leaves uncovered.
198 #[clap(long, value_enum, default_value_t, long_help = crate::cpu_profile::CPU_PROFILE_LONG_HELP)]
199 #[serde(default)]
200 pub cpu_profile: crate::cpu_profile::CpuProfile,
201
202 /// The host facts a v3 guest's leaf 0xD and xstate answers come from, set
203 /// by the CLI after the host qualifies; `None` under v2. Neither profile
204 /// field enters the legacy form the DBT runtime reads (DBT refuses v3).
205 #[clap(skip)]
206 #[serde(default)]
207 pub cpu_profile_host: Option<crate::cpu_profile::HostXstate>,
208
209 // AUTONOMOUS-BOT-IMPLEMENTED
210 // TODO-HUMAN-REVIEW(PR-845): Review in-process backend descriptor discovery.
211 // AUTONOMOUS-BOT-IMPLEMENTED
212 // TODO-HUMAN-REVIEW(PR-845): Review host-clock futex deadline detection.
213 // AUTONOMOUS-BOT-IMPLEMENTED
214 // TODO-HUMAN-REVIEW(PR-845): Review backend-owned syscall-clobber determinism.
215 // AUTONOMOUS-BOT-IMPLEMENTED
216 // TODO-HUMAN-REVIEW(PR-845): Review backend-local exit-group RPC cancellation.
217 // AUTONOMOUS-BOT-IMPLEMENTED
218 // TODO-HUMAN-REVIEW(PR-1058): Review process-signal identity translation.
219 // AUTONOMOUS-BOT-IMPLEMENTED
220 // TODO-HUMAN-REVIEW(PR-1125): Review backend-owned capability-control prctls.
221 // AUTONOMOUS-BOT-IMPLEMENTED
222 // TODO-HUMAN-REVIEW(PR-1152): Review deferred vfork child registration.
223 /// How the execution backend runs the guest, as the backend reports it
224 /// through Reverie (`reverie::Backend::capabilities`).
225 ///
226 /// Detcore reads facts about the backend only from here, never from the
227 /// backend's name, so a new backend is modelled correctly by reporting its
228 /// capabilities. The host copies the running backend's answer into this
229 /// field before the run starts. The default,
230 /// [`DEFAULT_BACKEND_CAPABILITIES`], describes a ptrace-hosted guest, the
231 /// backend Detcore's own tests use, with the three host-set facts and
232 /// `reports_sigreturns` off.
233 ///
234 /// JSON that the guest can see is written by [`to_legacy_backend_json`],
235 /// which carries this field as the separate keys used before it existed;
236 /// [`from_legacy_backend_json`] reads them back.
237 #[serde(default = "default_backend_capabilities")]
238 #[clap(skip = DEFAULT_BACKEND_CAPABILITIES)]
239 pub backend: BackendCapabilities,
240
241 /// The guest may start with a terminal: one of the launcher's standard
242 /// descriptors is a terminal, the launcher has a controlling terminal that
243 /// the guest inherits with its session, or the launcher could not tell.
244 /// Such a terminal makes Linux send signals at moments the host sets:
245 /// SIGHUP and SIGCONT when it hangs up, SIGINT, SIGQUIT and SIGTSTP for its
246 /// interrupt, quit and suspend characters, SIGWINCH when it is resized, and
247 /// SIGTTIN and SIGTTOU for a background process group's reads and writes.
248 /// The guest makes no traced call that arms them, so where Detcore treats
249 /// such signals as reaching the guest from the host (the legacy bundled
250 /// condition
251 /// [`crate::bundled_signal_facts::host_timed_signal_sources_are_physical`])
252 /// the scheduler records all eight as host-timed for every process before the
253 /// guest's first instruction, and no gated wait ends for them
254 /// (<https://github.com/rrnewton/hermit/issues/3146>).
255 ///
256 /// The host sets it while it prepares the backend configuration. It has no
257 /// legacy key: [`to_legacy_backend_json`] leaves it out and
258 /// [`from_legacy_backend_json`] reads it back as false.
259 #[serde(default)]
260 #[clap(skip)]
261 pub guest_may_inherit_a_terminal: bool,
262
263 /// The forwarding policy (`detcore::detlog::ForwardPolicy::encode`) every
264 /// in-guest Tool must forward its DETLOG records with, on the socket Hermit
265 /// passed it (`hermit run --verify` under SaBRe or in-guest LiteInst);
266 /// `None` when no socket is passed.
267 ///
268 /// The host sets it, not a flag, and every Tool image receives it in the
269 /// configuration handshake on its coordinator connection, which guest code
270 /// cannot change. A Tool image whose forwarder is missing, or forwards by
271 /// another policy (guest code that ran first changed its private
272 /// forwarding variables, so some records would be dropped before they are
273 /// counted), then reports every forwarded-record count as UNCOUNTED
274 /// (`detcore::detlog::require_forwarding`), so verification refuses the run
275 /// instead of accepting a log without those records. Like
276 /// `guest_may_inherit_a_terminal`, it has no legacy key.
277 #[serde(default)]
278 #[clap(skip)]
279 pub in_guest_detlog_forward_policy: Option<String>,
280
281 /// Whether every in-guest Tool image must run with syscall site patching
282 /// off and collect its exit statistics (`hermit --backend=in-guest-trap`).
283 ///
284 /// The host sets it, not a flag, and every Tool image receives it in the
285 /// configuration handshake on its coordinator connection, which guest code
286 /// cannot change. The in-guest LiteInst runtime takes both settings from
287 /// the guest environment, which guest code running before or during its
288 /// installation could change, so once installation returns a Tool image
289 /// compares the settings the runtime actually captured with this one and
290 /// refuses to run the program when they differ
291 /// (`detcore::in_guest_site_patching`). Like
292 /// `in_guest_detlog_forward_policy`, it has no legacy key.
293 #[serde(default)]
294 #[clap(skip)]
295 pub in_guest_site_patching_off: bool,
296
297 /// The guest's first image, as its `/proc/self/exe` link names it, and
298 /// the image the kernel exec'd in its place where a launcher loads the
299 /// guest ([`LaunchImage`]). Detcore answers that link from it until the
300 /// guest's next exec, which Detcore resolves itself. `None` leaves the
301 /// first image's link to the kernel.
302 ///
303 /// The host sets it, not a flag, from the program it launches. Like
304 /// `in_guest_detlog_forward_policy` it has no legacy key, so DBT's
305 /// legacy form never carries it.
306 #[serde(default)]
307 #[clap(skip)]
308 pub launch_image: Option<LaunchImage>,
309
310 /// The seccomp state the guest inherits from the thread that starts it
311 /// ([`InheritedSeccomp`]). The caller that starts the guest states it, as
312 /// only the caller knows the filters its launch installs, such as those of
313 /// a `pre_exec` callback; `hermit run` measures it. Not stated, it is
314 /// unknown. Nothing reads it. Whether a guest may start under an inherited
315 /// filter is decided by the `hermit` command, before it starts the guest,
316 /// from its own reading of `/proc/self/status` (`host_seccomp::admit`).
317 /// It has no legacy key:
318 /// [`to_legacy_backend_json`] leaves it out and
319 /// [`from_legacy_backend_json`] reads it back as unknown.
320 #[serde(default)]
321 #[clap(skip)]
322 pub inherited_seccomp: InheritedSeccomp,
323
324 /// Epoch of the logical time.
325 ///
326 /// This is the datetime from which all time and date modtimes begin and
327 /// monotonically increase. It is in RFC3339 format such as `2026-01-01T00:00:00Z`.
328 /// The stable default here is for library callers and wire-format fixtures;
329 /// the `hermit run` and `hermit oci run` commands replace an omitted CLI
330 /// default with one host wall-clock sample taken before backend dispatch.
331 #[clap(
332 long,
333 env = "HERMIT_EPOCH",
334 value_name = "YYYY-MM-DDThh:mm:ssZ",
335 default_value = DEFAULT_EPOCH_STR,
336 hide_default_value = true
337 )]
338 pub epoch: DateTime<Utc>,
339
340 /// Use this number to seed the PRNG randomness for both RNG and scheduler.
341 /// This acts as a global fallback in case either `sched_seed` or `rng-seed`
342 /// are not explicitly specified
343 #[clap(
344 long = "seed",
345 env = "HERMIT_PRNG",
346 default_value = "0",
347 value_name = "uint64"
348 )]
349 pub seed: u64,
350
351 /// Use this number to seed the PRNG that supplies randomness to the guest.
352 /// This supplies guest system calls that expose randomness, as well as
353 /// the `/dev/[u]random` files. It does not affect the `rdrand` instruction,
354 /// which is disabled in the guest.
355 #[clap(long, value_name = "uint64")]
356 pub rng_seed: Option<u64>,
357
358 /// Seeds the PRNG which drives syscall response fuzzing (i.e. chaotically exercising syscall
359 /// nondeterminism). Like other seeds, this is initialized from the `--seed` if not
360 /// specifically provided.
361 #[clap(long, value_name = "uint64")]
362 pub fuzz_seed: Option<u64>,
363
364 /// Logical clock multiplier. Values above one make time appear to go faster within the sandbox.
365 #[clap(long, value_name = "float")]
366 pub clock_multiplier: Option<f64>,
367
368 /// Disable substitution of virtual (deterministic) file metadata in lieu
369 /// of the real metadata returned by `stat`/`statx`. This also preserves raw
370 /// mountinfo device numbers so those interfaces continue to agree. Raw
371 /// device values are host/filesystem observations and are not promised to
372 /// reproduce across machines. Virtual metadata implies `virtualize_time`.
373 #[clap(long = "no-virtualize-metadata", action = clap::ArgAction::SetFalse)]
374 pub virtualize_metadata: bool,
375
376 /// Proven Hermit-owned mount roots to hide from `/proc/*/mountinfo`.
377 ///
378 /// This is runtime provenance, not a user option. `serde(default)` keeps
379 /// older serialized configurations compatible and makes backends which do
380 /// not use the common container setup explicitly receive no rewrite claim.
381 #[serde(default)]
382 #[clap(skip)]
383 pub mountinfo_root_rewrites: Vec<MountInfoRootRewrite>,
384
385 /// Backend-proven pairs of (`mountinfo` raw device, `stat`/`statx` raw device).
386 ///
387 /// A backend may synthesize mountinfo independently from its pathname
388 /// metadata implementation. These pairs state that the two raw numbers
389 /// describe the same filesystem, so Detcore can feed both surfaces through
390 /// one device identity. The pairs are runtime provenance, not a user
391 /// option; an absent pair must never be inferred from numeric coincidence.
392 #[serde(default)]
393 #[clap(skip)]
394 pub mountinfo_device_rewrites: Vec<(u64, u64)>,
395
396 /// Recording/container namespace mount IDs in canonical row order.
397 ///
398 /// Detcore validates every `/proc/*/mountinfo` view against this order.
399 /// It does not number mount IDs by position in it; see
400 /// `mount_id_assignment_order`. It is runtime provenance rather than a
401 /// user option; replay retains recording-time raw IDs because its read
402 /// events contain recording-time kernel bytes.
403 #[serde(default)]
404 #[clap(skip)]
405 pub mountinfo_mount_ids: Vec<u64>,
406
407 /// Whether `mountinfo_mount_ids` is an exact producer-owned snapshot.
408 ///
409 /// The distinction matters for an empty mountinfo file: an absent snapshot
410 /// asks Detcore to observe the completed guest namespace, while a captured
411 /// empty snapshot must remain empty during replay.
412 #[serde(default)]
413 #[clap(skip)]
414 pub mountinfo_mount_ids_captured: bool,
415
416 /// The mount namespace `mountinfo_mount_ids` was captured in
417 /// ([`MountNamespaceIdentity`]). A backend that checks its provenance
418 /// (KVM) requires its own namespace to be this one, instead of
419 /// recapturing the namespace's rows: a host can detach a copied host mount
420 /// from a private namespace at any time by removing that mount's
421 /// directory, so two captures of one namespace need not agree. `None`
422 /// when nothing was captured, and in recordings. Runtime provenance, not a
423 /// user option.
424 #[serde(default)]
425 #[clap(skip)]
426 pub mountinfo_mount_namespace: Option<MountNamespaceIdentity>,
427
428 /// Raw mount IDs in the order Detcore numbered them for the guest.
429 ///
430 /// Detcore numbers a raw mount ID when the guest first observes it through
431 /// `/proc/*/mountinfo` or `/proc/*/fdinfo/*`; `mountinfo_mount_ids` only
432 /// validates mountinfo views. A live run starts empty. Recording persists
433 /// the completed order so replay gives every raw ID its recorded number
434 /// rather than deriving one from its fresh namespace or launch descriptor
435 /// shape.
436 #[serde(default)]
437 #[clap(skip)]
438 pub mount_id_assignment_order: Vec<u64>,
439
440 /// The guest's container mount table, which Detcore renders as every
441 /// spelling of `/proc/<pid>/mountinfo` and `/proc/<pid>/mounts` on every
442 /// backend (`crate::container_mounts`,
443 /// <https://github.com/rrnewton/hermit/issues/4213>). hermit-cli builds it
444 /// once, in the completed container namespace before the guest starts,
445 /// or, for `--no-namespace` and a library caller on KVM that built no
446 /// container, in the namespace the guest runs in (its launch mounts and
447 /// base mountpoints); a recording carries it, so its replay renders the
448 /// recorded table. `None` (a library caller on a backend other than KVM,
449 /// whose command may chroot or mount where Hermit cannot see, and every
450 /// older configuration) leaves both files to the kernel, sanitized as
451 /// before. Runtime provenance, not a user option.
452 #[serde(default)]
453 #[clap(skip)]
454 pub container_mount_table: Option<crate::container_mounts::ContainerMountTable>,
455
456 /// Sequentialize thread execution deterministically.
457 #[clap(long)]
458 pub sequentialize_threads: bool,
459
460 /// Choose which side of an ordinary fork/clone runs first after the child is registered.
461 /// Random choices are deterministic under `--sched-seed`.
462 #[serde(default)]
463 #[clap(long, default_value = "child", value_name = "child|parent|random")]
464 pub runs_post_fork: RunsPostFork,
465
466 /// Use the optimized partial syscall subscription set instead of intercepting every syscall.
467 /// This permits unlisted syscalls to bypass Detcore and therefore weakens deterministic
468 /// accounting; leave it disabled for fail-closed execution.
469 #[serde(default)]
470 #[clap(long)]
471 pub passthru_opt: bool,
472
473 /// In chaos mode, uses much cheaper approximate preemption timers. Only makes sense
474 /// when recording preemptions for later (precise) replay.
475 #[clap(long)]
476 pub imprecise_timers: bool,
477
478 /// Turn off Detcore's own copy of each guest thread's signal dispositions
479 /// and masks (A5, docs/SIGNAL_STATE_CHECK.md). The copy is on by default
480 /// where it can run (ptrace with serialized threads): it is checked
481 /// against the kernel, and decisions A5 converted read it in place of the
482 /// kernel's `/proc` view. With it off, those decisions read `/proc`, and
483 /// no handler return is reported. A recorded schedule states the setting
484 /// it ran under, and replaying it under the other setting is refused.
485 #[serde(default = "signal_state_copy_default")]
486 #[clap(long = "no-signal-state-copy", action = clap::ArgAction::SetFalse)]
487 pub signal_state_copy: bool,
488
489 /// Whether a signal delivery that the kernel contradicts, where Detcore's
490 /// copy and the kernel are both certain (A5 step 3.2), ends the run as an
491 /// internal failure (`HERMIT_INTERNAL_FAILURE class=signal-delivery-check`)
492 /// rather than being logged as a divergence that drops the copy. It is a
493 /// Detcore defect either way. `hermit run --strict` sets it; nothing else
494 /// does, and it changes nothing while the copy matches the kernel.
495 ///
496 /// The host sets it. It has no legacy key: [`to_legacy_backend_json`]
497 /// leaves it out and [`from_legacy_backend_json`] reads it back as false.
498 #[serde(default)]
499 #[clap(skip)]
500 pub signal_delivery_check_fatal: bool,
501
502 /// Schedule threads chaotically.
503 ///
504 /// The behavior of this flag is subject to change. Current behavior is to randomize thread
505 /// priorities at every logical timeslice. Other randomization strategies are possible with
506 /// `--sched-heuristic`.
507 ///
508 /// Thread scheduling remains deterministic, determined by the random seed.
509 #[clap(long)]
510 pub chaos: bool,
511
512 /// Uses the `--fuzz-seed` to generate randomness and fuzz nondeterminism in the futex semantics.
513 #[clap(long)]
514 pub fuzz_futexes: bool,
515
516 /// Targeted chaos: bias scheduling toward known concurrency race patterns
517 /// instead of exploring interleavings uniformly. At the scheduler's existing
518 /// nondeterminism points it uses `--fuzz-seed` to (a) deliver a
519 /// process-directed signal to a randomly chosen thread in the group (signal
520 /// timing races) and (b) randomize the requeue position of a force-unblocked
521 /// thread (lock-ordering / wakeup races). Only takes effect with `--chaos`;
522 /// like the rest of chaos mode it remains reproducible under a fixed seed.
523 #[clap(long)]
524 pub chaos_target_races: bool,
525
526 // AUTONOMOUS-BOT-IMPLEMENTED
527 // TODO-HUMAN-REVIEW(PR-1149)
528 // TODO-HUMAN-REVIEW(PR-1151)
529 /// Reproducible per-thread slowdown factors for chaos mode. A factor greater
530 /// than one makes each RCB consume proportionally more virtual time, while a
531 /// factor below one makes it consume less. Thus scheduling deadlines and the
532 /// guest-visible virtual clock describe the same slowed execution rather than
533 /// applying an out-of-band scheduling bias. The factor is a pure function of
534 /// scheduler seed, stable deterministic thread id, and chaos epoch. A fixed
535 /// seed therefore reproduces both timing and interleavings.
536 #[clap(long)]
537 pub chaos_per_thread_slowdown: bool,
538
539 // AUTONOMOUS-BOT-IMPLEMENTED
540 // TODO-HUMAN-REVIEW(PR-1149)
541 // TODO-HUMAN-REVIEW(PR-1151)
542 /// Maximum ratio between the slowest and fastest per-thread slowdown factor
543 /// for `--chaos-per-thread-slowdown`. Each thread's factor is drawn
544 /// log-uniformly from `[1/R, R]` where `R` is this value. Must fit the Q32
545 /// virtual-time representation and be `>= 1.0`; `1.0` disables the spread.
546 #[clap(long, default_value = "10.0", value_name = "double")]
547 pub chaos_slowdown_max_factor: f64,
548
549 // AUTONOMOUS-BOT-IMPLEMENTED
550 // TODO-HUMAN-REVIEW(PR-1151)
551 /// Length of a deterministic slowdown epoch in elapsed per-thread logical
552 /// nanoseconds. At the first scheduler commit at or after each boundary the
553 /// factor is redrawn as `factor(seed, stable_dettid, epoch)`. This is never
554 /// wall time. `0` means one epoch for the entire run, making constant slowdown
555 /// the single-epoch special case. Recorded preemption artifacts carry exact
556 /// epoch transitions and factors for replay. Inert without chaos slowdown.
557 #[clap(long, default_value = "0", value_name = "nanos")]
558 pub chaos_epoch_length_ns: u64,
559
560 /// Record the timing of preemption events for future replay or experimentation.
561 /// This is only useful in chaos modes.
562 #[clap(long)]
563 pub record_preemptions: bool,
564
565 /// File to write the record of preemptions (in JSON). Implies `--record-preemptions`.
566 #[clap(long, value_name = "filepath")]
567 pub record_preemptions_to: Option<PathBuf>,
568
569 /// JSON file to read recorded preemptions from. When `--chaos` mode is activated, these
570 /// recorded preemption points take the place of randomized scheduling decisions.
571 #[clap(long, value_name = "filepath", conflicts_with = "replay_schedule_from")]
572 pub replay_preemptions_from: Option<PathBuf>,
573
574 /// File to read recorded schedule trace from. This execution will replay the schedule verbatim
575 /// from the file.
576 #[clap(
577 long,
578 value_name = "filepath",
579 conflicts_with = "replay_preemptions_from"
580 )]
581 pub replay_schedule_from: Option<PathBuf>,
582
583 /// If we run out of events while replaying a schedule, treat that as a fatal event and panic,
584 /// rather than continuing execution.
585 #[clap(long)]
586 pub replay_exhausted_panic: bool,
587
588 /// When playing a schedule trace from disk, bail out on the first time we desynchronize from
589 /// the event sequence specified in the trace.
590 #[clap(long)]
591 pub die_on_desync: bool,
592
593 /// Given schedule events traced on recording or replaying, print the stack trace at the moment
594 /// after the Nth event in the trace. Optionally, provide an output file into which the stack
595 /// trace will be printed, otherwise it goes to stderr.
596 #[clap(long,
597 short = 's',
598 value_name = "index[,path]",
599 value_parser = parse_index_with_path)]
600 pub stacktrace_event: Vec<(u64, Option<PathBuf>)>,
601
602 /// Internal feature used to signal the guest with SIGINT at every `--stacktrace-event`, this is
603 /// in-lieu of using hermit's internal stacktrace printing facility, to instead have an external
604 /// debugger handle it. Accepts either signal names or numbers.
605 #[clap(long, value_name = "signame")]
606 pub stacktrace_signal: Option<SigWrapper>,
607
608 /// **Deprecated:** Print a stacktrace each time the program is preempted. Only makes sense in `--chaos` mode
609 /// and typically goes with preemption recording/replaying.
610 #[clap(long)]
611 pub preemption_stacktrace: bool,
612
613 /// File to write preemption stacktraces to. Implies `--preemption-stacktrace`. If a
614 /// log file is not specified, preemption stacktraces are printed to stderr by default.
615 #[clap(long, value_name = "filepath")]
616 pub preemption_stacktrace_log_file: Option<PathBuf>,
617
618 /// Enable deterministic IO by reassuring we always read/write the maximum possible bytes
619 /// from IO syscalls. There might be cases that read/write syscalls return less bytes than
620 /// requests. Detcore, makes an effort to request additional bytes until we reach the ones
621 /// requested or EOF.
622 #[clap(long)]
623 pub deterministic_io: bool,
624
625 /// Fail immediately on unsupported syscalls instead of forwarding them.
626 /// Ordinary `hermit run` enables this policy; compatibility requires the
627 /// explicit `--allow-unsupported-syscalls` opt-out.
628 #[clap(long)]
629 pub panic_on_unsupported_syscalls: bool,
630
631 // AUTONOMOUS-BOT-IMPLEMENTED
632 // TODO-HUMAN-REVIEW(PR-644): Review backend-safe fail-closed termination.
633 /// Return a typed Tool error instead of unwinding through a backend callback.
634 #[serde(default)]
635 #[clap(skip)]
636 pub exit_on_unsupported_syscall: bool,
637 // AUTONOMOUS-BOT-IMPLEMENTED
638 // TODO-HUMAN-REVIEW(PR-644): Review process-tree shutdown for ptrace fail-closed mode.
639 /// Terminate the whole tracer when an unsupported syscall is observed.
640 #[serde(default)]
641 #[clap(skip)]
642 pub shutdown_on_unsupported_syscall: bool,
643
644 // AUTONOMOUS-BOT-IMPLEMENTED
645 // TODO-HUMAN-REVIEW(PR-644): Review the internal cross-process warning report channel.
646 /// Internal inherited file descriptor used to aggregate unsupported syscalls.
647 #[serde(default)]
648 #[clap(skip)]
649 pub unsupported_syscall_report_fd: Option<i32>,
650
651 /// Panic when a precise PMU timer overshoots its expected RCB target instead of logging an
652 /// error and continuing through normal timer handling. Intended for Detcore debugging.
653 #[serde(default)]
654 #[clap(
655 long = "panic-on-rbc-overshoot",
656 visible_alias = "panic-on-rcb-overshoot"
657 )]
658 pub panic_on_rcb_overshoot: bool,
659
660 /// **Internal:** Set to `true` if we're inside a UTS namespace.
661 // FIXME: This can be removed once spawn_fn-based tests support namespaces.
662 #[clap(skip)]
663 pub has_uts_namespace: bool,
664
665 /// **Internal:** Path to the replay data folder.
666 #[clap(skip)]
667 pub replay_data: Option<PathBuf>,
668
669 /// Kill all remaining tasks iff daemons are the only ones left.
670 /// Disabled by default.
671 #[clap(long)]
672 pub kill_daemons: bool,
673
674 /// Start gdbserver on `gdbserver_port` for remote debugging
675 /// Disabled by default.
676 #[clap(long)]
677 pub gdbserver: bool,
678 /// port gdbserver listening on
679 #[clap(
680 long,
681 value_name = "uint16",
682 help = "Port gdbserver listening on",
683 default_value = "1234"
684 )]
685 pub gdbserver_port: u16,
686
687 /// Configure the maximum time a guest thread may run without returning to Detcore. This is
688 /// measured in virtual nanoseconds and enforced with retired conditional branch (RCB)
689 /// counting. `--preemption-timeout` is retained as a deprecated alias.
690 ///
691 /// Set this to `disabled` or `0` to disable PMU-backed preemption. Positive values must be at
692 /// least one RCB (10 virtual nanoseconds at the default clock multiplier) and require
693 /// user-space hardware performance counters.
694 #[serde(alias = "preemption_timeout")]
695 #[clap(
696 long,
697 visible_alias = "preemption-timeout",
698 value_name = "uint64|'disabled'",
699 default_value = "200000000",
700 value_parser = parse_timeslice)]
701 pub max_timeslice: MaybeTimeslice,
702
703 /// Target logical timeslice, in virtual nanoseconds, checked at syscall boundaries and the
704 /// other points where the guest returns control to Detcore: signals, timer events, and
705 /// trapped `rdtsc` and `cpuid` instructions unless `--target-timeslice-syscalls-only` is given.
706 /// This avoids PMU preemption for workloads that enter the kernel frequently. Omit this option
707 /// to use only `--max-timeslice`.
708 #[serde(default)]
709 #[clap(long, value_name = "virtual-nanoseconds")]
710 pub target_timeslice: Option<NonZeroU64>,
711
712 /// Do not end an expired `--target-timeslice` at a trapped `rdtsc` or `cpuid` while a PMU
713 /// maximum (`--max-timeslice`) is armed; end it at the next syscall, signal or timer event,
714 /// or at the PMU maximum. A trapped instruction can sit inside a user-space spinlock: QEMU's
715 /// multi-threaded TCG reads the host TSC while holding its `vm_clock_lock`, and a vCPU that
716 /// yields there leaves the other vCPUs spinning for whole PMU slices. Has no effect without
717 /// `--target-timeslice`, or with `--max-timeslice disabled`, where the trap is the only way
718 /// out of a busy-wait on the TSC.
719 #[serde(default)]
720 #[clap(long, requires = "target_timeslice")]
721 pub target_timeslice_syscalls_only: bool,
722
723 /// After a `FUTEX_WAKE` or `FUTEX_WAKE_BITSET` that woke at least one waiter, move the waker to
724 /// the back of its priority band and have it yield, so that woken threads of its priority run
725 /// before it continues. Without
726 /// it, a thread that releases a contended lock keeps running until its slice ends and can
727 /// re-take the lock many times before the waiter is scheduled: QEMU's multi-threaded TCG vCPUs
728 /// starve its main loop of the big QEMU lock this way. The yield is a scheduler turn of its
729 /// own: the waker's timeslice keeps its deadlines. Each extra thread switch is charged
730 /// scheduler time that the guest can observe (see `--scheduler-turn-cost`), and costs wall
731 /// time: a two-vCPU QEMU boot took 5% to 48% longer with it. The waker keeps its priority, so a
732 /// woken thread of a lower priority still runs after it; `--chaos` redraws threads' priorities
733 /// from their chaos PRNG, which can put a woken thread in a lower band; and a random
734 /// `--sched-heuristic` does not select first in, first out. In those cases a woken thread is not
735 /// guaranteed to run first. Applies to the precise futex mode while threads are sequentialized,
736 /// on the ptrace backend (including e9patch preprocessing, which runs on it); replay applies it
737 /// as the recorded run did.
738 #[serde(default)]
739 #[clap(long)]
740 pub futex_wake_yields: bool,
741
742 /// Hand the turn to a thread polling a pipe or FIFO once another thread's action has readied it
743 /// (<https://github.com/rrnewton/hermit/issues/4380>), within this many virtual nanoseconds of
744 /// the acting thread's own time. A write that moves bytes into a scheduler-managed pipe, a read
745 /// that makes room in one, an explicit close of one end, or an open of a FIFO end readies the
746 /// threads polling for that: the scheduler restores their priority, and once the acting
747 /// thread's time is this far past its first readying action, at the next point where it
748 /// returns to Detcore (a syscall's entry or exit, or a signal or trapped instruction), it is
749 /// moved behind them and yields, so they run before it continues. A poller is restored to its
750 /// own priority and the acting thread moves only within its band, so where `--chaos` has drawn
751 /// a poller a lower priority than the acting thread, that poller still runs after it and is
752 /// not guaranteed to run first. `0` hands off at the end of
753 /// the readying syscall. Unset (the default), nothing changes: a polled thread whose peer is
754 /// ready waits for the acting thread's slice to end, as before. Each hand-off adds at least two
755 /// charged scheduler turns that the guest can observe as time (see `--scheduler-turn-cost`).
756 /// A thread that computes after its write without returning to Detcore delays the hand-off
757 /// until it next does, or its slice ends; an implicit close (an exit, an `O_CLOEXEC` exec)
758 /// readies nothing; and an end reopened by path (`/proc/self/fd/N`, as `/dev/fd/N` process
759 /// substitution does) is a channel of its own, so the other side's actions do not ready it. Recorded
760 /// schedules store the value, and a replay under another value is refused. Refused without
761 /// sequentialized threads, on the DBT, KVM and LiteInst backends, with `--namespace-only`,
762 /// `--strace-only` or `--debug-externalize-sockets`, and
763 /// under a `--sched-heuristic` that does not select by priority; never applied in record mode.
764 #[serde(default)]
765 #[clap(long, value_name = "nanos")]
766 pub pipe_wake_latency: Option<u64>,
767
768 /// Virtual nanoseconds that each committed scheduler turn adds to the global clock, before
769 /// `--clock-multiplier` (default 500000). The charge keeps time moving while threads take
770 /// turns without running. Every thread observes it as a jump in time across a thread switch,
771 /// so a guest that times short intervals while another thread runs, such as a QEMU guest
772 /// kernel calibrating its TSC against the emulated PIT, can see a gap far larger than any
773 /// work done. A smaller charge makes those jumps smaller; a finite poll or futex timeout then
774 /// takes more turns to expire. The charge, after the multiplier, must be between 1 and
775 /// 1000000000. If a charged turn would pass the end of representable virtual time, the run
776 /// stops with HERMIT_VIRTUAL_CLOCK_EXHAUSTED and exit status 125.
777 #[serde(default)]
778 #[clap(long, value_name = "virtual-nanoseconds")]
779 pub scheduler_turn_cost: Option<NonZeroU64>,
780
781 /// Shut down immediately upon SIGINT, rather than letting the guest handle it.
782 #[clap(long)]
783 pub sigint_instakill: bool,
784
785 /// Warn if binds are non-zero.
786 #[clap(long)]
787 pub warn_non_zero_binds: bool,
788
789 /// Apply a specialized scheduling heuristic which may help exercise certain bugs.
790 #[clap(long, default_value = "none", value_name = "str")]
791 // TODO: Rename this to scheduler_strategy?
792 pub sched_heuristic: SchedHeuristic,
793
794 /// Use this number to seed the PRNG that supplies randomness to the scheduler.
795 #[clap(long, env = "HERMIT_SCHED_SEED", value_name = "uint64")]
796 pub sched_seed: Option<u64>,
797
798 /// External network record or replay, set by `hermit run --record-networking`
799 /// or `--replay-networking`; `Off` otherwise, in which case Detcore never
800 /// consults it. Its perturbation seed has no fallback to `seed` or
801 /// `sched_seed`.
802 #[serde(default)]
803 #[clap(skip)]
804 pub network_trace: NetworkTraceConfig,
805
806 /// Configure the probability for the Sticky Random scheduler to stay in a thread.
807 /// For value 0.0, we are behaving like Random.
808 /// For value 1.0, we are behaving like a DFS, where the same thread is
809 /// always picked as long as it is available in the Run queue. After
810 /// this thread is exhausted, the next thread will be chosen randomly.
811 /// For value 0.5, we have a 50/50 chance to pick the same thread.
812 #[clap(long, default_value = "0.0", value_name = "double")]
813 pub sched_sticky_random_param: f64,
814
815 /// **Internal:** An internal flag for indicating to Detcore whether we are in `hermit record` or
816 /// `hermit replay` mode. This is necessary because there are DIFFERENT global
817 /// invariants in record mode (e.g. files dont exist). If we move to a chroot model
818 /// and reproduce more, recording less, then this flag should become obsolete.
819 #[clap(skip = false)]
820 pub recordreplay_modes: bool,
821
822 /// **Internal:** Set only by `hermit replay`, alongside `recordreplay_modes`. Replay serves
823 /// socket reads, writes, accepts and connects, and `poll`, `ppoll`, `select` and
824 /// `pselect6`, from the recording, so they cannot block. They still run as backgrounded
825 /// blocking I/O, as during recording, but Detcore's scheduler commits no other turn until
826 /// they finish. Otherwise the descriptor-table changes of different threads could
827 /// interleave differently from one replay to the next.
828 ///
829 /// It never enters the legacy form ([`to_legacy_backend_json`]), so the DBT runtime's
830 /// `HERMIT_DBT_DETCONFIG` in the guest's environment is unchanged by its introduction
831 /// and reads it as false. Record and replay run only on the ptrace backend.
832 #[serde(default)]
833 #[clap(skip = false)]
834 pub replaying: bool,
835
836 /// **Internal:** debugging option to stop execution after a specific scheduler commit, aka turn number
837 /// (non-negative integer). This only makes sense if `--sequentialize-threads` is specified, as the scheduler is otherwise not engaged.
838 #[clap(long, value_name = "turn_N")]
839 pub stop_after_turn: Option<u64>,
840
841 /// **Internal:** debugging option to stop execution after a scheduler loop iteration (non-negative integer).
842 /// This only makes sense if `--sequentialize-threads` is specified, as the scheduler is otherwise not engaged.
843 #[clap(long, value_name = "iter_N")]
844 pub stop_after_iter: Option<u64>,
845
846 /// **Internal:** Debugging option to treat all sockets as mysterious external, nondeterministic
847 /// entities, rather than container-internal and determinstically scheduled.
848 #[clap(long)]
849 pub debug_externalize_sockets: bool,
850
851 /// **Internal:** Debugging option to change how futexes are implemented, either precisely modeled
852 /// by hermit, by polling the kernel with non-blocking futex operations, or treated as external
853 /// (nondeterministic) operations which unblock at imprecise times.
854 #[clap(
855 long,
856 value_name = "precise|polling|external",
857 default_value = "precise"
858 )]
859 pub debug_futex_mode: BlockingMode,
860
861 /// Do not count the retired conditional branches (RCBs) of each thread towards its logical
862 /// time. Instead, count each checkin with the scheduler as a fixed increment to logical time.
863 /// Even when this option is set, HW RCB performance counters may still be enabled if a
864 /// max-timeslice is specified.
865 #[clap(long)]
866 pub no_rcb_time: bool,
867
868 /// An option to enable logging the hash of heap memory maps for the purpose of determinism checking
869 #[clap(long)]
870 pub detlog_heap: bool,
871
872 /// An option to enable logging the hash of stack memory maps for the purpose of determinism checking
873 ///
874 /// THIS HASH COVERS argv AND THE ENVIRONMENT, which the kernel places at the
875 /// top of the initial process stack. Two runs whose command lines differ by a
876 /// single character therefore produce different stack hashes from the first
877 /// sample, even when the command lines are the same LENGTH and every stack
878 /// address matches. Measured: equal-length-but-different argv diverged the
879 /// hash 14 records in, while byte-identical argv held it for 5023 records.
880 ///
881 /// Holding a run-directory name to a fixed WIDTH is a sufficient control when
882 /// only addresses matter, and is NOT sufficient here. Comparing two runs
883 /// under this flag requires byte-identical argv and environment; otherwise
884 /// the first divergence you find is your own input.
885 #[clap(long)]
886 pub detlog_stack: bool,
887
888 /// Log a hash of the guest REGISTER FILE at guest-logical-control points, for determinism
889 /// checking. stdout, the INFO log, the stack and the heap are all hashed today; the register
890 /// file is not, so two backends can differ in register state and every existing check still
891 /// reports parity.
892 ///
893 /// SAMPLED ONLY AT GUEST-LOGICAL-CONTROL POINTS -- see `Detcore::detlog_registers`. Registers
894 /// are NOT sampled inside a tool handler: a backend running its handler in-guest executes code
895 /// the ptrace reference never executes, so a difference there is correct behaviour, not a
896 /// determinism bug.
897 #[clap(long)]
898 pub detlog_regs: bool,
899
900 /// Log a hash of each syscall's OUTPUT BUFFER, taken at the syscall boundary from the
901 /// address and length in the syscall's own arguments.
902 ///
903 /// WHAT IT SEES THAT THE MAPPING HASHES DO NOT. `--detlog-heap` and `--detlog-stack` hash a
904 /// whole named mapping, so their coverage is decided by where the guest happened to ALLOCATE
905 /// a buffer. Measured, three runs per cell, same netlink exchange with only the receive
906 /// buffer's home changed: a `[stack]` buffer is missed by `--detlog-heap`, a `[heap]` buffer
907 /// is missed by `--detlog-stack`, and a BSS/static or anonymous-`mmap` buffer is missed by
908 /// BOTH even with both enabled. Anonymous `mmap` is where glibc puts any `malloc` above the
909 /// 128 KiB `M_MMAP_THRESHOLD`. Reading the extent out of the syscall arguments makes the
910 /// buffer's home irrelevant.
911 ///
912 /// WHY IT IS NOT REDUNDANT WITH `--verify`. A syscall whose buffer is a bare pointer in
913 /// Reverie prints the ADDRESS, not the contents, so a `recvmsg` returning a stable
914 /// `Ok(1468)` whose payload varies produces a character-identical record and `--verify`
915 /// reports `bitwise_parity: true`. 44.1% of the syscalls in a QEMU/Linux boot move bytes
916 /// through such a buffer.
917 ///
918 /// COST is proportional to bytes actually moved, NOT to syscall count or mapping size:
919 /// ~0.75 s per GB of guest I/O. A QEMU/Linux boot moves 139.1 MB through these buffers,
920 /// against the 10.9 TB `--detlog-heap` hashes over the same run.
921 ///
922 /// NAME IS PROVISIONAL: `io-buffers` is the owner's candidate and is not settled.
923 ///
924 /// ON BY DEFAULT. It was opt-in until 2026-08-24, and opt-in made the
925 /// determinism gate weaker than its name: with the hash absent, the netlink
926 /// `recvmsg` above compares equal and `--verify` reports success. A check
927 /// that must be requested is not a standard. The opt-out exists for the
928 /// deliberate case (bulk I/O where the cost matters and content parity is
929 /// not the question), not as the ordinary setting.
930 ///
931 /// COST OF THE DEFAULT, measured 2026-08-24 on a 316-core x86_64 Linux
932 /// build host: a typical small test guest pays about ONE MILLISECOND
933 /// (`/bin/true` 0.029s -> 0.030s, `/bin/ls` 0.041s -> 0.041s, 8 runs each).
934 /// 64 MiB through `cat` costs +0.07-0.10s in a RELEASE build, which is the
935 /// ~1.1-1.6 s/GB matching the figure quoted above. The same workload in a
936 /// DEBUG build costs +3.4s, roughly 50x more, because the hash loop is
937 /// unoptimized -- so a debug-built node moving tens of megabytes is the one
938 /// place the default is felt.
939 #[clap(long = "no-detlog-io-buffers", action = clap::ArgAction::SetFalse)]
940 pub detlog_io_buffers: bool,
941
942 /// Sampling cadence for `--detlog-regs`: hash every Nth guest-logical-control point.
943 ///
944 /// COST TIER. 1 (the default) is the FULL tier -- every control point hashed -- and is what a
945 /// short test should use. Measured cost at this scale is within run-to-run noise: /bin/true
946 /// (49 control points), `wc -l /etc/passwd` (135) and a 5-iteration shell loop (195) were
947 /// 0.04-0.07s with the flag on and the same with it off. A larger N is the SPOT-CHECK tier for
948 /// runs where full hashing is too expensive; it trades detection latency for cost, since a
949 /// divergence is only seen at the next sampled point. Every emitted line records the tier it
950 /// was produced under, so a cell can state which tier it met instead of leaving it implicit.
951 #[clap(long, default_value = "1", value_name = "uint64")]
952 pub detlog_regs_cadence: u64,
953
954 /// Configure a time offset (in seconds) between a container OS considered booted and a guest is executed
955 /// This primarily affects 'sysinfo' syscall's 'uptime' field reporting
956 #[clap(long, default_value = "120", value_name = "uint64")]
957 pub sysinfo_uptime_offset: u64,
958
959 /// Configure memory available for the container. Takes a number of bytes, or shorthand (e.g.
960 /// "1GB"). Right now this doesn't enforce an upper bound, but does affect the amount of memory
961 /// reported to the guest.
962 #[clap(long, default_value = "1GB", value_parser = try_parse_memory, value_name = "bytesize")]
963 pub memory: u64,
964
965 /// How much of `/proc` the guest sees. Every level is the same on every
966 /// backend and host. `minimal` (the default) shows a small set, modelled
967 /// on gVisor's; `standard` shows every system-wide name Detcore serves or
968 /// plans to serve. A system-wide or `/proc/sys` name outside the chosen level
969 /// does not exist: lookups give ENOENT and listings leave it out. So does
970 /// a name in a process's or a thread's directory, except a few that Hermit
971 /// still leaves to the kernel (`mem`, `uid_map`, `gid_map`, `setgroups`),
972 /// as are whether a process exists and the entries of its `fd`,
973 /// `fdinfo`, `ns` and `net`. A spelling through a symbolic link or `..` is
974 /// checked only when it opens a file.
975 #[serde(default)]
976 #[clap(
977 long = "proc",
978 default_value = "minimal",
979 value_name = "minimal|standard"
980 )]
981 pub proc_level: ProcLevel,
982
983 /// Configure extra interrupt points based on thread id and rcb counter. Detcore will raise a precise
984 /// timer for this RCB whenever it detects that current current thread timeslice intercects any of the
985 /// interrupt points specified
986 #[clap(long, value_name = "tid:rcbs", value_parser = try_parse_numbers_with_colon)]
987 pub interrupt_at: Vec<(DetTid, u64)>,
988
989 /// Resolved happens-before program: deterministic ordering edges between
990 /// anchored events (see `detcore_model::happens_before`). This is populated
991 /// programmatically by hermit-cli after loading and resolving a
992 /// `--happens-before` spec against the guest binary; it is not a direct CLI
993 /// flag and is not serialized (it is reconstructed from the spec file each
994 /// run, so `#[serde(skip)]` avoids requiring serde on `Sysno`-bearing
995 /// positions and keeps save-config output stable). The scheduler enforces
996 /// these edges only when `sequentialize_threads` is set.
997 #[serde(skip)]
998 #[clap(skip)]
999 pub happens_before: Option<HappensBeforeProgram>,
1000
1001 /// Whether Detcore records the host identity of each file the guest
1002 /// opens, sending each record to the global state, which writes the run's
1003 /// records to [`Self::host_input_log`] when the run ends (see
1004 /// [`crate::host_input`]). `hermit run --verify` sets it, so that a
1005 /// divergence caused by a host file replaced during a run can be named.
1006 /// The records are never part of the compared log. Serialized, so that it
1007 /// reaches the Detcore tool on every backend, including one that runs
1008 /// inside the guest and receives this `Config` over RPC; never a CLI flag.
1009 #[serde(default)]
1010 #[clap(skip)]
1011 pub record_host_inputs: bool,
1012
1013 /// Where the global state writes the run's host-input records, one
1014 /// [`crate::host_input::HostInputRecord`] JSON line each and a
1015 /// [`crate::host_input::HostInputLogEnd`] line, when the run ends.
1016 /// `hermit run --verify` sets a private file. A host path, read only by
1017 /// the global state, which every backend that hosts it builds from this
1018 /// `Config` in-process; so set programmatically, like `happens_before`,
1019 /// and never serialized.
1020 #[serde(skip)]
1021 #[clap(skip)]
1022 pub host_input_log: Option<PathBuf>,
1023
1024 /// A guest address range, `[start, end)`, holding code whose syscalls
1025 /// the backend lets through without Detcore seeing them, which the guest
1026 /// cannot otherwise use without faulting. With
1027 /// [`Self::record_host_inputs`] set, a guest call that may change the
1028 /// memory there (a fixed mapping over it, a protection or advice change
1029 /// or unmapping that covers it, an open of a process-memory file for
1030 /// writing) is reported as a change at `/`, so no host input change is
1031 /// named in that run (see [`crate::host_input`]). The backend that hosts
1032 /// Detcore in-process sets it, so set programmatically, like
1033 /// `happens_before`, and never serialized.
1034 #[serde(skip)]
1035 #[clap(skip)]
1036 pub untraced_code_range: Option<(u64, u64)>,
1037
1038 /// Opt-in capture of a core file for a guest thread killed by a signal
1039 /// whose default action dumps core; `None`, the default, writes nothing.
1040 /// A host path and host-side limits, read only by the global state at a
1041 /// fatal exit stop, so set programmatically, like `host_input_log`, and
1042 /// never serialized.
1043 #[serde(skip)]
1044 #[clap(skip)]
1045 pub fatal_core_capture: Option<FatalCoreCapture>,
1046}
1047
1048/// Where and how much [`Config::fatal_core_capture`] may write.
1049#[derive(Debug, Clone, PartialEq, Eq)]
1050pub struct FatalCoreCapture {
1051 /// Directory receiving the compressed cores. Its regular files, whoever
1052 /// wrote them, count against `max_total_bytes`.
1053 pub dir: PathBuf,
1054 /// Prefix of every file name this run writes, so the run can find and
1055 /// remove its own cores.
1056 pub file_prefix: String,
1057 /// Most bytes one compressed core may occupy.
1058 pub max_core_bytes: u64,
1059 /// Most bytes all regular files in `dir` may occupy together.
1060 pub max_total_bytes: u64,
1061 /// Longest one capture may take before it gives up.
1062 pub time_limit: std::time::Duration,
1063}
1064
1065fn try_parse_numbers_with_colon(from_str: &str) -> anyhow::Result<(DetTid, u64)> {
1066 if let Some((thread_id_str, time_str)) = from_str.split_once(':') {
1067 Ok((
1068 thread_id_str
1069 .parse::<DetTid>()
1070 .map_err(anyhow::Error::msg)?,
1071 time_str.parse::<u64>().map_err(anyhow::Error::msg)?,
1072 ))
1073 } else {
1074 anyhow::bail!(
1075 "unable to parse <thread_id>:<logical_time> from '{}'",
1076 from_str
1077 )
1078 }
1079}
1080
1081fn try_parse_memory(from_str: &str) -> anyhow::Result<u64> {
1082 <bytesize::ByteSize as FromStr>::from_str(from_str)
1083 .map(|res| res.as_u64())
1084 .map_err(anyhow::Error::msg)
1085}
1086
1087impl Config {
1088 /// This configuration with `change` applied to its backend capabilities.
1089 /// [`BackendCapabilities`] cannot be built field by field outside Reverie,
1090 /// so a caller that needs to adjust individual facts starts from the value
1091 /// already here.
1092 pub fn with_backend(mut self, change: impl FnOnce(&mut BackendCapabilities)) -> Self {
1093 change(&mut self.backend);
1094 self
1095 }
1096
1097 /// Whether the epoch is the stable library default omitted by `Display`.
1098 pub fn has_default_epoch(&self) -> bool {
1099 self.epoch == DEFAULT_EPOCH_STR.parse::<DateTime<Utc>>().unwrap()
1100 }
1101
1102 /// Replace the stable library/test default with the host wall clock captured
1103 /// by the outer `hermit run` invocation. The caller owns the single
1104 /// host-clock read boundary; all guest clock and metadata observations
1105 /// consume the resulting concrete epoch.
1106 pub fn capture_epoch_from_host_time(&mut self, now: SystemTime) {
1107 self.epoch = epoch_from_host_time(now);
1108 }
1109
1110 /// Smallest PMU-backed maximum representable by one RCB at this clock multiplier.
1111 pub fn minimum_max_timeslice_nanos(&self) -> u64 {
1112 let slowdown = if self.chaos && self.chaos_per_thread_slowdown {
1113 self.chaos_slowdown_max_factor
1114 } else {
1115 1.0
1116 };
1117 let multiplier = self.clock_multiplier.unwrap_or(1.0) * slowdown;
1118 ((NANOS_PER_RCB * multiplier).ceil() as u64).max(NANOS_PER_RCB as u64)
1119 }
1120
1121 /// Check invariants that must hold at every execution boundary without mutating the config.
1122 pub fn validate_invariants(&self) {
1123 assert!(self.sched_sticky_random_param >= 0.0);
1124 assert!(self.sched_sticky_random_param <= 1.0);
1125 // AUTONOMOUS-BOT-IMPLEMENTED
1126 // TODO-HUMAN-REVIEW(PR-1149)
1127 assert!(
1128 self.chaos_slowdown_max_factor.is_finite()
1129 && self.chaos_slowdown_max_factor >= 1.0
1130 && self.chaos_slowdown_max_factor <= RcbTimeMultiplier::MAX,
1131 "chaos_slowdown_max_factor must be finite and in [1.0, {}], got {}",
1132 RcbTimeMultiplier::MAX,
1133 self.chaos_slowdown_max_factor
1134 );
1135 if let Some(multiplier) = self.clock_multiplier {
1136 assert!(
1137 multiplier.is_finite() && multiplier > 0.0,
1138 "clock_multiplier must be finite and positive"
1139 );
1140 }
1141 let minimum_max_timeslice = self.minimum_max_timeslice_nanos();
1142 assert!(
1143 self.max_timeslice
1144 .is_none_or(|timeslice| u64::from(timeslice) >= minimum_max_timeslice),
1145 "max_timeslice must be at least one RCB ({} virtual nanoseconds)",
1146 minimum_max_timeslice
1147 );
1148 }
1149
1150 /// Sanity check the flags, and update any wherever flag B is implied by A.
1151 pub fn validate(&mut self) {
1152 self.validate_invariants();
1153
1154 // TODO(T124429978) Restore the eprintln! calls below to tracing::warn! when the tracing
1155 // subscriber is set up early enough for these warnings to print.
1156
1157 if self.record_preemptions_to.is_some() {
1158 self.record_preemptions = true;
1159 }
1160 // TODO: separate out recording flags: --record-preemptions vs --record-schedule-trace
1161 // if self.record_preemptions && !self.chaos {
1162 // tracing::warn!(
1163 // "Setting --record-preemptions when not in chaos mode doesn't do anything."
1164 // );
1165 // }
1166
1167 if self.replay_schedule_from.is_some() && self.replay_preemptions_from.is_some() {
1168 panic!("Cannot set both --replay-preemptions-from and --replay-schedule-from!!");
1169 }
1170
1171 if self.chaos {
1172 self.sequentialize_threads = true;
1173 }
1174
1175 if self.replay_preemptions_from.is_some() && self.imprecise_timers {
1176 eprintln!(
1177 "WARNING: Setting --imprecise timers with --replay-preemptions-from is probably not what you want. They won't replay precisely."
1178 );
1179 }
1180
1181 if self.stop_after_turn.is_some() && !self.sequentialize_threads {
1182 eprintln!(
1183 "WARNING: --stop-after-turn will have no effect if --no-sequentialize-threads is enabled"
1184 );
1185 self.stop_after_turn = None;
1186 }
1187 if self.stop_after_iter.is_some() && !self.sequentialize_threads {
1188 eprintln!(
1189 "WARNING: --stop-after-iter will have no effect if --no-sequentialize-threads is enabled"
1190 );
1191 self.stop_after_iter = None;
1192 }
1193
1194 if self.debug_externalize_sockets && !self.sequentialize_threads {
1195 eprintln!(
1196 "WARNING: --debug-externalize-sockets will have no effect if --no-sequentialize-threads is enabled"
1197 );
1198 self.debug_externalize_sockets = false;
1199 }
1200
1201 if !self.stacktrace_event.is_empty()
1202 && !self.record_preemptions
1203 && self.replay_schedule_from.is_none()
1204 {
1205 eprintln!(
1206 "WARNING: -s/--stacktrace-event has no effect if not recording/replaying events!"
1207 );
1208 }
1209
1210 if self.preemption_stacktrace_log_file.is_some() {
1211 self.preemption_stacktrace = true;
1212 }
1213 }
1214
1215 /// Whether configured preemption can use this backend's timer mechanism.
1216 ///
1217 /// This is independent of RCB accounting and does not certify a clock.
1218 pub fn use_preemption_timer(&self) -> bool {
1219 self.max_timeslice.is_some() && self.backend.delivers_preemption_timer_events
1220 }
1221
1222 /// Should we use RCB in computing logical time?
1223 ///
1224 /// The answer is NO either if `--no-rcb-time` is specified or if HW counters are disabled by
1225 /// setting `--max-timeslice=disabled`.
1226 pub fn use_rcb_time(&self) -> bool {
1227 self.max_timeslice.is_some() && !self.no_rcb_time
1228 }
1229
1230 /// Whether a `FUTEX_WAKE` that woke `woken` waiters makes the waker yield
1231 /// to them (`--futex-wake-yields`).
1232 ///
1233 /// A thread that releases a contended lock usually keeps running: the
1234 /// waiter it woke is queued behind it, and the waker can re-take the lock,
1235 /// uncontended, many times before that waiter runs.
1236 /// glibc and Rust mutexes both let a releasing thread barge back in, and on
1237 /// real hardware the woken thread wins on another CPU within the release
1238 /// window. Under sequentialized threads it never gets one, so QEMU's
1239 /// multi-threaded TCG vCPUs starved its main loop of the big QEMU lock for
1240 /// whole PMU slices at a time
1241 /// (<https://github.com/rrnewton/hermit/issues/3874>). When this holds, the
1242 /// scheduler moves the waker to the back of its priority band, and the
1243 /// waker takes a yield turn at the syscall's post-hook, so woken threads
1244 /// of its priority run before it continues (it keeps its band; `--chaos`
1245 /// can redraw priorities, and a random heuristic does not select first
1246 /// in, first out). The yield leaves the waker's timeslice alone.
1247 ///
1248 /// A thread switch is not free in virtual time: every scheduler decision
1249 /// is charged, so a policy that switches more often moves time that the
1250 /// guest observes. A QEMU guest kernel that calibrates its TSC against the
1251 /// emulated PIT failed that calibration with this policy, because the
1252 /// main loop now ran in the middle of it.
1253 ///
1254 /// The decision reads only the configuration and the wake's result, the
1255 /// number of waiters the scheduler took off the futex in the waker's turn,
1256 /// which is already deterministic. A wake that woke no one keeps the
1257 /// slice. Replay applies the policy exactly as the recorded run did: a
1258 /// preemption record holds slice ends but not this queue order, so the
1259 /// requeue and the yield must happen again for the replayed run to reach
1260 /// the same schedule. Because the yield consumes no slice end and draws
1261 /// nothing from the thread's chaos PRNG, making it again keeps the replay
1262 /// aligned with its record.
1263 pub fn yields_after_futex_wake(&self, woken: u64) -> bool {
1264 self.futex_wake_yields && woken > 0
1265 }
1266
1267 /// The virtual nanoseconds each committed scheduler turn adds to the
1268 /// global clock: `--scheduler-turn-cost` (default [`NANOS_PER_SCHED`])
1269 /// times `--clock-multiplier`, truncated as it always was. A configured
1270 /// cost must give a charge of at least one nanosecond, because the charge
1271 /// is what advances the clock through turns that run no guest code, such
1272 /// as the retries of a finite poll; a scaled charge of zero would leave
1273 /// such a timeout unable to expire. A configured cost, or its scaled
1274 /// charge, above [`MAX_SCHEDULER_TURN_COST`] is refused too, so that a
1275 /// configured charge never exceeds one second per turn.
1276 pub fn scheduler_turn_charge(&self) -> Result<u64, String> {
1277 let multiplier = self.clock_multiplier.unwrap_or(1.0);
1278 let Some(cost) = self.scheduler_turn_cost else {
1279 return Ok((NANOS_PER_SCHED * multiplier) as u64);
1280 };
1281 let cost = u64::from(cost);
1282 if cost > MAX_SCHEDULER_TURN_COST {
1283 return Err(format!(
1284 "--scheduler-turn-cost must be at most {MAX_SCHEDULER_TURN_COST} virtual \
1285 nanoseconds (received {cost})"
1286 ));
1287 }
1288 let charge = cost as f64 * multiplier;
1289 if !(1.0..=MAX_SCHEDULER_TURN_COST as f64).contains(&charge) {
1290 return Err(format!(
1291 "--scheduler-turn-cost {cost} at --clock-multiplier {multiplier} charges {charge} \
1292 virtual nanoseconds per scheduler turn; the charge must be at least 1, so that \
1293 timed waits keep advancing, and at most {MAX_SCHEDULER_TURN_COST}"
1294 ));
1295 }
1296 Ok(charge as u64)
1297 }
1298
1299 /// The `--pipe-wake-latency` in effect (<https://github.com/rrnewton/hermit/issues/4380>): the
1300 /// option's value in run mode, with sequentialized threads and a heuristic that selects by
1301 /// priority; `None` everywhere else, so nothing of the hand-off runs.
1302 pub fn pipe_wake_latency_in_effect(&self) -> Option<u64> {
1303 self.pipe_wake_latency.filter(|_| {
1304 self.use_nonblocking_sockets()
1305 && !self.recordreplay_modes
1306 && self.sched_heuristic.is_priority_ordered()
1307 })
1308 }
1309
1310 /// Should we convert sockets to SOCK_NONBLOCK?
1311 pub fn use_nonblocking_sockets(&self) -> bool {
1312 self.sequentialize_threads && !self.debug_externalize_sockets
1313 }
1314
1315 /// Should we call trace_schedevent to trace each SchedEvent?
1316 /// This applies to both record and replay for scheduled events.
1317 pub fn should_trace_schedevent(&self) -> bool {
1318 self.record_preemptions || self.replay_schedule_from.is_some()
1319 }
1320
1321 /// Returns manual interuption points for a given thread
1322 pub fn interrupts_for_thread(&self, thread_id: DetTid) -> BTreeSet<u64> {
1323 self.interrupt_at
1324 .iter()
1325 .filter_map(|(tid, time)| {
1326 if tid.eq(&thread_id) {
1327 Some(*time)
1328 } else {
1329 None
1330 }
1331 })
1332 .collect::<BTreeSet<u64>>()
1333 }
1334}
1335
1336impl fmt::Display for Config {
1337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1338 if !self.virtualize_time {
1339 write!(f, " --no-virtualize-time")?;
1340 }
1341 if !self.virtualize_cpuid {
1342 write!(f, " --no-virtualize-cpuid")?;
1343 }
1344 if !self.cpu_profile.is_default() {
1345 write!(f, " --cpu-profile={}", self.cpu_profile)?;
1346 }
1347 if !self.virtualize_metadata {
1348 write!(f, " --no-virtualize-metadata")?;
1349 }
1350 if self.passthru_opt {
1351 write!(f, " --passthru-opt")?;
1352 }
1353 match self.runs_post_fork {
1354 RunsPostFork::Child => {}
1355 RunsPostFork::Parent => write!(f, " --runs-post-fork=parent")?,
1356 RunsPostFork::Random => write!(f, " --runs-post-fork=random")?,
1357 }
1358 if !self.has_default_epoch() {
1359 write!(f, " --epoch={}", self.epoch.to_rfc3339())?;
1360 }
1361 if self.seed != 0 {
1362 write!(f, " --seed={}", self.seed)?;
1363 }
1364
1365 if let Some(rng_seed) = self.rng_seed {
1366 write!(f, " --rng-seed={}", rng_seed)?;
1367 }
1368 if let Some(fuzz_seed) = self.fuzz_seed {
1369 write!(f, " --fuzz-seed={}", fuzz_seed)?;
1370 }
1371
1372 if self.fuzz_futexes {
1373 write!(f, " --fuzz-futexes")?;
1374 }
1375 if self.chaos_target_races {
1376 write!(f, " --chaos-target-races")?;
1377 }
1378 // AUTONOMOUS-BOT-IMPLEMENTED
1379 // TODO-HUMAN-REVIEW(PR-1149)
1380 if self.chaos_per_thread_slowdown {
1381 write!(f, " --chaos-per-thread-slowdown")?;
1382 write!(
1383 f,
1384 " --chaos-slowdown-max-factor={}",
1385 self.chaos_slowdown_max_factor
1386 )?;
1387 // AUTONOMOUS-BOT-IMPLEMENTED
1388 // TODO-HUMAN-REVIEW(PR-1151)
1389 if self.chaos_epoch_length_ns > 0 {
1390 write!(f, " --chaos-epoch-length-ns={}", self.chaos_epoch_length_ns)?;
1391 }
1392 }
1393 if let Some(m) = self.clock_multiplier {
1394 write!(f, " --clock-multiplier={}", m)?;
1395 }
1396 if self.imprecise_timers {
1397 write!(f, " --imprecise-timers")?;
1398 }
1399 if !self.signal_state_copy {
1400 write!(f, " --no-signal-state-copy")?;
1401 }
1402 if self.chaos {
1403 write!(f, " --chaos")?;
1404 }
1405 if self.record_preemptions {
1406 write!(f, " --record-preemptions")?;
1407 }
1408
1409 if let Some(p) = &self.record_preemptions_to {
1410 let s = p.to_str().expect("valid unicode path");
1411 write!(f, " --record-preemptions-to={}", shell_words::quote(s))?;
1412 }
1413 if let Some(p) = &self.replay_preemptions_from {
1414 let s = p.to_str().expect("valid unicode path");
1415 write!(f, " --replay-preemptions-from={}", shell_words::quote(s))?;
1416 }
1417 if let Some(p) = &self.replay_schedule_from {
1418 let s = p.to_str().expect("valid unicode path");
1419 write!(f, " --replay-schedule-from={}", shell_words::quote(s))?;
1420 }
1421 if self.replay_exhausted_panic {
1422 write!(f, " --replay-exhausted-panic")?;
1423 }
1424 if self.die_on_desync {
1425 write!(f, " --die-on-desync")?;
1426 }
1427 for (index, path) in &self.stacktrace_event {
1428 write!(f, " --stacktrace-event={}", index)?;
1429 if let Some(p) = path {
1430 let s = p.to_str().expect("valid unicode path");
1431 write!(f, ",{}", shell_words::quote(s))?;
1432 }
1433 }
1434 if self.preemption_stacktrace {
1435 write!(f, " --preemption-stacktrace")?;
1436 }
1437 if self.panic_on_unsupported_syscalls {
1438 write!(f, " --panic-on-unsupported-syscalls")?;
1439 }
1440 if self.panic_on_rcb_overshoot {
1441 write!(f, " --panic-on-rbc-overshoot")?;
1442 }
1443 if self.kill_daemons {
1444 write!(f, " --kill-daemons")?;
1445 }
1446 if self.gdbserver {
1447 write!(f, " --gdbserver")?;
1448 }
1449 if self.gdbserver_port != /* default */ 1234u16 {
1450 write!(f, " --gdbserver-port={}", self.gdbserver_port)?;
1451 }
1452 match &self.max_timeslice {
1453 Some(x) => {
1454 if *x != NonZeroU64::new(200_000_000).unwrap() {
1455 write!(f, " --max-timeslice={}", x)?;
1456 }
1457 }
1458 None => {
1459 write!(f, " --max-timeslice=disabled")?;
1460 }
1461 }
1462 if let Some(target_timeslice) = self.target_timeslice {
1463 write!(f, " --target-timeslice={}", target_timeslice)?;
1464 }
1465 if self.target_timeslice_syscalls_only {
1466 write!(f, " --target-timeslice-syscalls-only")?;
1467 }
1468 if self.futex_wake_yields {
1469 write!(f, " --futex-wake-yields")?;
1470 }
1471 if let Some(latency) = self.pipe_wake_latency {
1472 write!(f, " --pipe-wake-latency={}", latency)?;
1473 }
1474 if let Some(cost) = self.scheduler_turn_cost {
1475 write!(f, " --scheduler-turn-cost={}", cost)?;
1476 }
1477 if self.sigint_instakill {
1478 write!(f, " --sigint-instakill")?;
1479 }
1480 if self.warn_non_zero_binds {
1481 write!(f, " --warn-non-zero-binds")?;
1482 }
1483 match &self.sched_heuristic {
1484 SchedHeuristic::None => {}
1485 SchedHeuristic::ConnectBind => {
1486 write!(f, " --sched-heuristic=connectbind")?;
1487 }
1488 SchedHeuristic::Random => {
1489 write!(f, " --sched-heuristic=random")?;
1490 }
1491 SchedHeuristic::StickyRandom => {
1492 write!(f, " --sched-heuristic=stickyrandom")?;
1493 }
1494 }
1495 if let Some(s) = self.sched_seed {
1496 write!(f, " --sched-seed={}", s)?;
1497 }
1498 if self.sched_sticky_random_param != 0.0 {
1499 write!(
1500 f,
1501 " --sched-sticky-random-param={}",
1502 self.sched_sticky_random_param
1503 )?;
1504 }
1505 if let Some(t) = self.stop_after_turn {
1506 write!(f, " --stop-after-turn={}", t)?;
1507 }
1508 if let Some(i) = self.stop_after_iter {
1509 write!(f, " --stop-after-iter={}", i)?;
1510 }
1511 if self.debug_externalize_sockets {
1512 write!(f, " --debug-externalize-sockets")?;
1513 }
1514 match &self.debug_futex_mode {
1515 BlockingMode::External => {
1516 write!(f, " --debug-futex-mode=external")?;
1517 }
1518 BlockingMode::Polling => {
1519 write!(f, " --debug-futex-mode=polling")?;
1520 }
1521 BlockingMode::Precise => { /* default */ }
1522 }
1523 if self.no_rcb_time {
1524 write!(f, " --no-rcb-time")?;
1525 }
1526 if self.detlog_heap {
1527 write!(f, " --detlog-heap")?;
1528 }
1529 if self.detlog_stack {
1530 write!(f, " --detlog-stack")?;
1531 }
1532 if self.detlog_regs {
1533 write!(f, " --detlog-regs")?;
1534 }
1535 if self.detlog_regs_cadence != /* default */ 1 {
1536 write!(f, " --detlog-regs-cadence={}", self.detlog_regs_cadence)?;
1537 }
1538 if !self.detlog_io_buffers {
1539 write!(f, " --no-detlog-io-buffers")?;
1540 }
1541 if self.sysinfo_uptime_offset != /* default */ 120 {
1542 write!(f, " --sysinfo-uptime-offset={}", self.sysinfo_uptime_offset)?;
1543 }
1544 if self.memory != 1_000_000_000 {
1545 write!(f, " --memory={}", self.memory)?;
1546 }
1547 match self.proc_level {
1548 ProcLevel::Minimal => {}
1549 ProcLevel::Standard => write!(f, " --proc=standard")?,
1550 }
1551 for (tid, rcb) in &self.interrupt_at {
1552 write!(f, " --interrupt-at={}:{}", tid, rcb)?;
1553 }
1554 Ok(())
1555 }
1556}
1557
1558/// How much of `/proc` the guest sees (`--proc`). Each level contains the
1559/// one before it.
1560#[derive(
1561 Debug,
1562 Default,
1563 Clone,
1564 Copy,
1565 Serialize,
1566 Deserialize,
1567 Parser,
1568 PartialEq,
1569 Eq,
1570 PartialOrd,
1571 Ord
1572)]
1573pub enum ProcLevel {
1574 /// The names most programs read, modelled on gVisor's `/proc`.
1575 #[default]
1576 Minimal,
1577 /// Every name Detcore serves or plans to serve.
1578 Standard,
1579}
1580
1581impl FromStr for ProcLevel {
1582 type Err = String;
1583
1584 fn from_str(s: &str) -> Result<Self, Self::Err> {
1585 match s.to_lowercase().as_str() {
1586 "minimal" => Ok(Self::Minimal),
1587 "standard" => Ok(Self::Standard),
1588 _ => Err(format!(
1589 "Expected minimal|standard, could not parse: {:?}",
1590 s
1591 )),
1592 }
1593 }
1594}
1595
1596/// Which side of an ordinary fork/clone receives the first post-registration turn.
1597#[derive(
1598 Debug,
1599 Default,
1600 Clone,
1601 Copy,
1602 Serialize,
1603 Deserialize,
1604 Parser,
1605 PartialEq,
1606 Eq
1607)]
1608pub enum RunsPostFork {
1609 /// Run the newly registered child before its parent resumes.
1610 #[default]
1611 Child,
1612 /// Allow the parent to resume before the newly registered child starts.
1613 Parent,
1614 /// Deterministically choose child-first or parent-first from the scheduler seed.
1615 Random,
1616}
1617
1618impl FromStr for RunsPostFork {
1619 type Err = String;
1620
1621 fn from_str(s: &str) -> Result<Self, Self::Err> {
1622 match s.to_lowercase().as_str() {
1623 "child" => Ok(Self::Child),
1624 "parent" => Ok(Self::Parent),
1625 "random" => Ok(Self::Random),
1626 _ => Err(format!(
1627 "Expected Child|Parent|Random, could not parse: {:?}",
1628 s
1629 )),
1630 }
1631 }
1632}
1633
1634/// How should we handle syscalls which may block, but are internal to the hermit container?
1635/// These syscalls are determinizable, but there are multiple methods of doing so.
1636/// These choices *do not* apply to blocking syscalls that wait for external conditions outside the
1637/// container, such as network responses.
1638///
1639/// Mostly it helps to switch this as: (1) a debugging aid to figure out what is going wrong with a
1640/// given guest program, or (2) in order to find the more performant mode for a given guest program.
1641#[derive(Debug, Clone, Copy, Serialize, Deserialize, Parser, PartialEq, Eq)]
1642pub enum BlockingMode {
1643 /// Handle the internal blocking syscall as though it was external, and unblocks at an
1644 /// unpredictable nondeterministic time. These blocked threads will be parked in the
1645 /// scheduler's BlockedPool.
1646 ///
1647 /// (TODO: In the future these scheduling decisions will be recorded, and this comment needs to
1648 /// be updated accordingly.)
1649 External,
1650 /// Transform each blocking syscall into non-blocking, and then the scheduler will use that
1651 /// non-blocking form to repeatedly poll for completion of the operation. When polling occurs
1652 /// (and the backoff policy there on) is decided by the scheduler.
1653 /// See NOTE [Blocking Syscalls via Internal Polling] in this folder.
1654 Polling,
1655 /// Precisely model the blocking and unblocking behavior inside hermit.
1656 /// TODO: This work is not completed yet for all forms of blocking syscalls.
1657 Precise,
1658}
1659
1660impl FromStr for BlockingMode {
1661 type Err = String;
1662
1663 fn from_str(s: &str) -> Result<Self, Self::Err> {
1664 match s.to_lowercase().as_str() {
1665 "polling" => Ok(BlockingMode::Polling),
1666 "precise" => Ok(BlockingMode::Precise),
1667 "external" => Ok(BlockingMode::External),
1668 _ => Err(format!(
1669 "Expected Polling|Precise|External, could not parse: {:?}",
1670 s
1671 )),
1672 }
1673 }
1674}
1675
1676#[derive(
1677 Debug,
1678 Default,
1679 Clone,
1680 Copy,
1681 Serialize,
1682 Deserialize,
1683 Parser,
1684 PartialEq,
1685 Eq
1686)]
1687/// Apply a specialized scheduling heuristic which may help exercise certain bugs.
1688pub enum SchedHeuristic {
1689 /// Don't modify the scheduling algorithm.
1690 // TODO: Is the default a round robin?
1691 #[default]
1692 None,
1693 /// Prioritize connect and deprioritize bind to exercise races
1694 ConnectBind,
1695 /// Random: Randomly pick any available thread to make progress.
1696 Random,
1697 /// Sticky Random: Randomly pick any available thread. On the next round,
1698 /// and after the thread is parked, randomly choose if we will continue
1699 /// executing on the same thread, or picking another one.
1700 StickyRandom,
1701 // TODO: make all sleeps "instant".
1702}
1703
1704impl SchedHeuristic {
1705 /// Whether selection follows priority order: `None` and `ConnectBind` pop
1706 /// the first queued entry, so a backed-off poller can be starved; `Random`
1707 /// and `StickyRandom` draw a uniform index into the queue and never are.
1708 /// The scheduler's run queue and `hermit run`'s refusals share this one
1709 /// definition.
1710 pub fn is_priority_ordered(self) -> bool {
1711 matches!(self, SchedHeuristic::None | SchedHeuristic::ConnectBind)
1712 }
1713}
1714
1715// Lame to not derive this, but even `derive_more` won't do enums.
1716impl FromStr for SchedHeuristic {
1717 type Err = String;
1718
1719 fn from_str(s: &str) -> Result<Self, Self::Err> {
1720 match s.to_lowercase().as_str() {
1721 "none" | "roundrobin" => Ok(SchedHeuristic::None),
1722 "connectbind" => Ok(SchedHeuristic::ConnectBind),
1723 "random" => Ok(SchedHeuristic::Random),
1724 "stickyrandom" => Ok(SchedHeuristic::StickyRandom),
1725 _ => Err(format!(
1726 "Expected None|ConnectBind|Random|StickyRandom, could not parse: {:?}",
1727 s
1728 )),
1729 }
1730 }
1731}
1732
1733/// An optional virtual-timeslice duration. `None` disables that preemption mechanism.
1734pub type MaybeTimeslice = Option<NonZeroU64>;
1735
1736/// Deprecated name for an optional PMU-backed virtual-timeslice duration.
1737#[deprecated(note = "use MaybeTimeslice")]
1738pub type MaybePreemptionTimeout = MaybeTimeslice;
1739
1740fn parse_timeslice(src: &str) -> Result<MaybeTimeslice, ParseTimesliceError> {
1741 if let Ok(n) = src.parse::<u64>() {
1742 if n != 0 && n < NANOS_PER_RCB as u64 {
1743 Err(ParseTimesliceError::new(
1744 "PMU-backed timeslices must be at least one RCB (10 virtual nanoseconds)",
1745 ))
1746 } else {
1747 Ok(NonZeroU64::new(n))
1748 }
1749 } else {
1750 match src {
1751 "disabled" => Ok(None),
1752 _ => Err(ParseTimesliceError::new(
1753 "Unable to parse timeslice, expected disabled or a non-negative integer",
1754 )),
1755 }
1756 }
1757}
1758
1759fn parse_index_with_path(src: &str) -> Result<(u64, Option<PathBuf>), String> {
1760 let convert = |e| format!("Failed to parse int index before comma: {e}");
1761 if let Some((index_str, path)) = src.split_once(',') {
1762 let ix = index_str.parse::<u64>().map_err(convert)?;
1763 let pathbuf = PathBuf::from_str(path).map_err(|_| "the impossible happened")?;
1764 Ok((ix, Some(pathbuf)))
1765 } else {
1766 let ix = src.parse::<u64>().map_err(convert)?;
1767 Ok((ix, None))
1768 }
1769}
1770
1771#[derive(Debug)]
1772struct ParseTimesliceError {
1773 details: String,
1774}
1775
1776impl fmt::Display for ParseTimesliceError {
1777 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1778 write!(f, "{}", self.details)
1779 }
1780}
1781
1782impl ParseTimesliceError {
1783 fn new(msg: &str) -> ParseTimesliceError {
1784 ParseTimesliceError {
1785 details: msg.to_string(),
1786 }
1787 }
1788}
1789
1790impl std::error::Error for ParseTimesliceError {
1791 fn description(&self) -> &str {
1792 &self.details
1793 }
1794}
1795
1796/// The default epoch used by DetCore for things like initial file modtimes.
1797///
1798/// N.B. Default to a reasonable date. Some programs (like zip) have trouble with the
1799/// original unix epoch (time zero).
1800pub static DEFAULT_EPOCH_STR: &str = "2026-01-01T00:00:00Z";
1801
1802pub use crate::canonical_test_epoch::CANONICAL_TEST_EPOCH;
1803pub use crate::canonical_test_epoch::CANONICAL_TEST_EPOCH_ARG;
1804
1805/// Convert one invocation's captured host instant without losing subsecond
1806/// precision. CLI and comparison orchestration share this input conversion;
1807/// guest clock progression never reads the host clock through it.
1808pub fn epoch_from_host_time(now: SystemTime) -> DateTime<Utc> {
1809 DateTime::<Utc>::from(now)
1810}
1811
1812impl Config {
1813 /// Construct the config using environment variables only, not CLI args.
1814 pub fn from_env() -> Self {
1815 let args: [OsString; 2] = [
1816 OsString::from("CMD"), // Silly/unused.
1817 OsString::from(format!("--epoch={}", DEFAULT_EPOCH_STR)),
1818 ];
1819 Config::parse_from(args.iter())
1820 }
1821
1822 /// Returns effective "rng-seed" parameter taking in account "seed"
1823 /// parameter if former isn't specified
1824 pub fn rng_seed(&self) -> u64 {
1825 self.rng_seed.unwrap_or(self.seed)
1826 }
1827
1828 /// Returns the fuzz_seed, as specified by the user or defaulting to the primary seed if
1829 /// unspecified.
1830 pub fn fuzz_seed(&self) -> u64 {
1831 self.fuzz_seed.unwrap_or(self.seed)
1832 }
1833
1834 /// Returns effective "sched-seed" parameter taking in account "seed"
1835 /// parameter if former isn't specified
1836 pub fn sched_seed(&self) -> u64 {
1837 self.sched_seed.unwrap_or(self.seed)
1838 }
1839}
1840
1841/// The largest `--scheduler-turn-cost` accepted, in virtual nanoseconds, both
1842/// before and after the clock multiplier scales it: one second per scheduler
1843/// turn.
1844pub const MAX_SCHEDULER_TURN_COST: u64 = 1_000_000_000;
1845
1846/// N.B. we don't want to specify two different notions of "default", so we use the
1847/// `Clap` instance above.
1848/// Environment variable carrying the coordinator's [`config_wire_fingerprint`]
1849/// to an out-of-process plugin.
1850///
1851/// Named alongside the other `REVERIE_SABRE_HERMIT_*` launch variables so the
1852/// two travel together and a reader finds them in one place.
1853pub const CONFIG_FINGERPRINT_ENV: &str = "REVERIE_SABRE_HERMIT_CONFIG_FINGERPRINT";
1854
1855/// Environment variable carrying the coordinator's [`config_wire_fingerprint`]
1856/// to the in-guest LiteInst runtime (`libdetcore_liteinst.so`), which checks it
1857/// before it decodes the configuration the coordinator sends. Without the
1858/// check, a runtime built from another tree fails with a bare decoding error
1859/// that names neither build (<https://github.com/rrnewton/hermit/issues/3986>).
1860/// The runtime removes it once checked, as it removes its DETLOG variables:
1861/// the value is zeroed in the environment block and the variable is unset, so
1862/// the fingerprint never reaches the guest.
1863pub const LITEINST_CONFIG_FINGERPRINT_ENV: &str = "HERMIT_LITEINST_CONFIG_FINGERPRINT";
1864
1865const CONFIG_DEFINITION_SOURCES: &[&[u8]] = &[
1866 include_bytes!("config.rs"),
1867 // `RawInode`, the host identity the inode RPCs (`DeterminizeInode`,
1868 // `TouchFile`, `SetFileMtime`) carry. Its layout changed from one `u64`
1869 // to a device and an inode number, which neither encoding of `Config`
1870 // shows.
1871 include_bytes!("fd.rs"),
1872 include_bytes!("happens_before.rs"),
1873 include_bytes!("network_trace.rs"),
1874 include_bytes!("pid.rs"),
1875 include_bytes!("schedule.rs"),
1876 include_bytes!("time.rs"),
1877];
1878
1879/// A fingerprint of this build's [`Config`] payload and the configuration and
1880/// clock RPC definitions shared by a plugin and its coordinator.
1881///
1882/// # Why this exists
1883///
1884/// An out-of-process plugin such as `libdetcore_sabre.so` is a separate Cargo
1885/// artifact that lands in the same target directory as `hermit`. Changing
1886/// `Config` or `DetTime` -- or merely switching branches -- leaves the plugin
1887/// stale while everything still *looks* built. `Config` is transferred during
1888/// the RPC handshake, and `DetTime` is the first field in every Detcore request.
1889/// A stale plugin decodes either against the wrong layout and the failure
1890/// surfaces as an opaque codec error: measured, one added `bool` field
1891/// produced `Decode(InvalidBooleanValue(20))` at connect, which points nowhere
1892/// near "your plugin is from a different build" and cost a long diagnosis while
1893/// blocking every SaBRe measurement.
1894///
1895/// # What it measures
1896///
1897/// Two encodings of `Config::default()` and the source definitions for the
1898/// configuration and clock RPC fields are fingerprinted with separate domains:
1899///
1900/// - the exact legacy-bincode bytes used by Reverie RPC, which detect changes
1901/// such as `u32` to `u64` even when both default to JSON number zero; and
1902/// - the JSON encoding, which carries every field name and makes a pure rename
1903/// visible even though bincode is positional; and
1904/// - the source files defining `Config`, its local serialized field types,
1905/// `DetTime`, and the `RawInode` the inode RPCs carry, which catch
1906/// wire-incompatible changes hidden by a default such as `Option<u64>::None`
1907/// to `Option<u32>::None`, or an added clock or inode field that leaves both
1908/// encodings of `Config` unchanged.
1909///
1910/// The source and JSON domains are deliberately stricter than the wire format
1911/// strictly requires. A documentation-only edit in one of these files can
1912/// require rebuilding the plugin; missing a wire-incompatible hidden variant
1913/// can make it decode the handshake or a subsequent request at the wrong offsets.
1914fn config_wire_default() -> Config {
1915 // `Config::default()` is intentionally environment-aware through Clap.
1916 // A coordinator may therefore inherit HERMIT_EPOCH/HERMIT_PRNG or
1917 // HERMIT_SCHED_SEED even though the separately loaded plugin receives a
1918 // minimal guest environment. Those invocation values are payload data,
1919 // not wire shape, and must not make two artifacts from the same source
1920 // reject one another. Explicit arguments take precedence over Clap's
1921 // environment provider; clear the scheduler override afterward to retain
1922 // the real environment-free default of `None` in the encoded shape.
1923 let mut config = Config::parse_from([
1924 "config-wire-fingerprint",
1925 &format!("--epoch={DEFAULT_EPOCH_STR}"),
1926 "--seed=0",
1927 "--sched-seed=0",
1928 ]);
1929 config.sched_seed = None;
1930 // `BackendCapabilities` is defined in Reverie, outside
1931 // `CONFIG_DEFINITION_SOURCES`, so the source domain cannot see a change to
1932 // it; only its encoding can. Every field is a bool, so any constant
1933 // carries every field's width (see
1934 // `config_fingerprint_sees_the_width_of_every_backend_capability`). KVM's
1935 // is kept, as it was when one field was optional and only KVM's set it.
1936 config.backend = BackendCapabilities::KVM;
1937 config
1938}
1939
1940pub fn config_wire_fingerprint() -> String {
1941 let config = config_wire_default();
1942 let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy())
1943 .expect("canonical Config wire default must encode with Reverie's bincode configuration");
1944 let named_shape = serde_json::to_string(&config)
1945 .expect("canonical Config wire default must encode as JSON for field-name checking");
1946 fingerprint_of_config_material(&wire, &named_shape, CONFIG_DEFINITION_SOURCES)
1947}
1948
1949/// What differs when a coordinator announced `expected` as its
1950/// [`config_wire_fingerprint`] and this build's is another, or `None` when
1951/// they are equal. The in-guest LiteInst runtime reports this before it
1952/// decodes the coordinator's configuration
1953/// (<https://github.com/rrnewton/hermit/issues/3986>).
1954pub fn config_fingerprint_mismatch(expected: &std::ffi::OsStr) -> Option<String> {
1955 let ours = config_wire_fingerprint();
1956 (expected.to_str() != Some(ours.as_str())).then(|| {
1957 format!(
1958 "its configuration and clock RPC fingerprint is {ours}, Hermit's is {}",
1959 expected.to_string_lossy()
1960 )
1961 })
1962}
1963
1964/// Domain-separated FNV-1a over wire bytes, named JSON, and defining source.
1965/// This is a mismatch detector, not a security boundary. Length-prefixing each
1966/// domain prevents two different source-file boundaries from hashing the same
1967/// concatenation.
1968fn fingerprint_of_config_material(
1969 wire: &[u8],
1970 named_shape: &str,
1971 definition_sources: &[&[u8]],
1972) -> String {
1973 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
1974 let mut update = |domain: u8, bytes: &[u8]| {
1975 for byte in std::iter::once(&domain)
1976 .chain((bytes.len() as u64).to_le_bytes().iter())
1977 .chain(bytes.iter())
1978 {
1979 hash ^= u64::from(*byte);
1980 hash = hash.wrapping_mul(0x1000_0000_01b3);
1981 }
1982 };
1983 update(0, wire);
1984 update(1, named_shape.as_bytes());
1985 for source in definition_sources {
1986 update(2, source);
1987 }
1988 format!("{hash:016x}")
1989}
1990
1991/// `Config::signal_state_copy` for a serialized configuration written before
1992/// the field existed: on, the default.
1993fn signal_state_copy_default() -> bool {
1994 true
1995}
1996
1997impl Default for Config {
1998 fn default() -> Self {
1999 let v: Vec<String> = vec![];
2000 Config::parse_from(v.iter())
2001 }
2002}
2003
2004/// Serializes `config` as JSON in the form it had before [`Config::backend`]
2005/// existed.
2006///
2007/// [`Config::backend`] is left out. In its place, at the same position in
2008/// the object, are the fifteen
2009/// separate backend keys that a serialized configuration carried before,
2010/// under the names and in the order it carried them, each with a value
2011/// computed from `config`. [`Config::record_host_inputs`], which the legacy
2012/// form never had, is left out too, and reads back as false: this form serves
2013/// only DBT, whose launcher collects no host inputs. So is
2014/// [`Config::guest_may_inherit_a_terminal`], which is read only where
2015/// [`crate::bundled_signal_facts::host_timed_signal_sources_are_physical`]
2016/// holds, false for DBT, and [`Config::in_guest_detlog_forward_policy`] and
2017/// [`Config::in_guest_site_patching_off`], which is unset for DBT, and
2018/// [`Config::launch_image`], which came after it. So is [`Config::target_timeslice_syscalls_only`],
2019/// added after this form froze; DBT runs without a PMU maximum, where the
2020/// option has no effect. So are [`Config::futex_wake_yields`] and
2021/// [`Config::scheduler_turn_cost`], also added after this form froze, which
2022/// `hermit run` refuses with the DBT backend, and [`Config::replaying`], set
2023/// only by `hermit replay`, which runs only on the ptrace backend. So is
2024/// [`Config::inherited_seccomp`], added after this form froze, which reads
2025/// back as unknown. Every other field is serialized exactly as
2026/// `serde_json::to_string(config)` serializes it.
2027///
2028/// Use this wherever the JSON is visible to the guest. `hermit run
2029/// --backend=dbt` passes the configuration to the in-guest DBT runtime in the
2030/// guest's own environment, so a guest that reads its environment, or whose
2031/// initial stack layout depends on the environment's size, observes this
2032/// string; producing the earlier bytes keeps that observation unchanged.
2033///
2034/// Read the result with [`from_legacy_backend_json`], which recovers
2035/// [`Config::backend`] from the fifteen keys. A plain `Config`
2036/// deserialization ignores the keys and gives the field its serde default.
2037pub fn to_legacy_backend_json(config: &Config) -> serde_json::Result<String> {
2038 let mut json = Vec::with_capacity(4096);
2039 let mut serializer = serde_json::Serializer::new(&mut json);
2040 config.serialize(legacy_backend_json::ConfigSerializer {
2041 inner: &mut serializer,
2042 config,
2043 })?;
2044 String::from_utf8(json).map_err(serde::ser::Error::custom)
2045}
2046
2047/// The JSON keys, in order, under which a serialized [`Config`] carried the
2048/// backend facts before they moved into [`Config::backend`], each with the
2049/// value it has for `config`.
2050///
2051/// `backend_is_kvm` named the backend rather than a fact; its value is
2052/// `provides_process_signal_control`, a capability only KVM reports.
2053/// `kvm_shared_dequeue_timers` was a startup policy, not a fact: the
2054/// production launcher, hermit-cli, set it exactly when that capability and
2055/// [`Config::sequentialize_threads`] held. Its value is that conjunction, and
2056/// [`from_legacy_backend_json`] refuses any other value.
2057fn legacy_backend_keys(config: &Config) -> [(&'static str, bool); 15] {
2058 let backend = &config.backend;
2059 [
2060 // No backend installs a CPUID policy of its own any more, so the key
2061 // is always written false; see `from_legacy_backend_json`.
2062 ("cpuid_virtualized_by_backend", false),
2063 ("backend_supports_madvise", backend.supports_madvise),
2064 (
2065 "discover_live_file_metadata",
2066 backend.tool_shares_guest_descriptor_table,
2067 ),
2068 (
2069 "detect_host_clock_futex_timeouts",
2070 backend.guest_clock_reads_bypass_backend,
2071 ),
2072 (
2073 "syscall_clobbers_virtualized_by_backend",
2074 backend.virtualizes_syscall_clobbers,
2075 ),
2076 (
2077 "cancel_killed_thread_rpcs",
2078 backend.needs_killed_thread_rpc_cancellation,
2079 ),
2080 (
2081 "backend_reports_physical_process_exits",
2082 backend.reports_physical_process_exits,
2083 ),
2084 (
2085 "backend_tracks_process_children",
2086 backend.tracks_process_children,
2087 ),
2088 (
2089 "backend_runs_exit_robust_list",
2090 backend.runs_exit_robust_list,
2091 ),
2092 (
2093 "backend_requires_thread_directed_process_signals",
2094 backend.requires_thread_directed_process_signals,
2095 ),
2096 ("backend_is_kvm", backend.provides_process_signal_control),
2097 (
2098 "kvm_shared_dequeue_timers",
2099 backend.provides_process_signal_control && config.sequentialize_threads,
2100 ),
2101 (
2102 "backend_supports_parked_write_signal_interruption",
2103 backend.supports_parked_write_signal_interruption,
2104 ),
2105 // No backend virtualizes the capability prctls any more; they reach
2106 // the kernel on every backend. Always false; see
2107 // `from_legacy_backend_json`.
2108 ("backend_virtualizes_capability_prctls", false),
2109 (
2110 "backend_defers_vfork_child_registration",
2111 backend.defers_vfork_child_registration,
2112 ),
2113 ]
2114}
2115
2116/// Parses JSON written by [`to_legacy_backend_json`], or any JSON in the form
2117/// a serialized [`Config`] had before [`Config::backend`] existed, and recovers
2118/// [`Config::backend`] from the fifteen legacy backend keys.
2119///
2120/// The keys are read exactly as they were read while each was a `Config`
2121/// field: a key that is absent takes the default that field had, and a key of
2122/// the wrong type fails the parse. Each key then supplies every capability that
2123/// replaced a read of it, so a decoded configuration behaves as the same JSON
2124/// did before:
2125///
2126/// - `discover_live_file_metadata` supplies the four descriptor and loopback
2127/// facts that were each a read of it;
2128/// - `backend_reports_physical_process_exits` supplies
2129/// `reports_physical_process_exits` and
2130/// `signal_interrupts_external_syscalls`;
2131/// - `backend_is_kvm` supplies the two behaviours it selected that remain
2132/// capabilities, `provides_process_signal_control` and
2133/// `emulates_child_waits` (the other three are now answered by the backend
2134/// itself: refusing a non-leader exec is a typed refusal it reports per
2135/// exec, the `gettimeofday` repair runs on every backend through its
2136/// `time(2)` probe and `Guest::storable_memory_ranges`, and the user
2137/// address limit is each guest's own `Guest::user_address_limit` report);
2138/// - every other key supplies the one capability of the same meaning.
2139///
2140/// This inverts [`to_legacy_backend_json`] for every capability value the keys
2141/// can express, which includes every backend's own constant except for
2142/// capabilities added after the legacy form froze: those never enter it, as
2143/// `record_host_inputs` does not, and read back as their default. There are
2144/// six. `process_exits_complete_asynchronously` and
2145/// `virtualizes_guest_sigalrm` are true only for in-guest LiteInst, which
2146/// never travels through this DBT-only form.
2147/// `supports_blocked_wait_signal_interruption`,
2148/// `delivers_preemption_timer_events` and
2149/// `runs_guest_code_between_injections` read back as false, the value DBT
2150/// has and the value their earlier `Config` fields read back as.
2151///
2152/// `cpuid_virtualized_by_backend` supplies no capability either: it said the
2153/// backend installed a CPUID policy of its own, which no backend does any
2154/// more (KVM stopped with Reverie 0f4d8852). It is still written, as false,
2155/// so DBT's guest-visible configuration keeps its bytes, and an input that
2156/// says `true` fails the parse rather than being read as a policy no backend
2157/// has.
2158///
2159/// `backend_virtualizes_capability_prctls` supplies no capability either: it
2160/// said the backend answered the capability-set prctls itself, and every
2161/// backend now passes them to the kernel. It is written as false, so DBT's
2162/// configuration keeps its bytes, and `true` fails the parse.
2163///
2164/// `kvm_shared_dequeue_timers` supplies no capability. It was read into a
2165/// `Config` field that chose the controlled signal path, and that choice is
2166/// now made from the capabilities, [`Config::sequentialize_threads`] and the
2167/// control the backend offers. It is read as it was, a boolean that is false
2168/// when absent, and the parse then fails unless it equals `backend_is_kvm &&
2169/// sequentialize_threads`, the value the production launcher always wrote. An
2170/// accepted input whose capabilities are those of the backend that runs it
2171/// selects the path it selected before. An input that would select another,
2172/// such as `true` without `backend_is_kvm`, or absent beside `backend_is_kvm`
2173/// and sequentialized threads, fails the parse rather than being silently
2174/// reinterpreted. (`backend_is_kvm` given to a backend that offers no control,
2175/// such as DBT, already misdescribed that backend and stays outside this
2176/// guarantee; the production launcher never writes it.) A failed parse is
2177/// handled like any malformed value: the DBT standalone JSON reader falls
2178/// back to its strict default configuration and emits its
2179/// `could not parse HERMIT_DBT_DETCONFIG` warning.
2180///
2181/// Everything else is read as the legacy form was read, by `Config`'s own
2182/// derived deserializer with the legacy keys taken out before it sees them:
2183///
2184/// - In an object, a key the legacy form did not name is ignored, whatever its
2185/// value. `backend` is such a key, so it is ignored rather than read as the
2186/// field it is now; no production writer emits it. A key the legacy form
2187/// named fails the parse when it appears twice or holds the wrong type.
2188/// - A JSON array lists the fields by position, as serde reads any derived
2189/// struct. The positions are those of the legacy form, which are the key
2190/// order of [`to_legacy_backend_json`]: the fifteen legacy keys stand where
2191/// [`Config::backend`] stands. Too many elements fail the parse; too few
2192/// leave the fields
2193/// after them missing, each taking its default or failing the parse as the
2194/// derived deserializer decides for that field.
2195pub fn from_legacy_backend_json(json: &str) -> serde_json::Result<Config> {
2196 let mut deserializer = serde_json::Deserializer::from_str(json);
2197 let (mut config, legacy) = serde::Deserializer::deserialize_struct(
2198 &mut deserializer,
2199 "Config",
2200 &[],
2201 legacy_backend_json::LegacyConfigVisitor,
2202 )?;
2203 deserializer.end()?;
2204 if legacy.cpuid_virtualized_by_backend {
2205 return Err(<serde_json::Error as serde::de::Error>::custom(
2206 "cpuid_virtualized_by_backend is true, but no backend installs a CPUID \
2207 policy of its own; the key must be false or absent",
2208 ));
2209 }
2210 if legacy.backend_virtualizes_capability_prctls {
2211 return Err(<serde_json::Error as serde::de::Error>::custom(
2212 "backend_virtualizes_capability_prctls is true, but no backend answers the \
2213 capability prctls itself; the key must be false or absent",
2214 ));
2215 }
2216 let controlled = legacy.backend_is_kvm && config.sequentialize_threads;
2217 if legacy.kvm_shared_dequeue_timers != controlled {
2218 return Err(<serde_json::Error as serde::de::Error>::custom(
2219 format_args!(
2220 "kvm_shared_dequeue_timers is {} but backend_is_kvm && \
2221 sequentialize_threads is {controlled}; the key is no longer an \
2222 independent setting and must equal that conjunction",
2223 legacy.kvm_shared_dequeue_timers,
2224 ),
2225 ));
2226 }
2227 config.backend = legacy.capabilities();
2228 Ok(config)
2229}
2230
2231/// Preserve the exact backend facts alongside an already encoded legacy config.
2232///
2233/// The legacy form couples some capabilities and omits others. When it can
2234/// express `backend` exactly, return `legacy_json` byte for byte: DBT exposes
2235/// this string in the guest's environment. Otherwise wrap it in a versioned
2236/// envelope whose typed backend replaces the legacy projection on decoding.
2237/// Non-backend fields keep the legacy form's semantics in either case.
2238pub fn encode_backend_config_json(
2239 legacy_json: String,
2240 backend: BackendCapabilities,
2241) -> serde_json::Result<String> {
2242 if from_legacy_backend_json(&legacy_json)?.backend == backend {
2243 return Ok(legacy_json);
2244 }
2245 serde_json::to_string(&VersionedBackendConfig {
2246 dbt_config_version: 1,
2247 config: serde_json::from_str(&legacy_json)?,
2248 backend,
2249 })
2250}
2251
2252/// Read a legacy configuration or a versioned envelope with exact backend facts.
2253///
2254/// Any valid legacy object or positional array retains
2255/// [`from_legacy_backend_json`]'s behavior, including ignored unknown fields.
2256/// Otherwise the input must be an envelope: unknown versions, duplicate fields
2257/// and missing typed capabilities are parse errors.
2258/// This parser does not choose the caller's error policy. The admitted DBT
2259/// standalone JSON path retains its strict-default parse fallback; coordinated
2260/// startup receives its authoritative typed Config through the RPC handshake.
2261pub fn decode_backend_config_json(json: &str) -> serde_json::Result<Config> {
2262 // Legacy inputs take precedence: even dbt_config_version was an ignored
2263 // unknown key in that form, and its presence must not change a valid run.
2264 if let Ok(config) = from_legacy_backend_json(json) {
2265 return Ok(config);
2266 }
2267 // Deserialize the original bytes, not a Value map that would erase
2268 // duplicate keys before the typed deserializers can reject them.
2269 let envelope: VersionedBackendConfig<'_> = serde_json::from_str(json)?;
2270 if envelope.dbt_config_version != 1 {
2271 return Err(<serde_json::Error as serde::de::Error>::custom(
2272 format_args!(
2273 "unsupported DBT configuration version {}",
2274 envelope.dbt_config_version
2275 ),
2276 ));
2277 }
2278 let mut config = from_legacy_backend_json(envelope.config.get())?;
2279 config.backend = envelope.backend;
2280 Ok(config)
2281}
2282
2283#[derive(Serialize, Deserialize)]
2284#[serde(deny_unknown_fields)]
2285struct VersionedBackendConfig<'a> {
2286 dbt_config_version: u32,
2287 #[serde(borrow)]
2288 config: &'a serde_json::value::RawValue,
2289 backend: BackendCapabilities,
2290}
2291
2292/// The names of the fifteen legacy backend keys, in the order
2293/// [`legacy_backend_keys`] gives them.
2294const LEGACY_BACKEND_KEY_NAMES: [&str; 15] = [
2295 "cpuid_virtualized_by_backend",
2296 "backend_supports_madvise",
2297 "discover_live_file_metadata",
2298 "detect_host_clock_futex_timeouts",
2299 "syscall_clobbers_virtualized_by_backend",
2300 "cancel_killed_thread_rpcs",
2301 "backend_reports_physical_process_exits",
2302 "backend_tracks_process_children",
2303 "backend_runs_exit_robust_list",
2304 "backend_requires_thread_directed_process_signals",
2305 "backend_is_kvm",
2306 "kvm_shared_dequeue_timers",
2307 "backend_supports_parked_write_signal_interruption",
2308 "backend_virtualizes_capability_prctls",
2309 "backend_defers_vfork_child_registration",
2310];
2311
2312const fn legacy_backend_key_default_true() -> bool {
2313 true
2314}
2315
2316/// The fifteen legacy backend keys with the types and serde defaults they had
2317/// as `Config` fields. It is deserialized from the keys
2318/// [`legacy_backend_json::LegacyConfigVisitor`] takes out of the input, so a
2319/// key given twice fails here as it failed as a `Config` field.
2320#[derive(Deserialize)]
2321struct LegacyBackendKeys {
2322 #[serde(default)]
2323 cpuid_virtualized_by_backend: bool,
2324 #[serde(default = "legacy_backend_key_default_true")]
2325 backend_supports_madvise: bool,
2326 #[serde(default)]
2327 discover_live_file_metadata: bool,
2328 #[serde(default)]
2329 detect_host_clock_futex_timeouts: bool,
2330 #[serde(default)]
2331 syscall_clobbers_virtualized_by_backend: bool,
2332 #[serde(default)]
2333 cancel_killed_thread_rpcs: bool,
2334 #[serde(default)]
2335 backend_reports_physical_process_exits: bool,
2336 #[serde(default = "legacy_backend_key_default_true")]
2337 backend_tracks_process_children: bool,
2338 #[serde(default = "legacy_backend_key_default_true")]
2339 backend_runs_exit_robust_list: bool,
2340 #[serde(default)]
2341 backend_requires_thread_directed_process_signals: bool,
2342 #[serde(default)]
2343 backend_is_kvm: bool,
2344 /// Read as it was while it was a `Config` field, then checked by
2345 /// [`from_legacy_backend_json`] against `backend_is_kvm` and
2346 /// [`Config::sequentialize_threads`]; it supplies no capability.
2347 #[serde(default)]
2348 kvm_shared_dequeue_timers: bool,
2349 #[serde(default = "legacy_backend_key_default_true")]
2350 backend_supports_parked_write_signal_interruption: bool,
2351 #[serde(default)]
2352 backend_virtualizes_capability_prctls: bool,
2353 #[serde(default)]
2354 backend_defers_vfork_child_registration: bool,
2355}
2356
2357impl LegacyBackendKeys {
2358 /// The capabilities these keys describe; the inverse of
2359 /// [`legacy_backend_keys`]. Every field is assigned, so the starting
2360 /// constant contributes nothing a key decides.
2361 fn capabilities(&self) -> BackendCapabilities {
2362 let mut backend = BackendCapabilities::PTRACE;
2363 backend.tool_shares_guest_descriptor_table = self.discover_live_file_metadata;
2364 backend.rediscovers_descriptors_after_exec = self.discover_live_file_metadata;
2365 backend.internal_pipe_turns_are_host_timed = self.discover_live_file_metadata;
2366 backend.loopback_pollers_yield_to_peers = self.discover_live_file_metadata;
2367 backend.guest_clock_reads_bypass_backend = self.detect_host_clock_futex_timeouts;
2368 backend.virtualizes_syscall_clobbers = self.syscall_clobbers_virtualized_by_backend;
2369 backend.needs_killed_thread_rpc_cancellation = self.cancel_killed_thread_rpcs;
2370 // A legacy encoding predates this key. Only the ptrace tracer reports
2371 // child-exit publication, and it is the one backend that needs no
2372 // killed-thread RPC cancellation.
2373 backend.reports_child_exit_publication = !self.cancel_killed_thread_rpcs;
2374 // Newer than the legacy form. It took over the child-exit ledger's gates
2375 // from reports_child_exit_publication and has its value on every backend
2376 // the form can express (true for ptrace and the default, false for DBT,
2377 // the form's only reader), so it is read back the same way.
2378 backend.reports_kernel_child_exit_signals = backend.reports_child_exit_publication;
2379 backend.reports_physical_process_exits = self.backend_reports_physical_process_exits;
2380 backend.signal_interrupts_external_syscalls = self.backend_reports_physical_process_exits;
2381 backend.tracks_process_children = self.backend_tracks_process_children;
2382 backend.runs_exit_robust_list = self.backend_runs_exit_robust_list;
2383 backend.requires_thread_directed_process_signals =
2384 self.backend_requires_thread_directed_process_signals;
2385 backend.supports_parked_write_signal_interruption =
2386 self.backend_supports_parked_write_signal_interruption;
2387 backend.defers_vfork_child_registration = self.backend_defers_vfork_child_registration;
2388 backend.supports_madvise = self.backend_supports_madvise;
2389 // A legacy encoding predates this key: every backend that supports
2390 // madvise supports MADV_DONTNEED, and KVM implements it alone.
2391 backend.supports_madv_dontneed = self.backend_supports_madvise || self.backend_is_kvm;
2392 backend.provides_process_signal_control = self.backend_is_kvm;
2393 backend.emulates_child_waits = self.backend_is_kvm;
2394 // A legacy encoding predates this key. DBT, the form's only reader,
2395 // promotes shared open-file descriptions before a native fork or exec
2396 // and alone requires thread-directed process signals (DBT's runtime
2397 // also states it from any source, `assert_dbt_execution_model`).
2398 backend.promotes_open_files_before_native_lifecycle =
2399 self.backend_requires_thread_directed_process_signals;
2400 // Added after the legacy form froze. Each was a `Config` field with no
2401 // legacy key that read back as false, and each is false for DBT, the
2402 // form's only reader, so a DBT configuration stays exact.
2403 backend.supports_blocked_wait_signal_interruption = false;
2404 backend.reports_sigreturns = false;
2405 backend.delivers_preemption_timer_events = false;
2406 backend.runs_guest_code_between_injections = false;
2407 backend
2408 }
2409}
2410
2411/// The serde adapters behind [`to_legacy_backend_json`] and
2412/// [`from_legacy_backend_json`].
2413///
2414/// The serializer adapter wraps the JSON serializer only at the top level,
2415/// where `Config`'s derived `Serialize` opens one struct and writes its fields
2416/// in declaration order. Nested values go straight to the wrapped serializer,
2417/// so they, and every field other than the two it replaces, are encoded
2418/// unchanged.
2419///
2420/// The deserializer adapters likewise wrap only the top-level object or array,
2421/// and hand every nested value to the wrapped JSON deserializer.
2422mod legacy_backend_json {
2423 use std::fmt;
2424
2425 use serde::Deserialize;
2426 use serde::Serialize;
2427 use serde::de;
2428 use serde::de::DeserializeSeed;
2429 use serde::de::IgnoredAny;
2430 use serde::de::MapAccess;
2431 use serde::de::SeqAccess;
2432 use serde::de::Visitor;
2433 use serde::de::value::BoolDeserializer;
2434 use serde::de::value::MapAccessDeserializer;
2435 use serde::de::value::MapDeserializer;
2436 use serde::de::value::SeqAccessDeserializer;
2437 use serde::de::value::StringDeserializer;
2438 use serde::ser::Error as _;
2439 use serde::ser::Impossible;
2440 use serde::ser::SerializeStruct;
2441 use serde::ser::Serializer;
2442
2443 use super::BackendCapabilities;
2444 use super::Config;
2445 use super::LEGACY_BACKEND_KEY_NAMES;
2446 use super::LegacyBackendKeys;
2447 use super::legacy_backend_keys;
2448
2449 /// The keys `Config` has now that its legacy form did not. The legacy
2450 /// form ignored them, as it ignored every key it did not name.
2451 /// `record_host_inputs` has no legacy key and no legacy value: the legacy
2452 /// form serves only DBT, whose launcher collects no host inputs, so it is
2453 /// never written and always reads as false.
2454 /// So is `guest_may_inherit_a_terminal`, which is read only where
2455 /// `bundled_signal_facts::host_timed_signal_sources_are_physical` holds;
2456 /// that is false for DBT.
2457 /// `target_timeslice_syscalls_only` came after the legacy form froze; the
2458 /// legacy form never carried it, so it is never written and reads as false,
2459 /// the behaviour every legacy reader already has.
2460 /// `in_guest_detlog_forward_policy` is unset for DBT (its runtime forwards
2461 /// no records on a socket), so it is never written and reads as unset.
2462 /// `futex_wake_yields`, `pipe_wake_latency` and `scheduler_turn_cost` came
2463 /// after the legacy form froze too, and `hermit run` refuses them with the
2464 /// DBT backend.
2465 /// `replaying` is never written either: only `hermit replay` sets it, and
2466 /// replay runs only on the ptrace backend.
2467 /// `in_guest_site_patching_off` is false for DBT (it is set only for
2468 /// in-guest LiteInst), so it is never written and reads as false.
2469 /// `launch_image` came after the legacy form froze: it is never written
2470 /// and reads as unset. DBT's runtime takes it from the coordinator's
2471 /// configuration instead, which declares DynamoRIO's library as the
2472 /// launcher.
2473 /// `inherited_seccomp` came after the legacy form froze too. It is never
2474 /// written and reads as unknown.
2475 /// `cpu_profile` and `cpu_profile_host` came after it as well. DBT refuses
2476 /// the x86-64-v3 profile, so they are never written and read as v2.
2477 /// `signal_state_copy` came after it too. The copy is never kept on DBT
2478 /// (its kernel signal state is not the guest's), so it is never written
2479 /// and reads as on, its serde default.
2480 /// And `container_mount_table`. DBT's launcher encodes the
2481 /// legacy form before the container exists, so it has no table to write;
2482 /// it is never written and reads as absent. The coordinated startup's
2483 /// typed configuration carries the table.
2484 /// `mountinfo_mount_namespace` too, for the same reason: it is never
2485 /// written and reads as absent.
2486 /// `signal_delivery_check_fatal` matters only where the copy is kept, so
2487 /// it is never written and reads as false.
2488 const FIELDS_WITHOUT_A_LEGACY_KEY: [&str; 18] = [
2489 "backend",
2490 "record_host_inputs",
2491 "guest_may_inherit_a_terminal",
2492 "in_guest_detlog_forward_policy",
2493 "in_guest_site_patching_off",
2494 "launch_image",
2495 "target_timeslice_syscalls_only",
2496 "futex_wake_yields",
2497 "pipe_wake_latency",
2498 "replaying",
2499 "scheduler_turn_cost",
2500 "inherited_seccomp",
2501 "cpu_profile",
2502 "cpu_profile_host",
2503 "signal_state_copy",
2504 "container_mount_table",
2505 "mountinfo_mount_namespace",
2506 "signal_delivery_check_fatal",
2507 ];
2508
2509 /// Reads the top-level object or array of a legacy configuration. The
2510 /// derived `Config` deserializer reads every field; this takes the legacy
2511 /// backend keys out of the input before it sees them and collects them for
2512 /// [`LegacyBackendKeys`].
2513 pub(super) struct LegacyConfigVisitor;
2514
2515 impl<'de> Visitor<'de> for LegacyConfigVisitor {
2516 type Value = (Config, LegacyBackendKeys);
2517
2518 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2519 formatter.write_str("struct Config")
2520 }
2521
2522 fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
2523 let mut legacy = Vec::new();
2524 let config = Config::deserialize(MapAccessDeserializer::new(LegacyKeys {
2525 inner: map,
2526 legacy: &mut legacy,
2527 }))?;
2528 Ok((config, legacy_backend_keys_from(legacy)?))
2529 }
2530
2531 fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
2532 let fields = config_field_order().map_err(<A::Error as de::Error>::custom)?;
2533 let mut legacy = Vec::new();
2534 let config = Config::deserialize(SeqAccessDeserializer::new(LegacyPositions {
2535 inner: seq,
2536 fields: fields.iter(),
2537 legacy: &mut legacy,
2538 }))?;
2539 Ok((config, legacy_backend_keys_from(legacy)?))
2540 }
2541 }
2542
2543 /// Reads the collected legacy keys with their old types and defaults. A
2544 /// key that appeared twice is collected twice, and fails here as a
2545 /// duplicate field.
2546 fn legacy_backend_keys_from<E: de::Error>(
2547 legacy: Vec<(&'static str, bool)>,
2548 ) -> Result<LegacyBackendKeys, E> {
2549 LegacyBackendKeys::deserialize(MapDeserializer::<_, E>::new(legacy.into_iter()))
2550 }
2551
2552 /// The top-level object's entries, with each legacy backend key read as the
2553 /// boolean it was and collected rather than passed on, and each key of
2554 /// [`FIELDS_WITHOUT_A_LEGACY_KEY`] skipped as the unknown key it was.
2555 struct LegacyKeys<'l, A> {
2556 inner: A,
2557 legacy: &'l mut Vec<(&'static str, bool)>,
2558 }
2559
2560 impl<'de, A: MapAccess<'de>> MapAccess<'de> for LegacyKeys<'_, A> {
2561 type Error = A::Error;
2562
2563 fn next_key_seed<K: DeserializeSeed<'de>>(
2564 &mut self,
2565 seed: K,
2566 ) -> Result<Option<K::Value>, A::Error> {
2567 while let Some(key) = self.inner.next_key::<String>()? {
2568 if let Some(name) = LEGACY_BACKEND_KEY_NAMES
2569 .into_iter()
2570 .find(|name| *name == key)
2571 {
2572 let value = self.inner.next_value::<bool>()?;
2573 self.legacy.push((name, value));
2574 } else if FIELDS_WITHOUT_A_LEGACY_KEY.contains(&key.as_str()) {
2575 self.inner.next_value::<IgnoredAny>()?;
2576 } else {
2577 return seed.deserialize(StringDeserializer::new(key)).map(Some);
2578 }
2579 }
2580 Ok(None)
2581 }
2582
2583 fn next_value_seed<V: DeserializeSeed<'de>>(
2584 &mut self,
2585 seed: V,
2586 ) -> Result<V::Value, A::Error> {
2587 self.inner.next_value_seed(seed)
2588 }
2589 }
2590
2591 /// The top-level array's elements, in the legacy form's positions. The
2592 /// derived `Config` deserializer asks for one element per field in
2593 /// declaration order; at [`Config::backend`] this reads up to fifteen
2594 /// elements as the legacy backend keys, and neither the field it asks for
2595 /// there nor [`Config::record_host_inputs`],
2596 /// [`Config::guest_may_inherit_a_terminal`],
2597 /// [`Config::in_guest_detlog_forward_policy`],
2598 /// [`Config::in_guest_site_patching_off`], [`Config::launch_image`],
2599 /// [`Config::target_timeslice_syscalls_only`],
2600 /// [`Config::futex_wake_yields`], [`Config::replaying`],
2601 /// [`Config::scheduler_turn_cost`] or [`Config::inherited_seccomp`] takes
2602 /// an element. Each gets a
2603 /// placeholder; [`super::from_legacy_backend_json`] replaces the first.
2604 struct LegacyPositions<'f, 'l, A> {
2605 inner: A,
2606 fields: std::slice::Iter<'f, String>,
2607 legacy: &'l mut Vec<(&'static str, bool)>,
2608 }
2609
2610 impl<'de, A: SeqAccess<'de>> SeqAccess<'de> for LegacyPositions<'_, '_, A> {
2611 type Error = A::Error;
2612
2613 fn next_element_seed<T: DeserializeSeed<'de>>(
2614 &mut self,
2615 seed: T,
2616 ) -> Result<Option<T::Value>, A::Error> {
2617 match self.fields.next().map(String::as_str) {
2618 Some("backend") => {
2619 for name in LEGACY_BACKEND_KEY_NAMES {
2620 match self.inner.next_element::<bool>()? {
2621 Some(value) => self.legacy.push((name, value)),
2622 // A short array; the rest take their defaults.
2623 None => break,
2624 }
2625 }
2626 let placeholder = serde_json::to_value(BackendCapabilities::PTRACE)
2627 .map_err(<A::Error as de::Error>::custom)?;
2628 seed.deserialize(placeholder)
2629 .map(Some)
2630 .map_err(<A::Error as de::Error>::custom)
2631 }
2632 Some(
2633 "record_host_inputs"
2634 | "guest_may_inherit_a_terminal"
2635 | "in_guest_site_patching_off"
2636 | "target_timeslice_syscalls_only"
2637 | "futex_wake_yields"
2638 | "replaying"
2639 | "signal_delivery_check_fatal",
2640 ) => seed.deserialize(BoolDeserializer::new(false)).map(Some),
2641 // On, as its serde default is.
2642 Some("signal_state_copy") => {
2643 seed.deserialize(BoolDeserializer::new(true)).map(Some)
2644 }
2645 // Unset, as its serde default is.
2646 Some(
2647 "in_guest_detlog_forward_policy"
2648 | "launch_image"
2649 | "scheduler_turn_cost"
2650 | "pipe_wake_latency"
2651 | "container_mount_table"
2652 | "mountinfo_mount_namespace",
2653 ) => seed
2654 .deserialize(serde_json::Value::Null)
2655 .map(Some)
2656 .map_err(<A::Error as de::Error>::custom),
2657 // x86-64-v2, as their serde defaults are.
2658 Some("cpu_profile") => {
2659 let v2 = serde_json::to_value(crate::cpu_profile::CpuProfile::X86_64V2)
2660 .map_err(<A::Error as de::Error>::custom)?;
2661 seed.deserialize(v2)
2662 .map(Some)
2663 .map_err(<A::Error as de::Error>::custom)
2664 }
2665 Some("cpu_profile_host") => seed
2666 .deserialize(serde_json::Value::Null)
2667 .map(Some)
2668 .map_err(<A::Error as de::Error>::custom),
2669 // Unknown, as its serde default is.
2670 Some("inherited_seccomp") => {
2671 let unknown = serde_json::to_value(super::InheritedSeccomp::Unknown)
2672 .map_err(<A::Error as de::Error>::custom)?;
2673 seed.deserialize(unknown)
2674 .map(Some)
2675 .map_err(<A::Error as de::Error>::custom)
2676 }
2677 _ => self.inner.next_element_seed(seed),
2678 }
2679 }
2680 }
2681
2682 /// The names of `Config`'s serialized fields in declaration order, which
2683 /// is the order its derived deserializer reads an array in: no field is
2684 /// serialized without being deserialized or the reverse.
2685 ///
2686 /// The configuration serialized to learn them is built by Clap from no
2687 /// arguments, with every environment binding removed before parsing.
2688 /// Building `Config::command()` still reads the bound variables (Clap's
2689 /// `Arg::env` reads a variable's value when the binding is made), but
2690 /// removing the bindings discards those values, so no ambient value
2691 /// reaches the parse. `Config::default()` would instead parse
2692 /// HERMIT_EPOCH, HERMIT_PRNG and HERMIT_SCHED_SEED, and exit the process
2693 /// when one of them does not parse; the legacy decoder was not affected
2694 /// by any of them.
2695 fn config_field_order() -> serde_json::Result<Vec<String>> {
2696 let config = environment_free_config().map_err(<serde_json::Error as de::Error>::custom)?;
2697 let json = serde_json::to_string(&config)?;
2698 Ok(serde_json::from_str::<KeyOrder>(&json)?.0)
2699 }
2700
2701 /// `Config` as Clap builds it from no arguments and no environment.
2702 fn environment_free_config() -> Result<Config, clap::Error> {
2703 use clap::CommandFactory;
2704 use clap::FromArgMatches;
2705
2706 let matches = Config::command()
2707 .mut_args(|arg| arg.env(None::<&'static str>))
2708 .try_get_matches_from(["config-field-order"])?;
2709 Config::from_arg_matches(&matches)
2710 }
2711
2712 /// The keys of a JSON object, in the order they appear.
2713 pub(super) struct KeyOrder(pub(super) Vec<String>);
2714
2715 impl<'de> Deserialize<'de> for KeyOrder {
2716 fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2717 struct KeyOrderVisitor;
2718
2719 impl<'de> Visitor<'de> for KeyOrderVisitor {
2720 type Value = KeyOrder;
2721
2722 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2723 formatter.write_str("a JSON object")
2724 }
2725
2726 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<KeyOrder, A::Error> {
2727 let mut keys = Vec::new();
2728 while let Some(key) = map.next_key::<String>()? {
2729 map.next_value::<IgnoredAny>()?;
2730 keys.push(key);
2731 }
2732 Ok(KeyOrder(keys))
2733 }
2734 }
2735
2736 deserializer.deserialize_map(KeyOrderVisitor)
2737 }
2738 }
2739
2740 pub(super) struct ConfigSerializer<'c, S> {
2741 pub(super) inner: S,
2742 pub(super) config: &'c Config,
2743 }
2744
2745 pub(super) struct ConfigFields<'c, S> {
2746 inner: S,
2747 config: &'c Config,
2748 wrote_backend_keys: bool,
2749 }
2750
2751 fn not_a_config<E: serde::ser::Error>() -> E {
2752 E::custom("the legacy backend JSON encoding applies only to a Detcore Config")
2753 }
2754
2755 impl<'c, S: Serializer> Serializer for ConfigSerializer<'c, S> {
2756 type Ok = S::Ok;
2757 type Error = S::Error;
2758 type SerializeSeq = Impossible<S::Ok, S::Error>;
2759 type SerializeTuple = Impossible<S::Ok, S::Error>;
2760 type SerializeTupleStruct = Impossible<S::Ok, S::Error>;
2761 type SerializeTupleVariant = Impossible<S::Ok, S::Error>;
2762 type SerializeMap = Impossible<S::Ok, S::Error>;
2763 type SerializeStruct = ConfigFields<'c, S::SerializeStruct>;
2764 type SerializeStructVariant = Impossible<S::Ok, S::Error>;
2765
2766 fn is_human_readable(&self) -> bool {
2767 self.inner.is_human_readable()
2768 }
2769
2770 fn serialize_struct(
2771 self,
2772 name: &'static str,
2773 len: usize,
2774 ) -> Result<Self::SerializeStruct, S::Error> {
2775 // Two fields are replaced by fifteen keys.
2776 let len = len + legacy_backend_keys(self.config).len() - 2;
2777 Ok(ConfigFields {
2778 inner: self.inner.serialize_struct(name, len)?,
2779 config: self.config,
2780 wrote_backend_keys: false,
2781 })
2782 }
2783
2784 fn serialize_bool(self, _: bool) -> Result<S::Ok, S::Error> {
2785 Err(not_a_config())
2786 }
2787 fn serialize_i8(self, _: i8) -> Result<S::Ok, S::Error> {
2788 Err(not_a_config())
2789 }
2790 fn serialize_i16(self, _: i16) -> Result<S::Ok, S::Error> {
2791 Err(not_a_config())
2792 }
2793 fn serialize_i32(self, _: i32) -> Result<S::Ok, S::Error> {
2794 Err(not_a_config())
2795 }
2796 fn serialize_i64(self, _: i64) -> Result<S::Ok, S::Error> {
2797 Err(not_a_config())
2798 }
2799 fn serialize_u8(self, _: u8) -> Result<S::Ok, S::Error> {
2800 Err(not_a_config())
2801 }
2802 fn serialize_u16(self, _: u16) -> Result<S::Ok, S::Error> {
2803 Err(not_a_config())
2804 }
2805 fn serialize_u32(self, _: u32) -> Result<S::Ok, S::Error> {
2806 Err(not_a_config())
2807 }
2808 fn serialize_u64(self, _: u64) -> Result<S::Ok, S::Error> {
2809 Err(not_a_config())
2810 }
2811 fn serialize_f32(self, _: f32) -> Result<S::Ok, S::Error> {
2812 Err(not_a_config())
2813 }
2814 fn serialize_f64(self, _: f64) -> Result<S::Ok, S::Error> {
2815 Err(not_a_config())
2816 }
2817 fn serialize_char(self, _: char) -> Result<S::Ok, S::Error> {
2818 Err(not_a_config())
2819 }
2820 fn serialize_str(self, _: &str) -> Result<S::Ok, S::Error> {
2821 Err(not_a_config())
2822 }
2823 fn serialize_bytes(self, _: &[u8]) -> Result<S::Ok, S::Error> {
2824 Err(not_a_config())
2825 }
2826 fn serialize_none(self) -> Result<S::Ok, S::Error> {
2827 Err(not_a_config())
2828 }
2829 fn serialize_some<T: ?Sized + Serialize>(self, _: &T) -> Result<S::Ok, S::Error> {
2830 Err(not_a_config())
2831 }
2832 fn serialize_unit(self) -> Result<S::Ok, S::Error> {
2833 Err(not_a_config())
2834 }
2835 fn serialize_unit_struct(self, _: &'static str) -> Result<S::Ok, S::Error> {
2836 Err(not_a_config())
2837 }
2838 fn serialize_unit_variant(
2839 self,
2840 _: &'static str,
2841 _: u32,
2842 _: &'static str,
2843 ) -> Result<S::Ok, S::Error> {
2844 Err(not_a_config())
2845 }
2846 fn serialize_newtype_struct<T: ?Sized + Serialize>(
2847 self,
2848 _: &'static str,
2849 _: &T,
2850 ) -> Result<S::Ok, S::Error> {
2851 Err(not_a_config())
2852 }
2853 fn serialize_newtype_variant<T: ?Sized + Serialize>(
2854 self,
2855 _: &'static str,
2856 _: u32,
2857 _: &'static str,
2858 _: &T,
2859 ) -> Result<S::Ok, S::Error> {
2860 Err(not_a_config())
2861 }
2862 fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, S::Error> {
2863 Err(not_a_config())
2864 }
2865 fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, S::Error> {
2866 Err(not_a_config())
2867 }
2868 fn serialize_tuple_struct(
2869 self,
2870 _: &'static str,
2871 _: usize,
2872 ) -> Result<Self::SerializeTupleStruct, S::Error> {
2873 Err(not_a_config())
2874 }
2875 fn serialize_tuple_variant(
2876 self,
2877 _: &'static str,
2878 _: u32,
2879 _: &'static str,
2880 _: usize,
2881 ) -> Result<Self::SerializeTupleVariant, S::Error> {
2882 Err(not_a_config())
2883 }
2884 fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, S::Error> {
2885 Err(not_a_config())
2886 }
2887 fn serialize_struct_variant(
2888 self,
2889 _: &'static str,
2890 _: u32,
2891 _: &'static str,
2892 _: usize,
2893 ) -> Result<Self::SerializeStructVariant, S::Error> {
2894 Err(not_a_config())
2895 }
2896 }
2897
2898 impl<S: SerializeStruct> SerializeStruct for ConfigFields<'_, S> {
2899 type Ok = S::Ok;
2900 type Error = S::Error;
2901
2902 fn serialize_field<T: ?Sized + Serialize>(
2903 &mut self,
2904 key: &'static str,
2905 value: &T,
2906 ) -> Result<(), S::Error> {
2907 match key {
2908 "backend" => {
2909 for (legacy_key, legacy_value) in legacy_backend_keys(self.config) {
2910 self.inner.serialize_field(legacy_key, &legacy_value)?;
2911 }
2912 self.wrote_backend_keys = true;
2913 Ok(())
2914 }
2915 // No legacy key; see FIELDS_WITHOUT_A_LEGACY_KEY.
2916 "record_host_inputs"
2917 | "guest_may_inherit_a_terminal"
2918 | "in_guest_detlog_forward_policy"
2919 | "in_guest_site_patching_off"
2920 | "launch_image"
2921 | "target_timeslice_syscalls_only"
2922 | "futex_wake_yields"
2923 | "pipe_wake_latency"
2924 | "replaying"
2925 | "scheduler_turn_cost"
2926 | "inherited_seccomp"
2927 | "cpu_profile"
2928 | "cpu_profile_host"
2929 | "signal_state_copy"
2930 | "container_mount_table"
2931 | "mountinfo_mount_namespace"
2932 | "signal_delivery_check_fatal" => Ok(()),
2933 _ => self.inner.serialize_field(key, value),
2934 }
2935 }
2936
2937 fn skip_field(&mut self, key: &'static str) -> Result<(), S::Error> {
2938 self.inner.skip_field(key)
2939 }
2940
2941 fn end(self) -> Result<S::Ok, S::Error> {
2942 if !self.wrote_backend_keys {
2943 return Err(S::Error::custom(
2944 "Config serialized no `backend` field to replace with the legacy backend keys",
2945 ));
2946 }
2947 self.inner.end()
2948 }
2949 }
2950}
2951
2952#[cfg(test)]
2953mod tests {
2954 use super::*;
2955
2956 #[test]
2957 fn default_epoch_is_2026() {
2958 assert_eq!(DEFAULT_EPOCH_STR, "2026-01-01T00:00:00Z");
2959 let epoch = DEFAULT_EPOCH_STR.parse::<DateTime<Utc>>().unwrap();
2960 assert_eq!(epoch.timestamp(), 1_767_225_600);
2961 }
2962
2963 #[test]
2964 fn resolved_epoch_is_serialized_as_an_exact_config_input() {
2965 let epoch = "2000-12-31T23:59:59.123456789Z"
2966 .parse::<DateTime<Utc>>()
2967 .unwrap();
2968 let config = Config {
2969 epoch,
2970 ..Config::default()
2971 };
2972 let encoded = serde_json::to_value(&config).unwrap();
2973 assert_eq!(
2974 encoded["epoch"],
2975 serde_json::json!("2000-12-31T23:59:59.123456789Z")
2976 );
2977 let decoded: Config = serde_json::from_value(encoded).unwrap();
2978 assert_eq!(decoded.epoch, epoch);
2979 }
2980
2981 #[test]
2982 fn default_backend_capabilities_match_instrumented_backends() {
2983 let config = Config::default();
2984 assert_eq!(config.backend, DEFAULT_BACKEND_CAPABILITIES);
2985 assert!(!config.backend.reports_physical_process_exits);
2986 assert!(config.backend.tracks_process_children);
2987 assert!(config.backend.runs_exit_robust_list);
2988 assert!(!config.backend.requires_thread_directed_process_signals);
2989 assert!(config.backend.supports_parked_write_signal_interruption);
2990 assert!(!config.backend.defers_vfork_child_registration);
2991 assert!(!config.sequentialize_threads);
2992 assert!(
2993 legacy_backend_keys(&config).contains(&("kvm_shared_dequeue_timers", false)),
2994 "the default configuration must not write a controlled-run legacy key"
2995 );
2996 assert!(!config.backend.supports_blocked_wait_signal_interruption);
2997 assert!(!config.backend.delivers_preemption_timer_events);
2998 assert!(!config.backend.runs_guest_code_between_injections);
2999 assert!(!config.guest_may_inherit_a_terminal);
3000 assert!(config.in_guest_detlog_forward_policy.is_none());
3001 assert!(!config.in_guest_site_patching_off);
3002 assert!(config.launch_image.is_none());
3003 }
3004
3005 #[test]
3006 fn a_config_without_backend_capabilities_deserializes_as_ptrace() {
3007 let mut encoded = serde_json::to_value(Config::default()).unwrap();
3008 let fields = encoded.as_object_mut().unwrap();
3009 assert!(fields.remove("backend").is_some());
3010 assert!(!fields.contains_key("shared_dequeue_timers"));
3011 let decoded: Config = serde_json::from_value(encoded).unwrap();
3012 assert_eq!(decoded.backend, DEFAULT_BACKEND_CAPABILITIES);
3013 }
3014
3015 /// `Config`'s own derived deserializer ignores a key it does not name, and
3016 /// `shared_dequeue_timers` is no longer one it names, so JSON saved while
3017 /// it was a field still reads and the key decides nothing, whatever it
3018 /// holds and however often it appears. This is the whole compatibility
3019 /// policy for the named form, and it is safe because no production code
3020 /// reads a `Config` by field name: the guest-visible DBT form is read by
3021 /// [`from_legacy_backend_json`], which checks the key, and the bincode form
3022 /// that crosses process boundaries is positional. Removing the field
3023 /// changed that positional form and [`config_wire_fingerprint`]. SaBRe's
3024 /// plugin compares the fingerprint and refuses a coordinator from another
3025 /// build; LiteInst's in-guest runtime does not, so a runtime library built
3026 /// before the removal and loaded by a newer coordinator can misdecode the
3027 /// Config and fail its initialization (exit 127). That mixed-build hazard
3028 /// is not new: every change to the positional form has it.
3029 #[test]
3030 fn a_saved_shared_dequeue_timers_field_is_ignored() {
3031 let baseline = serde_json::to_string(&Config::default()).unwrap();
3032 for extra in [
3033 r#""shared_dequeue_timers":false"#,
3034 r#""shared_dequeue_timers":true"#,
3035 r#""shared_dequeue_timers":"yes""#,
3036 r#""shared_dequeue_timers":true,"shared_dequeue_timers":false"#,
3037 ] {
3038 let edited = baseline.replacen('{', &format!("{{{extra},"), 1);
3039 let decoded: Config = serde_json::from_str(&edited).unwrap();
3040 assert_eq!(
3041 serde_json::to_string(&decoded).unwrap(),
3042 baseline,
3043 "{edited}"
3044 );
3045 }
3046 }
3047
3048 /// Ptrace's capabilities with the robust-list transition and parked-write
3049 /// signal interruption both left to Detcore: the value the retired
3050 /// ptrace-hosted LiteInst runtime reported. No backend reports it now, but
3051 /// the legacy keys can still express it, so the round trips keep it.
3052 fn ptrace_without_exit_transitions() -> BackendCapabilities {
3053 let mut backend = BackendCapabilities::PTRACE;
3054 backend.runs_exit_robust_list = false;
3055 backend.supports_parked_write_signal_interruption = false;
3056 backend
3057 }
3058
3059 /// `backend` as the legacy form can carry it: capabilities added after the
3060 /// form froze never enter it and read back as their default (see
3061 /// [`process_exits_complete_asynchronously_never_enters_the_legacy_form`]).
3062 fn legacy_expressible(mut backend: BackendCapabilities) -> BackendCapabilities {
3063 backend.process_exits_complete_asynchronously = false;
3064 backend.virtualizes_guest_sigalrm = false;
3065 backend.supports_blocked_wait_signal_interruption = false;
3066 backend.delivers_preemption_timer_events = false;
3067 backend.runs_guest_code_between_injections = false;
3068 backend.reports_sigreturns = false;
3069 backend.reports_kernel_child_exit_signals = backend.reports_child_exit_publication;
3070 // The legacy discover_live_file_metadata bit couples four facts.
3071 backend.rediscovers_descriptors_after_exec = backend.tool_shares_guest_descriptor_table;
3072 // The legacy form derives promotion from the thread-directed signal
3073 // bit, which only DBT, the form's only reader, sets.
3074 backend.promotes_open_files_before_native_lifecycle =
3075 backend.requires_thread_directed_process_signals;
3076 backend.internal_pipe_turns_are_host_timed = backend.tool_shares_guest_descriptor_table;
3077 backend.loopback_pollers_yield_to_peers = backend.tool_shares_guest_descriptor_table;
3078 backend
3079 }
3080
3081 #[test]
3082 fn legacy_backend_json_round_trips_every_backend_capabilities_constant() {
3083 for (name, backend) in [
3084 ("PTRACE", BackendCapabilities::PTRACE),
3085 ("E9PATCH", BackendCapabilities::E9PATCH),
3086 (
3087 "ptrace without exit transitions",
3088 ptrace_without_exit_transitions(),
3089 ),
3090 ("LITEINST_IN_GUEST", BackendCapabilities::LITEINST_IN_GUEST),
3091 ("SABRE", BackendCapabilities::SABRE),
3092 ("DBT", BackendCapabilities::DBT),
3093 ("KVM", BackendCapabilities::KVM),
3094 ] {
3095 for sequentialize_threads in [false, true] {
3096 let sent = Config {
3097 backend,
3098 sequentialize_threads,
3099 ..Config::default()
3100 };
3101 let json = to_legacy_backend_json(&sent).unwrap();
3102 let received = from_legacy_backend_json(&json).unwrap();
3103 assert_eq!(received.backend, legacy_expressible(backend), "{name}");
3104 assert_eq!(
3105 received.sequentialize_threads, sequentialize_threads,
3106 "{name}"
3107 );
3108 assert_controlled_key(&json, &backend, sequentialize_threads, name);
3109 let expressible = Config {
3110 backend: legacy_expressible(backend),
3111 ..sent.clone()
3112 };
3113 assert_eq!(
3114 serde_json::to_string(&received).unwrap(),
3115 serde_json::to_string(&expressible).unwrap(),
3116 "{name}"
3117 );
3118 assert_eq!(to_legacy_backend_json(&received).unwrap(), json, "{name}");
3119 assert_controlled_key_is_checked(&json, &sent, name);
3120 }
3121 }
3122 }
3123
3124 #[test]
3125 fn backend_config_json_preserves_every_backend_and_representable_bytes() {
3126 for (name, backend, needs_envelope) in [
3127 ("PTRACE", BackendCapabilities::PTRACE, true),
3128 ("E9PATCH", BackendCapabilities::E9PATCH, true),
3129 (
3130 "LITEINST_IN_GUEST",
3131 BackendCapabilities::LITEINST_IN_GUEST,
3132 true,
3133 ),
3134 ("SABRE", BackendCapabilities::SABRE, true),
3135 ("DBT", BackendCapabilities::DBT, true),
3136 ("KVM", BackendCapabilities::KVM, false),
3137 ] {
3138 for sequentialize_threads in [false, true] {
3139 let sent = Config {
3140 backend,
3141 sequentialize_threads,
3142 ..Config::default()
3143 };
3144 let legacy = to_legacy_backend_json(&sent).unwrap();
3145 let encoded = encode_backend_config_json(legacy.clone(), backend).unwrap();
3146 assert_eq!(encoded != legacy, needs_envelope, "{name}");
3147 assert_eq!(
3148 from_legacy_backend_json(&encoded).is_err(),
3149 needs_envelope,
3150 "{name}: an envelope must not be accepted as a legacy config"
3151 );
3152 let received = decode_backend_config_json(&encoded).unwrap();
3153 assert_eq!(received.backend, backend, "{name}");
3154 assert_eq!(
3155 serde_json::to_string(&received).unwrap(),
3156 serde_json::to_string(&sent).unwrap(),
3157 "{name}"
3158 );
3159 }
3160 }
3161 }
3162
3163 #[test]
3164 fn backend_config_json_round_trips_each_independent_capability() {
3165 let baseline = serde_json::to_value(BackendCapabilities::DBT).unwrap();
3166 for (name, value) in baseline.as_object().unwrap() {
3167 let mut edited = baseline.clone();
3168 edited[name] = serde_json::Value::Bool(!value.as_bool().unwrap());
3169 let backend = serde_json::from_value(edited).unwrap();
3170 let sent = Config {
3171 backend,
3172 ..Config::default()
3173 };
3174 let legacy = to_legacy_backend_json(&sent).unwrap();
3175 let encoded = encode_backend_config_json(legacy, backend).unwrap();
3176 let received = decode_backend_config_json(&encoded).unwrap();
3177 assert_eq!(received.backend, backend, "{name}");
3178 }
3179 }
3180
3181 #[test]
3182 fn backend_config_json_requires_each_typed_capability_once() {
3183 let sent = Config {
3184 backend: BackendCapabilities::LITEINST_IN_GUEST,
3185 ..Config::default()
3186 };
3187 let encoded =
3188 encode_backend_config_json(to_legacy_backend_json(&sent).unwrap(), sent.backend)
3189 .unwrap();
3190 let envelope: serde_json::Value = serde_json::from_str(&encoded).unwrap();
3191 for (name, value) in envelope["backend"].as_object().unwrap() {
3192 let mut missing = envelope.clone();
3193 missing["backend"].as_object_mut().unwrap().remove(name);
3194 assert!(
3195 decode_backend_config_json(&missing.to_string()).is_err(),
3196 "missing {name}"
3197 );
3198 let backend = serde_json::to_string(&sent.backend).unwrap();
3199 let duplicate = backend.replacen('{', &format!("{{\"{name}\":{value},"), 1);
3200 let duplicate = encoded.replace(&backend, &duplicate);
3201 assert_ne!(duplicate, encoded);
3202 assert!(
3203 decode_backend_config_json(&duplicate).is_err(),
3204 "duplicate {name}"
3205 );
3206 }
3207 }
3208
3209 #[test]
3210 fn backend_config_json_keeps_legacy_object_and_array_semantics() {
3211 let legacy = to_legacy_backend_json(&Config::default()).unwrap();
3212 let unknown_duplicates = legacy.replacen(
3213 '{',
3214 r#"{"unrecognized":1,"unrecognized":null,"backend":null,"backend":true,"dbt_config_version":null,"dbt_config_version":2,"#,
3215 1,
3216 );
3217 let known_duplicate = legacy.replacen('{', r#"{"seed":1,"#, 1);
3218 let mistyped = legacy.replacen("\"backend_is_kvm\":false", "\"backend_is_kvm\":null", 1);
3219 assert_ne!(mistyped, legacy);
3220 for json in [
3221 legacy.clone(),
3222 positional(&legacy),
3223 unknown_duplicates,
3224 known_duplicate,
3225 mistyped,
3226 format!("{legacy} trailing"),
3227 "[]".to_owned(),
3228 ] {
3229 let old = from_legacy_backend_json(&json);
3230 let new = decode_backend_config_json(&json);
3231 match (old, new) {
3232 (Ok(old), Ok(new)) => assert_eq!(
3233 serde_json::to_string(&old).unwrap(),
3234 serde_json::to_string(&new).unwrap()
3235 ),
3236 (Err(_), Err(_)) => {}
3237 _ => panic!("legacy parse outcome changed for {json}"),
3238 }
3239 }
3240 }
3241
3242 /// `kvm_shared_dequeue_timers` is read independently of the other keys,
3243 /// absent, false or true, and the parse succeeds exactly when the value
3244 /// read (false when absent) equals `backend_is_kvm &&
3245 /// sequentialize_threads`. Under that condition the accepted value is the
3246 /// one the decoded capabilities and `sequentialize_threads` imply, so the
3247 /// decoded configuration is the one sent; otherwise the error names the
3248 /// key.
3249 fn assert_controlled_key_is_checked(json: &str, sent: &Config, name: &str) {
3250 let controlled = sent.backend.provides_process_signal_control && sent.sequentialize_threads;
3251 let written = format!("\"kvm_shared_dequeue_timers\":{controlled}");
3252 assert_eq!(json.matches(&written).count(), 1, "{name}");
3253 for value in [None, Some(false), Some(true)] {
3254 let edited = match value {
3255 None => json.replacen(&format!(",{written}"), "", 1),
3256 Some(value) => json.replacen(
3257 &written,
3258 &format!("\"kvm_shared_dequeue_timers\":{value}"),
3259 1,
3260 ),
3261 };
3262 assert_eq!(
3263 edited.contains("kvm_shared_dequeue_timers"),
3264 value.is_some(),
3265 "{name} {value:?}"
3266 );
3267 let case = format!(
3268 "{name} sequentialize_threads={} key={value:?}",
3269 sent.sequentialize_threads
3270 );
3271 match from_legacy_backend_json(&edited) {
3272 Ok(received) => {
3273 assert_eq!(value.unwrap_or(false), controlled, "{case} was accepted");
3274 // Compared with what the legacy form can carry; see
3275 // `legacy_expressible`.
3276 let expressible = Config {
3277 backend: legacy_expressible(sent.backend),
3278 ..sent.clone()
3279 };
3280 assert_eq!(
3281 serde_json::to_string(&received).unwrap(),
3282 serde_json::to_string(&expressible).unwrap(),
3283 "{case}"
3284 );
3285 }
3286 Err(error) => {
3287 assert_ne!(value.unwrap_or(false), controlled, "{case}: {error}");
3288 assert!(
3289 error.to_string().contains("kvm_shared_dequeue_timers"),
3290 "{case}: {error}"
3291 );
3292 }
3293 }
3294 }
3295 }
3296
3297 /// The four controlled-key outcomes that differ from simply ignoring the
3298 /// key, spelled out: each would otherwise run a configuration on a path
3299 /// other than the one the same JSON selected before.
3300 #[test]
3301 fn a_controlled_key_that_contradicts_the_capabilities_fails_the_parse() {
3302 let kvm = Config {
3303 backend: BackendCapabilities::KVM,
3304 sequentialize_threads: true,
3305 ..Config::default()
3306 };
3307 let kvm_json = to_legacy_backend_json(&kvm).unwrap();
3308 assert!(from_legacy_backend_json(&kvm_json).is_ok());
3309 let dbt = Config {
3310 backend: BackendCapabilities::DBT,
3311 sequentialize_threads: true,
3312 ..Config::default()
3313 };
3314 let dbt_json = to_legacy_backend_json(&dbt).unwrap();
3315 assert!(from_legacy_backend_json(&dbt_json).is_ok());
3316 for edited in [
3317 // KVM, sequentialized, key false: the control was left uninstalled.
3318 kvm_json.replacen(
3319 r#""kvm_shared_dequeue_timers":true"#,
3320 r#""kvm_shared_dequeue_timers":false"#,
3321 1,
3322 ),
3323 // KVM, sequentialized, key absent: read as false, as before.
3324 kvm_json.replacen(r#","kvm_shared_dequeue_timers":true"#, "", 1),
3325 // No control capability, key true: the controlled loop was chosen.
3326 dbt_json.replacen(
3327 r#""kvm_shared_dequeue_timers":false"#,
3328 r#""kvm_shared_dequeue_timers":true"#,
3329 1,
3330 ),
3331 // KVM without sequentialized threads, key true.
3332 to_legacy_backend_json(&Config {
3333 sequentialize_threads: false,
3334 ..kvm.clone()
3335 })
3336 .unwrap()
3337 .replacen(
3338 r#""kvm_shared_dequeue_timers":false"#,
3339 r#""kvm_shared_dequeue_timers":true"#,
3340 1,
3341 ),
3342 ] {
3343 assert_ne!(edited, kvm_json);
3344 assert_ne!(edited, dbt_json);
3345 let error = from_legacy_backend_json(&edited).unwrap_err();
3346 assert!(
3347 error.to_string().contains("kvm_shared_dequeue_timers"),
3348 "{error}"
3349 );
3350 }
3351 }
3352
3353 /// Each legacy key decodes as the `Config` field it was: absent, it takes
3354 /// that field's default, and set alone, it gives exactly the capabilities
3355 /// that replaced Detcore's reads of that field.
3356 #[test]
3357 fn legacy_backend_keys_decode_as_the_fields_they_were() {
3358 let ptrace_json = to_legacy_backend_json(&Config::default()).unwrap();
3359 let ptrace: serde_json::Map<String, serde_json::Value> =
3360 serde_json::from_str(&ptrace_json).unwrap();
3361 let keys = legacy_backend_keys(&Config::default());
3362
3363 let mut absent = ptrace.clone();
3364 for (key, _) in keys {
3365 assert!(absent.remove(key).is_some(), "{key}");
3366 }
3367 let decoded = from_legacy_backend_json(&serde_json::to_string(&absent).unwrap()).unwrap();
3368 // The capabilities added after the legacy form froze read back as
3369 // false (`legacy_expressible`), whatever ptrace reports.
3370 let legacy_ptrace = legacy_expressible(BackendCapabilities::PTRACE);
3371 assert_eq!(decoded.backend, legacy_ptrace);
3372 let unflipped =
3373 serde_json::to_string(&from_legacy_backend_json(&ptrace_json).unwrap()).unwrap();
3374 assert_eq!(serde_json::to_string(&decoded).unwrap(), unflipped);
3375
3376 for (key, ptrace_value) in keys {
3377 let mut expected = legacy_ptrace;
3378 match key {
3379 "cpuid_virtualized_by_backend" => {
3380 // No backend installs a CPUID policy of its own, so `true`
3381 // fails the parse.
3382 let mut flipped = ptrace.clone();
3383 flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
3384 let error = from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap())
3385 .unwrap_err();
3386 assert!(error.to_string().contains(key), "{error}");
3387 continue;
3388 }
3389 "backend_supports_madvise" => {
3390 expected.supports_madvise = false;
3391 expected.supports_madv_dontneed = false;
3392 }
3393 "discover_live_file_metadata" => {
3394 expected.tool_shares_guest_descriptor_table = true;
3395 expected.rediscovers_descriptors_after_exec = true;
3396 expected.internal_pipe_turns_are_host_timed = true;
3397 expected.loopback_pollers_yield_to_peers = true;
3398 }
3399 "detect_host_clock_futex_timeouts" => {
3400 expected.guest_clock_reads_bypass_backend = true
3401 }
3402 "syscall_clobbers_virtualized_by_backend" => {
3403 expected.virtualizes_syscall_clobbers = true
3404 }
3405 "cancel_killed_thread_rpcs" => {
3406 expected.needs_killed_thread_rpc_cancellation = true;
3407 expected.reports_child_exit_publication = false;
3408 expected.reports_kernel_child_exit_signals = false;
3409 }
3410 "backend_reports_physical_process_exits" => {
3411 expected.reports_physical_process_exits = true;
3412 expected.signal_interrupts_external_syscalls = true;
3413 }
3414 "backend_tracks_process_children" => expected.tracks_process_children = false,
3415 "backend_runs_exit_robust_list" => expected.runs_exit_robust_list = false,
3416 "backend_requires_thread_directed_process_signals" => {
3417 expected.requires_thread_directed_process_signals = true;
3418 expected.promotes_open_files_before_native_lifecycle = true;
3419 }
3420 "backend_is_kvm" => {
3421 expected.provides_process_signal_control = true;
3422 expected.emulates_child_waits = true;
3423 }
3424 "kvm_shared_dequeue_timers" => {
3425 // Set alone it contradicts `backend_is_kvm`, so the parse
3426 // fails; see
3427 // `a_controlled_key_that_contradicts_the_capabilities_fails_the_parse`.
3428 let mut flipped = ptrace.clone();
3429 flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
3430 assert!(
3431 from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap())
3432 .is_err(),
3433 "{key}"
3434 );
3435 continue;
3436 }
3437 "backend_supports_parked_write_signal_interruption" => {
3438 expected.supports_parked_write_signal_interruption = false
3439 }
3440 "backend_virtualizes_capability_prctls" => {
3441 // No backend answers the capability prctls itself, so
3442 // `true` fails the parse.
3443 let mut flipped = ptrace.clone();
3444 flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
3445 let error = from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap())
3446 .unwrap_err();
3447 assert!(error.to_string().contains(key), "{error}");
3448 continue;
3449 }
3450 "backend_defers_vfork_child_registration" => {
3451 expected.defers_vfork_child_registration = true
3452 }
3453 other => panic!("no expectation for legacy key {other}"),
3454 }
3455 let mut flipped = ptrace.clone();
3456 flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
3457 let decoded =
3458 from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap()).unwrap();
3459 assert_eq!(decoded.backend, expected, "{key}");
3460 assert_ne!(serde_json::to_string(&decoded).unwrap(), unflipped, "{key}");
3461 }
3462 }
3463
3464 /// The legacy `kvm_shared_dequeue_timers` key holds exactly when the
3465 /// backend provides process signal control and threads are sequentialized,
3466 /// the condition under which Detcore installs that control.
3467 fn assert_controlled_key(
3468 json: &str,
3469 backend: &BackendCapabilities,
3470 sequentialize_threads: bool,
3471 name: &str,
3472 ) {
3473 let object: serde_json::Map<String, serde_json::Value> =
3474 serde_json::from_str(json).unwrap();
3475 assert_eq!(
3476 object["kvm_shared_dequeue_timers"],
3477 serde_json::Value::Bool(
3478 backend.provides_process_signal_control && sequentialize_threads
3479 ),
3480 "{name} sequentialize_threads={sequentialize_threads}"
3481 );
3482 }
3483
3484 /// A legacy key failed the parse when it held the wrong type, or appeared
3485 /// twice, while it was a `Config` field; it still does, so a reader falls
3486 /// back as it did.
3487 #[test]
3488 fn a_legacy_backend_key_of_the_wrong_type_fails_the_parse() {
3489 let json = to_legacy_backend_json(&Config::default()).unwrap();
3490 assert!(from_legacy_backend_json(&json).is_ok());
3491 for (key, value) in legacy_backend_keys(&Config::default()) {
3492 let field = format!("\"{key}\":{value}");
3493 assert_eq!(json.matches(&field).count(), 1, "{field}");
3494 let mistyped = json.replacen(&field, &format!("\"{key}\":0"), 1);
3495 assert!(from_legacy_backend_json(&mistyped).is_err(), "{mistyped}");
3496 let repeated = json.replacen(&field, &format!("{field},{field}"), 1);
3497 assert!(from_legacy_backend_json(&repeated).is_err(), "{repeated}");
3498 }
3499 }
3500
3501 /// The entries of a JSON object, in the order they appear.
3502 fn ordered_entries(json: &str) -> Vec<(String, serde_json::Value)> {
3503 struct Entries(Vec<(String, serde_json::Value)>);
3504
3505 impl<'de> Deserialize<'de> for Entries {
3506 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3507 struct EntriesVisitor;
3508
3509 impl<'de> serde::de::Visitor<'de> for EntriesVisitor {
3510 type Value = Entries;
3511
3512 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3513 formatter.write_str("a JSON object")
3514 }
3515
3516 fn visit_map<A: serde::de::MapAccess<'de>>(
3517 self,
3518 mut map: A,
3519 ) -> Result<Entries, A::Error> {
3520 let mut entries = Vec::new();
3521 while let Some(entry) = map.next_entry()? {
3522 entries.push(entry);
3523 }
3524 Ok(Entries(entries))
3525 }
3526 }
3527
3528 deserializer.deserialize_map(EntriesVisitor)
3529 }
3530 }
3531
3532 serde_json::from_str::<Entries>(json).unwrap().0
3533 }
3534
3535 /// The JSON array of `json`'s values in its key order: the same
3536 /// configuration, listed by position.
3537 fn positional(json: &str) -> String {
3538 let values: Vec<serde_json::Value> = ordered_entries(json)
3539 .into_iter()
3540 .map(|(_, value)| value)
3541 .collect();
3542 serde_json::to_string(&values).unwrap()
3543 }
3544
3545 /// The legacy form's positions are `Config`'s fields in declaration order
3546 /// with the fifteen legacy keys where `backend` stands and no
3547 /// `record_host_inputs`, `guest_may_inherit_a_terminal`,
3548 /// `in_guest_detlog_forward_policy`, `in_guest_site_patching_off`,
3549 /// `launch_image`, `target_timeslice_syscalls_only`, `futex_wake_yields`,
3550 /// `replaying`,
3551 /// `scheduler_turn_cost` or
3552 /// `inherited_seccomp`, which is the
3553 /// key order the encoder writes.
3554 #[test]
3555 fn legacy_positions_are_the_encoded_key_order() {
3556 let names = legacy_backend_keys(&Config::default()).map(|(name, _)| name);
3557 assert_eq!(names, LEGACY_BACKEND_KEY_NAMES);
3558
3559 let fields = serde_json::from_str::<legacy_backend_json::KeyOrder>(
3560 &serde_json::to_string(&Config::default()).unwrap(),
3561 )
3562 .unwrap()
3563 .0;
3564 let mut expected = Vec::new();
3565 for field in &fields {
3566 match field.as_str() {
3567 "backend" => expected.extend(names.map(str::to_owned)),
3568 "record_host_inputs"
3569 | "guest_may_inherit_a_terminal"
3570 | "in_guest_detlog_forward_policy"
3571 | "in_guest_site_patching_off"
3572 | "launch_image"
3573 | "target_timeslice_syscalls_only"
3574 | "futex_wake_yields"
3575 | "pipe_wake_latency"
3576 | "replaying"
3577 | "scheduler_turn_cost"
3578 | "inherited_seccomp"
3579 | "cpu_profile"
3580 | "cpu_profile_host"
3581 | "signal_state_copy"
3582 | "container_mount_table"
3583 | "mountinfo_mount_namespace"
3584 | "signal_delivery_check_fatal" => {}
3585 other => expected.push(other.to_owned()),
3586 }
3587 }
3588 let encoded = to_legacy_backend_json(&Config::default()).unwrap();
3589 let keys: Vec<String> = ordered_entries(&encoded)
3590 .into_iter()
3591 .map(|(key, _)| key)
3592 .collect();
3593 assert_eq!(keys, expected);
3594 // `backend` becomes fifteen keys; `record_host_inputs`,
3595 // `guest_may_inherit_a_terminal`,
3596 // `in_guest_detlog_forward_policy`, `in_guest_site_patching_off`,
3597 // `launch_image`, `target_timeslice_syscalls_only`, `futex_wake_yields`,
3598 // `pipe_wake_latency`, `replaying`, `scheduler_turn_cost`,
3599 // `inherited_seccomp`, `cpu_profile`, `cpu_profile_host`,
3600 // `signal_state_copy`, `container_mount_table`,
3601 // `mountinfo_mount_namespace` and `signal_delivery_check_fatal` none:
3602 // fourteen more keys, and seventeen fewer, so three keys fewer than
3603 // fields.
3604 assert!(!fields.iter().any(|field| field == "shared_dequeue_timers"));
3605 assert_eq!(fields.len(), keys.len() + 3);
3606 }
3607
3608 /// `record_host_inputs` never enters the legacy form, whatever its value:
3609 /// the guest-visible string stays the legacy bytes, and it reads back as
3610 /// false from both the object and the array form.
3611 #[test]
3612 fn record_host_inputs_never_enters_the_legacy_form() {
3613 let off = Config {
3614 backend: BackendCapabilities::DBT,
3615 ..Config::default()
3616 };
3617 let on = Config {
3618 record_host_inputs: true,
3619 ..off.clone()
3620 };
3621 let json = to_legacy_backend_json(&on).unwrap();
3622 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3623 assert!(!json.contains("record_host_inputs"), "{json}");
3624 assert!(!from_legacy_backend_json(&json).unwrap().record_host_inputs);
3625 let values: Vec<serde_json::Value> = ordered_entries(&json)
3626 .into_iter()
3627 .map(|(_, value)| value)
3628 .collect();
3629 let array = serde_json::to_string(&values).unwrap();
3630 assert!(!from_legacy_backend_json(&array).unwrap().record_host_inputs);
3631 }
3632
3633 /// `process_exits_complete_asynchronously`, added after the legacy form
3634 /// froze, never enters it, whatever its value, exactly as
3635 /// `record_host_inputs` does not: the guest-visible bytes stay the legacy
3636 /// bytes, and it reads back as false from the object and the array form.
3637 #[test]
3638 fn process_exits_complete_asynchronously_never_enters_the_legacy_form() {
3639 let on = Config {
3640 backend: BackendCapabilities::LITEINST_IN_GUEST,
3641 ..Config::default()
3642 };
3643 assert!(on.backend.process_exits_complete_asynchronously);
3644 assert!(on.backend.virtualizes_guest_sigalrm);
3645 let off = Config {
3646 backend: legacy_expressible(on.backend),
3647 ..on.clone()
3648 };
3649 let json = to_legacy_backend_json(&on).unwrap();
3650 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3651 assert!(
3652 !json.contains("process_exits_complete_asynchronously"),
3653 "{json}"
3654 );
3655 assert!(!json.contains("virtualizes_guest_sigalrm"), "{json}");
3656 let decoded = from_legacy_backend_json(&json).unwrap();
3657 assert!(!decoded.backend.process_exits_complete_asynchronously);
3658 assert!(!decoded.backend.virtualizes_guest_sigalrm);
3659 let array = positional(&json);
3660 assert!(
3661 !from_legacy_backend_json(&array)
3662 .unwrap()
3663 .backend
3664 .process_exits_complete_asynchronously
3665 );
3666 }
3667
3668 /// The capabilities added after the legacy form froze that a legacy
3669 /// configuration reads back as false
3670 /// (`supports_blocked_wait_signal_interruption`,
3671 /// `delivers_preemption_timer_events`,
3672 /// `runs_guest_code_between_injections`, `reports_sigreturns`) never enter
3673 /// it, whatever their
3674 /// value: the guest-visible string stays the legacy bytes, and they read
3675 /// back as false from both the object and the array form.
3676 #[test]
3677 fn post_freeze_capabilities_never_enter_the_legacy_form() {
3678 let off = Config {
3679 backend: BackendCapabilities::DBT,
3680 ..Config::default()
3681 };
3682 let mut on = off.clone();
3683 on.backend.supports_blocked_wait_signal_interruption = true;
3684 on.backend.delivers_preemption_timer_events = true;
3685 on.backend.runs_guest_code_between_injections = true;
3686 on.backend.reports_sigreturns = true;
3687 let json = to_legacy_backend_json(&on).unwrap();
3688 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3689 for key in [
3690 "supports_blocked_wait_signal_interruption",
3691 "delivers_preemption_timer_events",
3692 "runs_guest_code_between_injections",
3693 "reports_sigreturns",
3694 ] {
3695 assert!(!json.contains(key), "{json}");
3696 }
3697 let values: Vec<serde_json::Value> = ordered_entries(&json)
3698 .into_iter()
3699 .map(|(_, value)| value)
3700 .collect();
3701 let array = serde_json::to_string(&values).unwrap();
3702 for decoded in [&json, &array] {
3703 let backend = from_legacy_backend_json(decoded).unwrap().backend;
3704 assert!(!backend.supports_blocked_wait_signal_interruption);
3705 assert!(!backend.delivers_preemption_timer_events);
3706 assert!(!backend.runs_guest_code_between_injections);
3707 assert!(!backend.reports_sigreturns);
3708 assert_eq!(backend, legacy_expressible(BackendCapabilities::DBT));
3709 }
3710 }
3711
3712 /// `guest_may_inherit_a_terminal` never enters the legacy form, whatever
3713 /// its value: the guest-visible string stays the legacy bytes, and it reads
3714 /// back as false from both the object and the array form.
3715 /// `in_guest_detlog_forward_policy` is unset for DBT, so the legacy form
3716 /// never carries it, and it reads back as unset.
3717 #[test]
3718 fn in_guest_detlog_forward_policy_never_enters_the_legacy_form() {
3719 let off = Config {
3720 backend: BackendCapabilities::DBT,
3721 ..Config::default()
3722 };
3723 let on = Config {
3724 in_guest_detlog_forward_policy: Some("1".to_owned()),
3725 ..off.clone()
3726 };
3727 let json = to_legacy_backend_json(&on).unwrap();
3728 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3729 assert!(!json.contains("in_guest_detlog_forward_policy"), "{json}");
3730 assert!(
3731 from_legacy_backend_json(&json)
3732 .unwrap()
3733 .in_guest_detlog_forward_policy
3734 .is_none()
3735 );
3736 }
3737
3738 /// `launch_image` has no legacy key, so the legacy form never carries
3739 /// it, and it reads back as unset from both the object and the array
3740 /// form.
3741 #[test]
3742 fn launch_image_never_enters_the_legacy_form() {
3743 let off = Config {
3744 backend: BackendCapabilities::DBT,
3745 ..Config::default()
3746 };
3747 let on = Config {
3748 launch_image: Some(LaunchImage {
3749 exe: Some(PathBuf::from("/usr/bin/true")),
3750 launcher: Some(PathBuf::from("/usr/bin/env")),
3751 }),
3752 ..off.clone()
3753 };
3754 let json = to_legacy_backend_json(&on).unwrap();
3755 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3756 assert!(!json.contains("launch_image"), "{json}");
3757 assert!(
3758 from_legacy_backend_json(&json)
3759 .unwrap()
3760 .launch_image
3761 .is_none()
3762 );
3763 let values: Vec<serde_json::Value> = ordered_entries(&json)
3764 .into_iter()
3765 .map(|(_, value)| value)
3766 .collect();
3767 let array = serde_json::to_string(&values).unwrap();
3768 assert!(
3769 from_legacy_backend_json(&array)
3770 .unwrap()
3771 .launch_image
3772 .is_none()
3773 );
3774 }
3775
3776 /// `in_guest_site_patching_off` is false for DBT, so the legacy form never
3777 /// carries it, and it reads back as false from both the object and the
3778 /// array form.
3779 #[test]
3780 fn in_guest_site_patching_off_never_enters_the_legacy_form() {
3781 let off = Config {
3782 backend: BackendCapabilities::DBT,
3783 ..Config::default()
3784 };
3785 let on = Config {
3786 in_guest_site_patching_off: true,
3787 ..off.clone()
3788 };
3789 let json = to_legacy_backend_json(&on).unwrap();
3790 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3791 assert!(!json.contains("in_guest_site_patching_off"), "{json}");
3792 assert!(
3793 !from_legacy_backend_json(&json)
3794 .unwrap()
3795 .in_guest_site_patching_off
3796 );
3797 let values: Vec<serde_json::Value> = ordered_entries(&json)
3798 .into_iter()
3799 .map(|(_, value)| value)
3800 .collect();
3801 let array = serde_json::to_string(&values).unwrap();
3802 assert!(
3803 !from_legacy_backend_json(&array)
3804 .unwrap()
3805 .in_guest_site_patching_off
3806 );
3807 }
3808
3809 #[test]
3810 fn guest_may_inherit_a_terminal_never_enters_the_legacy_form() {
3811 let off = Config {
3812 backend: BackendCapabilities::DBT,
3813 ..Config::default()
3814 };
3815 let on = Config {
3816 guest_may_inherit_a_terminal: true,
3817 ..off.clone()
3818 };
3819 let json = to_legacy_backend_json(&on).unwrap();
3820 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3821 assert!(!json.contains("guest_may_inherit_a_terminal"), "{json}");
3822 assert!(
3823 !from_legacy_backend_json(&json)
3824 .unwrap()
3825 .guest_may_inherit_a_terminal
3826 );
3827 let values: Vec<serde_json::Value> = ordered_entries(&json)
3828 .into_iter()
3829 .map(|(_, value)| value)
3830 .collect();
3831 let array = serde_json::to_string(&values).unwrap();
3832 assert!(
3833 !from_legacy_backend_json(&array)
3834 .unwrap()
3835 .guest_may_inherit_a_terminal
3836 );
3837 }
3838
3839 /// `inherited_seccomp` never enters the legacy form, whatever its value:
3840 /// the guest-visible string stays the legacy bytes, and it reads back as
3841 /// unknown from both the object and the array form.
3842 #[test]
3843 fn the_cpu_profile_never_enters_the_legacy_form() {
3844 let v2 = Config {
3845 backend: BackendCapabilities::DBT,
3846 ..Config::default()
3847 };
3848 let v3 = Config {
3849 cpu_profile: crate::cpu_profile::CpuProfile::X86_64V3,
3850 ..v2.clone()
3851 };
3852 let json = to_legacy_backend_json(&v3).unwrap();
3853 assert_eq!(json, to_legacy_backend_json(&v2).unwrap());
3854 assert!(!json.contains("cpu_profile"), "{json}");
3855 assert_eq!(
3856 from_legacy_backend_json(&json).unwrap().cpu_profile,
3857 crate::cpu_profile::CpuProfile::X86_64V2
3858 );
3859 // The bincode form the tool reads carries both fields.
3860 let wire = bincode::serde::encode_to_vec(&v3, bincode::config::legacy()).unwrap();
3861 let (decoded, _): (Config, usize) =
3862 bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
3863 assert_eq!(
3864 decoded.cpu_profile,
3865 crate::cpu_profile::CpuProfile::X86_64V3
3866 );
3867 }
3868
3869 #[test]
3870 fn inherited_seccomp_never_enters_the_legacy_form() {
3871 use crate::config::InheritedSeccomp;
3872 let unknown = Config {
3873 backend: BackendCapabilities::DBT,
3874 ..Config::default()
3875 };
3876 assert_eq!(unknown.inherited_seccomp, InheritedSeccomp::Unknown);
3877 let measured = Config {
3878 inherited_seccomp: InheritedSeccomp::Filter(Some(2)),
3879 ..unknown.clone()
3880 };
3881 let json = to_legacy_backend_json(&measured).unwrap();
3882 assert_eq!(json, to_legacy_backend_json(&unknown).unwrap());
3883 assert!(!json.contains("inherited_seccomp"), "{json}");
3884 assert_eq!(
3885 from_legacy_backend_json(&json).unwrap().inherited_seccomp,
3886 InheritedSeccomp::Unknown
3887 );
3888 let values: Vec<serde_json::Value> = ordered_entries(&json)
3889 .into_iter()
3890 .map(|(_, value)| value)
3891 .collect();
3892 let array = serde_json::to_string(&values).unwrap();
3893 assert_eq!(
3894 from_legacy_backend_json(&array).unwrap().inherited_seccomp,
3895 InheritedSeccomp::Unknown
3896 );
3897 }
3898
3899 /// `Config` crosses Reverie RPC as legacy bincode, which is positional, so
3900 /// `inherited_seccomp` must be encoded whatever its value, the number of
3901 /// filters included.
3902 #[test]
3903 fn inherited_seccomp_round_trips_through_reverie_bincode() {
3904 use crate::config::InheritedSeccomp;
3905 for inherited_seccomp in [
3906 InheritedSeccomp::Unknown,
3907 InheritedSeccomp::Disabled,
3908 InheritedSeccomp::Strict,
3909 InheritedSeccomp::Filter(None),
3910 InheritedSeccomp::Filter(Some(3)),
3911 ] {
3912 let config = Config {
3913 inherited_seccomp,
3914 ..Config::default()
3915 };
3916 let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
3917 let (decoded, read): (Config, usize) =
3918 bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
3919 assert_eq!(read, wire.len());
3920 assert_eq!(decoded.inherited_seccomp, inherited_seccomp);
3921 assert_eq!(
3922 bincode::serde::encode_to_vec(&decoded, bincode::config::legacy()).unwrap(),
3923 wire
3924 );
3925 }
3926 }
3927
3928 /// `Seccomp` gives the mode, and `Seccomp_filters` the number of filters in
3929 /// filter mode.
3930 #[test]
3931 fn inherited_seccomp_is_read_from_a_status_file() {
3932 use crate::config::InheritedSeccomp;
3933 let status = |lines: &str| {
3934 InheritedSeccomp::parse(&format!(
3935 "Name:\tguest\nNoNewPrivs:\t1\n{lines}Speculation_Store_Bypass:\tthread vulnerable\n"
3936 ))
3937 };
3938 assert_eq!(
3939 status("Seccomp:\t0\nSeccomp_filters:\t0\n"),
3940 InheritedSeccomp::Disabled
3941 );
3942 assert_eq!(
3943 status("Seccomp:\t1\nSeccomp_filters:\t0\n"),
3944 InheritedSeccomp::Strict
3945 );
3946 assert_eq!(
3947 status("Seccomp:\t2\nSeccomp_filters:\t3\n"),
3948 InheritedSeccomp::Filter(Some(3))
3949 );
3950 assert_eq!(status("Seccomp:\t2\n"), InheritedSeccomp::Filter(None));
3951 assert_eq!(status(""), InheritedSeccomp::Unknown);
3952 assert_eq!(status("Seccomp:\t7\n"), InheritedSeccomp::Unknown);
3953 // This thread's own state is readable.
3954 assert_ne!(InheritedSeccomp::measure(), InheritedSeccomp::Unknown);
3955 }
3956
3957 /// `target_timeslice_syscalls_only` never enters the legacy form, whatever
3958 /// its value: the guest-visible string stays the legacy bytes, and it reads
3959 /// back as false from both the object and the array form.
3960 #[test]
3961 fn target_timeslice_syscalls_only_never_enters_the_legacy_form() {
3962 let off = Config {
3963 backend: BackendCapabilities::DBT,
3964 target_timeslice: NonZeroU64::new(1_000_000),
3965 ..Config::default()
3966 };
3967 let on = Config {
3968 target_timeslice_syscalls_only: true,
3969 ..off.clone()
3970 };
3971 let json = to_legacy_backend_json(&on).unwrap();
3972 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
3973 assert!(!json.contains("target_timeslice_syscalls_only"), "{json}");
3974 assert!(
3975 !from_legacy_backend_json(&json)
3976 .unwrap()
3977 .target_timeslice_syscalls_only
3978 );
3979 let values: Vec<serde_json::Value> = ordered_entries(&json)
3980 .into_iter()
3981 .map(|(_, value)| value)
3982 .collect();
3983 let array = serde_json::to_string(&values).unwrap();
3984 assert!(
3985 !from_legacy_backend_json(&array)
3986 .unwrap()
3987 .target_timeslice_syscalls_only
3988 );
3989 }
3990
3991 #[test]
3992 fn a_futex_wake_yields_only_when_it_woke_a_waiter() {
3993 let config = Config {
3994 futex_wake_yields: true,
3995 ..Config::default()
3996 };
3997 assert!(config.yields_after_futex_wake(1));
3998 assert!(config.yields_after_futex_wake(3));
3999 // A wake that found no waiter hands nothing off and keeps the slice.
4000 assert!(!config.yields_after_futex_wake(0));
4001 // Off by default.
4002 assert!(!Config::default().futex_wake_yields);
4003 assert!(!Config::default().yields_after_futex_wake(1));
4004 }
4005
4006 #[test]
4007 fn a_futex_wake_yields_under_replay_too() {
4008 // Neither record holds the queue order the policy creates, so replay
4009 // must make the same decision as the recorded run.
4010 let config = Config {
4011 futex_wake_yields: true,
4012 ..Config::default()
4013 };
4014 let preemption_replay = Config {
4015 replay_preemptions_from: Some(PathBuf::from("/nonexistent/preemptions.json")),
4016 ..config.clone()
4017 };
4018 assert!(preemption_replay.yields_after_futex_wake(1));
4019 assert!(!preemption_replay.yields_after_futex_wake(0));
4020 let schedule_replay = Config {
4021 replay_schedule_from: Some(PathBuf::from("/nonexistent/schedule.json")),
4022 ..config
4023 };
4024 assert!(schedule_replay.yields_after_futex_wake(1));
4025 }
4026
4027 #[test]
4028 fn scheduler_turn_charge_refuses_a_scaled_charge_below_one_nanosecond() {
4029 let default = Config::default();
4030 assert_eq!(default.scheduler_turn_charge(), Ok(500_000));
4031 let scaled = Config {
4032 clock_multiplier: Some(0.1),
4033 ..Config::default()
4034 };
4035 assert_eq!(scaled.scheduler_turn_charge(), Ok(50_000));
4036 let cost = |cost: u64, multiplier: f64| Config {
4037 scheduler_turn_cost: NonZeroU64::new(cost),
4038 clock_multiplier: Some(multiplier),
4039 ..Config::default()
4040 };
4041 assert_eq!(cost(10_000, 0.1).scheduler_turn_charge(), Ok(1_000));
4042 assert_eq!(cost(10, 0.1).scheduler_turn_charge(), Ok(1));
4043 // Truncation would make these zero: a finite poll would never expire.
4044 assert!(cost(9, 0.1).scheduler_turn_charge().is_err());
4045 assert!(cost(1, 0.1).scheduler_turn_charge().is_err());
4046 assert_eq!(
4047 cost(MAX_SCHEDULER_TURN_COST, 1.0).scheduler_turn_charge(),
4048 Ok(MAX_SCHEDULER_TURN_COST)
4049 );
4050 assert!(
4051 cost(MAX_SCHEDULER_TURN_COST + 1, 1.0)
4052 .scheduler_turn_charge()
4053 .is_err()
4054 );
4055 assert!(cost(u64::MAX, 1.0).scheduler_turn_charge().is_err());
4056 assert!(
4057 cost(MAX_SCHEDULER_TURN_COST, 1e12)
4058 .scheduler_turn_charge()
4059 .is_err()
4060 );
4061 // The scaled charge has the same upper bound as the cost: one charge
4062 // of 9e18 ns would exhaust the clock in two turns.
4063 assert!(
4064 cost(MAX_SCHEDULER_TURN_COST, 9e9)
4065 .scheduler_turn_charge()
4066 .is_err()
4067 );
4068 assert!(cost(1_000_000, 1_001.0).scheduler_turn_charge().is_err());
4069 assert_eq!(
4070 cost(1_000_000, 1_000.0).scheduler_turn_charge(),
4071 Ok(MAX_SCHEDULER_TURN_COST)
4072 );
4073 let message = cost(MAX_SCHEDULER_TURN_COST, 9e9)
4074 .scheduler_turn_charge()
4075 .unwrap_err();
4076 assert!(message.contains("at least 1"), "{message}");
4077 assert!(message.contains("at most 1000000000"), "{message}");
4078 }
4079
4080 /// `futex_wake_yields` never enters the legacy form, whatever its
4081 /// value: the guest-visible string stays the legacy bytes, and it reads
4082 /// back as false from both the object and the array form.
4083 #[test]
4084 fn futex_wake_yields_never_enters_the_legacy_form() {
4085 let off = Config {
4086 backend: BackendCapabilities::DBT,
4087 ..Config::default()
4088 };
4089 let on = Config {
4090 futex_wake_yields: true,
4091 ..off.clone()
4092 };
4093 let json = to_legacy_backend_json(&on).unwrap();
4094 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
4095 assert!(!json.contains("futex_wake_yields"), "{json}");
4096 assert!(!from_legacy_backend_json(&json).unwrap().futex_wake_yields);
4097 let values: Vec<serde_json::Value> = ordered_entries(&json)
4098 .into_iter()
4099 .map(|(_, value)| value)
4100 .collect();
4101 let array = serde_json::to_string(&values).unwrap();
4102 assert!(!from_legacy_backend_json(&array).unwrap().futex_wake_yields);
4103 }
4104
4105 /// `scheduler_turn_cost` never enters the legacy form, whatever its value:
4106 /// the guest-visible string stays the legacy bytes, and it reads back as
4107 /// unset from both the object and the array form.
4108 #[test]
4109 fn scheduler_turn_cost_never_enters_the_legacy_form() {
4110 let off = Config {
4111 backend: BackendCapabilities::DBT,
4112 ..Config::default()
4113 };
4114 let on = Config {
4115 scheduler_turn_cost: NonZeroU64::new(10_000),
4116 ..off.clone()
4117 };
4118 let json = to_legacy_backend_json(&on).unwrap();
4119 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
4120 assert!(!json.contains("scheduler_turn_cost"), "{json}");
4121 assert_eq!(
4122 from_legacy_backend_json(&json).unwrap().scheduler_turn_cost,
4123 None
4124 );
4125 let values: Vec<serde_json::Value> = ordered_entries(&json)
4126 .into_iter()
4127 .map(|(_, value)| value)
4128 .collect();
4129 let array = serde_json::to_string(&values).unwrap();
4130 assert_eq!(
4131 from_legacy_backend_json(&array)
4132 .unwrap()
4133 .scheduler_turn_cost,
4134 None
4135 );
4136 }
4137
4138 /// `replaying` never enters the legacy form, whatever its value: the
4139 /// guest-visible string stays the legacy bytes, and it reads back as false
4140 /// from both the object and the array form.
4141 #[test]
4142 fn replaying_never_enters_the_legacy_form() {
4143 let off = Config {
4144 backend: BackendCapabilities::DBT,
4145 ..Config::default()
4146 };
4147 let on = Config {
4148 replaying: true,
4149 ..off.clone()
4150 };
4151 let json = to_legacy_backend_json(&on).unwrap();
4152 assert_eq!(json, to_legacy_backend_json(&off).unwrap());
4153 assert!(!json.contains("replaying"), "{json}");
4154 assert!(!from_legacy_backend_json(&json).unwrap().replaying);
4155 let values: Vec<serde_json::Value> = ordered_entries(&json)
4156 .into_iter()
4157 .map(|(_, value)| value)
4158 .collect();
4159 let array = serde_json::to_string(&values).unwrap();
4160 assert!(!from_legacy_backend_json(&array).unwrap().replaying);
4161 }
4162
4163 /// `Config` crosses Reverie RPC as legacy bincode, which is positional, so
4164 /// `replaying` must be encoded whatever its value: a field left out when
4165 /// false would shift every later field for the decoder.
4166 #[test]
4167 fn replaying_round_trips_through_reverie_bincode() {
4168 for replaying in [false, true] {
4169 let config = Config {
4170 replaying,
4171 ..Config::default()
4172 };
4173 let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
4174 let (decoded, read): (Config, usize) =
4175 bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
4176 assert_eq!(read, wire.len());
4177 assert_eq!(decoded.replaying, replaying);
4178 assert_eq!(
4179 bincode::serde::encode_to_vec(&decoded, bincode::config::legacy()).unwrap(),
4180 wire
4181 );
4182 }
4183 }
4184
4185 /// Serde reads a derived struct from a JSON array by position, so the
4186 /// legacy form could be given as one. Each array reads as the object
4187 /// whose values it lists in order, every backend's capabilities included.
4188 #[test]
4189 fn a_legacy_positional_array_reads_as_the_object_it_lists() {
4190 for (name, backend) in [
4191 ("PTRACE", BackendCapabilities::PTRACE),
4192 ("E9PATCH", BackendCapabilities::E9PATCH),
4193 (
4194 "ptrace without exit transitions",
4195 ptrace_without_exit_transitions(),
4196 ),
4197 ("LITEINST_IN_GUEST", BackendCapabilities::LITEINST_IN_GUEST),
4198 ("SABRE", BackendCapabilities::SABRE),
4199 ("DBT", BackendCapabilities::DBT),
4200 ("KVM", BackendCapabilities::KVM),
4201 ] {
4202 for sequentialize_threads in [false, true] {
4203 let sent = Config {
4204 backend,
4205 sequentialize_threads,
4206 seed: 7,
4207 chaos: true,
4208 ..Config::default()
4209 };
4210 let json = to_legacy_backend_json(&sent).unwrap();
4211 assert_controlled_key(&json, &backend, sequentialize_threads, name);
4212 let array = positional(&json);
4213 assert!(array.starts_with('['), "{array}");
4214 let received = from_legacy_backend_json(&array).unwrap();
4215 assert_eq!(received.backend, legacy_expressible(backend), "{name}");
4216 assert_eq!(
4217 received.sequentialize_threads, sequentialize_threads,
4218 "{name}"
4219 );
4220 assert_eq!(received.seed, 7, "{name}");
4221 assert!(received.chaos, "{name}");
4222 assert_eq!(to_legacy_backend_json(&received).unwrap(), json, "{name}");
4223 }
4224 }
4225 }
4226
4227 /// An array fails the parse where the legacy form's array did: with an
4228 /// element past the last position, with an element of the wrong type, or
4229 /// short of a field that has no default. The last position,
4230 /// `interrupt_at`, has none, so every shorter array fails.
4231 #[test]
4232 fn a_malformed_legacy_positional_array_fails_the_parse() {
4233 let json = to_legacy_backend_json(&Config {
4234 backend: BackendCapabilities::DBT,
4235 ..Config::default()
4236 })
4237 .unwrap();
4238 let entries = ordered_entries(&json);
4239 let values: Vec<serde_json::Value> =
4240 entries.iter().map(|(_, value)| value.clone()).collect();
4241 let parse = |values: &[serde_json::Value]| {
4242 from_legacy_backend_json(&serde_json::to_string(values).unwrap())
4243 };
4244 assert!(parse(&values).is_ok());
4245
4246 let mut longer = values.clone();
4247 longer.push(serde_json::Value::Bool(false));
4248 assert!(parse(&longer).is_err());
4249
4250 assert_eq!(entries.last().unwrap().0, "interrupt_at");
4251 for len in 0..values.len() {
4252 assert!(parse(&values[..len]).is_err(), "{len} elements");
4253 }
4254
4255 for (position, (key, _)) in entries.iter().enumerate() {
4256 if LEGACY_BACKEND_KEY_NAMES.contains(&key.as_str()) || key == "seed" {
4257 let mut mistyped = values.clone();
4258 mistyped[position] = serde_json::json!("0");
4259 assert!(parse(&mistyped).is_err(), "{key}");
4260 }
4261 }
4262 }
4263
4264 /// Selects the child half of
4265 /// [`a_legacy_configuration_decodes_whatever_the_ambient_hermit_settings`] and
4266 /// carries the input it decodes.
4267 const LEGACY_INPUT_IN_CHILD: &str = "DETCORE_MODEL_TEST_LEGACY_INPUT";
4268 /// The legacy object the child's decoded configuration must re-encode as.
4269 const LEGACY_EXPECTED_IN_CHILD: &str = "DETCORE_MODEL_TEST_LEGACY_EXPECTED";
4270 /// Printed by a child that decoded its input, so that a parent can tell
4271 /// that run from one that selected no test.
4272 const LEGACY_DECODED_IN_CHILD: &str = "legacy configuration decoded under the ambient settings";
4273
4274 /// Clap reads HERMIT_EPOCH, HERMIT_PRNG and HERMIT_SCHED_SEED when it
4275 /// parses a `Config`, and exits the process when one of them does not
4276 /// parse. The legacy decoder read none of them, so a valid legacy object
4277 /// or array decodes to the configuration it lists whatever they hold. Each
4278 /// decode runs in a child process given those variables unset, set to
4279 /// text that does not parse, or set to bytes that are not UTF-8. The child
4280 /// builds no `Config` before decoding, which would read them itself.
4281 #[test]
4282 fn a_legacy_configuration_decodes_whatever_the_ambient_hermit_settings() {
4283 use std::ffi::OsStr;
4284 use std::os::unix::ffi::OsStrExt;
4285
4286 if let Some(input) = std::env::var_os(LEGACY_INPUT_IN_CHILD) {
4287 let expected = std::env::var(LEGACY_EXPECTED_IN_CHILD).unwrap();
4288 let received = from_legacy_backend_json(input.to_str().unwrap()).unwrap();
4289 assert_eq!(
4290 received.backend,
4291 legacy_expressible(BackendCapabilities::DBT)
4292 );
4293 assert_eq!(received.seed, 7);
4294 assert_eq!(received.sched_seed, Some(11));
4295 assert_eq!(to_legacy_backend_json(&received).unwrap(), expected);
4296 println!("{LEGACY_DECODED_IN_CHILD}");
4297 return;
4298 }
4299
4300 const VARIABLES: [&str; 3] = ["HERMIT_EPOCH", "HERMIT_PRNG", "HERMIT_SCHED_SEED"];
4301 let text = OsStr::new("not-a-value");
4302 let bytes = OsStr::from_bytes(b"\xff");
4303 let mut settings: Vec<Vec<(&str, &OsStr)>> = vec![Vec::new()];
4304 for variable in VARIABLES {
4305 settings.push(vec![(variable, text)]);
4306 settings.push(vec![(variable, bytes)]);
4307 }
4308 settings.push(VARIABLES.map(|variable| (variable, text)).to_vec());
4309 settings.push(VARIABLES.map(|variable| (variable, bytes)).to_vec());
4310
4311 let object = to_legacy_backend_json(&Config {
4312 backend: BackendCapabilities::DBT,
4313 seed: 7,
4314 sched_seed: Some(11),
4315 ..Config::default()
4316 })
4317 .unwrap();
4318 let array = positional(&object);
4319 assert!(array.starts_with('['), "{array}");
4320 let test = format!(
4321 "{}::a_legacy_configuration_decodes_whatever_the_ambient_hermit_settings",
4322 module_path!().split_once("::").unwrap().1
4323 );
4324 for input in [&object, &array] {
4325 for setting in &settings {
4326 let mut child = std::process::Command::new(std::env::current_exe().unwrap());
4327 child
4328 .args(["--exact", &test, "--nocapture"])
4329 .env(LEGACY_INPUT_IN_CHILD, input)
4330 .env(LEGACY_EXPECTED_IN_CHILD, &object);
4331 for variable in VARIABLES {
4332 child.env_remove(variable);
4333 }
4334 for (variable, value) in setting {
4335 child.env(variable, value);
4336 }
4337 let output = child.output().unwrap();
4338 let stdout = String::from_utf8_lossy(&output.stdout);
4339 let stderr = String::from_utf8_lossy(&output.stderr);
4340 assert!(
4341 output.status.success()
4342 && stdout.contains(LEGACY_DECODED_IN_CHILD)
4343 && stdout.contains("test result: ok. 1 passed; 0 failed;"),
4344 "decoding {} under {setting:?} did not succeed exactly once: {}\n{stdout}\n{stderr}",
4345 if input.starts_with('[') {
4346 "the array"
4347 } else {
4348 "the object"
4349 },
4350 output.status,
4351 );
4352 }
4353 }
4354 }
4355
4356 /// `backend` and `shared_dequeue_timers` were not keys of the legacy form,
4357 /// which ignored every key it did not name. They are still ignored,
4358 /// whatever they hold, however often they appear and wherever they stand,
4359 /// so the legacy keys alone decide the capabilities. A key the legacy form
4360 /// named still fails the parse when it appears twice.
4361 #[test]
4362 fn keys_the_legacy_form_did_not_name_are_ignored() {
4363 let sent = Config {
4364 backend: legacy_expressible(BackendCapabilities::DBT),
4365 seed: 7,
4366 ..Config::default()
4367 };
4368 let json = to_legacy_backend_json(&sent).unwrap();
4369 let kvm = serde_json::to_string(&BackendCapabilities::KVM).unwrap();
4370 for extra in [
4371 r#""backend":null"#.to_owned(),
4372 r#""shared_dequeue_timers":null"#.to_owned(),
4373 r#""backend":null,"shared_dequeue_timers":null"#.to_owned(),
4374 format!(r#""backend":{kvm},"shared_dequeue_timers":true"#),
4375 r#""backend":7,"backend":{"supports_madvise":false}"#.to_owned(),
4376 r#""shared_dequeue_timers":"yes","shared_dequeue_timers":true"#.to_owned(),
4377 r#""no_such_field":[1,{"x":null}]"#.to_owned(),
4378 ] {
4379 for edited in [
4380 json.replacen('{', &format!("{{{extra},"), 1),
4381 format!("{},{extra}}}", &json[..json.len() - 1]),
4382 ] {
4383 let received = from_legacy_backend_json(&edited).unwrap();
4384 assert_eq!(received.backend, sent.backend, "{edited}");
4385 assert_eq!(
4386 serde_json::to_string(&received).unwrap(),
4387 serde_json::to_string(&sent).unwrap(),
4388 "{edited}"
4389 );
4390 assert_eq!(to_legacy_backend_json(&received).unwrap(), json, "{edited}");
4391 }
4392 }
4393
4394 let repeated = format!("{},\"seed\":7}}", &json[..json.len() - 1]);
4395 assert!(from_legacy_backend_json(&repeated).is_err());
4396 }
4397
4398 #[test]
4399 fn network_perturbation_seed_never_falls_back_to_scheduler_seeds() {
4400 let mut config = Config {
4401 seed: 41,
4402 sched_seed: Some(42),
4403 ..Config::default()
4404 };
4405 assert_eq!(config.network_trace.network_perturb_seed, None);
4406
4407 config.network_trace = NetworkTraceConfig {
4408 mode: crate::network_trace::NetworkTraceMode::Replay,
4409 path: Some("network.trace".into()),
4410 network_perturb_seed: Some(43),
4411 };
4412 assert_eq!(config.seed, 41);
4413 assert_eq!(config.sched_seed(), 42);
4414 assert_eq!(config.network_trace.network_perturb_seed, Some(43));
4415 }
4416
4417 #[test]
4418 fn missing_mountinfo_provenance_deserializes_as_empty() {
4419 let mut value = serde_json::to_value(Config::default()).unwrap();
4420 value
4421 .as_object_mut()
4422 .unwrap()
4423 .remove("mountinfo_root_rewrites");
4424 value
4425 .as_object_mut()
4426 .unwrap()
4427 .remove("mountinfo_device_rewrites");
4428 value.as_object_mut().unwrap().remove("mountinfo_mount_ids");
4429 value
4430 .as_object_mut()
4431 .unwrap()
4432 .remove("mountinfo_mount_ids_captured");
4433 value
4434 .as_object_mut()
4435 .unwrap()
4436 .remove("mount_id_assignment_order");
4437 value
4438 .as_object_mut()
4439 .unwrap()
4440 .remove("container_mount_table");
4441 value
4442 .as_object_mut()
4443 .unwrap()
4444 .remove("mountinfo_mount_namespace");
4445 let restored: Config = serde_json::from_value(value).unwrap();
4446 assert!(restored.mountinfo_root_rewrites.is_empty());
4447 assert!(restored.mountinfo_device_rewrites.is_empty());
4448 assert!(restored.mountinfo_mount_ids.is_empty());
4449 assert!(!restored.mountinfo_mount_ids_captured);
4450 assert!(restored.mount_id_assignment_order.is_empty());
4451 assert!(restored.container_mount_table.is_none());
4452 assert!(restored.mountinfo_mount_namespace.is_none());
4453 }
4454
4455 #[test]
4456 fn runs_post_fork_parses_all_modes_and_defaults_to_child() {
4457 assert_eq!(Config::default().runs_post_fork, RunsPostFork::Child);
4458 assert_eq!(
4459 Config::parse_from(["detcore", "--runs-post-fork=parent"]).runs_post_fork,
4460 RunsPostFork::Parent
4461 );
4462 assert_eq!(
4463 Config::parse_from(["detcore", "--runs-post-fork=random"]).runs_post_fork,
4464 RunsPostFork::Random
4465 );
4466 assert!(Config::try_parse_from(["detcore", "--runs-post-fork=invalid"]).is_err());
4467 }
4468
4469 #[test]
4470 fn proc_level_parses_both_levels_defaults_to_minimal_and_round_trips() {
4471 assert_eq!(Config::default().proc_level, ProcLevel::Minimal);
4472 assert!(!Config::default().to_string().contains("--proc"));
4473 let standard = Config::parse_from(["detcore", "--proc=standard"]);
4474 assert_eq!(standard.proc_level, ProcLevel::Standard);
4475 assert!(standard.to_string().contains(" --proc=standard"));
4476 assert_eq!(
4477 Config::parse_from(["detcore", "--proc=minimal"]).proc_level,
4478 ProcLevel::Minimal
4479 );
4480 assert!(Config::try_parse_from(["detcore", "--proc=host"]).is_err());
4481 assert!(ProcLevel::Minimal < ProcLevel::Standard);
4482 }
4483
4484 #[test]
4485 fn panic_on_rcb_overshoot_is_opt_in_and_round_trips() {
4486 assert!(!Config::default().panic_on_rcb_overshoot);
4487
4488 let config = Config::parse_from(["detcore", "--panic-on-rbc-overshoot"]);
4489 assert!(config.panic_on_rcb_overshoot);
4490 assert!(config.to_string().contains(" --panic-on-rbc-overshoot"));
4491
4492 let alias = Config::parse_from(["detcore", "--panic-on-rcb-overshoot"]);
4493 assert!(alias.panic_on_rcb_overshoot);
4494 }
4495
4496 #[test]
4497 fn config_display_preserves_nondefault_post_fork_modes() {
4498 let mut config = Config {
4499 runs_post_fork: RunsPostFork::Parent,
4500 ..Config::default()
4501 };
4502 assert!(config.to_string().contains(" --runs-post-fork=parent"));
4503
4504 config.runs_post_fork = RunsPostFork::Random;
4505 assert!(config.to_string().contains(" --runs-post-fork=random"));
4506 }
4507
4508 #[test]
4509 fn a_fatal_delivery_check_is_off_by_default_and_never_enters_the_legacy_form() {
4510 assert!(!Config::default().signal_delivery_check_fatal);
4511 let fatal = Config {
4512 signal_delivery_check_fatal: true,
4513 ..Config::default()
4514 };
4515 let json = serde_json::to_string(&fatal).unwrap();
4516 let reparsed: Config = serde_json::from_str(&json).unwrap();
4517 assert!(reparsed.signal_delivery_check_fatal);
4518 let mut old = serde_json::to_value(Config::default()).unwrap();
4519 old.as_object_mut()
4520 .unwrap()
4521 .remove("signal_delivery_check_fatal");
4522 let old: Config = serde_json::from_value(old).unwrap();
4523 assert!(!old.signal_delivery_check_fatal);
4524 let legacy = to_legacy_backend_json(&fatal).unwrap();
4525 assert!(!legacy.contains("signal_delivery_check_fatal"), "{legacy}");
4526 assert!(
4527 !from_legacy_backend_json(&legacy)
4528 .unwrap()
4529 .signal_delivery_check_fatal
4530 );
4531 }
4532
4533 #[test]
4534 fn the_signal_state_copy_is_on_by_default_and_its_off_switch_round_trips() {
4535 let dflt = Config::default();
4536 assert!(dflt.signal_state_copy);
4537 assert!(!dflt.to_string().contains("signal-state-copy"));
4538 // A configuration serialized before the field existed reads as on.
4539 let mut json = serde_json::to_value(&dflt).unwrap();
4540 json.as_object_mut().unwrap().remove("signal_state_copy");
4541 let old: Config = serde_json::from_value(json).unwrap();
4542 assert!(old.signal_state_copy);
4543 // Off renders as the flag, so that a command rebuilt from a
4544 // configuration (analyze's reproduction commands) keeps it off.
4545 let off = Config::parse_from(["detcore", "--no-signal-state-copy"]);
4546 assert!(!off.signal_state_copy);
4547 let rendered = off.to_string();
4548 assert!(rendered.contains(" --no-signal-state-copy"), "{rendered}");
4549 let reparsed = Config::parse_from(
4550 std::iter::once("detcore".to_string())
4551 .chain(rendered.split_whitespace().map(String::from)),
4552 );
4553 assert!(!reparsed.signal_state_copy);
4554 }
4555
4556 // AUTONOMOUS-BOT-IMPLEMENTED
4557 // TODO-HUMAN-REVIEW(PR-1149)
4558 #[test]
4559 fn chaos_per_thread_slowdown_is_opt_in_and_round_trips() {
4560 // Off by default; the factor default is present but inert.
4561 let dflt = Config::default();
4562 assert!(!dflt.chaos_per_thread_slowdown);
4563 assert_eq!(dflt.chaos_slowdown_max_factor, 10.0);
4564 // Default (disabled) config does not emit the flags.
4565 assert!(!dflt.to_string().contains("--chaos-per-thread-slowdown"));
4566
4567 let config = Config::parse_from([
4568 "detcore",
4569 "--chaos",
4570 "--chaos-per-thread-slowdown",
4571 "--chaos-slowdown-max-factor=4.5",
4572 ]);
4573 assert!(config.chaos_per_thread_slowdown);
4574 assert_eq!(config.chaos_slowdown_max_factor, 4.5);
4575
4576 // The Display round-trips both flags into the recorded schedule artifact.
4577 let rendered = config.to_string();
4578 assert!(rendered.contains(" --chaos-per-thread-slowdown"));
4579 assert!(rendered.contains(" --chaos-slowdown-max-factor=4.5"));
4580 let reparsed = Config::parse_from(
4581 std::iter::once("detcore".to_string())
4582 .chain(rendered.split_whitespace().map(String::from)),
4583 );
4584 assert!(reparsed.chaos_per_thread_slowdown);
4585 assert_eq!(reparsed.chaos_slowdown_max_factor, 4.5);
4586 }
4587
4588 // AUTONOMOUS-BOT-IMPLEMENTED
4589 // TODO-HUMAN-REVIEW(PR-1151)
4590 #[test]
4591 fn chaos_epoch_length_is_opt_in_and_round_trips() {
4592 // Off by default (single stable factor == plain per-thread-slowdown).
4593 let dflt = Config::default();
4594 assert_eq!(dflt.chaos_epoch_length_ns, 0);
4595 assert!(!dflt.to_string().contains("--chaos-epoch-length-ns"));
4596
4597 // Epochs are only emitted alongside per-thread-slowdown.
4598 let config = Config::parse_from([
4599 "detcore",
4600 "--chaos",
4601 "--chaos-per-thread-slowdown",
4602 "--chaos-epoch-length-ns=100000",
4603 ]);
4604 assert_eq!(config.chaos_epoch_length_ns, 100000);
4605
4606 let rendered = config.to_string();
4607 assert!(rendered.contains(" --chaos-epoch-length-ns=100000"));
4608 let reparsed = Config::parse_from(
4609 std::iter::once("detcore".to_string())
4610 .chain(rendered.split_whitespace().map(String::from)),
4611 );
4612 assert_eq!(reparsed.chaos_epoch_length_ns, 100000);
4613
4614 // Without per-thread-slowdown the epoch flag is inert and not rendered.
4615 let no_slowdown = Config::parse_from(["detcore", "--chaos", "--chaos-epoch-length-ns=100"]);
4616 assert_eq!(no_slowdown.chaos_epoch_length_ns, 100);
4617 assert!(!no_slowdown.to_string().contains("--chaos-epoch-length-ns"));
4618 }
4619
4620 // AUTONOMOUS-BOT-IMPLEMENTED
4621 // TODO-HUMAN-REVIEW(PR-1149)
4622 #[test]
4623 #[should_panic(expected = "chaos_slowdown_max_factor must be finite and in")]
4624 fn validate_rejects_chaos_slowdown_max_factor_below_one() {
4625 let mut config = Config {
4626 chaos_slowdown_max_factor: 0.5,
4627 ..Default::default()
4628 };
4629 config.validate();
4630 }
4631
4632 #[test]
4633 #[should_panic(expected = "max_timeslice must be at least one RCB")]
4634 fn validate_rejects_max_timeslice_below_one_rcb() {
4635 let mut config = Config {
4636 max_timeslice: NonZeroU64::new(NANOS_PER_RCB as u64 - 1),
4637 ..Default::default()
4638 };
4639
4640 config.validate();
4641 }
4642
4643 #[test]
4644 fn validate_accepts_one_rcb_max_timeslice() {
4645 let mut config = Config {
4646 max_timeslice: NonZeroU64::new(NANOS_PER_RCB as u64),
4647 ..Default::default()
4648 };
4649
4650 config.validate();
4651 }
4652
4653 #[test]
4654 #[should_panic(expected = "clock_multiplier must be finite and positive")]
4655 fn validate_rejects_invalid_clock_multiplier() {
4656 let mut config = Config {
4657 clock_multiplier: Some(0.0),
4658 ..Default::default()
4659 };
4660 config.validate();
4661 }
4662
4663 #[test]
4664 #[should_panic(expected = "max_timeslice must be at least one RCB")]
4665 fn validate_scales_one_rcb_minimum_with_clock_multiplier() {
4666 let mut config = Config {
4667 max_timeslice: NonZeroU64::new(10),
4668 clock_multiplier: Some(2.0),
4669 ..Default::default()
4670 };
4671 config.validate();
4672 }
4673
4674 #[test]
4675 fn config_fingerprint_sees_the_width_of_every_backend_capability() {
4676 // `BackendCapabilities` lives in Reverie, outside the fingerprinted
4677 // sources, so only its encoding can reveal a change to it. Every
4678 // field is a bool, one byte in the encoding whatever its value, so the
4679 // encoded default carries every field, and adding, removing or
4680 // widening one changes the bytes. A field that is optional would have
4681 // to be present in the default, or a change to its width would encode
4682 // as the same bare `None`; this fails first.
4683 let config = config_wire_default();
4684 let fields = serde_json::to_value(config.backend).unwrap();
4685 let fields = fields.as_object().unwrap();
4686 assert!(
4687 fields.values().all(serde_json::Value::is_boolean),
4688 "{fields:?}"
4689 );
4690 let encode = |config: &Config| {
4691 bincode::serde::encode_to_vec(config, bincode::config::legacy()).unwrap()
4692 };
4693 assert_eq!(
4694 bincode::serde::encode_to_vec(config.backend, bincode::config::legacy())
4695 .unwrap()
4696 .len(),
4697 fields.len()
4698 );
4699 // The backend's values are part of the encoded default.
4700 let flipped = config
4701 .clone()
4702 .with_backend(|backend| backend.supports_madvise = !backend.supports_madvise);
4703 assert_eq!(encode(&flipped).len(), encode(&config).len());
4704 assert_ne!(encode(&flipped), encode(&config));
4705 }
4706
4707 #[test]
4708 fn config_fingerprint_includes_clock_rpc_definitions() {
4709 let config = config_wire_default();
4710 let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
4711 let named_shape = serde_json::to_string(&config).unwrap();
4712 let current = config_wire_fingerprint();
4713 let clock_source = include_bytes!("time.rs").as_slice();
4714
4715 // The previous guard covered these same Config bytes and definitions,
4716 // but omitted DetTime. Adding a positional clock field could therefore
4717 // pass the handshake guard and corrupt the following request on decode.
4718 let without_clock: Vec<_> = CONFIG_DEFINITION_SOURCES
4719 .iter()
4720 .copied()
4721 .filter(|source| *source != clock_source)
4722 .collect();
4723 assert_ne!(
4724 fingerprint_of_config_material(&wire, &named_shape, &without_clock),
4725 current,
4726 "the published fingerprint must reject source inputs that omit the RPC clock"
4727 );
4728
4729 // Hold all Config material fixed and remove only the added serialized
4730 // clock field from its definition. A future clock-only change must also
4731 // invalidate the existing artifact guard, independently of config.rs.
4732 let changed_clock =
4733 include_str!("time.rs").replacen(" inherited_nanos: LogicalDuration,", "", 1);
4734 assert_ne!(changed_clock.as_bytes(), clock_source);
4735 let changed_sources: Vec<_> = CONFIG_DEFINITION_SOURCES
4736 .iter()
4737 .map(|source| {
4738 if *source == clock_source {
4739 changed_clock.as_bytes()
4740 } else {
4741 *source
4742 }
4743 })
4744 .collect();
4745 assert_ne!(
4746 fingerprint_of_config_material(&wire, &named_shape, &changed_sources),
4747 current,
4748 "a clock-only serialized field change must invalidate the fingerprint"
4749 );
4750 }
4751
4752 /// The inode RPCs carry `RawInode`, whose layout neither encoding of
4753 /// `Config` shows. A plugin built before `RawInode` gained its device
4754 /// sends one `u64` where the coordinator decodes two, so a change to its
4755 /// definition must invalidate the fingerprint.
4756 #[test]
4757 fn config_fingerprint_includes_the_inode_rpc_identity() {
4758 let config = config_wire_default();
4759 let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
4760 let named_shape = serde_json::to_string(&config).unwrap();
4761 let current = config_wire_fingerprint();
4762 let inode_source = include_bytes!("fd.rs").as_slice();
4763 assert!(CONFIG_DEFINITION_SOURCES.contains(&inode_source));
4764 let without_device = include_str!("fd.rs").replacen(" pub dev: u64,\n", "", 1);
4765 assert_ne!(without_device.as_bytes(), inode_source);
4766 let changed_sources: Vec<_> = CONFIG_DEFINITION_SOURCES
4767 .iter()
4768 .map(|source| {
4769 if *source == inode_source {
4770 without_device.as_bytes()
4771 } else {
4772 *source
4773 }
4774 })
4775 .collect();
4776 assert_ne!(
4777 fingerprint_of_config_material(&wire, &named_shape, &changed_sources),
4778 current,
4779 "an inode-identity layout change must invalidate the fingerprint"
4780 );
4781 }
4782
4783 #[test]
4784 fn a_config_fingerprint_mismatch_names_both_fingerprints() {
4785 let ours = config_wire_fingerprint();
4786 assert_eq!(
4787 config_fingerprint_mismatch(std::ffi::OsStr::new(&ours)),
4788 None
4789 );
4790 let other = config_fingerprint_mismatch(std::ffi::OsStr::new("0123456789abcdef"))
4791 .expect("another fingerprint is a mismatch");
4792 assert!(other.contains(&ours), "{other}");
4793 assert!(other.contains("0123456789abcdef"), "{other}");
4794 use std::os::unix::ffi::OsStrExt;
4795 assert!(config_fingerprint_mismatch(std::ffi::OsStr::from_bytes(b"\xff")).is_some());
4796 }
4797
4798 #[test]
4799 fn config_fingerprint_is_stable_and_shape_sensitive() {
4800 // STABLE: a build must agree with itself, or the guard would reject a
4801 // MATCHED pair -- which would be worse than having no guard at all.
4802 assert_eq!(config_wire_fingerprint(), config_wire_fingerprint());
4803 assert_eq!(config_wire_fingerprint().len(), 16);
4804
4805 let config = config_wire_default();
4806 let base = serde_json::to_string(&config).unwrap();
4807 let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
4808 assert_eq!(
4809 fingerprint_of_config_material(&wire, &base, CONFIG_DEFINITION_SOURCES),
4810 config_wire_fingerprint()
4811 );
4812
4813 // SHAPE-SENSITIVE, checked on the same mechanism the real function uses.
4814 // One added field is exactly the change that caused the outage.
4815 let with_extra_field = format!("{},\"a_new_flag\":false}}", &base[..base.len() - 1]);
4816 assert_ne!(
4817 fingerprint_of_config_material(&wire, &with_extra_field, CONFIG_DEFINITION_SOURCES),
4818 config_wire_fingerprint()
4819 );
4820 // A removed field.
4821 let removed = base.replacen("\"virtualize_time\":true,", "", 1);
4822 assert_ne!(
4823 fingerprint_of_config_material(&wire, &removed, CONFIG_DEFINITION_SOURCES),
4824 config_wire_fingerprint()
4825 );
4826 // A pure rename, which bincode would tolerate but which we still refuse.
4827 let renamed = base.replacen("\"virtualize_time\"", "\"virtualise_time\"", 1);
4828 assert_ne!(
4829 fingerprint_of_config_material(&wire, &renamed, CONFIG_DEFINITION_SOURCES),
4830 config_wire_fingerprint()
4831 );
4832
4833 // The counterexample the JSON-only fingerprint missed: serde_json emits
4834 // the same text for integer zero regardless of width, but legacy bincode
4835 // changes the payload width. A stale peer would decode every following
4836 // field at the wrong offset.
4837 #[derive(Serialize)]
4838 struct U32Field {
4839 field: u32,
4840 }
4841 #[derive(Serialize)]
4842 struct U64Field {
4843 field: u64,
4844 }
4845 let u32_value = U32Field { field: 0 };
4846 let u64_value = U64Field { field: 0 };
4847 let u32_json = serde_json::to_string(&u32_value).unwrap();
4848 let u64_json = serde_json::to_string(&u64_value).unwrap();
4849 assert_eq!(
4850 u32_json, u64_json,
4851 "the planted JSON collision must be real"
4852 );
4853 let u32_wire =
4854 bincode::serde::encode_to_vec(&u32_value, bincode::config::legacy()).unwrap();
4855 let u64_wire =
4856 bincode::serde::encode_to_vec(&u64_value, bincode::config::legacy()).unwrap();
4857 assert_ne!(u32_wire, u64_wire, "the planted wire retype must be real");
4858 assert_ne!(
4859 fingerprint_of_config_material(&u32_wire, &u32_json, &[b"struct S { field: u32 }"]),
4860 fingerprint_of_config_material(&u64_wire, &u64_json, &[b"struct S { field: u64 }"]),
4861 "a wire-incompatible integer retype must change the fingerprint"
4862 );
4863
4864 // Defaults can hide an incompatible inner type in BOTH value encodings.
4865 // The definition source is therefore load-bearing, not decorative.
4866 #[derive(Serialize)]
4867 struct OptionalU32 {
4868 field: Option<u32>,
4869 }
4870 #[derive(Serialize)]
4871 struct OptionalU64 {
4872 field: Option<u64>,
4873 }
4874 let optional_u32 = OptionalU32 { field: None };
4875 let optional_u64 = OptionalU64 { field: None };
4876 let optional_u32_json = serde_json::to_string(&optional_u32).unwrap();
4877 let optional_u64_json = serde_json::to_string(&optional_u64).unwrap();
4878 assert_eq!(optional_u32_json, optional_u64_json);
4879 let optional_u32_wire =
4880 bincode::serde::encode_to_vec(&optional_u32, bincode::config::legacy()).unwrap();
4881 let optional_u64_wire =
4882 bincode::serde::encode_to_vec(&optional_u64, bincode::config::legacy()).unwrap();
4883 assert_eq!(
4884 optional_u32_wire, optional_u64_wire,
4885 "the planted default must be invisible in both value encodings"
4886 );
4887 assert_ne!(
4888 fingerprint_of_config_material(
4889 &optional_u32_wire,
4890 &optional_u32_json,
4891 &[b"struct S { field: Option<u32> }"]
4892 ),
4893 fingerprint_of_config_material(
4894 &optional_u64_wire,
4895 &optional_u64_json,
4896 &[b"struct S { field: Option<u64> }"]
4897 ),
4898 "a hidden wire-incompatible inner-type change must alter the fingerprint"
4899 );
4900 }
4901
4902 #[test]
4903 fn config_fingerprint_uses_environment_free_wire_defaults() {
4904 let environment_derived = Config {
4905 epoch: "2042-03-04T05:06:07.890123456Z".parse().unwrap(),
4906 seed: 41,
4907 sched_seed: Some(42),
4908 ..Config::default()
4909 };
4910
4911 let canonical = config_wire_default();
4912
4913 assert_ne!(
4914 serde_json::to_string(&environment_derived).unwrap(),
4915 serde_json::to_string(&canonical).unwrap()
4916 );
4917 assert_eq!(
4918 canonical.epoch,
4919 DEFAULT_EPOCH_STR.parse::<DateTime<Utc>>().unwrap()
4920 );
4921 assert_eq!(canonical.seed, 0);
4922 assert_eq!(canonical.sched_seed, None);
4923 }
4924
4925 // AUTONOMOUS-BOT-IMPLEMENTED
4926 // TODO-HUMAN-REVIEW(PR-1151)
4927 #[test]
4928 #[should_panic(expected = "max_timeslice must be at least one RCB")]
4929 fn validate_scales_one_rcb_minimum_with_chaos_slowdown() {
4930 let mut config = Config {
4931 chaos: true,
4932 chaos_per_thread_slowdown: true,
4933 chaos_slowdown_max_factor: 4.0,
4934 max_timeslice: NonZeroU64::new(39),
4935 ..Default::default()
4936 };
4937 config.validate();
4938 }
4939
4940 // AUTONOMOUS-BOT-IMPLEMENTED
4941 // TODO-HUMAN-REVIEW(PR-1151)
4942 #[test]
4943 #[should_panic(expected = "chaos_slowdown_max_factor must be finite and in")]
4944 fn validate_rejects_unrepresentable_chaos_slowdown_factor() {
4945 let mut config = Config {
4946 chaos_slowdown_max_factor: RcbTimeMultiplier::MAX * 2.0,
4947 ..Default::default()
4948 };
4949 config.validate();
4950 }
4951}