hermit-detcore 0.4.0

Detcore: the deterministic scheduler and syscall determinization core of the Hermit execution engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! Miscellaneous virtualized syscalls.

use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;

use reverie::Error;
use reverie::Guest;
use reverie::syscalls;
use reverie::syscalls::AddrMut;
use reverie::syscalls::ArchPrctlCmd;
use reverie::syscalls::Errno;
use reverie::syscalls::MemoryAccess;

use crate::consts::DEFAULT_HOSTNAME;
use crate::detlog;
#[cfg(test)]
use crate::random::GETRANDOM_MAX_BYTES;
use crate::random::RANDOM_FILL_CHUNK_BYTES;
#[cfg(test)]
use crate::random::getrandom_request_len;
#[cfg(test)]
use crate::random::validate_getrandom_flags;
use crate::random::write_random_chunk;
use crate::record_or_replay::RecordOrReplay;
use crate::tool_global::create_session;
use crate::tool_global::set_process_group;
use crate::tool_local::Detcore;
use crate::types::DetPid;

const ARCH_GET_XCOMP_SUPP: libc::c_int = 0x1021;
const ARCH_GET_XCOMP_PERM: libc::c_int = 0x1022;
const ARCH_REQ_XCOMP_PERM: libc::c_int = 0x1023;
const ARCH_GET_XCOMP_GUEST_PERM: libc::c_int = 0x1024;
const ARCH_REQ_XCOMP_GUEST_PERM: libc::c_int = 0x1025;

const ARCH_SHSTK_ENABLE: libc::c_int = 0x5001;
const ARCH_SHSTK_DISABLE: libc::c_int = 0x5002;
const ARCH_SHSTK_LOCK: libc::c_int = 0x5003;
const ARCH_SHSTK_UNLOCK: libc::c_int = 0x5004;
const ARCH_SHSTK_STATUS: libc::c_int = 0x5005;
const ARCH_SHSTK_VALID_MASK: usize = 0b11;

const SECCOMP_SET_MODE_STRICT: u32 = 0;
const SECCOMP_SET_MODE_FILTER: u32 = 1;
const SECCOMP_GET_ACTION_AVAIL: u32 = 2;
const SECCOMP_GET_NOTIF_SIZES: u32 = 3;
const SECCOMP_FILTER_FLAG_TSYNC: u32 = 1;

fn seccomp_result(op: u32, flags: u32, has_args: bool) -> Result<i64, Errno> {
    if op > SECCOMP_GET_NOTIF_SIZES {
        return Err(Errno::EINVAL);
    }
    if op == SECCOMP_SET_MODE_STRICT && (flags != 0 || has_args) {
        return Err(Errno::EINVAL);
    }
    if op == SECCOMP_SET_MODE_FILTER && flags & !SECCOMP_FILTER_FLAG_TSYNC != 0 {
        return Err(Errno::EINVAL);
    }
    if matches!(
        op,
        SECCOMP_SET_MODE_FILTER | SECCOMP_GET_ACTION_AVAIL | SECCOMP_GET_NOTIF_SIZES
    ) && !has_args
    {
        return Err(Errno::EFAULT);
    }

    // Hermit cannot enforce a guest-installed BPF policy in every backend.
    // Report the operation as unsupported instead of claiming a filter exists.
    Err(Errno::EOPNOTSUPP)
}

fn is_supported_prctl_option(option: libc::c_int) -> bool {
    matches!(
        option,
        libc::PR_SET_NAME
            | libc::PR_GET_NAME
            | libc::PR_SET_THP_DISABLE
            | libc::PR_GET_THP_DISABLE
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#919)
            //
            // Dumpability is per-process state initialized deterministically by
            // ordinary exec and subsequently controlled only by the guest. Keep
            // Linux's 0/1 validation and state transitions rather than refusing
            // applications that explicitly disable or restore core-dump access.
            | libc::PR_SET_DUMPABLE
            | libc::PR_GET_DUMPABLE
            // PR_SET_TIMERSLACK and PR_GET_TIMERSLACK are deliberately absent:
            // `handle_prctl` emulates them against per-thread Detcore state.
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#802)
            //
            // PR_{SET,GET}_KEEPCAPS only read/toggle the calling thread's
            // "keep capabilities across a UID change" flag. The result is a pure
            // function of the guest's own prior prctl calls (0/1), never host
            // state, so passthrough is deterministic and bitwise-identical across
            // runs. Supporting it lets `setpriv` (and the `date`/privilege-drop
            // wrappers that call it) run under --strict instead of aborting with
            // "keep process capabilities failed: Function not implemented".
            | libc::PR_SET_KEEPCAPS
            | libc::PR_GET_KEEPCAPS
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#824)
            //
            // PR_{SET,GET}_PDEATHSIG only read/toggle the calling thread's
            // parent-death-signal attribute. PR_SET_PDEATHSIG validates its
            // signal argument (a valid signal or 0 succeeds, anything else
            // faults EINVAL) and PR_GET_PDEATHSIG reports the value the guest
            // previously set. The result is a pure function of the guest's own
            // prior prctl calls and its argument, never host state, so
            // passthrough is deterministic and bitwise-identical across runs.
            // The registered signal only ever fires on parent death, which is a
            // deterministically scheduled event under Hermit. Supporting it lets
            // `setpriv --pdeathsig` run under --strict instead of aborting with
            // "set parent death signal failed: Function not implemented".
            | libc::PR_SET_PDEATHSIG
            | libc::PR_GET_PDEATHSIG
    )
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-1125): Review KVM capability-control prctl forwarding.
fn is_backend_virtualized_capability_prctl(option: libc::c_int) -> bool {
    matches!(option, libc::PR_CAPBSET_DROP | libc::PR_CAP_AMBIENT)
}

