1use 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 Err(Errno::EOPNOTSUPP)
88}
89
90fn emulates_parent_death_signal(config: &crate::config::Config) -> bool {
95 config.sequentialize_threads && bundled_signal_facts::host_task_reads_enabled(&config.backend)
96}
97
98fn 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 | libc::PR_SET_DUMPABLE
123 | libc::PR_GET_DUMPABLE
124 | libc::PR_SET_KEEPCAPS
137 | libc::PR_GET_KEEPCAPS
138 | libc::PR_SET_PDEATHSIG
156 | libc::PR_GET_PDEATHSIG
157 | libc::PR_CAPBSET_DROP
171 | libc::PR_CAP_AMBIENT
172 )
173}
174
175fn 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
194fn 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
201fn 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
216fn 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
228fn 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
240fn 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
271fn 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
281fn 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 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 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 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 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 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 ArchPrctlCmd::ARCH_GET_CPUID(_) | ArchPrctlCmd::ARCH_SET_CPUID(_) => {
404 Ok(guest.inject(call).await?)
405 }
406
407 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 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 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 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 libc::PR_CAPBSET_READ => Ok(self.record_or_replay(guest, call).await?),
474 libc::PR_SET_TIMERSLACK => {
480 let requested = call.arg2();
481 let state = guest.thread_state_mut();
482 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 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 let emulated = emulates_parent_death_signal(guest.config());
530 if emulated && (signal == 0 || detcore_sends_parent_death_signal(signal)) {
531 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 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 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 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 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 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 if (pidfd as libc::c_int) < 0 {
677 Err(Errno::EBADF.into())
678 } else {
679 Err(Errno::EPERM.into())
680 }
681 }
682
683 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 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 un.nodename = from_str(DEFAULT_HOSTNAME);
746 un.domainname = from_str(DEFAULT_HOSTNAME.split('.').next_back().unwrap_or(""));
747 }
748
749 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 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 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 if guest.config().kill_daemons {
804 guest.daemonize().await;
805 }
806 Ok(res)
807 }
808
809 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 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 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 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 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 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 pub async fn handle_membarrier<G: Guest<Self>>(
979 &self,
980 guest: &mut G,
981 call: syscalls::Membarrier,
982 ) -> Result<i64, Error> {
983 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 pub async fn handle_getcpu<G: Guest<Self>>(
1016 &self,
1017 guest: &mut G,
1018 call: syscalls::Getcpu,
1019 ) -> Result<i64, Error> {
1020 if let Some(cpu) = call.cpu() {
1022 guest.memory().write_value(cpu, &0)?;
1023 }
1024
1025 if let Some(node) = call.node() {
1027 guest.memory().write_value(node, &0)?;
1028 }
1029
1030 Ok(0)
1031 }
1032
1033 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 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 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 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 pub async fn handle_move_pages<G: Guest<Self>>(
1169 &self,
1170 guest: &mut G,
1171 call: syscalls::MovePages,
1172 ) -> Result<i64, Error> {
1173 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 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 #[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 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 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 libc::PR_SET_DUMPABLE,
1585 libc::PR_GET_DUMPABLE,
1586 libc::PR_SET_KEEPCAPS,
1588 libc::PR_GET_KEEPCAPS,
1589 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 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 #[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 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 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 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}