Skip to main content

detcore/syscalls/
misc.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//! Miscellaneous virtualized syscalls.
10
11use std::collections::hash_map::DefaultHasher;
12use std::hash::Hash;
13use std::hash::Hasher;
14
15use detcore_model::bundled_signal_facts;
16use reverie::BackendCapabilities;
17use reverie::Error;
18use reverie::Guest;
19use reverie::syscalls;
20use reverie::syscalls::AddrMut;
21use reverie::syscalls::ArchPrctlCmd;
22use reverie::syscalls::Errno;
23use reverie::syscalls::MemoryAccess;
24use reverie::syscalls::Sysno;
25
26use crate::consts::DEFAULT_HOSTNAME;
27use crate::detlog;
28#[cfg(test)]
29use crate::random::GETRANDOM_MAX_BYTES;
30use crate::random::RANDOM_FILL_CHUNK_BYTES;
31#[cfg(test)]
32use crate::random::getrandom_request_len;
33#[cfg(test)]
34use crate::random::validate_getrandom_flags;
35use crate::random::write_random_chunk;
36use crate::record_or_replay::RecordOrReplay;
37use crate::scheduler::HostTimedSignalScope;
38use crate::tool_global::SigalrmControl;
39use crate::tool_global::create_session;
40use crate::tool_global::record_host_timed_signals;
41use crate::tool_global::refuse_sigalrm;
42use crate::tool_global::registered_process_of;
43use crate::tool_global::set_child_subreaper;
44use crate::tool_global::set_process_group;
45use crate::tool_local::Detcore;
46use crate::types::DetPid;
47
48const ARCH_GET_XCOMP_SUPP: libc::c_int = 0x1021;
49const ARCH_GET_XCOMP_PERM: libc::c_int = 0x1022;
50const ARCH_REQ_XCOMP_PERM: libc::c_int = 0x1023;
51const ARCH_GET_XCOMP_GUEST_PERM: libc::c_int = 0x1024;
52const ARCH_REQ_XCOMP_GUEST_PERM: libc::c_int = 0x1025;
53
54const ARCH_SHSTK_ENABLE: libc::c_int = 0x5001;
55const ARCH_SHSTK_DISABLE: libc::c_int = 0x5002;
56const ARCH_SHSTK_LOCK: libc::c_int = 0x5003;
57const ARCH_SHSTK_UNLOCK: libc::c_int = 0x5004;
58const ARCH_SHSTK_STATUS: libc::c_int = 0x5005;
59const ARCH_SHSTK_VALID_MASK: usize = 0b11;
60
61const SECCOMP_SET_MODE_STRICT: u32 = 0;
62const SECCOMP_SET_MODE_FILTER: u32 = 1;
63const SECCOMP_GET_ACTION_AVAIL: u32 = 2;
64const SECCOMP_GET_NOTIF_SIZES: u32 = 3;
65const SECCOMP_FILTER_FLAG_TSYNC: u32 = 1;
66
67fn seccomp_result(op: u32, flags: u32, has_args: bool) -> Result<i64, Errno> {
68    if op > SECCOMP_GET_NOTIF_SIZES {
69        return Err(Errno::EINVAL);
70    }
71    if op == SECCOMP_SET_MODE_STRICT && (flags != 0 || has_args) {
72        return Err(Errno::EINVAL);
73    }
74    if op == SECCOMP_SET_MODE_FILTER && flags & !SECCOMP_FILTER_FLAG_TSYNC != 0 {
75        return Err(Errno::EINVAL);
76    }
77    if matches!(
78        op,
79        SECCOMP_SET_MODE_FILTER | SECCOMP_GET_ACTION_AVAIL | SECCOMP_GET_NOTIF_SIZES
80    ) && !has_args
81    {
82        return Err(Errno::EFAULT);
83    }
84
85    // Hermit cannot enforce a guest-installed BPF policy in every backend.
86    // Report the operation as unsupported instead of claiming a filter exists.
87    Err(Errno::EOPNOTSUPP)
88}
89
90/// Whether Detcore sends parent-death signals itself
91/// (https://github.com/rrnewton/hermit/issues/4440): only where a thread's
92/// exit reaches the scheduler in order (sequentialized threads) and the
93/// guest's tasks are host tasks it can signal (ptrace).
94fn emulates_parent_death_signal(config: &crate::config::Config) -> bool {
95    config.sequentialize_threads && bundled_signal_facts::host_task_reads_enabled(&config.backend)
96}
97
98/// Whether parent-death signal `signal` is one Detcore sends itself: a
99/// standard signal (1 to 31) other than SIGKILL and SIGSTOP, which the
100/// kernel keeps acting on as before (a SIGKILL'd child is never counted as
101/// stuck, `Scheduler::child_is_stuck`), and SIGALRM, whose scheduler sends go
102/// to the process's alarm ledger.
103fn detcore_sends_parent_death_signal(signal: libc::c_ulong) -> bool {
104    (1..=31).contains(&signal)
105        && ![libc::SIGKILL, libc::SIGSTOP, libc::SIGALRM].contains(&(signal as libc::c_int))
106}
107
108fn is_supported_prctl_option(option: libc::c_int) -> bool {
109    matches!(
110        option,
111        libc::PR_SET_NAME
112            | libc::PR_GET_NAME
113            | libc::PR_SET_THP_DISABLE
114            | libc::PR_GET_THP_DISABLE
115            // AUTONOMOUS-BOT-IMPLEMENTED
116            // TODO-HUMAN-REVIEW(#919)
117            //
118            // Dumpability is per-process state initialized deterministically by
119            // ordinary exec and subsequently controlled only by the guest. Keep
120            // Linux's 0/1 validation and state transitions rather than refusing
121            // applications that explicitly disable or restore core-dump access.
122            | libc::PR_SET_DUMPABLE
123            | libc::PR_GET_DUMPABLE
124            // PR_SET_TIMERSLACK and PR_GET_TIMERSLACK are deliberately absent:
125            // `handle_prctl` emulates them against per-thread Detcore state.
126            // AUTONOMOUS-BOT-IMPLEMENTED
127            // TODO-HUMAN-REVIEW(#802)
128            //
129            // PR_{SET,GET}_KEEPCAPS only read/toggle the calling thread's
130            // "keep capabilities across a UID change" flag. The result is a pure
131            // function of the guest's own prior prctl calls (0/1), never host
132            // state, so passthrough is deterministic and bitwise-identical across
133            // runs. Supporting it lets `setpriv` (and the `date`/privilege-drop
134            // wrappers that call it) run under --strict instead of aborting with
135            // "keep process capabilities failed: Function not implemented".
136            | libc::PR_SET_KEEPCAPS
137            | libc::PR_GET_KEEPCAPS
138            // AUTONOMOUS-BOT-IMPLEMENTED
139            // TODO-HUMAN-REVIEW(#824)
140            //
141            // PR_{SET,GET}_PDEATHSIG only read/toggle the calling thread's
142            // parent-death-signal attribute. PR_SET_PDEATHSIG validates its
143            // signal argument (a valid signal or 0 succeeds, anything else
144            // faults EINVAL) and PR_GET_PDEATHSIG reports the value the guest
145            // previously set. The result is a pure function of the guest's own
146            // prior prctl calls and its argument, never host state, so
147            // passthrough is deterministic and bitwise-identical across runs.
148            // The registered signal fires when the parent thread exits, and the
149            // kernel posts it at a moment set by host timing, so `handle_prctl`
150            // first records a nonzero PR_SET_PDEATHSIG signal as host-timed for
151            // the caller's process: no gated wait of that process ends for it
152            // (https://github.com/rrnewton/hermit/issues/3146). Supporting it lets
153            // `setpriv --pdeathsig` run under --strict instead of aborting with
154            // "set parent death signal failed: Function not implemented".
155            | libc::PR_SET_PDEATHSIG
156            | libc::PR_GET_PDEATHSIG
157            // AUTONOMOUS-BOT-IMPLEMENTED
158            // TODO-HUMAN-REVIEW(PR-1125): Review KVM capability-control prctl forwarding.
159            //
160            // PR_CAPBSET_DROP and PR_CAP_AMBIENT change and read the calling
161            // thread's capability bounding and ambient sets. They reach the
162            // kernel on every backend (the host's, or KVM's provider), as
163            // PR_CAPBSET_READ and capget already do, so each backend answers as
164            // native Linux does for the same credentials: a drop or a raise
165            // the caller is not entitled to fails with EPERM, an unknown
166            // capability with EINVAL. The result is a function of the
167            // container's initial credentials and the guest's own earlier
168            // calls. They used to reach the kernel on KVM only, and fail with
169            // ENOSYS everywhere else.
170            | libc::PR_CAPBSET_DROP
171            | libc::PR_CAP_AMBIENT
172    )
173}
174
175/// Whether Detcore can admit `PR_SET_CHILD_SUBREAPER`: threads are
176/// sequentialized, so every exit reaches the scheduler through
177/// `deregister_thread` and re-parents there (`Scheduler::reparent_orphans`);
178/// without that, Detcore's record never learns the orphan moved while it still
179/// decides ECHILD. And on `backend`, its own record of children decides waits
180/// (`tracks_process_children`), the kernel rather than the backend performs
181/// them (`!emulates_child_waits`), and a process's exit reaches Detcore only
182/// after the kernel's `exit_notify` has re-parented its children (neither
183/// asynchronous nor separately reported physical exits), so the record agrees
184/// with the kernel. Today that is ptrace, and e9patch preprocessing run under
185/// ptrace, in a sequentialized run.
186fn models_child_subreapers(sequentialize_threads: bool, backend: &BackendCapabilities) -> bool {
187    sequentialize_threads
188        && backend.tracks_process_children
189        && !backend.emulates_child_waits
190        && !backend.process_exits_complete_asynchronously
191        && !backend.reports_physical_process_exits
192}
193
194/// Is `which` one of the Linux `PRIO_*` target selectors for get/setpriority?
195fn is_valid_prio_which(which: i32) -> bool {
196    which == libc::PRIO_PROCESS as i32
197        || which == libc::PRIO_PGRP as i32
198        || which == libc::PRIO_USER as i32
199}
200
201// AUTONOMOUS-BOT-IMPLEMENTED
202// TODO-HUMAN-REVIEW(#806)
203/// Deterministic raw `getpriority(2)` result under Hermit's inert-nice model.
204///
205/// Returns `20 - nice` (nice 0 -> 20) for any valid target regardless of `who`,
206/// because nice is inert under the virtualized scheduler and `getpriority` never
207/// checks permissions; an unknown `which` faults with `EINVAL`, matching Linux.
208fn getpriority_result(which: i32) -> Result<i64, Errno> {
209    if is_valid_prio_which(which) {
210        Ok(20)
211    } else {
212        Err(Errno::EINVAL)
213    }
214}
215
216// AUTONOMOUS-BOT-IMPLEMENTED
217// TODO-HUMAN-REVIEW(#806)
218/// Deterministic raw `setpriority(2)` result: accept any priority change for a
219/// valid target as an inert no-op (returns 0), `EINVAL` for an unknown `which`.
220fn setpriority_result(which: i32) -> Result<i64, Errno> {
221    if is_valid_prio_which(which) {
222        Ok(0)
223    } else {
224        Err(Errno::EINVAL)
225    }
226}
227
228// AUTONOMOUS-BOT-IMPLEMENTED
229// TODO-HUMAN-REVIEW(PR-857): Deterministic empty kernel-log action policy.
230fn deterministic_syslog_result(action: i32, len: usize) -> Result<i64, Errno> {
231    const SYSLOG_ACTION_CONSOLE_LEVEL: i32 = 8;
232
233    match action {
234        0..=7 | 9..=10 => Ok(0),
235        SYSLOG_ACTION_CONSOLE_LEVEL if (1..=8).contains(&len) => Ok(0),
236        _ => Err(Errno::EINVAL),
237    }
238}
239
240/// Write get_mempolicy's output as Linux's `put_user`/`copy_to_user` do:
241/// through the guest's page protections, so a buffer that cannot take all the
242/// bytes is `EFAULT`. Any other failure is the backend's, not a guest fault,
243/// and is reported as a tool error rather than handed to the guest as an
244/// errno get_mempolicy never returns (Claude re-check of
245/// https://github.com/rrnewton/hermit/pull/4249).
246fn write_get_mempolicy_output<M: MemoryAccess>(
247    memory: &mut M,
248    address: AddrMut<'_, u8>,
249    bytes: &[u8],
250) -> Result<(), Error> {
251    match memory.write_with_user_access(address, bytes) {
252        Ok(written) if written == bytes.len() => Ok(()),
253        Ok(_) | Err(Errno::EFAULT) => Err(Errno::EFAULT.into()),
254        Err(errno) => Err(Error::Tool(anyhow::anyhow!(
255            "get_mempolicy output write failed: {errno}"
256        ))),
257    }
258}
259
260fn from_str(s: &str) -> [i8; 65] {
261    let mut ret: [i8; 65] = [0; 65];
262    for (i, ch) in s.bytes().take(64).enumerate() {
263        ret[i] = ch as i8;
264    }
265    ret
266}
267
268const RANDOM_DEVICE_BYTE_STRIDE: u8 = 73;
269const RANDOM_DEVICE_FIRST_BYTE: u8 = 41;
270
271// AUTONOMOUS-BOT-IMPLEMENTED
272// TODO-HUMAN-REVIEW(PR-1096): Review the backend-independent random-device stream.
273fn canonical_random_device_byte(seed: u64, index: u64) -> u8 {
274    let seed_byte = seed.rotate_right(((index % 8) * 8) as u32) as u8;
275    (index as u8)
276        .wrapping_mul(RANDOM_DEVICE_BYTE_STRIDE)
277        .wrapping_add(RANDOM_DEVICE_FIRST_BYTE)
278        ^ seed_byte
279}
280
281/// Scatter one stream through an already-imported array. Scratch space is
282/// independent of request size; only EFAULT becomes a successful copied prefix.
283fn fill_canonical_random_iovecs(
284    memory: &mut impl MemoryAccess,
285    iovecs: &[crate::iovecs::ImportedIovec],
286    seed: u64,
287    stream_offset: u64,
288    hasher: &mut DefaultHasher,
289) -> Result<usize, Error> {
290    let mut local_words = [0_u64; RANDOM_FILL_CHUNK_BYTES / std::mem::size_of::<u64>()];
291    let mut written = 0_usize;
292    for iov in iovecs {
293        let mut segment_written = 0;
294        while segment_written < iov.len {
295            let remote_chunk = match iov
296                .base
297                .checked_add(segment_written)
298                .and_then(AddrMut::<u8>::from_raw)
299            {
300                Some(address) => address,
301                None if written == 0 => return Err(Errno::EFAULT.into()),
302                None => return Ok(written),
303            };
304            let chunk_len = (iov.len - segment_written).min(RANDOM_FILL_CHUNK_BYTES);
305            let local_buf = unsafe {
306                std::slice::from_raw_parts_mut(local_words.as_mut_ptr().cast::<u8>(), chunk_len)
307            };
308            for (index, byte) in local_buf.iter_mut().enumerate() {
309                *byte = canonical_random_device_byte(
310                    seed,
311                    stream_offset
312                        .saturating_add(written as u64)
313                        .saturating_add(index as u64),
314                );
315            }
316            let n = match write_random_chunk(memory, remote_chunk, local_buf) {
317                Ok(n) => n,
318                Err(Errno::EFAULT) if written > 0 => return Ok(written),
319                Err(error) => return Err(crate::random::copy_error(error)),
320            };
321            if n == 0 && written == 0 {
322                return Err(Errno::EFAULT.into());
323            }
324            if cfg!(debug_assertions) {
325                Hash::hash_slice(&local_buf[..n], hasher);
326            }
327            written += n;
328            segment_written += n;
329            if n < chunk_len {
330                return Ok(written);
331            }
332        }
333    }
334    Ok(written)
335}
336
337impl<T: RecordOrReplay> Detcore<T> {
338    /// Validates seccomp capability probes without installing guest filters.
339    // TODO-HUMAN-REVIEW(PR-874): Review deterministic seccomp probe validation.
340    pub async fn handle_seccomp<G: Guest<Self>>(
341        &self,
342        _guest: &mut G,
343        call: syscalls::Seccomp,
344    ) -> Result<i64, Error> {
345        seccomp_result(call.op(), call.flags(), call.args().is_some()).map_err(Into::into)
346    }
347
348    /// The host xstate facts of an x86-64-v3 run, or `None` under v2.
349    fn v3_host_xstate(&self) -> Option<&detcore_model::cpu_profile::HostXstate> {
350        (self.cfg.cpu_profile == detcore_model::cpu_profile::CpuProfile::X86_64V3)
351            .then_some(self.cfg.cpu_profile_host.as_ref())
352            .flatten()
353    }
354
355    fn write_arch_prctl_u64<G: Guest<Self>>(
356        &self,
357        guest: &mut G,
358        raw_addr: usize,
359        value: u64,
360    ) -> Result<i64, Error> {
361        let addr = AddrMut::<u64>::from_raw(raw_addr).ok_or(Errno::EFAULT)?;
362        guest.memory().write_value(addr, &value)?;
363        Ok(0)
364    }
365
366    // AUTONOMOUS-BOT-IMPLEMENTED
367    // TODO-HUMAN-REVIEW(#539): Confirm the virtual arch_prctl control policy.
368    /// Preserve thread-local bases while hiding host CPU feature controls.
369    pub async fn handle_arch_prctl<G: Guest<Self>>(
370        &self,
371        guest: &mut G,
372        call: syscalls::ArchPrctl,
373    ) -> Result<i64, Error> {
374        let cpuid_uses_faulting = self.cfg.virtualize_cpuid && guest.has_cpuid_interception();
375        match call.cmd() {
376            ArchPrctlCmd::ARCH_SET_FS(_)
377            | ArchPrctlCmd::ARCH_SET_GS(_)
378            | ArchPrctlCmd::ARCH_GET_FS(_)
379            | ArchPrctlCmd::ARCH_GET_GS(_) => Ok(guest.inject(call).await?),
380
381            // When Reverie successfully disables native CPUID, Detcore answers its fault from a
382            // fixed table. Preserve that backend state and reject attempts to re-enable CPUID.
383            ArchPrctlCmd::ARCH_GET_CPUID(_) if cpuid_uses_faulting => Ok(0),
384            ArchPrctlCmd::ARCH_SET_CPUID(value) if cpuid_uses_faulting => {
385                if value == 0 {
386                    Ok(0)
387                } else {
388                    Err(Errno::EPERM.into())
389                }
390            }
391            // Reverie cannot faithfully deliver a CPUID fault requested by the tracee. In
392            // explicit host-CPUID mode, expose a fixed enabled control state and reject disable.
393            ArchPrctlCmd::ARCH_GET_CPUID(_) if !self.cfg.virtualize_cpuid => Ok(1),
394            ArchPrctlCmd::ARCH_SET_CPUID(value) if !self.cfg.virtualize_cpuid => {
395                if value == 0 {
396                    Err(Errno::EPERM.into())
397                } else {
398                    Ok(0)
399                }
400            }
401
402            // Ptrace hosts without CPUID-faulting support retain the kernel's honest state.
403            ArchPrctlCmd::ARCH_GET_CPUID(_) | ArchPrctlCmd::ARCH_SET_CPUID(_) => {
404                Ok(guest.inject(call).await?)
405            }
406
407            // Under x86-64-v3 the guest's XGETBV and XSAVE run on the host, so
408            // the xstate queries answer with the host's masks, captured at
409            // startup on a host without dynamic features and bound in the
410            // recording; the requests answer as Linux does on such a host:
411            // EOPNOTSUPP below XFEATURE_MAX and EINVAL from it up
412            // (https://github.com/rrnewton/hermit/issues/4243).
413            ArchPrctlCmd::Other(
414                cmd @ (ARCH_GET_XCOMP_SUPP | ARCH_GET_XCOMP_PERM | ARCH_GET_XCOMP_GUEST_PERM),
415                addr,
416            ) if let Some(host) = self.v3_host_xstate() => {
417                let mask = match cmd {
418                    ARCH_GET_XCOMP_SUPP => host.xcomp_supp,
419                    ARCH_GET_XCOMP_PERM => host.xcomp_perm,
420                    _ => host.xcomp_guest_perm,
421                };
422                self.write_arch_prctl_u64(guest, addr, mask)
423            }
424            ArchPrctlCmd::Other(ARCH_REQ_XCOMP_PERM | ARCH_REQ_XCOMP_GUEST_PERM, index)
425                if let Some(host) = self.v3_host_xstate() =>
426            {
427                if index >= host.xfeature_max as usize {
428                    Err(Errno::EINVAL.into())
429                } else {
430                    Err(Errno::EOPNOTSUPP.into())
431                }
432            }
433            // Expose a conservative virtual CPU with no optional extended-state permissions.
434            ArchPrctlCmd::Other(
435                ARCH_GET_XCOMP_SUPP | ARCH_GET_XCOMP_PERM | ARCH_GET_XCOMP_GUEST_PERM,
436                addr,
437            ) => self.write_arch_prctl_u64(guest, addr, 0),
438            ArchPrctlCmd::Other(ARCH_REQ_XCOMP_PERM | ARCH_REQ_XCOMP_GUEST_PERM, _) => {
439                Err(Errno::EINVAL.into())
440            }
441
442            // Keep shadow stacks disabled in the virtual policy. Disabling an already-disabled
443            // feature is idempotent; enable/lock/unlock requests cannot be honored.
444            ArchPrctlCmd::Other(ARCH_SHSTK_STATUS, addr) => {
445                self.write_arch_prctl_u64(guest, addr, 0)
446            }
447            ArchPrctlCmd::Other(ARCH_SHSTK_DISABLE, features)
448                if features != 0 && features & !ARCH_SHSTK_VALID_MASK == 0 =>
449            {
450                Ok(0)
451            }
452            ArchPrctlCmd::Other(ARCH_SHSTK_DISABLE, _)
453            | ArchPrctlCmd::Other(ARCH_SHSTK_ENABLE | ARCH_SHSTK_LOCK | ARCH_SHSTK_UNLOCK, _) => {
454                Err(Errno::EINVAL.into())
455            }
456
457            ArchPrctlCmd::Other(_, _) => Err(Errno::EINVAL.into()),
458        }
459    }
460
461    // AUTONOMOUS-BOT-IMPLEMENTED
462    // TODO-HUMAN-REVIEW(#663)
463    /// Preserve deterministic Ruby thread controls, report the container's fixed
464    /// capability bounding set, and reject options that expose unmodeled process
465    /// or host state.
466    pub async fn handle_prctl<G: Guest<Self>>(
467        &self,
468        guest: &mut G,
469        call: syscalls::Prctl,
470    ) -> Result<i64, Error> {
471        match call.option() {
472            // The capability bounding set is fixed by the container launch policy.
473            libc::PR_CAPBSET_READ => Ok(self.record_or_replay(guest, call).await?),
474            // AUTONOMOUS-BOT-IMPLEMENTED
475            // TODO-HUMAN-REVIEW(PR-2150): Timer slack is shared with the
476            // virtual `/proc/<tid>/timerslack_ns` channel.  Never pass either
477            // setter through to the physical tracee: a large physical slack
478            // changes wake timing on Detcore's remaining host-timed waits.
479            libc::PR_SET_TIMERSLACK => {
480                let requested = call.arg2();
481                let state = guest.thread_state_mut();
482                // Linux treats zero as reset-to-default. Hermit virtualizes the
483                // Linux scheduling policy as SCHED_OTHER, so the kernel's
484                // RT/DL no-op branch is unreachable in the guest model.
485                state.timer_slack_ns = if requested == 0 {
486                    state.default_timer_slack_ns
487                } else {
488                    requested
489                };
490                Ok(0)
491            }
492            libc::PR_GET_TIMERSLACK => Ok(guest.thread_state().timer_slack_ns as i64),
493            // The kernel sends a parent-death signal process-directed
494            // (`group_send_sig_info` with `PIDTYPE_TGID`) when the parent thread
495            // exits, at a moment set by host timing. Record it in this turn,
496            // before the call reaches the kernel, for every thread of the
497            // caller's process, and never forget it: a later disarm or `exec`
498            // does not remove it (`Scheduler::record_host_timed_signals`). Linux
499            // accepts 0 (disarm) and 1 to 64; anything else fails with EINVAL in
500            // the kernel and arms nothing.
501            // A parent-death signal Detcore sends itself is held by Detcore,
502            // not the kernel (armed with 0); any other comes from the kernel.
503            libc::PR_GET_PDEATHSIG if emulates_parent_death_signal(guest.config()) => {
504                let held = crate::tool_global::parent_death_signal(guest, None).await;
505                if held == 0 {
506                    return self.passthrough(guest, call.into()).await;
507                }
508                let target =
509                    AddrMut::<libc::c_int>::from_raw(call.arg2() as usize).ok_or(Errno::EFAULT)?;
510                guest
511                    .memory()
512                    .write_value(target, &held)
513                    .map_err(|_| Errno::EFAULT)?;
514                Ok(0)
515            }
516            libc::PR_SET_PDEATHSIG => {
517                let signal = call.arg2();
518                if signal == libc::SIGALRM as libc::c_ulong {
519                    refuse_sigalrm(guest, SigalrmControl::ArmProducer).await?;
520                }
521                // A signal Detcore sends itself when the parent thread leaves
522                // (`Scheduler::deliver_parent_death_signals`,
523                // https://github.com/rrnewton/hermit/issues/4440): the kernel
524                // is armed with 0, so it never posts a copy of its own at a
525                // host-timed moment, and Detcore keeps the value. Any other
526                // value takes the kernel's path below, and disarms Detcore's
527                // only once the kernel has accepted it (an invalid one, which
528                // the kernel refuses with EINVAL, changes nothing).
529                let emulated = emulates_parent_death_signal(guest.config());
530                if emulated && (signal == 0 || detcore_sends_parent_death_signal(signal)) {
531                    // The call is Detcore's, not recorded: replay decides it
532                    // the same way. The kernel may hold a value an earlier
533                    // kernel-path call armed, which this one replaces, so it
534                    // is disarmed (retried if interrupted). Detcore's record
535                    // changes first: a parent that dies at a host-timed moment
536                    // between the two then sends the new signal and the old
537                    // (a death just before the call, on Linux, sends the old,
538                    // which a fatal old one makes the outcome), never neither.
539                    // A disarm that fails restores Detcore's previous value.
540                    let previous = crate::tool_global::parent_death_signal(guest, None).await;
541                    crate::tool_global::parent_death_signal(guest, Some(signal as i32)).await;
542                    if let Err(errno) = guest
543                        .inject_with_retry(syscalls::Syscall::from(call.with_arg2(0)))
544                        .await
545                    {
546                        crate::tool_global::parent_death_signal(guest, Some(previous)).await;
547                        return Err(errno.into());
548                    }
549                    return Ok(0);
550                }
551                if (1..=64).contains(&signal)
552                    && bundled_signal_facts::host_timed_signal_sources_are_physical(
553                        &guest.config().backend,
554                    )
555                {
556                    record_host_timed_signals(
557                        guest,
558                        HostTimedSignalScope::Caller,
559                        1_u64 << (signal - 1),
560                    )
561                    .await;
562                }
563                let result = self.passthrough(guest, call.into()).await?;
564                if emulated {
565                    crate::tool_global::parent_death_signal(guest, Some(0)).await;
566                }
567                Ok(result)
568            }
569            // AUTONOMOUS-BOT-IMPLEMENTED
570            // TODO-HUMAN-REVIEW(PR-4000)
571            //
572            // The subreaper flag is per-process state only the guest sets, so
573            // the kernel call is deterministic. It is injected in replay too,
574            // like setpgid, rather than replayed from the log: the kernel must
575            // hold the flag for orphans to become this process's children, so
576            // that the waits Detcore injects for them succeed. On success
577            // Detcore mirrors it in its thread tree, in this turn, so that an
578            // orphan re-parented to this process becomes its child for
579            // Detcore's waits too (`Scheduler::reparent_orphans`). The process
580            // is the one Detcore registered the calling thread in, resolved
581            // before the call: a raw clone child with a non-SIGCHLD exit
582            // signal is its own process there, although the backend reports
583            // its creator's pid. A thread with no registered process is
584            // refused before any effect. Linux treats any nonzero argument as
585            // "on". PR_GET_CHILD_SUBREAPER reads the caller's own flag back
586            // from the kernel.
587            libc::PR_SET_CHILD_SUBREAPER
588                if models_child_subreapers(
589                    guest.config().sequentialize_threads,
590                    &guest.config().backend,
591                ) =>
592            {
593                let dettid = guest.thread_state().dettid;
594                let Some(process) = registered_process_of(guest, dettid).await else {
595                    return Err(Errno::ENOSYS.into());
596                };
597                let result = guest.inject(call).await?;
598                set_child_subreaper(guest, process, call.arg2() != 0).await;
599                Ok(result)
600            }
601            libc::PR_GET_CHILD_SUBREAPER
602                if models_child_subreapers(
603                    guest.config().sequentialize_threads,
604                    &guest.config().backend,
605                ) =>
606            {
607                Ok(guest.inject(call).await?)
608            }
609            option if is_supported_prctl_option(option) => {
610                self.passthrough(guest, call.into()).await
611            }
612            _ => Err(Errno::ENOSYS.into()),
613        }
614    }
615
616    // AUTONOMOUS-BOT-IMPLEMENTED
617    // TODO-HUMAN-REVIEW(#806)
618    /// Report the deterministic default nice value for any scheduling target.
619    ///
620    /// Under Hermit the Linux nice value is inert: the scheduler is virtualized
621    /// and guest threads are serialized onto one virtual CPU, so a process's,
622    /// group's, or user's scheduling priority never affects guest-visible
623    /// computation. Report the deterministic default nice (0) for every valid
624    /// target regardless of `who` — real tools such as `renice -p <pid>` always
625    /// pass an explicit pid, and the raw `getpriority(2)` never checks
626    /// permissions on a read, so it must never return `EPERM`. An unknown
627    /// `which` still faults with `EINVAL`, matching Linux.
628    pub async fn handle_getpriority<G: Guest<Self>>(
629        &self,
630        _guest: &mut G,
631        call: syscalls::Getpriority,
632    ) -> Result<i64, Error> {
633        Ok(getpriority_result(call.which())?)
634    }
635
636    // AUTONOMOUS-BOT-IMPLEMENTED
637    // TODO-HUMAN-REVIEW(PR-857): Deterministic syslog(2) virtualization.
638    /// Present an empty kernel ring buffer. Reads and size queries return zero,
639    /// controls are inert, and invalid actions preserve Linux's EINVAL boundary.
640    pub async fn handle_syslog<G: Guest<Self>>(
641        &self,
642        _guest: &mut G,
643        call: syscalls::Syslog,
644    ) -> Result<i64, Error> {
645        Ok(deterministic_syslog_result(call.priority(), call.len())?)
646    }
647
648    // AUTONOMOUS-BOT-IMPLEMENTED
649    // TODO-HUMAN-REVIEW(#806)
650    /// Accept any priority change as a deterministic no-op.
651    ///
652    /// Nice values are inert under Hermit's virtualized, serialized scheduler,
653    /// so accept the request without touching host scheduling. The guest runs as
654    /// a single uid-0 container principal, so a real `setpriority(2)` from the
655    /// caller would succeed anyway; never fabricate `EPERM` for tools such as
656    /// `nice -n 5 <cmd>`, `renice -p <pid>`, or Python's `os.nice`. An unknown
657    /// `which` still faults with `EINVAL`, matching Linux.
658    pub async fn handle_setpriority<G: Guest<Self>>(
659        &self,
660        _guest: &mut G,
661        call: syscalls::Setpriority,
662    ) -> Result<i64, Error> {
663        Ok(setpriority_result(call.which())?)
664    }
665
666    // AUTONOMOUS-BOT-IMPLEMENTED
667    // TODO-HUMAN-REVIEW(#663)
668    /// Reject cross-process memory advice without consulting host process state.
669    pub fn handle_process_madvise(pidfd: usize, flags: usize) -> Result<i64, Error> {
670        if flags != 0 {
671            return Err(Errno::EINVAL.into());
672        }
673
674        // Linux interprets pidfd as an int. Preserve its deterministic invalid-fd
675        // rejection, but never let a valid host pidfd alter another process's memory.
676        if (pidfd as libc::c_int) < 0 {
677            Err(Errno::EBADF.into())
678        } else {
679            Err(Errno::EPERM.into())
680        }
681    }
682
683    // AUTONOMOUS-BOT-IMPLEMENTED
684    // TODO-HUMAN-REVIEW(PR-1096): Review the backend-independent random-device stream.
685    /// Fill guest memory from the canonical stream used by every backend's
686    /// `/dev/random` and `/dev/urandom` virtualization.
687    pub(super) fn fill_random_device_bytes<G: Guest<Self>>(
688        &self,
689        guest: &mut G,
690        remote_buf: AddrMut<u8>,
691        len: usize,
692        stream_offset: u64,
693    ) -> Result<usize, Error> {
694        self.fill_random_device_iovecs(
695            guest,
696            &[crate::iovecs::ImportedIovec {
697                base: remote_buf.as_raw(),
698                len,
699            }],
700            stream_offset,
701        )
702    }
703
704    pub(super) fn fill_random_device_iovecs<G: Guest<Self>>(
705        &self,
706        guest: &mut G,
707        iovecs: &[crate::iovecs::ImportedIovec],
708        stream_offset: u64,
709    ) -> Result<usize, Error> {
710        let seed = guest.config().rng_seed();
711        let mut hasher = DefaultHasher::new();
712        let written = fill_canonical_random_iovecs(
713            &mut guest.memory(),
714            iovecs,
715            seed,
716            stream_offset,
717            &mut hasher,
718        )?;
719        if cfg!(debug_assertions) {
720            detlog!(
721                "[dtid {}] USER RAND [/dev/[u]random] Filled guest memory with {} canonical random bytes at offset {}, hash of bytes: {}",
722                guest.thread_state().dettid,
723                written,
724                stream_offset,
725                hasher.finish()
726            );
727        }
728        Ok(written)
729    }
730
731    /// uname syscall
732    pub async fn handle_uname<G: Guest<Self>>(
733        &self,
734        guest: &mut G,
735        call: syscalls::Uname,
736    ) -> Result<i64, Error> {
737        let ret = self.record_or_replay(guest, call).await?;
738        if let Some(buf) = call.buf() {
739            let mut un = guest.memory().read_value(buf)?;
740            let kernel = crate::machine::MachineDescription::of(guest.config()).kernel;
741
742            if !guest.config().has_uts_namespace {
743                // FIXME: It should be possible to remove this once all tests
744                // are also using namespaces.
745                un.nodename = from_str(DEFAULT_HOSTNAME);
746                un.domainname = from_str(DEFAULT_HOSTNAME.split('.').next_back().unwrap_or(""));
747            }
748
749            // The kernel procfs describes too (`procfs::fixed`).
750            un.sysname = from_str(&kernel.sysname);
751            un.release = from_str(&kernel.release);
752            un.version = from_str(&kernel.version());
753            guest.memory().write_value(buf, &un)?;
754        }
755
756        Ok(ret)
757    }
758
759    /// Fill `getrandom(2)` requests from the current thread's seeded deterministic PRNG.
760    /// Supported blocking/source-selection flags share that always-ready stream; invalid Linux
761    /// flag combinations are rejected before guest memory is touched.
762    pub async fn handle_getrandom<G: Guest<Self>>(
763        &self,
764        guest: &mut G,
765        call: syscalls::Getrandom,
766    ) -> Result<i64, Error> {
767        let memory = guest.memory();
768        let dettid = guest.thread_state().dettid;
769        crate::random::getrandom(guest.thread_state_mut().thread_prng(), memory, dettid, call)
770    }
771
772    /// setsid system call, answered as Linux answers it from Detcore's model
773    /// of the guest's sessions and process groups (`ThreadTree`), the same on
774    /// every backend (slice B3a-4c of
775    /// <https://github.com/rrnewton/hermit/issues/4266>). The call then goes to
776    /// the backend too, so that a kernel that keeps process groups (ptrace's)
777    /// stays in step; a backend that keeps none answers ENOSYS (KVM's
778    /// executor), and the model is the guest's answer. Any other disagreement
779    /// is refused by name, never answered with the backend's errno. A caller
780    /// in a nested PID namespace, whose ids are not the model's, is answered
781    /// by the kernel and mirrored, as before.
782    // TODO-HUMAN-REVIEW(PR-b3a4c): Review setsid from the model.
783    pub async fn handle_setsid<G: Guest<Self>>(
784        &self,
785        guest: &mut G,
786        call: syscalls::Setsid,
787    ) -> Result<i64, Error> {
788        let process = guest.thread_state().detpid.expect("detpid unset");
789        let res = if guest.thread_state().nested_pid_namespace {
790            let res = guest.inject(call).await?;
791            let _ = create_session(guest, process).await;
792            res
793        } else {
794            crate::tool_global::setsid_decision(guest, process).await?;
795            self.mirror_group_change(guest, reverie::syscalls::Syscall::Setsid(call))
796                .await?;
797            let _ = create_session(guest, process).await;
798            i64::from(process.as_raw())
799        };
800
801        // task is trying to become a daemon process. for more details
802        // see: https://notes.shichao.io/apue/ch13/
803        if guest.config().kill_daemons {
804            guest.daemonize().await;
805        }
806        Ok(res)
807    }
808
809    /// `getpgrp`, `getpgid` and `getsid`, answered from Detcore's model of the
810    /// guest's process groups and sessions (`ThreadTree`), which `setpgid` and
811    /// `setsid` keep, the same on every backend. The root process's group and
812    /// session come from outside the container's PID namespace and read as 0,
813    /// as on Linux (`scheduler::OUTSIDE_NAMESPACE`), and so do the namespace
814    /// init's, pid 1. A pid that names no task Linux still has (none
815    /// registered, an exited thread, a process already reaped, automatically
816    /// or by the namespace's init) is ESRCH; a negative one too, as Linux
817    /// finds no task for it (`Scheduler::group_or_session_of`). A caller in a
818    /// nested PID namespace, whose ids are not the model's, is answered by the
819    /// kernel as before.
820    // TODO-HUMAN-REVIEW(PR-b3a4c): Review the group and session model answers
821    // (slice B3a-4c of https://github.com/rrnewton/hermit/issues/4266).
822    pub async fn handle_group_or_session_getter<G: Guest<Self>>(
823        &self,
824        guest: &mut G,
825        call: reverie::syscalls::Syscall,
826    ) -> Result<i64, Error> {
827        if guest.thread_state().nested_pid_namespace {
828            return Ok(guest.inject(call).await?);
829        }
830        let (sysno, args) = reverie::syscalls::SyscallInfo::into_parts(call);
831        let pid = if sysno == Sysno::getpgrp {
832            0
833        } else {
834            args.arg0 as libc::pid_t
835        };
836        let task = match pid {
837            0 => guest.thread_state().detpid.expect("detpid unset"),
838            pid if pid < 0 => return Err(Errno::ESRCH.into()),
839            pid => DetPid::from_raw(pid),
840        };
841        let answer =
842            crate::tool_global::group_or_session_of(guest, task, sysno == Sysno::getsid).await;
843        Ok(i64::from(answer.ok_or(Errno::ESRCH)?.as_raw()))
844    }
845
846    /// setpgid system call, answered as Linux answers it from Detcore's model
847    /// (`ThreadTree::setpgid_decision`), and mirrored to the backend, as
848    /// `handle_setsid`. A caller in a nested PID namespace is answered by the
849    /// kernel and the model mirrors it, as before: the kernel validates, and
850    /// group-selecting waits read the model rather than host `/proc` state.
851    // TODO-HUMAN-REVIEW(PR-b3a4c): Review setpgid from the model.
852    pub async fn handle_setpgid<G: Guest<Self>>(
853        &self,
854        guest: &mut G,
855        call: syscalls::Setpgid,
856    ) -> Result<i64, Error> {
857        let caller = guest.thread_state().detpid.expect("detpid unset");
858        if !guest.thread_state().nested_pid_namespace {
859            let (process, group) =
860                crate::tool_global::setpgid_decision(guest, caller, call.pid(), call.pgid())
861                    .await?;
862            self.mirror_group_change(guest, reverie::syscalls::Syscall::Setpgid(call))
863                .await?;
864            let _ = set_process_group(guest, process, group).await;
865            return Ok(0);
866        }
867        let res = guest.inject(call).await?;
868        // A nested caller's ids are its own PID namespace's; the kernel took
869        // them so, and the model records the tasks they name
870        // (https://github.com/rrnewton/hermit/issues/4155).
871        let process = if call.pid() == 0 {
872            caller
873        } else {
874            self.task_named_after_success(guest, Sysno::setpgid, call.pid())
875                .await?
876        };
877        let group = if call.pgid() == 0 {
878            process
879        } else {
880            self.task_named_after_success(guest, Sysno::setpgid, call.pgid())
881                .await?
882        };
883        let _ = set_process_group(guest, process, group).await;
884        Ok(res)
885    }
886
887    /// Give the backend a `setsid` or `setpgid` the model accepted, so that a
888    /// kernel that keeps process groups stays in step with the model. A
889    /// backend that keeps none says so with a typed refusal
890    /// (`UnsupportedOperation::ProcessGroups`), and the model's answer stands.
891    /// Any other failure, whatever its errno, means the backend's process
892    /// groups disagree with the model's: refused by name rather than answered
893    /// with the backend's errno. An errno alone never stands for a refusal: a
894    /// kernel ENOSYS for another reason would otherwise read as success.
895    async fn mirror_group_change<G: Guest<Self>>(
896        &self,
897        guest: &mut G,
898        call: reverie::syscalls::Syscall,
899    ) -> Result<(), Error> {
900        let result = guest.inject(call).await;
901        // Ask before anything else is injected: the next injection replaces
902        // the backend's record.
903        let refusal = result
904            .is_err()
905            .then(|| guest.take_unsupported_refusal())
906            .flatten();
907        match result {
908            Ok(_) => Ok(()),
909            Err(_)
910                if refusal.is_some_and(|refusal| {
911                    refusal.operation == reverie::UnsupportedOperation::ProcessGroups
912                }) =>
913            {
914                Ok(())
915            }
916            Err(errno) => {
917                let sysno = reverie::syscalls::SyscallInfo::number(&call);
918                tracing::error!(
919                    "[detcore, dtid {}] {} was accepted by Detcore's process-group model but the backend answered {}: its process groups disagree with the model's (slice B3a-4c of https://github.com/rrnewton/hermit/issues/4266)",
920                    guest.thread_state().dettid,
921                    sysno,
922                    errno,
923                );
924                self.refuse_unserviceable_operation(guest, sysno, errno)
925                    .await
926                    .map(|_| ())
927            }
928        }
929    }
930
931    /// The task a positive id the calling thread passed names, after the
932    /// kernel accepted it: the id itself at depth 0, translated from the
933    /// caller's PID namespace below that. An id the record cannot name is
934    /// refused by name; the kernel found it, so the record is incomplete.
935    async fn task_named_after_success<G: Guest<Self>>(
936        &self,
937        guest: &mut G,
938        sysno: Sysno,
939        id: libc::pid_t,
940    ) -> Result<DetPid, Error> {
941        if !guest.thread_state().nested_pid_namespace {
942            return Ok(DetPid::from_raw(id));
943        }
944        let reason = match crate::tool_global::guest_pid(guest, id).await {
945            crate::scheduler::pid_namespaces::GuestPidAnswer::Task { task, .. } => return Ok(task),
946            crate::scheduler::pid_namespaces::GuestPidAnswer::NoSuchPid => {
947                format!(
948                    "the kernel accepted id {id}, which no recorded task of the caller's namespace has"
949                )
950            }
951            crate::scheduler::pid_namespaces::GuestPidAnswer::Untranslatable(reason) => reason,
952        };
953        tracing::error!(
954            "[detcore, dtid {}] {} from a nested PID namespace is not supported: {} (https://github.com/rrnewton/hermit/issues/4155)",
955            guest.thread_state().dettid,
956            sysno,
957            reason,
958        );
959        match self
960            .refuse_unserviceable_operation(guest, sysno, Errno::ENOSYS)
961            .await
962        {
963            Err(error) => Err(error),
964            Ok(_) => Err(Errno::ENOSYS.into()),
965        }
966    }
967
968    /// membarrier (system call).
969    ///
970    /// `membarrier(2)` issues process-wide memory barriers so that userspace can
971    /// use asymmetric fences (e.g. CPython's QSBR, RCU-style reclamation).
972    /// Detcore serializes all guest threads onto a single logical CPU with a
973    /// total memory order, so any requested barrier is *already* satisfied and
974    /// every command is a deterministic no-op. For `MEMBARRIER_CMD_QUERY` we
975    /// report the set of commands we emulate so the guest stays on this
976    /// controlled path instead of a host-dependent fallback; every other command
977    /// returns success without doing anything.
978    pub async fn handle_membarrier<G: Guest<Self>>(
979        &self,
980        guest: &mut G,
981        call: syscalls::Membarrier,
982    ) -> Result<i64, Error> {
983        // Values from <linux/membarrier.h>.
984        const MEMBARRIER_CMD_QUERY: i32 = 0;
985        const MEMBARRIER_CMD_GLOBAL: i32 = 1 << 0;
986        const MEMBARRIER_CMD_GLOBAL_EXPEDITED: i32 = 1 << 1;
987        const MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED: i32 = 1 << 2;
988        const MEMBARRIER_CMD_PRIVATE_EXPEDITED: i32 = 1 << 3;
989        const MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED: i32 = 1 << 4;
990        const SUPPORTED: i32 = MEMBARRIER_CMD_GLOBAL
991            | MEMBARRIER_CMD_GLOBAL_EXPEDITED
992            | MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED
993            | MEMBARRIER_CMD_PRIVATE_EXPEDITED
994            | MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED;
995
996        let cmd = call.cmd();
997        if cmd == MEMBARRIER_CMD_QUERY {
998            detlog!(
999                "[dtid {}] membarrier(QUERY) => reporting emulated commands {:#x}",
1000                guest.thread_state().dettid,
1001                SUPPORTED,
1002            );
1003            Ok(SUPPORTED as i64)
1004        } else {
1005            detlog!(
1006                "[dtid {}] membarrier(cmd={}) no-op (threads are serialized on one CPU)",
1007                guest.thread_state().dettid,
1008                cmd,
1009            );
1010            Ok(0)
1011        }
1012    }
1013
1014    /// getcpu system call
1015    pub async fn handle_getcpu<G: Guest<Self>>(
1016        &self,
1017        guest: &mut G,
1018        call: syscalls::Getcpu,
1019    ) -> Result<i64, Error> {
1020        // Always set the CPU to 0.
1021        if let Some(cpu) = call.cpu() {
1022            guest.memory().write_value(cpu, &0)?;
1023        }
1024
1025        // Always set the NUMA node to 0.
1026        if let Some(node) = call.node() {
1027            guest.memory().write_value(node, &0)?;
1028        }
1029
1030        Ok(0)
1031    }
1032
1033    /// getresuid under Hermit. Detcore presents a fixed virtual-root identity, so
1034    /// the real, effective, and saved user IDs are all the constant 0. Under the
1035    /// ptrace backend the guest runs inside a CLONE_NEWUSER namespace that already
1036    /// maps the host uid to 0; emulating the same constant here makes in-process
1037    /// backends (DBT) agree with that golden reference instead of leaking the host
1038    /// uid, and the fully emulated result is bitwise-identical across --verify and
1039    /// record/replay.
1040    // AUTONOMOUS-BOT-IMPLEMENTED
1041    // TODO-HUMAN-REVIEW(#1549)
1042    pub async fn handle_getresuid<G: Guest<Self>>(
1043        &self,
1044        guest: &mut G,
1045        call: syscalls::Getresuid,
1046    ) -> Result<i64, Error> {
1047        if let Some(ruid) = call.ruid() {
1048            guest.memory().write_value(ruid, &0)?;
1049        }
1050        if let Some(euid) = call.euid() {
1051            guest.memory().write_value(euid, &0)?;
1052        }
1053        if let Some(suid) = call.suid() {
1054            guest.memory().write_value(suid, &0)?;
1055        }
1056        Ok(0)
1057    }
1058
1059    /// getresgid under Hermit. The group-ID counterpart of `handle_getresuid`:
1060    /// the real, effective, and saved group IDs are all the fixed virtual-root
1061    /// constant 0, matching the ptrace CLONE_NEWUSER identity and deterministic
1062    /// across --verify and record/replay.
1063    // AUTONOMOUS-BOT-IMPLEMENTED
1064    // TODO-HUMAN-REVIEW(#1549)
1065    pub async fn handle_getresgid<G: Guest<Self>>(
1066        &self,
1067        guest: &mut G,
1068        call: syscalls::Getresgid,
1069    ) -> Result<i64, Error> {
1070        if let Some(rgid) = call.rgid() {
1071            guest.memory().write_value(rgid, &0)?;
1072        }
1073        if let Some(egid) = call.egid() {
1074            guest.memory().write_value(egid, &0)?;
1075        }
1076        if let Some(sgid) = call.sgid() {
1077            guest.memory().write_value(sgid, &0)?;
1078        }
1079        Ok(0)
1080    }
1081
1082    /// get_mempolicy under Hermit. The container exposes a single virtual NUMA
1083    /// node, so the effective policy is always the default and every address
1084    /// resolves to node 0. The result is fully emulated (never injected), so it
1085    /// is bitwise-identical across the two --verify runs and under record/replay,
1086    /// removing the host-NUMA-topology dependence a passthrough would introduce.
1087    ///
1088    /// It follows Linux's `kernel_get_mempolicy` and `do_get_mempolicy`
1089    /// (mm/mempolicy.c) for a kernel with one node (`nr_node_ids` 1):
1090    /// - a node mask with `maxnode` below 1 is EINVAL;
1091    /// - an unknown flag (any bit beyond `MPOL_F_NODE`, `MPOL_F_ADDR` and
1092    ///   `MPOL_F_MEMS_ALLOWED`, including those above bit 31 of the raw
1093    ///   argument, which Reverie's typed call drops), `MPOL_F_MEMS_ALLOWED`
1094    ///   with `MPOL_F_NODE` or `MPOL_F_ADDR`, and an address without
1095    ///   `MPOL_F_ADDR` are EINVAL;
1096    /// - `*policy` is 0: `MPOL_DEFAULT`, or node 0 for `MPOL_F_NODE`;
1097    /// - the node mask is written as `copy_nodes_to_user` writes it: node 0
1098    ///   alone for `MPOL_F_MEMS_ALLOWED`, as `/proc/<pid>/status` reports
1099    ///   `Mems_allowed_list` (<https://github.com/rrnewton/hermit/issues/4214>),
1100    ///   and no node for the default policy, in `ALIGN(maxnode - 1, 64) / 8`
1101    ///   bytes (none for a `maxnode` of 1), EINVAL beyond a page;
1102    /// - both are written with the guest's own access rights, so a read-only or
1103    ///   unmapped buffer is EFAULT, as from `put_user` and `copy_to_user`.
1104    ///
1105    /// Limits: `set_mempolicy` and `mbind` succeed without recording a policy,
1106    /// so this always reports the default policy, where Linux reports, say,
1107    /// `MPOL_INTERLEAVE` after `set_mempolicy(MPOL_INTERLEAVE)`. For the same
1108    /// reason `MPOL_F_NODE` without `MPOL_F_ADDR` answers node 0, as Linux does
1109    /// for an interleave policy (libnuma's `numa_get_interleave_node`), where
1110    /// it refuses it under the default policy. `MPOL_F_ADDR` does not check
1111    /// that the address is mapped, where Linux answers EFAULT for an unmapped
1112    /// one.
1113    // AUTONOMOUS-BOT-IMPLEMENTED
1114    // TODO-HUMAN-REVIEW(#720)
1115    pub async fn handle_get_mempolicy<G: Guest<Self>>(
1116        &self,
1117        guest: &mut G,
1118        call: syscalls::GetMempolicy,
1119    ) -> Result<i64, Error> {
1120        const MPOL_F_NODE: u64 = 1;
1121        const MPOL_F_ADDR: u64 = 2;
1122        const MPOL_F_MEMS_ALLOWED: u64 = 4;
1123        const PAGE: u64 = 4096;
1124        let mask = call.nodemask();
1125        if mask.is_some() && call.maxnode() < 1 {
1126            return Err(Errno::EINVAL.into());
1127        }
1128        // The flags argument is an unsigned long; Reverie decodes it as u32.
1129        let flags = guest.regs().await.r8;
1130        if flags & !(MPOL_F_NODE | MPOL_F_ADDR | MPOL_F_MEMS_ALLOWED) != 0 {
1131            return Err(Errno::EINVAL.into());
1132        }
1133        let mems_allowed = flags & MPOL_F_MEMS_ALLOWED != 0;
1134        if mems_allowed {
1135            if flags & (MPOL_F_NODE | MPOL_F_ADDR) != 0 {
1136                return Err(Errno::EINVAL.into());
1137            }
1138        } else if flags & MPOL_F_ADDR == 0 && call.addr().is_some() {
1139            return Err(Errno::EINVAL.into());
1140        }
1141        if let Some(policy) = call.policy() {
1142            let policy = AddrMut::<u8>::from_raw(policy.as_raw()).ok_or(Errno::EFAULT)?;
1143            write_get_mempolicy_output(&mut guest.memory(), policy, &0i32.to_ne_bytes())?;
1144        }
1145        if let Some(mask) = mask {
1146            let bytes = (call.maxnode() - 1).div_ceil(64) * 8;
1147            if bytes > PAGE.max(8) {
1148                return Err(Errno::EINVAL.into());
1149            }
1150            let mut words = vec![0u8; bytes as usize];
1151            if mems_allowed && !words.is_empty() {
1152                words[0] = 1;
1153            }
1154            if !words.is_empty() {
1155                let mask = AddrMut::<u8>::from_raw(mask.as_raw()).ok_or(Errno::EFAULT)?;
1156                write_get_mempolicy_output(&mut guest.memory(), mask, &words)?;
1157            }
1158        }
1159        Ok(0)
1160    }
1161
1162    /// move_pages under Hermit. On a single virtual NUMA node nothing can be
1163    /// relocated, so report every page as residing on node 0 and succeed. The
1164    /// answer is a fixed constant, so it is deterministic across --verify and
1165    /// record/replay.
1166    // AUTONOMOUS-BOT-IMPLEMENTED
1167    // TODO-HUMAN-REVIEW(#720)
1168    pub async fn handle_move_pages<G: Guest<Self>>(
1169        &self,
1170        guest: &mut G,
1171        call: syscalls::MovePages,
1172    ) -> Result<i64, Error> {
1173        // When a status buffer is supplied (either a real move request or a
1174        // location query with nodes == NULL), report node 0 for every page.
1175        if let Some(status) = call.status() {
1176            let count = call.nr_pages() as usize;
1177            let zeros = vec![0i32; count];
1178            guest.memory().write_values(status, &zeros)?;
1179        }
1180        Ok(0)
1181    }
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186    use super::*;
1187
1188    mod group_mirror {
1189        use std::sync::Mutex;
1190
1191        use reverie::GlobalRPC;
1192        use reverie::GlobalTool;
1193        use reverie::Tid;
1194        use reverie::Tool;
1195        use reverie::syscalls::Addr;
1196        use reverie::syscalls::AddrMut;
1197        use reverie::syscalls::SyscallInfo;
1198
1199        use super::*;
1200        use crate::config::Config;
1201        use crate::tool_global::GlobalState;
1202
1203        /// A guest whose backend answers the mirrored `setsid` with `answer`,
1204        /// recording `refusal` as its typed refusal when the answer fails.
1205        struct MirrorGuest<'a> {
1206            config: &'a Config,
1207            global: &'a GlobalState,
1208            thread: crate::ThreadState<()>,
1209            sender: Tid,
1210            answer: Result<i64, Errno>,
1211            refusal: Option<reverie::UnsupportedOperation>,
1212            recorded: Option<reverie::UnsupportedRefusal>,
1213            injections: Mutex<usize>,
1214        }
1215
1216        struct NoStack;
1217        struct NoStackGuard;
1218        impl Drop for NoStackGuard {
1219            fn drop(&mut self) {}
1220        }
1221        impl reverie::Stack for NoStack {
1222            type StackGuard = NoStackGuard;
1223            fn size(&self) -> usize {
1224                panic!("a mirror must not use the guest stack")
1225            }
1226            fn capacity(&self) -> usize {
1227                panic!("a mirror must not use the guest stack")
1228            }
1229            fn push<'stack, T>(&mut self, _: T) -> Addr<'stack, T> {
1230                panic!("a mirror must not use the guest stack")
1231            }
1232            fn reserve<'stack, T>(&mut self) -> AddrMut<'stack, T> {
1233                panic!("a mirror must not use the guest stack")
1234            }
1235            fn commit(self) -> Result<Self::StackGuard, Errno> {
1236                panic!("a mirror must not use the guest stack")
1237            }
1238        }
1239
1240        #[reverie::tool]
1241        impl GlobalRPC<GlobalState> for MirrorGuest<'_> {
1242            async fn send_rpc(
1243                &self,
1244                message: <GlobalState as GlobalTool>::Request,
1245            ) -> <GlobalState as GlobalTool>::Response {
1246                self.global.receive_rpc(self.sender, message).await
1247            }
1248            fn config(&self) -> &Config {
1249                self.config
1250            }
1251        }
1252
1253        #[reverie::tool]
1254        impl Guest<Detcore> for MirrorGuest<'_> {
1255            type Memory = reverie::syscalls::LocalMemory;
1256            type Stack = NoStack;
1257
1258            fn tid(&self) -> Tid {
1259                self.sender
1260            }
1261            fn pid(&self) -> Tid {
1262                self.sender
1263            }
1264            fn ppid(&self) -> Option<Tid> {
1265                None
1266            }
1267            fn memory(&self) -> Self::Memory {
1268                reverie::syscalls::LocalMemory::new()
1269            }
1270            fn thread_state(&self) -> &crate::ThreadState<()> {
1271                &self.thread
1272            }
1273            fn thread_state_mut(&mut self) -> &mut crate::ThreadState<()> {
1274                &mut self.thread
1275            }
1276            async fn regs(&mut self) -> libc::user_regs_struct {
1277                panic!("a mirror must not read registers")
1278            }
1279            async fn stack(&mut self) -> Self::Stack {
1280                panic!("a mirror must not use a guest stack")
1281            }
1282            async fn daemonize(&mut self) {
1283                panic!("a mirror must not daemonize")
1284            }
1285            async fn inject<S: SyscallInfo>(&mut self, call: S) -> Result<i64, Errno> {
1286                assert_eq!(call.number(), Sysno::setsid);
1287                *self.injections.lock().unwrap() += 1;
1288                if let Err(errno) = self.answer {
1289                    self.recorded = self.refusal.map(|operation| {
1290                        reverie::UnsupportedRefusal::new(operation, errno, "test backend")
1291                    });
1292                }
1293                self.answer
1294            }
1295            fn take_unsupported_refusal(&mut self) -> Option<reverie::UnsupportedRefusal> {
1296                self.recorded.take()
1297            }
1298            async fn tail_inject<S: SyscallInfo>(&mut self, _: S) -> reverie::Never {
1299                panic!("a mirror must not retire the guest")
1300            }
1301            fn set_timer(&mut self, _: reverie::TimerSchedule) -> Result<(), Error> {
1302                panic!("a mirror must not set a timer")
1303            }
1304            fn set_timer_precise(&mut self, _: reverie::TimerSchedule) -> Result<(), Error> {
1305                panic!("a mirror must not set a timer")
1306            }
1307            fn read_clock(&mut self) -> Result<u64, Error> {
1308                panic!("a mirror must not read the clock")
1309            }
1310        }
1311
1312        /// The negative control for the mirror of a group change the model
1313        /// accepted: the backend's success, or its typed statement that it
1314        /// keeps no process groups, lets the model's answer stand; any other
1315        /// failure, a bare ENOSYS (as a guest's seccomp filter could give)
1316        /// or an errno the model did not predict, refuses the run by name in
1317        /// a fail-closed run, never passing the errno on.
1318        #[tokio::test]
1319        async fn a_failed_mirror_stands_only_with_the_typed_process_group_refusal() {
1320            use reverie::UnsupportedOperation::Flock;
1321            use reverie::UnsupportedOperation::ProcessGroups;
1322            let process = DetPid::from_raw(23);
1323            for (answer, refusal, accepted) in [
1324                (Ok(23), None, true),
1325                (Err(Errno::ENOSYS), Some(ProcessGroups), true),
1326                (Err(Errno::ENOSYS), None, false),
1327                (Err(Errno::EPERM), None, false),
1328                (Err(Errno::ENOSYS), Some(Flock), false),
1329            ] {
1330                let config = Config {
1331                    panic_on_unsupported_syscalls: true,
1332                    exit_on_unsupported_syscall: true,
1333                    shutdown_on_unsupported_syscall: false,
1334                    ..Config::default()
1335                };
1336                let global = GlobalState::init_global_state(&config).await;
1337                let tool = Detcore::new(Tid::from_raw(process.as_raw()), &config);
1338                let mut thread = crate::ThreadState::new(process, &config, ());
1339                thread.detpid = Some(process);
1340                let mut guest = MirrorGuest {
1341                    config: &config,
1342                    global: &global,
1343                    thread,
1344                    sender: Tid::from_raw(process.as_raw()),
1345                    answer,
1346                    refusal,
1347                    recorded: None,
1348                    injections: Mutex::new(0),
1349                };
1350                let result = tool
1351                    .mirror_group_change(
1352                        &mut guest,
1353                        reverie::syscalls::Syscall::Setsid(reverie::syscalls::Setsid::new()),
1354                    )
1355                    .await;
1356                match result {
1357                    Ok(()) if accepted => {}
1358                    Err(Error::Tool(error)) if !accepted => assert_eq!(
1359                        error
1360                            .downcast_ref::<crate::UnsupportedSyscallError>()
1361                            .unwrap()
1362                            .0,
1363                        Sysno::setsid,
1364                        "{answer:?} {refusal:?}"
1365                    ),
1366                    result => panic!("wrong mirror policy for {answer:?} {refusal:?}: {result:?}"),
1367                }
1368                assert_eq!(*guest.injections.lock().unwrap(), 1);
1369                assert_eq!(guest.recorded, None, "a reported refusal must be taken");
1370            }
1371        }
1372    }
1373
1374    struct ScatterMemory {
1375        bytes: Vec<u8>,
1376        outcomes: std::collections::VecDeque<Result<usize, Errno>>,
1377        writes: usize,
1378    }
1379
1380    impl ScatterMemory {
1381        fn new(size: usize, outcomes: impl IntoIterator<Item = Result<usize, Errno>>) -> Self {
1382            Self {
1383                bytes: vec![0xa5; size],
1384                outcomes: outcomes.into_iter().collect(),
1385                writes: 0,
1386            }
1387        }
1388    }
1389
1390    impl MemoryAccess for ScatterMemory {
1391        fn read_vectored(
1392            &self,
1393            _: &[std::io::IoSlice],
1394            _: &mut [std::io::IoSliceMut],
1395        ) -> Result<usize, Errno> {
1396            panic!("canonical scatter must not read guest bytes")
1397        }
1398        fn write_vectored(
1399            &mut self,
1400            _: &[std::io::IoSlice],
1401            _: &mut [std::io::IoSliceMut],
1402        ) -> Result<usize, Errno> {
1403            panic!("canonical scatter must use the user-access capability")
1404        }
1405        fn write_with_user_access(
1406            &mut self,
1407            address: AddrMut<u8>,
1408            bytes: &[u8],
1409        ) -> Result<usize, Errno> {
1410            self.writes += 1;
1411            let count = self.outcomes.pop_front().unwrap_or(Ok(bytes.len()))?;
1412            assert!(count <= bytes.len());
1413            let offset = address.as_raw() - 0x1000;
1414            self.bytes[offset..offset + count].copy_from_slice(&bytes[..count]);
1415            Ok(count)
1416        }
1417    }
1418
1419    fn assert_copy_failure(error: Error, expected: Errno) {
1420        let Error::Tool(error) = error else {
1421            panic!("copy failure became a guest errno: {error:?}")
1422        };
1423        assert_eq!(
1424            error
1425                .downcast_ref::<crate::random::RandomCopyFailure>()
1426                .expect("typed copy failure")
1427                .errno(),
1428            expected
1429        );
1430    }
1431
1432    fn scatter(memory: &mut ScatterMemory, lengths: &[usize], offset: u64) -> Result<usize, Error> {
1433        let mut base = 0x1000;
1434        let vectors: Vec<_> = lengths
1435            .iter()
1436            .map(|&len| {
1437                let vector = crate::iovecs::ImportedIovec { base, len };
1438                base += len;
1439                vector
1440            })
1441            .collect();
1442        fill_canonical_random_iovecs(memory, &vectors, 0, offset, &mut DefaultHasher::new())
1443    }
1444
1445    #[test]
1446    fn get_mempolicy_output_faults_are_efault_and_backend_errors_are_tool_errors() {
1447        let address = AddrMut::<u8>::from_raw(0x1000).unwrap();
1448        let write = |outcome| {
1449            write_get_mempolicy_output(&mut ScatterMemory::new(8, [outcome]), address, &[1; 8])
1450        };
1451        assert!(write(Ok(8)).is_ok());
1452        for fault in [Ok(0), Ok(3), Err(Errno::EFAULT)] {
1453            assert!(
1454                matches!(write(fault), Err(Error::Errno(Errno::EFAULT))),
1455                "{fault:?}"
1456            );
1457        }
1458        for errno in [Errno::ENOSYS, Errno::ESRCH, Errno::EIO] {
1459            assert!(
1460                matches!(write(Err(errno)), Err(Error::Tool(_))),
1461                "{errno:?}"
1462            );
1463        }
1464    }
1465
1466    #[test]
1467    fn random_scatter_distinguishes_fault_prefixes_from_backend_errors() {
1468        // Exercise both an earlier complete iovec and an earlier complete chunk.
1469        for lengths in [vec![3, 5], vec![RANDOM_FILL_CHUNK_BYTES + 5]] {
1470            let prefix = if lengths.len() == 2 {
1471                3
1472            } else {
1473                RANDOM_FILL_CHUNK_BYTES
1474            };
1475            for error in [Errno::EFAULT, Errno::EIO, Errno::ENOMEM] {
1476                let mut memory = ScatterMemory::new(prefix + 5, [Ok(prefix), Err(error)]);
1477                let result = scatter(&mut memory, &lengths, 7);
1478                match error {
1479                    Errno::EFAULT => assert_eq!(result.unwrap(), prefix),
1480                    _ => assert_copy_failure(result.unwrap_err(), error),
1481                }
1482                let expected: Vec<_> = (7..7 + prefix as u64)
1483                    .map(|index| canonical_random_device_byte(0, index))
1484                    .collect();
1485                assert_eq!(&memory.bytes[..prefix], expected);
1486                assert_eq!(&memory.bytes[prefix..], &[0xa5; 5]);
1487                assert_eq!(memory.writes, 2);
1488            }
1489        }
1490    }
1491
1492    #[test]
1493    fn random_scatter_short_or_zero_copy_stops_without_touching_later_segments() {
1494        for first in [0, 2] {
1495            let mut memory = ScatterMemory::new(10, [Ok(first)]);
1496            let result = scatter(&mut memory, &[5, 5], 0);
1497            if first == 0 {
1498                assert!(matches!(result, Err(Error::Errno(Errno::EFAULT))));
1499            } else {
1500                assert_eq!(result.unwrap(), first);
1501                assert_eq!(&memory.bytes[..2], &[41, 114]);
1502            }
1503            assert!(memory.bytes[first..].iter().all(|&byte| byte == 0xa5));
1504            assert_eq!(memory.writes, 1);
1505        }
1506        let mut memory = ScatterMemory::new(10, [Ok(5), Ok(0)]);
1507        assert_eq!(scatter(&mut memory, &[5, 5], 0).unwrap(), 5);
1508        assert!(memory.bytes[5..].iter().all(|&byte| byte == 0xa5));
1509        assert_eq!(memory.writes, 2);
1510    }
1511
1512    #[test]
1513    fn random_scatter_saturated_bytes_match_partitioned_calls() {
1514        for (offset, expected) in [(u64::MAX - 2, [78, 151, 224, 224]), (u64::MAX, [224; 4])] {
1515            let mut single = ScatterMemory::new(4, []);
1516            assert_eq!(scatter(&mut single, &[4], offset).unwrap(), 4);
1517            let mut partitioned = ScatterMemory::new(4, []);
1518            let mut hash = DefaultHasher::new();
1519            assert_eq!(
1520                fill_canonical_random_iovecs(
1521                    &mut partitioned,
1522                    &[crate::iovecs::ImportedIovec {
1523                        base: 0x1000,
1524                        len: 1
1525                    }],
1526                    0,
1527                    offset,
1528                    &mut hash
1529                )
1530                .unwrap(),
1531                1
1532            );
1533            assert_eq!(
1534                fill_canonical_random_iovecs(
1535                    &mut partitioned,
1536                    &[crate::iovecs::ImportedIovec {
1537                        base: 0x1001,
1538                        len: 3
1539                    }],
1540                    0,
1541                    offset.saturating_add(1),
1542                    &mut hash
1543                )
1544                .unwrap(),
1545                3
1546            );
1547            assert_eq!(single.bytes, expected);
1548            assert_eq!(partitioned.bytes, expected);
1549        }
1550    }
1551
1552    #[test]
1553    fn random_scatter_backend_error_rolls_back_shared_cursor_after_eight_byte_prefix() {
1554        let fd = crate::fd::DetFd::new(
1555            3,
1556            nix::fcntl::OFlag::O_RDONLY,
1557            crate::fd::FdType::Rng,
1558            crate::types::OpenFileId::new(crate::types::DetTid::from_raw(1), 0),
1559        );
1560        for error in [Errno::EFAULT, Errno::EIO] {
1561            let mut memory = ScatterMemory::new(8, [Ok(4), Err(error)]);
1562            let result = fd.with_random_device_stream(|offset| scatter(&mut memory, &[8], offset));
1563            if error == Errno::EFAULT {
1564                assert_eq!(result.unwrap(), 4);
1565            } else {
1566                assert_copy_failure(result.unwrap_err(), Errno::EIO);
1567            }
1568            // First iteration commits four; the EIO iteration must not commit
1569            // its physically copied prefix or fabricate a successful result.
1570            assert_eq!(fd.random_device_offset(), 4);
1571            assert_eq!(&memory.bytes[4..], &[0xa5; 4]);
1572            assert_eq!(memory.writes, 2);
1573        }
1574    }
1575
1576    #[test]
1577    fn prctl_support_covers_deterministic_controls() {
1578        for option in [
1579            libc::PR_SET_NAME,
1580            libc::PR_GET_NAME,
1581            libc::PR_SET_THP_DISABLE,
1582            libc::PR_GET_THP_DISABLE,
1583            // Deterministic per-process dumpability state.
1584            libc::PR_SET_DUMPABLE,
1585            libc::PR_GET_DUMPABLE,
1586            // Deterministic per-thread capability-retention flag used by setpriv.
1587            libc::PR_SET_KEEPCAPS,
1588            libc::PR_GET_KEEPCAPS,
1589            // Deterministic per-thread parent-death-signal flag used by setpriv.
1590            libc::PR_SET_PDEATHSIG,
1591            libc::PR_GET_PDEATHSIG,
1592        ] {
1593            assert!(is_supported_prctl_option(option));
1594        }
1595
1596        assert!(!is_supported_prctl_option(libc::PR_SET_NO_NEW_PRIVS));
1597        // Detcore's serialized-execution contract
1598        // (`Tool::enforces_serialized_execution`) rests on refusing it.
1599        assert!(!is_supported_prctl_option(libc::PR_SET_SECCOMP));
1600        assert!(!is_supported_prctl_option(libc::PR_SET_TIMERSLACK));
1601        assert!(!is_supported_prctl_option(libc::PR_GET_TIMERSLACK));
1602    }
1603
1604    /// The subreaper prctls are admitted only where Detcore's record of
1605    /// children decides waits and the kernel has re-parented by the time an
1606    /// exit reaches Detcore: ptrace, and e9patch preprocessing under ptrace,
1607    /// with threads sequentialized. Without sequentialization no exit reaches
1608    /// the scheduler, nothing re-parents, and a subreaper's wait would see
1609    /// ECHILD while its orphan lives, so the call keeps failing with ENOSYS.
1610    #[test]
1611    fn child_subreaper_prctls_are_admitted_only_where_detcore_models_them() {
1612        for backend in [BackendCapabilities::PTRACE, BackendCapabilities::E9PATCH] {
1613            assert!(models_child_subreapers(true, &backend), "{backend:?}");
1614            assert!(!models_child_subreapers(false, &backend), "{backend:?}");
1615        }
1616        for backend in [
1617            BackendCapabilities::LITEINST_IN_GUEST,
1618            BackendCapabilities::SABRE,
1619            BackendCapabilities::DBT,
1620            BackendCapabilities::KVM,
1621        ] {
1622            assert!(!models_child_subreapers(true, &backend), "{backend:?}");
1623            assert!(!models_child_subreapers(false, &backend), "{backend:?}");
1624        }
1625        assert!(!is_supported_prctl_option(libc::PR_SET_CHILD_SUBREAPER));
1626        assert!(!is_supported_prctl_option(libc::PR_GET_CHILD_SUBREAPER));
1627    }
1628
1629    #[test]
1630    fn capability_set_prctls_are_supported_on_every_backend() {
1631        for option in [libc::PR_CAPBSET_DROP, libc::PR_CAP_AMBIENT] {
1632            assert!(is_supported_prctl_option(option));
1633        }
1634        assert!(!is_supported_prctl_option(libc::PR_SET_SECUREBITS));
1635    }
1636
1637    #[test]
1638    fn getrandom_accepts_linux_flags() {
1639        for flags in [
1640            0,
1641            libc::GRND_NONBLOCK as usize,
1642            libc::GRND_RANDOM as usize,
1643            (libc::GRND_NONBLOCK | libc::GRND_RANDOM) as usize,
1644            libc::GRND_INSECURE as usize,
1645            (libc::GRND_NONBLOCK | libc::GRND_INSECURE) as usize,
1646            1_usize << 32,
1647        ] {
1648            assert!(
1649                validate_getrandom_flags(flags).is_ok(),
1650                "valid flags rejected: {flags:#x}"
1651            );
1652        }
1653    }
1654
1655    #[test]
1656    fn getrandom_rejects_invalid_flags() {
1657        for flags in [
1658            0x8000_0000,
1659            (1_usize << 32) | 0x8000_0000,
1660            (libc::GRND_RANDOM | libc::GRND_INSECURE) as usize,
1661        ] {
1662            assert_eq!(validate_getrandom_flags(flags), Err(Errno::EINVAL));
1663        }
1664    }
1665
1666    #[test]
1667    fn getrandom_caps_requests_at_linux_max_rw_count() {
1668        assert_eq!(getrandom_request_len(16), 16);
1669        assert_eq!(getrandom_request_len(usize::MAX), GETRANDOM_MAX_BYTES);
1670    }
1671
1672    #[test]
1673    fn canonical_random_device_stream_matches_kvm_root_contract() {
1674        let first: Vec<_> = (0..8)
1675            .map(|index| canonical_random_device_byte(0, index))
1676            .collect();
1677        assert_eq!(first, [41, 114, 187, 4, 77, 150, 223, 40]);
1678
1679        let continued: Vec<_> = (8..16)
1680            .map(|index| canonical_random_device_byte(0, index))
1681            .collect();
1682        assert_eq!(continued, [113, 186, 3, 76, 149, 222, 39, 112]);
1683
1684        let seeded: Vec<_> = (0..16)
1685            .map(|index| canonical_random_device_byte(17, index))
1686            .collect();
1687        assert_eq!(
1688            seeded,
1689            [
1690                56, 114, 187, 4, 77, 150, 223, 40, 96, 186, 3, 76, 149, 222, 39, 112
1691            ]
1692        );
1693        assert_ne!(seeded, [first, continued].concat());
1694    }
1695
1696    #[test]
1697    fn getpriority_reports_default_nice_for_every_target() {
1698        // Every valid PRIO_* selector reports the default nice (raw 20 = nice 0),
1699        // regardless of `who`. Real tools such as `renice -p <pid>` pass an
1700        // explicit pid, and getpriority never checks permissions, so this must
1701        // never be EPERM (the pre-fix stub only accepted PRIO_PROCESS/who==0).
1702        for which in [libc::PRIO_PROCESS, libc::PRIO_PGRP, libc::PRIO_USER] {
1703            assert_eq!(getpriority_result(which as i32), Ok(20));
1704        }
1705    }
1706
1707    #[test]
1708    fn setpriority_accepts_any_change_for_valid_target() {
1709        // Nice is inert under Hermit, so any priority change for a valid target
1710        // succeeds as a no-op — including nonzero nice (`nice -n 5`, os.nice).
1711        for which in [libc::PRIO_PROCESS, libc::PRIO_PGRP, libc::PRIO_USER] {
1712            assert_eq!(setpriority_result(which as i32), Ok(0));
1713        }
1714    }
1715
1716    #[test]
1717    fn get_and_set_priority_reject_unknown_which_with_einval() {
1718        // Match Linux: an unknown target selector faults with EINVAL, not EPERM.
1719        for which in [-1, 3, 42] {
1720            assert_eq!(getpriority_result(which), Err(Errno::EINVAL));
1721            assert_eq!(setpriority_result(which), Err(Errno::EINVAL));
1722        }
1723    }
1724
1725    #[test]
1726    fn seccomp_tsync_null_probe_matches_linux_validation() {
1727        assert_eq!(
1728            seccomp_result(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, false,),
1729            Err(Errno::EFAULT)
1730        );
1731        assert_eq!(
1732            seccomp_result(SECCOMP_SET_MODE_FILTER, 1 << 31, false),
1733            Err(Errno::EINVAL)
1734        );
1735        assert_eq!(
1736            seccomp_result(SECCOMP_SET_MODE_FILTER, 0, true),
1737            Err(Errno::EOPNOTSUPP)
1738        );
1739    }
1740
1741    #[test]
1742    fn process_madvise_is_rejected_deterministically() {
1743        assert!(matches!(
1744            Detcore::<crate::record_or_replay::NoopTool>::handle_process_madvise(
1745                (-10_000_i32) as usize,
1746                0
1747            ),
1748            Err(Error::Errno(Errno::EBADF))
1749        ));
1750        assert!(matches!(
1751            Detcore::<crate::record_or_replay::NoopTool>::handle_process_madvise(3, 1),
1752            Err(Error::Errno(Errno::EINVAL))
1753        ));
1754        assert!(matches!(
1755            Detcore::<crate::record_or_replay::NoopTool>::handle_process_madvise(3, 0),
1756            Err(Error::Errno(Errno::EPERM))
1757        ));
1758    }
1759
1760    #[test]
1761    fn syslog_exposes_an_empty_log_and_validates_actions() {
1762        for action in 0..=7 {
1763            assert_eq!(deterministic_syslog_result(action, 0), Ok(0));
1764        }
1765        for action in [9, 10] {
1766            assert_eq!(deterministic_syslog_result(action, 0), Ok(0));
1767        }
1768        assert_eq!(deterministic_syslog_result(8, 1), Ok(0));
1769        assert_eq!(deterministic_syslog_result(8, 8), Ok(0));
1770        assert_eq!(deterministic_syslog_result(8, 0), Err(Errno::EINVAL));
1771        assert_eq!(deterministic_syslog_result(8, 9), Err(Errno::EINVAL));
1772        assert_eq!(deterministic_syslog_result(11, 0), Err(Errno::EINVAL));
1773    }
1774}