/// Is `which` one of the Linux `PRIO_*` target selectors for get/setpriority?
fn is_valid_prio_which(which: i32) -> bool {
    which == libc::PRIO_PROCESS as i32
        || which == libc::PRIO_PGRP as i32
        || which == libc::PRIO_USER as i32
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(#806)
/// Deterministic raw `getpriority(2)` result under Hermit's inert-nice model.
///
/// Returns `20 - nice` (nice 0 -> 20) for any valid target regardless of `who`,
/// because nice is inert under the virtualized scheduler and `getpriority` never
/// checks permissions; an unknown `which` faults with `EINVAL`, matching Linux.
fn getpriority_result(which: i32) -> Result<i64, Errno> {
    if is_valid_prio_which(which) {
        Ok(20)
    } else {
        Err(Errno::EINVAL)
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(#806)
/// Deterministic raw `setpriority(2)` result: accept any priority change for a
/// valid target as an inert no-op (returns 0), `EINVAL` for an unknown `which`.
fn setpriority_result(which: i32) -> Result<i64, Errno> {
    if is_valid_prio_which(which) {
        Ok(0)
    } else {
        Err(Errno::EINVAL)
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-857): Deterministic empty kernel-log action policy.
fn deterministic_syslog_result(action: i32, len: usize) -> Result<i64, Errno> {
    const SYSLOG_ACTION_CONSOLE_LEVEL: i32 = 8;

    match action {
        0..=7 | 9..=10 => Ok(0),
        SYSLOG_ACTION_CONSOLE_LEVEL if (1..=8).contains(&len) => Ok(0),
        _ => Err(Errno::EINVAL),
    }
}

fn from_str(s: &str) -> [i8; 65] {
    let mut ret: [i8; 65] = [0; 65];
    for (i, ch) in s.bytes().take(64).enumerate() {
        ret[i] = ch as i8;
    }
    ret
}

const RANDOM_DEVICE_BYTE_STRIDE: u8 = 73;
const RANDOM_DEVICE_FIRST_BYTE: u8 = 41;

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-1096): Review the backend-independent random-device stream.
fn canonical_random_device_byte(seed: u64, index: u64) -> u8 {
    let seed_byte = seed.rotate_right(((index % 8) * 8) as u32) as u8;
    (index as u8)
        .wrapping_mul(RANDOM_DEVICE_BYTE_STRIDE)
        .wrapping_add(RANDOM_DEVICE_FIRST_BYTE)
        ^ seed_byte
}

/// Scatter one stream through an already-imported array. Scratch space is
/// independent of request size; only EFAULT becomes a successful copied prefix.
fn fill_canonical_random_iovecs(
    memory: &mut impl MemoryAccess,
    iovecs: &[crate::iovecs::ImportedIovec],
    seed: u64,
    stream_offset: u64,
    hasher: &mut DefaultHasher,
) -> Result<usize, Error> {
    let mut local_words = [0_u64; RANDOM_FILL_CHUNK_BYTES / std::mem::size_of::<u64>()];
    let mut written = 0_usize;
    for iov in iovecs {
        let mut segment_written = 0;
        while segment_written < iov.len {
            let remote_chunk = match iov
                .base
                .checked_add(segment_written)
                .and_then(AddrMut::<u8>::from_raw)
            {
                Some(address) => address,
                None if written == 0 => return Err(Errno::EFAULT.into()),
                None => return Ok(written),
            };
            let chunk_len = (iov.len - segment_written).min(RANDOM_FILL_CHUNK_BYTES);
            let local_buf = unsafe {
                std::slice::from_raw_parts_mut(local_words.as_mut_ptr().cast::<u8>(), chunk_len)
            };
            for (index, byte) in local_buf.iter_mut().enumerate() {
                *byte = canonical_random_device_byte(
                    seed,
                    stream_offset
                        .saturating_add(written as u64)
                        .saturating_add(index as u64),
                );
            }
            let n = match write_random_chunk(memory, remote_chunk, local_buf) {
                Ok(n) => n,
                Err(Errno::EFAULT) if written > 0 => return Ok(written),
                Err(error) => return Err(crate::random::copy_error(error)),
            };
            if n == 0 && written == 0 {
                return Err(Errno::EFAULT.into());
            }
            if cfg!(debug_assertions) {
                Hash::hash_slice(&local_buf[..n], hasher);
            }
            written += n;
            segment_written += n;
            if n < chunk_len {
                return Ok(written);
            }
        }
    }
    Ok(written)
}

impl<T: RecordOrReplay> Detcore<T> {
    /// Validates seccomp capability probes without installing guest filters.
    // TODO-HUMAN-REVIEW(PR-874): Review deterministic seccomp probe validation.
    pub async fn handle_seccomp<G: Guest<Self>>(
        &self,
        _guest: &mut G,
        call: syscalls::Seccomp,
    ) -> Result<i64, Error> {
        seccomp_result(call.op(), call.flags(), call.args().is_some()).map_err(Into::into)
    }

    fn write_arch_prctl_u64<G: Guest<Self>>(
        &self,
        guest: &mut G,
        raw_addr: usize,
        value: u64,
    ) -> Result<i64, Error> {
        let addr = AddrMut::<u64>::from_raw(raw_addr).ok_or(Errno::EFAULT)?;
        guest.memory().write_value(addr, &value)?;
        Ok(0)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#539): Confirm the virtual arch_prctl control policy.
    /// Preserve thread-local bases while hiding host CPU feature controls.
    pub async fn handle_arch_prctl<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::ArchPrctl,
    ) -> Result<i64, Error> {
        let cpuid_uses_backend_policy =
            self.cfg.virtualize_cpuid && self.cfg.cpuid_virtualized_by_backend;
        let cpuid_uses_faulting = self.cfg.virtualize_cpuid && guest.has_cpuid_interception();
        match call.cmd() {
            ArchPrctlCmd::ARCH_SET_FS(_)
            | ArchPrctlCmd::ARCH_SET_GS(_)
            | ArchPrctlCmd::ARCH_GET_FS(_)
            | ArchPrctlCmd::ARCH_GET_GS(_) => Ok(guest.inject(call).await?),

            // KVM installs a deterministic CPUID table while leaving the instruction enabled.
            ArchPrctlCmd::ARCH_GET_CPUID(_) if cpuid_uses_backend_policy => Ok(1),
            ArchPrctlCmd::ARCH_SET_CPUID(value) if cpuid_uses_backend_policy => {
                if value == 0 {
                    Err(Errno::EPERM.into())
                } else {
                    Ok(0)
                }
            }

            // When Reverie successfully disables native CPUID, Detcore answers its fault from a
            // fixed table. Preserve that backend state and reject attempts to re-enable CPUID.
            ArchPrctlCmd::ARCH_GET_CPUID(_) if cpuid_uses_faulting => Ok(0),
            ArchPrctlCmd::ARCH_SET_CPUID(value) if cpuid_uses_faulting => {
                if value == 0 {
                    Ok(0)
                } else {
                    Err(Errno::EPERM.into())
                }
            }
            // Reverie cannot faithfully deliver a CPUID fault requested by the tracee. In
            // explicit host-CPUID mode, expose a fixed enabled control state and reject disable.
            ArchPrctlCmd::ARCH_GET_CPUID(_) if !self.cfg.virtualize_cpuid => Ok(1),
            ArchPrctlCmd::ARCH_SET_CPUID(value) if !self.cfg.virtualize_cpuid => {
                if value == 0 {
                    Err(Errno::EPERM.into())
                } else {
                    Ok(0)
                }
            }

            // Ptrace hosts without CPUID-faulting support retain the kernel's honest state.
            ArchPrctlCmd::ARCH_GET_CPUID(_) | ArchPrctlCmd::ARCH_SET_CPUID(_) => {
                Ok(guest.inject(call).await?)
            }

            // Expose a conservative virtual CPU with no optional extended-state permissions.
            ArchPrctlCmd::Other(
                ARCH_GET_XCOMP_SUPP | ARCH_GET_XCOMP_PERM | ARCH_GET_XCOMP_GUEST_PERM,
                addr,
            ) => self.write_arch_prctl_u64(guest, addr, 0),
            ArchPrctlCmd::Other(ARCH_REQ_XCOMP_PERM | ARCH_REQ_XCOMP_GUEST_PERM, _) => {
                Err(Errno::EINVAL.into())
            }

            // Keep shadow stacks disabled in the virtual policy. Disabling an already-disabled
            // feature is idempotent; enable/lock/unlock requests cannot be honored.
            ArchPrctlCmd::Other(ARCH_SHSTK_STATUS, addr) => {
                self.write_arch_prctl_u64(guest, addr, 0)
            }
            ArchPrctlCmd::Other(ARCH_SHSTK_DISABLE, features)
                if features != 0 && features & !ARCH_SHSTK_VALID_MASK == 0 =>
            {
                Ok(0)
            }
            ArchPrctlCmd::Other(ARCH_SHSTK_DISABLE, _)
            | ArchPrctlCmd::Other(ARCH_SHSTK_ENABLE | ARCH_SHSTK_LOCK | ARCH_SHSTK_UNLOCK, _) => {
                Err(Errno::EINVAL.into())
            }

            ArchPrctlCmd::Other(_, _) => Err(Errno::EINVAL.into()),
        }
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#663)
    /// Preserve deterministic Ruby thread controls, report the container's fixed
    /// capability bounding set, and reject options that expose unmodeled process
    /// or host state.
    pub async fn handle_prctl<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Prctl,
    ) -> Result<i64, Error> {
        match call.option() {
            // The capability bounding set is fixed by the container launch policy.
            libc::PR_CAPBSET_READ => Ok(self.record_or_replay(guest, call).await?),
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(PR-2150): Timer slack is shared with the
            // virtual `/proc/<tid>/timerslack_ns` channel.  Never pass either
            // setter through to the physical tracee: a large physical slack
            // changes wake timing on Detcore's remaining host-timed waits.
            libc::PR_SET_TIMERSLACK => {
                let requested = call.arg2();
                let state = guest.thread_state_mut();
                // Linux treats zero as reset-to-default. Hermit virtualizes the
                // Linux scheduling policy as SCHED_OTHER, so the kernel's
                // RT/DL no-op branch is unreachable in the guest model.
                state.timer_slack_ns = if requested == 0 {
                    state.default_timer_slack_ns
                } else {
                    requested
                };
                Ok(0)
            }
            libc::PR_GET_TIMERSLACK => Ok(guest.thread_state().timer_slack_ns as i64),
            option
                if guest.config().backend_virtualizes_capability_prctls
                    && is_backend_virtualized_capability_prctl(option) =>
            {
                self.passthrough(guest, call.into()).await
            }
            option if is_supported_prctl_option(option) => {
                self.passthrough(guest, call.into()).await
            }
            _ => Err(Errno::ENOSYS.into()),
        }
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#806)
    /// Report the deterministic default nice value for any scheduling target.
    ///
    /// Under Hermit the Linux nice value is inert: the scheduler is virtualized
    /// and guest threads are serialized onto one virtual CPU, so a process's,
    /// group's, or user's scheduling priority never affects guest-visible
    /// computation. Report the deterministic default nice (0) for every valid
    /// target regardless of `who` — real tools such as `renice -p <pid>` always
    /// pass an explicit pid, and the raw `getpriority(2)` never checks
    /// permissions on a read, so it must never return `EPERM`. An unknown
    /// `which` still faults with `EINVAL`, matching Linux.
    pub async fn handle_getpriority<G: Guest<Self>>(
        &self,
        _guest: &mut G,
        call: syscalls::Getpriority,
    ) -> Result<i64, Error> {
        Ok(getpriority_result(call.which())?)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-857): Deterministic syslog(2) virtualization.
    /// Present an empty kernel ring buffer. Reads and size queries return zero,
    /// controls are inert, and invalid actions preserve Linux's EINVAL boundary.
    pub async fn handle_syslog<G: Guest<Self>>(
        &self,
        _guest: &mut G,
        call: syscalls::Syslog,
    ) -> Result<i64, Error> {
        Ok(deterministic_syslog_result(call.priority(), call.len())?)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#806)
    /// Accept any priority change as a deterministic no-op.
    ///
    /// Nice values are inert under Hermit's virtualized, serialized scheduler,
    /// so accept the request without touching host scheduling. The guest runs as
    /// a single uid-0 container principal, so a real `setpriority(2)` from the
    /// caller would succeed anyway; never fabricate `EPERM` for tools such as
    /// `nice -n 5 <cmd>`, `renice -p <pid>`, or Python's `os.nice`. An unknown
    /// `which` still faults with `EINVAL`, matching Linux.
    pub async fn handle_setpriority<G: Guest<Self>>(
        &self,
        _guest: &mut G,
        call: syscalls::Setpriority,
    ) -> Result<i64, Error> {
        Ok(setpriority_result(call.which())?)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#663)
    /// Reject cross-process memory advice without consulting host process state.
    pub fn handle_process_madvise(pidfd: usize, flags: usize) -> Result<i64, Error> {
        if flags != 0 {
            return Err(Errno::EINVAL.into());
        }

        // Linux interprets pidfd as an int. Preserve its deterministic invalid-fd
        // rejection, but never let a valid host pidfd alter another process's memory.
        if (pidfd as libc::c_int) < 0 {
            Err(Errno::EBADF.into())
        } else {
            Err(Errno::EPERM.into())
        }
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1096): Review the backend-independent random-device stream.
    /// Fill guest memory from the canonical stream used by every backend's
    /// `/dev/random` and `/dev/urandom` virtualization.
    pub(super) fn fill_random_device_bytes<G: Guest<Self>>(
        &self,
        guest: &mut G,
        remote_buf: AddrMut<u8>,
        len: usize,
        stream_offset: u64,
    ) -> Result<usize, Error> {
        self.fill_random_device_iovecs(
            guest,
            &[crate::iovecs::ImportedIovec {
                base: remote_buf.as_raw(),
                len,
            }],
            stream_offset,
        )
    }

    pub(super) fn fill_random_device_iovecs<G: Guest<Self>>(
        &self,
        guest: &mut G,
        iovecs: &[crate::iovecs::ImportedIovec],
        stream_offset: u64,
    ) -> Result<usize, Error> {
        let seed = guest.config().rng_seed();
        let mut hasher = DefaultHasher::new();
        let written = fill_canonical_random_iovecs(
            &mut guest.memory(),
            iovecs,
            seed,
            stream_offset,
            &mut hasher,
        )?;
        if cfg!(debug_assertions) {
            detlog!(
                "[dtid {}] USER RAND [/dev/[u]random] Filled guest memory with {} canonical random bytes at offset {}, hash of bytes: {}",
                guest.thread_state().dettid,
                written,
                stream_offset,
                hasher.finish()
            );
        }
        Ok(written)
    }

    /// uname syscall
    pub async fn handle_uname<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Uname,
    ) -> Result<i64, Error> {
        let ret = self.record_or_replay(guest, call).await?;
        if let Some(buf) = call.buf() {
            let mut un = guest.memory().read_value(buf)?;
            // Keep this in configured UTC: `Local` initializes libc TLS, which is unavailable
            // while a DynamoRIO application thread is executing a client callback.
            let epoch = guest.config().epoch;

            if !guest.config().has_uts_namespace {
                // FIXME: It should be possible to remove this once all tests
                // are also using namespaces.
                un.nodename = from_str(DEFAULT_HOSTNAME);
                un.domainname = from_str(DEFAULT_HOSTNAME.split('.').next_back().unwrap_or(""));
            }

            un.release = from_str("5.2.0");
            un.version = from_str(&format!("#1 SMP {}", epoch.format("%a %b %d %T %Z %Y")));
            guest.memory().write_value(buf, &un)?;
        }

        Ok(ret)
    }

    /// Fill `getrandom(2)` requests from the current thread's seeded deterministic PRNG.
    /// Supported blocking/source-selection flags share that always-ready stream; invalid Linux
    /// flag combinations are rejected before guest memory is touched.
    pub async fn handle_getrandom<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Getrandom,
    ) -> Result<i64, Error> {
        let memory = guest.memory();
        let dettid = guest.thread_state().dettid;
        crate::random::getrandom(guest.thread_state_mut().thread_prng(), memory, dettid, call)
    }

    /// setsid system call
    pub async fn handle_setsid<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Setsid,
    ) -> Result<i64, Error> {
        let res = guest.inject(call).await?;
        let process = guest.thread_state().detpid.expect("detpid unset");
        let _ = create_session(guest, process).await;

        // task is trying to become a daemon process. for more details
        // see: https://notes.shichao.io/apue/ch13/
        if guest.config().kill_daemons {
            guest.daemonize().await;
        }
        Ok(res)
    }

    /// setpgid system call. The kernel remains authoritative for validation;
    /// after success Detcore mirrors the guest-visible process-group change so
    /// group-selecting waits do not consult host `/proc` state.
    pub async fn handle_setpgid<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Setpgid,
    ) -> Result<i64, Error> {
        let res = guest.inject(call).await?;
        let caller = guest.thread_state().detpid.expect("detpid unset");
        let process = if call.pid() == 0 {
            caller
        } else {
            DetPid::from_raw(call.pid())
        };
        let group = if call.pgid() == 0 {
            process
        } else {
            DetPid::from_raw(call.pgid())
        };
        let _ = set_process_group(guest, process, group).await;
        Ok(res)
    }

    /// membarrier (system call).
    ///
    /// `membarrier(2)` issues process-wide memory barriers so that userspace can
    /// use asymmetric fences (e.g. CPython's QSBR, RCU-style reclamation).
    /// Detcore serializes all guest threads onto a single logical CPU with a
    /// total memory order, so any requested barrier is *already* satisfied and
    /// every command is a deterministic no-op. For `MEMBARRIER_CMD_QUERY` we
    /// report the set of commands we emulate so the guest stays on this
    /// controlled path instead of a host-dependent fallback; every other command
    /// returns success without doing anything.
    pub async fn handle_membarrier<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Membarrier,
    ) -> Result<i64, Error> {
        // Values from <linux/membarrier.h>.
        const MEMBARRIER_CMD_QUERY: i32 = 0;
        const MEMBARRIER_CMD_GLOBAL: i32 = 1 << 0;
        const MEMBARRIER_CMD_GLOBAL_EXPEDITED: i32 = 1 << 1;
        const MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED: i32 = 1 << 2;
        const MEMBARRIER_CMD_PRIVATE_EXPEDITED: i32 = 1 << 3;
        const MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED: i32 = 1 << 4;
        const SUPPORTED: i32 = MEMBARRIER_CMD_GLOBAL
            | MEMBARRIER_CMD_GLOBAL_EXPEDITED
            | MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED
            | MEMBARRIER_CMD_PRIVATE_EXPEDITED
            | MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED;

        let cmd = call.cmd();
        if cmd == MEMBARRIER_CMD_QUERY {
            detlog!(
                "[dtid {}] membarrier(QUERY) => reporting emulated commands {:#x}",
                guest.thread_state().dettid,
                SUPPORTED,
            );
            Ok(SUPPORTED as i64)
        } else {
            detlog!(
                "[dtid {}] membarrier(cmd={}) no-op (threads are serialized on one CPU)",
                guest.thread_state().dettid,
                cmd,
            );
            Ok(0)
        }
    }

    /// getcpu system call
    pub async fn handle_getcpu<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Getcpu,
    ) -> Result<i64, Error> {
        // Always set the CPU to 0.
        if let Some(cpu) = call.cpu() {
            guest.memory().write_value(cpu, &0)?;
        }

        // Always set the NUMA node to 0.
        if let Some(node) = call.node() {
            guest.memory().write_value(node, &0)?;
        }

        Ok(0)
    }

    /// getresuid under Hermit. Detcore presents a fixed virtual-root identity, so
    /// the real, effective, and saved user IDs are all the constant 0. Under the
    /// ptrace backend the guest runs inside a CLONE_NEWUSER namespace that already
    /// maps the host uid to 0; emulating the same constant here makes in-process
    /// backends (DBT) agree with that golden reference instead of leaking the host
    /// uid, and the fully emulated result is bitwise-identical across --verify and
    /// record/replay.
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#1549)
    pub async fn handle_getresuid<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Getresuid,
    ) -> Result<i64, Error> {
        if let Some(ruid) = call.ruid() {
            guest.memory().write_value(ruid, &0)?;
        }
        if let Some(euid) = call.euid() {
            guest.memory().write_value(euid, &0)?;
        }
        if let Some(suid) = call.suid() {
            guest.memory().write_value(suid, &0)?;
        }
        Ok(0)
    }

    /// getresgid under Hermit. The group-ID counterpart of `handle_getresuid`:
    /// the real, effective, and saved group IDs are all the fixed virtual-root
    /// constant 0, matching the ptrace CLONE_NEWUSER identity and deterministic
    /// across --verify and record/replay.
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#1549)
    pub async fn handle_getresgid<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::Getresgid,
    ) -> Result<i64, Error> {
        if let Some(rgid) = call.rgid() {
            guest.memory().write_value(rgid, &0)?;
        }
        if let Some(egid) = call.egid() {
            guest.memory().write_value(egid, &0)?;
        }
        if let Some(sgid) = call.sgid() {
            guest.memory().write_value(sgid, &0)?;
        }
        Ok(0)
    }

    /// get_mempolicy under Hermit. The container exposes a single virtual NUMA
    /// node, so the effective policy is always the default and every address
    /// resolves to node 0. The result is fully emulated (never injected), so it
    /// is bitwise-identical across the two --verify runs and under record/replay,
    /// removing the host-NUMA-topology dependence a passthrough would introduce.
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#720)
    pub async fn handle_get_mempolicy<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::GetMempolicy,
    ) -> Result<i64, Error> {
        // Report MPOL_DEFAULT (0) for the current policy / node when requested.
        // The nodemask output is left untouched: reverie exposes it as an
        // immutable pointer, and MPOL_DEFAULT carries no node set.
        if let Some(policy) = call.policy() {
            guest.memory().write_value(policy, &0)?;
        }
        Ok(0)
    }

    /// move_pages under Hermit. On a single virtual NUMA node nothing can be
    /// relocated, so report every page as residing on node 0 and succeed. The
    /// answer is a fixed constant, so it is deterministic across --verify and
    /// record/replay.
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#720)
    pub async fn handle_move_pages<G: Guest<Self>>(
        &self,
        guest: &mut G,
        call: syscalls::MovePages,
    ) -> Result<i64, Error> {
        // When a status buffer is supplied (either a real move request or a
        // location query with nodes == NULL), report node 0 for every page.
        if let Some(status) = call.status() {
            let count = call.nr_pages() as usize;
            let zeros = vec![0i32; count];
            guest.memory().write_values(status, &zeros)?;
        }
        Ok(0)
    }
}

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

    struct ScatterMemory {
        bytes: Vec<u8>,
        outcomes: std::collections::VecDeque<Result<usize, Errno>>,
        writes: usize,
    }

    impl ScatterMemory {
        fn new(size: usize, outcomes: impl IntoIterator<Item = Result<usize, Errno>>) -> Self {
            Self {
                bytes: vec![0xa5; size],
                outcomes: outcomes.into_iter().collect(),
                writes: 0,
            }
        }
    }

    impl MemoryAccess for ScatterMemory {
        fn read_vectored(
            &self,
            _: &[std::io::IoSlice],
            _: &mut [std::io::IoSliceMut],
        ) -> Result<usize, Errno> {
            panic!("canonical scatter must not read guest bytes")
        }
        fn write_vectored(
            &mut self,
            _: &[std::io::IoSlice],
            _: &mut [std::io::IoSliceMut],
        ) -> Result<usize, Errno> {
            panic!("canonical scatter must use the user-access capability")
        }
        fn write_with_user_access(
            &mut self,
            address: AddrMut<u8>,
            bytes: &[u8],
        ) -> Result<usize, Errno> {
            self.writes += 1;
            let count = self.outcomes.pop_front().unwrap_or(Ok(bytes.len()))?;
            assert!(count <= bytes.len());
            let offset = address.as_raw() - 0x1000;
            self.bytes[offset..offset + count].copy_from_slice(&bytes[..count]);
            Ok(count)
        }
    }

    fn assert_copy_failure(error: Error, expected: Errno) {
        let Error::Tool(error) = error else {
            panic!("copy failure became a guest errno: {error:?}")
        };
        assert_eq!(
            error
                .downcast_ref::<crate::random::RandomCopyFailure>()
                .expect("typed copy failure")
                .errno(),
            expected
        );
    }

    fn scatter(memory: &mut ScatterMemory, lengths: &[usize], offset: u64) -> Result<usize, Error> {
        let mut base = 0x1000;
        let vectors: Vec<_> = lengths
            .iter()
            .map(|&len| {
                let vector = crate::iovecs::ImportedIovec { base, len };
                base += len;
                vector
            })
            .collect();
        fill_canonical_random_iovecs(memory, &vectors, 0, offset, &mut DefaultHasher::new())
    }

    #[test]
    fn random_scatter_distinguishes_fault_prefixes_from_backend_errors() {
        // Exercise both an earlier complete iovec and an earlier complete chunk.
        for lengths in [vec![3, 5], vec![RANDOM_FILL_CHUNK_BYTES + 5]] {
            let prefix = if lengths.len() == 2 {
                3
            } else {
                RANDOM_FILL_CHUNK_BYTES
            };
            for error in [Errno::EFAULT, Errno::EIO, Errno::ENOMEM] {
                let mut memory = ScatterMemory::new(prefix + 5, [Ok(prefix), Err(error)]);
                let result = scatter(&mut memory, &lengths, 7);
                match error {
                    Errno::EFAULT => assert_eq!(result.unwrap(), prefix),
                    _ => assert_copy_failure(result.unwrap_err(), error),
                }
                let expected: Vec<_> = (7..7 + prefix as u64)
                    .map(|index| canonical_random_device_byte(0, index))
                    .collect();
                assert_eq!(&memory.bytes[..prefix], expected);
                assert_eq!(&memory.bytes[prefix..], &[0xa5; 5]);
                assert_eq!(memory.writes, 2);
            }
        }
    }

    #[test]
    fn random_scatter_short_or_zero_copy_stops_without_touching_later_segments() {
        for first in [0, 2] {
            let mut memory = ScatterMemory::new(10, [Ok(first)]);
            let result = scatter(&mut memory, &[5, 5], 0);
            if first == 0 {
                assert!(matches!(result, Err(Error::Errno(Errno::EFAULT))));
            } else {
                assert_eq!(result.unwrap(), first);
                assert_eq!(&memory.bytes[..2], &[41, 114]);
            }
            assert!(memory.bytes[first..].iter().all(|&byte| byte == 0xa5));
            assert_eq!(memory.writes, 1);
        }
        let mut memory = ScatterMemory::new(10, [Ok(5), Ok(0)]);
        assert_eq!(scatter(&mut memory, &[5, 5], 0).unwrap(), 5);
        assert!(memory.bytes[5..].iter().all(|&byte| byte == 0xa5));
        assert_eq!(memory.writes, 2);
    }

    #[test]
    fn random_scatter_saturated_bytes_match_partitioned_calls() {
        for (offset, expected) in [(u64::MAX - 2, [78, 151, 224, 224]), (u64::MAX, [224; 4])] {
            let mut single = ScatterMemory::new(4, []);
            assert_eq!(scatter(&mut single, &[4], offset).unwrap(), 4);
            let mut partitioned = ScatterMemory::new(4, []);
            let mut hash = DefaultHasher::new();
            assert_eq!(
                fill_canonical_random_iovecs(
                    &mut partitioned,
                    &[crate::iovecs::ImportedIovec {
                        base: 0x1000,
                        len: 1
                    }],
                    0,
                    offset,
                    &mut hash
                )
                .unwrap(),
                1
            );
            assert_eq!(
                fill_canonical_random_iovecs(
                    &mut partitioned,
                    &[crate::iovecs::ImportedIovec {
                        base: 0x1001,
                        len: 3
                    }],
                    0,
                    offset.saturating_add(1),
                    &mut hash
                )
                .unwrap(),
                3
            );
            assert_eq!(single.bytes, expected);
            assert_eq!(partitioned.bytes, expected);
        }
    }

    #[test]
    fn random_scatter_backend_error_rolls_back_shared_cursor_after_eight_byte_prefix() {
        let fd = crate::fd::DetFd::new(
            3,
            nix::fcntl::OFlag::O_RDONLY,
            crate::fd::FdType::Rng,
            crate::types::OpenFileId::new(crate::types::DetTid::from_raw(1), 0),
        );
        for error in [Errno::EFAULT, Errno::EIO] {
            let mut memory = ScatterMemory::new(8, [Ok(4), Err(error)]);
            let result = fd.with_random_device_stream(|offset| scatter(&mut memory, &[8], offset));
            if error == Errno::EFAULT {
                assert_eq!(result.unwrap(), 4);
            } else {
                assert_copy_failure(result.unwrap_err(), Errno::EIO);
            }
            // First iteration commits four; the EIO iteration must not commit
            // its physically copied prefix or fabricate a successful result.
            assert_eq!(fd.random_device_offset(), 4);
            assert_eq!(&memory.bytes[4..], &[0xa5; 4]);
            assert_eq!(memory.writes, 2);
        }
    }

    #[test]
    fn prctl_support_covers_deterministic_controls() {
        for option in [
            libc::PR_SET_NAME,
            libc::PR_GET_NAME,
            libc::PR_SET_THP_DISABLE,
            libc::PR_GET_THP_DISABLE,
            // Deterministic per-process dumpability state.
            libc::PR_SET_DUMPABLE,
            libc::PR_GET_DUMPABLE,
            // Deterministic per-thread capability-retention flag used by setpriv.
            libc::PR_SET_KEEPCAPS,
            libc::PR_GET_KEEPCAPS,
            // Deterministic per-thread parent-death-signal flag used by setpriv.
            libc::PR_SET_PDEATHSIG,
            libc::PR_GET_PDEATHSIG,
        ] {
            assert!(is_supported_prctl_option(option));
        }

        assert!(!is_supported_prctl_option(libc::PR_SET_NO_NEW_PRIVS));
        assert!(!is_supported_prctl_option(libc::PR_SET_TIMERSLACK));
        assert!(!is_supported_prctl_option(libc::PR_GET_TIMERSLACK));
    }

    #[test]
    fn backend_virtualized_prctl_support_is_capability_scoped() {
        for option in [libc::PR_CAPBSET_DROP, libc::PR_CAP_AMBIENT] {
            assert!(is_backend_virtualized_capability_prctl(option));
        }
        for option in [libc::PR_SET_KEEPCAPS, libc::PR_SET_SECUREBITS] {
            assert!(!is_backend_virtualized_capability_prctl(option));
        }
    }

    #[test]
    fn getrandom_accepts_linux_flags() {
        for flags in [
            0,
            libc::GRND_NONBLOCK as usize,
            libc::GRND_RANDOM as usize,
            (libc::GRND_NONBLOCK | libc::GRND_RANDOM) as usize,
            libc::GRND_INSECURE as usize,
            (libc::GRND_NONBLOCK | libc::GRND_INSECURE) as usize,
            1_usize << 32,
        ] {
            assert!(
                validate_getrandom_flags(flags).is_ok(),
                "valid flags rejected: {flags:#x}"
            );
        }
    }

    #[test]
    fn getrandom_rejects_invalid_flags() {
        for flags in [
            0x8000_0000,
            (1_usize << 32) | 0x8000_0000,
            (libc::GRND_RANDOM | libc::GRND_INSECURE) as usize,
        ] {
            assert_eq!(validate_getrandom_flags(flags), Err(Errno::EINVAL));
        }
    }

    #[test]
    fn getrandom_caps_requests_at_linux_max_rw_count() {
        assert_eq!(getrandom_request_len(16), 16);
        assert_eq!(getrandom_request_len(usize::MAX), GETRANDOM_MAX_BYTES);
    }

    #[test]
    fn canonical_random_device_stream_matches_kvm_root_contract() {
        let first: Vec<_> = (0..8)
            .map(|index| canonical_random_device_byte(0, index))
            .collect();
        assert_eq!(first, [41, 114, 187, 4, 77, 150, 223, 40]);

        let continued: Vec<_> = (8..16)
            .map(|index| canonical_random_device_byte(0, index))
            .collect();
        assert_eq!(continued, [113, 186, 3, 76, 149, 222, 39, 112]);

        let seeded: Vec<_> = (0..16)
            .map(|index| canonical_random_device_byte(17, index))
            .collect();
        assert_eq!(
            seeded,
            [
                56, 114, 187, 4, 77, 150, 223, 40, 96, 186, 3, 76, 149, 222, 39, 112
            ]
        );
        assert_ne!(seeded, [first, continued].concat());
    }

    #[test]
    fn getpriority_reports_default_nice_for_every_target() {
        // Every valid PRIO_* selector reports the default nice (raw 20 = nice 0),
        // regardless of `who`. Real tools such as `renice -p <pid>` pass an
        // explicit pid, and getpriority never checks permissions, so this must
        // never be EPERM (the pre-fix stub only accepted PRIO_PROCESS/who==0).
        for which in [libc::PRIO_PROCESS, libc::PRIO_PGRP, libc::PRIO_USER] {
            assert_eq!(getpriority_result(which as i32), Ok(20));
        }
    }

    #[test]
    fn setpriority_accepts_any_change_for_valid_target() {
        // Nice is inert under Hermit, so any priority change for a valid target
        // succeeds as a no-op — including nonzero nice (`nice -n 5`, os.nice).
        for which in [libc::PRIO_PROCESS, libc::PRIO_PGRP, libc::PRIO_USER] {
            assert_eq!(setpriority_result(which as i32), Ok(0));
        }
    }

    #[test]
    fn get_and_set_priority_reject_unknown_which_with_einval() {
        // Match Linux: an unknown target selector faults with EINVAL, not EPERM.
        for which in [-1, 3, 42] {
            assert_eq!(getpriority_result(which), Err(Errno::EINVAL));
            assert_eq!(setpriority_result(which), Err(Errno::EINVAL));
        }
    }

    #[test]
    fn seccomp_tsync_null_probe_matches_linux_validation() {
        assert_eq!(
            seccomp_result(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, false,),
            Err(Errno::EFAULT)
        );
        assert_eq!(
            seccomp_result(SECCOMP_SET_MODE_FILTER, 1 << 31, false),
            Err(Errno::EINVAL)
        );
        assert_eq!(
            seccomp_result(SECCOMP_SET_MODE_FILTER, 0, true),
            Err(Errno::EOPNOTSUPP)
        );
    }

    #[test]
    fn process_madvise_is_rejected_deterministically() {
        assert!(matches!(
            Detcore::<crate::record_or_replay::NoopTool>::handle_process_madvise(
                (-10_000_i32) as usize,
                0
            ),
            Err(Error::Errno(Errno::EBADF))
        ));
        assert!(matches!(
            Detcore::<crate::record_or_replay::NoopTool>::handle_process_madvise(3, 1),
            Err(Error::Errno(Errno::EINVAL))
        ));
        assert!(matches!(
            Detcore::<crate::record_or_replay::NoopTool>::handle_process_madvise(3, 0),
            Err(Error::Errno(Errno::EPERM))
        ));
    }

    #[test]
    fn syslog_exposes_an_empty_log_and_validates_actions() {
        for action in 0..=7 {
            assert_eq!(deterministic_syslog_result(action, 0), Ok(0));
        }
        for action in [9, 10] {
            assert_eq!(deterministic_syslog_result(action, 0), Ok(0));
        }
        assert_eq!(deterministic_syslog_result(8, 1), Ok(0));
        assert_eq!(deterministic_syslog_result(8, 8), Ok(0));
        assert_eq!(deterministic_syslog_result(8, 0), Err(Errno::EINVAL));
        assert_eq!(deterministic_syslog_result(8, 9), Err(Errno::EINVAL));
        assert_eq!(deterministic_syslog_result(11, 0), Err(Errno::EINVAL));
    }
}