yash-env 0.13.2

Yash shell execution environment interface
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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2021 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Implementation of system traits that actually interacts with the underlying system
//!
//! This module is implemented on Unix-like targets only. It provides [`RealSystem`],
//! an implementation of system traits that interact with the underlying
//! operating system. This implementation is intended to be used for the actual
//! shell environment.

mod errno;
mod file_system;
mod open_flag;
mod resource;
mod signal;

use super::AT_FDCWD;
use super::CaughtSignals;
use super::Chdir;
use super::ChildProcessStarter;
use super::Clock;
use super::Close;
use super::CpuTimes;
use super::Dir;
use super::DirEntry;
use super::Disposition;
use super::Dup;
use super::Errno;
use super::Exec;
use super::Exit;
use super::Fcntl;
use super::FdFlag;
use super::Fork;
use super::Fstat;
use super::GetCwd;
use super::GetPid;
use super::GetPw;
use super::GetRlimit;
use super::GetSigaction;
use super::GetUid;
use super::Gid;
use super::IsExecutableFile;
use super::Isatty;
use super::Mode;
use super::OfdAccess;
use super::Open;
use super::OpenFlag;
use super::Pipe;
use super::Read;
use super::Result;
use super::Seek;
use super::Select;
use super::SendSignal;
use super::SetPgid;
use super::SetRlimit;
use super::ShellPath;
use super::Sigaction;
use super::Sigmask;
use super::SigmaskOp;
use super::Signals;
use super::Stat as _;
use super::Sysconf;
use super::TcGetPgrp;
use super::TcSetPgrp;
use super::Times;
use super::Uid;
use super::Umask;
use super::Wait;
use super::Write;
use super::resource::LimitPair;
use super::resource::Resource;
#[cfg(doc)]
use crate::Env;
use crate::io::Fd;
use crate::job::Pid;
use crate::job::ProcessResult;
use crate::job::ProcessState;
use crate::path::Path;
use crate::path::PathBuf;
use crate::semantics::ExitStatus;
use crate::str::UnixStr;
use crate::str::UnixString;
use enumset::EnumSet;
pub use file_system::Stat;
use libc::DIR;
use std::convert::Infallible;
use std::convert::TryInto;
use std::ffi::CStr;
use std::ffi::CString;
use std::ffi::OsStr;
use std::ffi::c_int;
use std::future::ready;
use std::io::SeekFrom;
use std::mem::MaybeUninit;
use std::num::NonZero;
use std::ops::RangeInclusive;
use std::os::unix::ffi::OsStrExt as _;
use std::os::unix::io::IntoRawFd;
use std::ptr::NonNull;
use std::rc::Rc;
use std::sync::atomic::AtomicIsize;
use std::sync::atomic::Ordering;
use std::sync::atomic::compiler_fence;
use std::time::Duration;
use std::time::Instant;

trait ErrnoIfM1: PartialEq + Sized {
    const MINUS_1: Self;

    /// Convenience function to convert a result of -1 to an `Error` with the
    /// current `errno`.
    ///
    /// This function is intended to be used just after calling a function that
    /// returns -1 on error and sets `errno` to the error number. This function
    /// filters out the `-1` result and returns an error containing the current
    /// `errno`.
    fn errno_if_m1(self) -> Result<Self> {
        if self == Self::MINUS_1 {
            Err(Errno::last())
        } else {
            Ok(self)
        }
    }
}

impl ErrnoIfM1 for i8 {
    const MINUS_1: Self = -1;
}
impl ErrnoIfM1 for i16 {
    const MINUS_1: Self = -1;
}
impl ErrnoIfM1 for i32 {
    const MINUS_1: Self = -1;
}
impl ErrnoIfM1 for i64 {
    const MINUS_1: Self = -1;
}
impl ErrnoIfM1 for isize {
    const MINUS_1: Self = -1;
}

/// Converts a `Duration` to a `timespec`.
///
/// The return value is a `MaybeUninit` because the `timespec` struct may have
/// padding or extension fields that are not initialized by this function.
#[must_use]
fn to_timespec(duration: Duration) -> MaybeUninit<libc::timespec> {
    let seconds = duration.as_secs().try_into().unwrap_or(libc::time_t::MAX);
    let mut timespec = MaybeUninit::<libc::timespec>::uninit();
    unsafe {
        (&raw mut (*timespec.as_mut_ptr()).tv_sec).write(seconds);
        (&raw mut (*timespec.as_mut_ptr()).tv_nsec).write(duration.subsec_nanos() as _);
    }
    timespec
}

/// Array of slots to store caught signals.
///
/// This array is used to store caught signals. All slots are initialized with
/// 0, which indicates that the slot is available. When a signal is caught, the
/// signal number is written into one of unoccupied slots.
static CAUGHT_SIGNALS: [AtomicIsize; 8] = [const { AtomicIsize::new(0) }; 8];

/// Signal catching function.
///
/// This function is set as a signal handler for all signals that the shell
/// wants to catch. When a signal is caught, the signal number is written into
/// one of the slots in [`CAUGHT_SIGNALS`].
extern "C" fn catch_signal(signal: c_int) {
    // This function can only perform async-signal-safe operations.
    // Performing unsafe operations is undefined behavior!

    // Find an unused slot (having a value of 0) in CAUGHT_SIGNALS and write the
    // signal number into it.
    // If there is a slot having a value of the signal already, do nothing.
    // If there is no available slot, the signal will be lost!
    let signal = signal as isize;
    for slot in &CAUGHT_SIGNALS {
        match slot.compare_exchange(0, signal, Ordering::Relaxed, Ordering::Relaxed) {
            Ok(_) => break,
            Err(slot_value) if slot_value == signal => break,
            _ => continue,
        }
    }
}

fn sigaction_impl(signal: signal::Number, disposition: Option<Disposition>) -> Result<Disposition> {
    let new_action = disposition.map(Disposition::to_sigaction);
    let new_action_ptr = new_action
        .as_ref()
        .map_or(std::ptr::null(), |action| action.as_ptr());

    let mut old_action = MaybeUninit::<libc::sigaction>::uninit();
    // SAFETY: We're just creating a new raw pointer to the struct field.
    // Nothing is dereferenced.
    let old_mask_ptr = unsafe { &raw mut (*old_action.as_mut_ptr()).sa_mask };
    // POSIX requires *all* sigset_t objects to be initialized before use,
    // even if they are output parameters.
    unsafe { libc::sigemptyset(old_mask_ptr) }.errno_if_m1()?;

    unsafe { libc::sigaction(signal.as_raw(), new_action_ptr, old_action.as_mut_ptr()) }
        .errno_if_m1()?;

    // SAFETY: the `old_action` has been initialized by `sigaction`.
    let old_disposition = unsafe { Disposition::from_sigaction(&old_action) };
    Ok(old_disposition)
}

/// Implementation of system traits that actually interact with the underlying system
///
/// `RealSystem` is an empty `struct` because the underlying operating system
/// manages the system's internal state.
///
/// Some trait methods implemented by `RealSystem` (such as [`SendSignal::kill`])
/// return futures, but the returned futures do not perform asynchronous operations.
/// Those methods block the current thread until the underlying system calls
/// complete and then return ready futures.
/// See also the [`system` module](super) documentation.
#[derive(Debug)]
pub struct RealSystem(());

impl RealSystem {
    /// Returns an instance of `RealSystem`.
    ///
    /// # Safety
    ///
    /// This function is marked `unsafe` because improper use of `RealSystem`
    /// may lead to undefined behavior. Remember that most operations performed
    /// on the system by [`Env`] are not thread-safe. You should never use
    /// `RealSystem` in a multi-threaded program, and it is your responsibility
    /// to make sure you are using only one instance of `ReadSystem` in the
    /// process.
    pub unsafe fn new() -> Self {
        RealSystem(())
    }

    // TODO Should use AT_EACCESS on all platforms
    #[cfg(not(target_os = "redox"))]
    fn has_execute_permission(&self, path: &CStr) -> bool {
        (unsafe { libc::faccessat(libc::AT_FDCWD, path.as_ptr(), libc::X_OK, libc::AT_EACCESS) })
            != -1
    }
    #[cfg(target_os = "redox")]
    fn has_execute_permission(&self, path: &CStr) -> bool {
        (unsafe { libc::access(path.as_ptr(), libc::X_OK) }) != -1
    }
}

impl Fstat for RealSystem {
    type Stat = file_system::Stat;

    fn fstat(&self, fd: Fd) -> Result<file_system::Stat> {
        let mut stat = MaybeUninit::<libc::stat>::uninit();
        unsafe { libc::fstat(fd.0, stat.as_mut_ptr()) }.errno_if_m1()?;
        let stat = unsafe { file_system::Stat::from_raw(stat) };
        Ok(stat)
    }

    fn fstatat(&self, dir_fd: Fd, path: &CStr, follow_symlinks: bool) -> Result<file_system::Stat> {
        let flags = if follow_symlinks {
            0
        } else {
            libc::AT_SYMLINK_NOFOLLOW
        };

        let mut stat = MaybeUninit::<libc::stat>::uninit();
        unsafe { libc::fstatat(dir_fd.0, path.as_ptr(), stat.as_mut_ptr(), flags) }
            .errno_if_m1()?;
        let stat = unsafe { file_system::Stat::from_raw(stat) };
        Ok(stat)
    }
}

impl IsExecutableFile for RealSystem {
    fn is_executable_file(&self, path: &CStr) -> bool {
        self.fstatat(AT_FDCWD, path, true)
            .is_ok_and(|stat| stat.is_regular_file())
            && self.has_execute_permission(path)
    }
}

impl Pipe for RealSystem {
    fn pipe(&self) -> Result<(Fd, Fd)> {
        let mut fds = MaybeUninit::<[c_int; 2]>::uninit();
        // TODO Use as_mut_ptr rather than cast when array_ptr_get is stabilized
        unsafe { libc::pipe(fds.as_mut_ptr().cast()) }.errno_if_m1()?;
        let fds = unsafe { fds.assume_init() };
        Ok((Fd(fds[0]), Fd(fds[1])))
    }
}

impl Dup for RealSystem {
    fn dup(&self, from: Fd, to_min: Fd, flags: EnumSet<FdFlag>) -> Result<Fd> {
        let command = if flags.contains(FdFlag::CloseOnExec) {
            libc::F_DUPFD_CLOEXEC
        } else {
            libc::F_DUPFD
        };
        unsafe { libc::fcntl(from.0, command, to_min.0) }
            .errno_if_m1()
            .map(Fd)
    }

    fn dup2(&self, from: Fd, to: Fd) -> Result<Fd> {
        loop {
            let result = unsafe { libc::dup2(from.0, to.0) }.errno_if_m1().map(Fd);
            if result != Err(Errno::EINTR) {
                return result;
            }
        }
    }
}

impl Open for RealSystem {
    fn open(
        &self,
        path: &CStr,
        access: OfdAccess,
        flags: EnumSet<OpenFlag>,
        mode: Mode,
    ) -> impl Future<Output = Result<Fd>> + use<> {
        ready((|| {
            let mut raw_flags = access.to_real_flag().ok_or(Errno::EINVAL)?;
            for flag in flags {
                raw_flags |= flag.to_real_flag().ok_or(Errno::EINVAL)?;
            }

            // Rust does not perform default argument promotion for C variadic
            // functions, so we need to promote manually.
            #[cfg(not(target_os = "redox"))]
            let mode_bits = mode.bits() as std::ffi::c_uint;
            #[cfg(target_os = "redox")]
            let mode_bits = mode.bits() as c_int;

            let result = unsafe { libc::open(path.as_ptr(), raw_flags, mode_bits) };
            result.errno_if_m1().map(Fd)
        })())
    }

    fn open_tmpfile(&self, parent_dir: &Path) -> Result<Fd> {
        let parent_dir = OsStr::from_bytes(parent_dir.as_unix_str().as_bytes());
        let file = tempfile::tempfile_in(parent_dir)
            .map_err(|errno| Errno(errno.raw_os_error().unwrap_or(0)))?;
        let fd = Fd(file.into_raw_fd());

        // Clear the CLOEXEC flag
        _ = self.fcntl_setfd(fd, EnumSet::empty());

        Ok(fd)
    }

    fn fdopendir(&self, fd: Fd) -> Result<impl Dir + use<>> {
        let dir = unsafe { libc::fdopendir(fd.0) };
        let dir = NonNull::new(dir).ok_or_else(Errno::last)?;
        Ok(RealDir(dir))
    }

    fn opendir(&self, path: &CStr) -> Result<impl Dir + use<>> {
        let dir = unsafe { libc::opendir(path.as_ptr()) };
        let dir = NonNull::new(dir).ok_or_else(Errno::last)?;
        Ok(RealDir(dir))
    }
}

impl Close for RealSystem {
    fn close(&self, fd: Fd) -> Result<()> {
        // TODO: Use posix_close when available
        loop {
            let result = unsafe { libc::close(fd.0) }.errno_if_m1().map(drop);
            match result {
                Err(Errno::EBADF) => return Ok(()),
                Err(Errno::EINTR) => continue,
                other => return other,
            }
        }
    }
}

impl Fcntl for RealSystem {
    fn ofd_access(&self, fd: Fd) -> Result<OfdAccess> {
        let flags = unsafe { libc::fcntl(fd.0, libc::F_GETFL) }.errno_if_m1()?;
        Ok(OfdAccess::from_real_flag(flags))
    }

    fn get_and_set_nonblocking(&self, fd: Fd, nonblocking: bool) -> Result<bool> {
        let old_flags = unsafe { libc::fcntl(fd.0, libc::F_GETFL) }.errno_if_m1()?;
        let new_flags = if nonblocking {
            old_flags | libc::O_NONBLOCK
        } else {
            old_flags & !libc::O_NONBLOCK
        };
        if new_flags != old_flags {
            unsafe { libc::fcntl(fd.0, libc::F_SETFL, new_flags) }.errno_if_m1()?;
        }
        let was_nonblocking = old_flags & libc::O_NONBLOCK != 0;
        Ok(was_nonblocking)
    }

    fn fcntl_getfd(&self, fd: Fd) -> Result<EnumSet<FdFlag>> {
        let bits = unsafe { libc::fcntl(fd.0, libc::F_GETFD) }.errno_if_m1()?;
        let mut flags = EnumSet::empty();
        if bits & libc::FD_CLOEXEC != 0 {
            flags.insert(FdFlag::CloseOnExec);
        }
        Ok(flags)
    }

    fn fcntl_setfd(&self, fd: Fd, flags: EnumSet<FdFlag>) -> Result<()> {
        let mut bits = 0 as c_int;
        if flags.contains(FdFlag::CloseOnExec) {
            bits |= libc::FD_CLOEXEC;
        }
        unsafe { libc::fcntl(fd.0, libc::F_SETFD, bits) }
            .errno_if_m1()
            .map(drop)
    }
}

impl Read for RealSystem {
    /// Reads data from the file descriptor into the buffer.
    fn read<'a>(
        &self,
        fd: Fd,
        buffer: &'a mut [u8],
    ) -> impl Future<Output = Result<usize>> + use<'a> {
        let result =
            unsafe { libc::read(fd.0, buffer.as_mut_ptr().cast(), buffer.len()) }.errno_if_m1();
        ready(result.map(|len| len.try_into().unwrap()))
    }
}

impl Write for RealSystem {
    /// Writes data from the buffer to the file descriptor.
    fn write<'a>(&self, fd: Fd, buffer: &'a [u8]) -> impl Future<Output = Result<usize>> + use<'a> {
        let result =
            unsafe { libc::write(fd.0, buffer.as_ptr().cast(), buffer.len()) }.errno_if_m1();
        ready(result.map(|len| len.try_into().unwrap()))
    }
}

impl Seek for RealSystem {
    fn lseek(&self, fd: Fd, position: SeekFrom) -> Result<u64> {
        let (offset, whence) = match position {
            SeekFrom::Start(offset) => {
                let offset = offset.try_into().map_err(|_| Errno::EOVERFLOW)?;
                (offset, libc::SEEK_SET)
            }
            SeekFrom::End(offset) => (offset, libc::SEEK_END),
            SeekFrom::Current(offset) => (offset, libc::SEEK_CUR),
        };
        let new_offset = unsafe { libc::lseek(fd.0, offset, whence) }.errno_if_m1()?;
        Ok(new_offset.try_into().unwrap())
    }
}

impl Umask for RealSystem {
    fn umask(&self, new_mask: Mode) -> Mode {
        Mode::from_bits_retain(unsafe { libc::umask(new_mask.bits()) })
    }
}

impl GetCwd for RealSystem {
    fn getcwd(&self) -> Result<PathBuf> {
        // Some getcwd implementations allocate a buffer for the path if the
        // first argument is null, but we cannot use that feature because Vec's
        // allocator may not be compatible with the system's allocator.

        // Since there is no way to know the required buffer size, we try
        // several buffer sizes.
        let mut buffer = Vec::<u8>::new();
        for capacity in [1 << 10, 1 << 12, 1 << 14, 1 << 16] {
            buffer.reserve_exact(capacity);

            let result = unsafe { libc::getcwd(buffer.as_mut_ptr().cast(), capacity) };
            if !result.is_null() {
                // len does not include the null terminator
                let len = unsafe { CStr::from_ptr(buffer.as_ptr().cast()) }.count_bytes();
                unsafe { buffer.set_len(len) }
                buffer.shrink_to_fit();
                return Ok(PathBuf::from(UnixString::from_vec(buffer)));
            }
            let errno = Errno::last();
            if errno != Errno::ERANGE {
                return Err(errno);
            }
        }
        Err(Errno::ERANGE)
    }
}

impl Chdir for RealSystem {
    fn chdir(&self, path: &CStr) -> Result<()> {
        let result = unsafe { libc::chdir(path.as_ptr()) };
        result.errno_if_m1().map(drop)
    }
}

impl Clock for RealSystem {
    fn now(&self) -> Instant {
        Instant::now()
    }
}

impl Times for RealSystem {
    /// Returns consumed CPU times.
    ///
    /// This function actually uses `getrusage` rather than `times` because it
    /// provides better resolution on many systems.
    fn times(&self) -> Result<CpuTimes> {
        let mut usage = MaybeUninit::<libc::rusage>::uninit();

        unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) }.errno_if_m1()?;
        let self_user = unsafe {
            (*usage.as_ptr()).ru_utime.tv_sec as f64
                + (*usage.as_ptr()).ru_utime.tv_usec as f64 * 1e-6
        };
        let self_system = unsafe {
            (*usage.as_ptr()).ru_stime.tv_sec as f64
                + (*usage.as_ptr()).ru_stime.tv_usec as f64 * 1e-6
        };

        unsafe { libc::getrusage(libc::RUSAGE_CHILDREN, usage.as_mut_ptr()) }.errno_if_m1()?;
        let children_user = unsafe {
            (*usage.as_ptr()).ru_utime.tv_sec as f64
                + (*usage.as_ptr()).ru_utime.tv_usec as f64 * 1e-6
        };
        let children_system = unsafe {
            (*usage.as_ptr()).ru_stime.tv_sec as f64
                + (*usage.as_ptr()).ru_stime.tv_usec as f64 * 1e-6
        };

        Ok(CpuTimes {
            self_user,
            self_system,
            children_user,
            children_system,
        })
    }
}

impl GetPid for RealSystem {
    fn getsid(&self, pid: Pid) -> Result<Pid> {
        unsafe { libc::getsid(pid.0) }.errno_if_m1().map(Pid)
    }

    fn getpid(&self) -> Pid {
        Pid(unsafe { libc::getpid() })
    }

    fn getppid(&self) -> Pid {
        Pid(unsafe { libc::getppid() })
    }

    fn getpgrp(&self) -> Pid {
        Pid(unsafe { libc::getpgrp() })
    }
}

impl SetPgid for RealSystem {
    fn setpgid(&self, pid: Pid, pgid: Pid) -> Result<()> {
        let result = unsafe { libc::setpgid(pid.0, pgid.0) };
        result.errno_if_m1().map(drop)
    }
}

const fn to_signal_number(sig: c_int) -> signal::Number {
    signal::Number::from_raw_unchecked(NonZero::new(sig).unwrap())
}

impl Signals for RealSystem {
    const SIGABRT: signal::Number = to_signal_number(libc::SIGABRT);
    const SIGALRM: signal::Number = to_signal_number(libc::SIGALRM);
    const SIGBUS: signal::Number = to_signal_number(libc::SIGBUS);
    const SIGCHLD: signal::Number = to_signal_number(libc::SIGCHLD);
    #[cfg(any(
        target_os = "aix",
        target_os = "horizon",
        target_os = "illumos",
        target_os = "solaris",
    ))]
    const SIGCLD: Option<signal::Number> = Some(to_signal_number(libc::SIGCLD));
    #[cfg(not(any(
        target_os = "aix",
        target_os = "horizon",
        target_os = "illumos",
        target_os = "solaris",
    )))]
    const SIGCLD: Option<signal::Number> = None;
    const SIGCONT: signal::Number = to_signal_number(libc::SIGCONT);
    #[cfg(not(any(
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "haiku",
        target_os = "linux",
        target_os = "redox",
    )))]
    const SIGEMT: Option<signal::Number> = Some(to_signal_number(libc::SIGEMT));
    #[cfg(any(
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "haiku",
        target_os = "linux",
        target_os = "redox",
    ))]
    const SIGEMT: Option<signal::Number> = None;
    const SIGFPE: signal::Number = to_signal_number(libc::SIGFPE);
    const SIGHUP: signal::Number = to_signal_number(libc::SIGHUP);
    const SIGILL: signal::Number = to_signal_number(libc::SIGILL);
    #[cfg(not(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "haiku",
        target_os = "linux",
        target_os = "redox",
    )))]
    const SIGINFO: Option<signal::Number> = Some(to_signal_number(libc::SIGINFO));
    #[cfg(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "haiku",
        target_os = "linux",
        target_os = "redox",
    ))]
    const SIGINFO: Option<signal::Number> = None;
    const SIGINT: signal::Number = to_signal_number(libc::SIGINT);
    #[cfg(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "horizon",
        target_os = "illumos",
        target_os = "linux",
        target_os = "nto",
        target_os = "solaris",
    ))]
    const SIGIO: Option<signal::Number> = Some(to_signal_number(libc::SIGIO));
    #[cfg(not(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "horizon",
        target_os = "illumos",
        target_os = "linux",
        target_os = "nto",
        target_os = "solaris",
    )))]
    const SIGIO: Option<signal::Number> = None;
    const SIGIOT: signal::Number = to_signal_number(libc::SIGIOT);
    const SIGKILL: signal::Number = to_signal_number(libc::SIGKILL);
    #[cfg(target_os = "horizon")]
    const SIGLOST: Option<signal::Number> = Some(to_signal_number(libc::SIGLOST));
    #[cfg(not(target_os = "horizon"))]
    const SIGLOST: Option<signal::Number> = None;
    const SIGPIPE: signal::Number = to_signal_number(libc::SIGPIPE);
    #[cfg(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "haiku",
        target_os = "horizon",
        target_os = "illumos",
        target_os = "linux",
        target_os = "nto",
        target_os = "solaris",
    ))]
    const SIGPOLL: Option<signal::Number> = Some(to_signal_number(libc::SIGPOLL));
    #[cfg(not(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "haiku",
        target_os = "horizon",
        target_os = "illumos",
        target_os = "linux",
        target_os = "nto",
        target_os = "solaris",
    )))]
    const SIGPOLL: Option<signal::Number> = None;
    const SIGPROF: signal::Number = to_signal_number(libc::SIGPROF);
    #[cfg(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "illumos",
        target_os = "linux",
        target_os = "nto",
        target_os = "redox",
        target_os = "solaris",
    ))]
    const SIGPWR: Option<signal::Number> = Some(to_signal_number(libc::SIGPWR));
    #[cfg(not(any(
        target_os = "aix",
        target_os = "android",
        target_os = "emscripten",
        target_os = "fuchsia",
        target_os = "illumos",
        target_os = "linux",
        target_os = "nto",
        target_os = "redox",
        target_os = "solaris",
    )))]
    const SIGPWR: Option<signal::Number> = None;
    const SIGQUIT: signal::Number = to_signal_number(libc::SIGQUIT);
    const SIGSEGV: signal::Number = to_signal_number(libc::SIGSEGV);
    #[cfg(all(
        any(
            target_os = "android",
            target_os = "emscripten",
            target_os = "fuchsia",
            target_os = "linux"
        ),
        not(any(target_arch = "mips", target_arch = "mips64", target_arch = "sparc64"))
    ))]
    const SIGSTKFLT: Option<signal::Number> = Some(to_signal_number(libc::SIGSTKFLT));
    #[cfg(not(all(
        any(
            target_os = "android",
            target_os = "emscripten",
            target_os = "fuchsia",
            target_os = "linux"
        ),
        not(any(target_arch = "mips", target_arch = "mips64", target_arch = "sparc64"))
    )))]
    const SIGSTKFLT: Option<signal::Number> = None;
    const SIGSTOP: signal::Number = to_signal_number(libc::SIGSTOP);
    const SIGSYS: signal::Number = to_signal_number(libc::SIGSYS);
    const SIGTERM: signal::Number = to_signal_number(libc::SIGTERM);
    #[cfg(target_os = "freebsd")]
    const SIGTHR: Option<signal::Number> = Some(to_signal_number(libc::SIGTHR));
    #[cfg(not(target_os = "freebsd"))]
    const SIGTHR: Option<signal::Number> = None;
    const SIGTRAP: signal::Number = to_signal_number(libc::SIGTRAP);
    const SIGTSTP: signal::Number = to_signal_number(libc::SIGTSTP);
    const SIGTTIN: signal::Number = to_signal_number(libc::SIGTTIN);
    const SIGTTOU: signal::Number = to_signal_number(libc::SIGTTOU);
    const SIGURG: signal::Number = to_signal_number(libc::SIGURG);
    const SIGUSR1: signal::Number = to_signal_number(libc::SIGUSR1);
    const SIGUSR2: signal::Number = to_signal_number(libc::SIGUSR2);
    const SIGVTALRM: signal::Number = to_signal_number(libc::SIGVTALRM);
    const SIGWINCH: signal::Number = to_signal_number(libc::SIGWINCH);
    const SIGXCPU: signal::Number = to_signal_number(libc::SIGXCPU);
    const SIGXFSZ: signal::Number = to_signal_number(libc::SIGXFSZ);

    fn sigrt_range(&self) -> Option<RangeInclusive<signal::Number>> {
        let raw_range = signal::rt_range();
        let start = signal::Number::from_raw_unchecked(NonZero::new(*raw_range.start())?);
        let end = signal::Number::from_raw_unchecked(NonZero::new(*raw_range.end())?);
        Some(start..=end).filter(|range| !range.is_empty())
    }

    // TODO: Implement sig2str and str2sig methods
}

impl Sigmask for RealSystem {
    fn sigmask(
        &self,
        op: Option<(SigmaskOp, &[signal::Number])>,
        old_mask: Option<&mut Vec<signal::Number>>,
    ) -> impl Future<Output = Result<()>> + use<> {
        ready((|| unsafe {
            let (how, raw_mask) = match op {
                None => (libc::SIG_BLOCK, None),
                Some((op, mask)) => {
                    let how = match op {
                        SigmaskOp::Add => libc::SIG_BLOCK,
                        SigmaskOp::Remove => libc::SIG_UNBLOCK,
                        SigmaskOp::Set => libc::SIG_SETMASK,
                    };

                    let mut raw_mask = MaybeUninit::<libc::sigset_t>::uninit();
                    libc::sigemptyset(raw_mask.as_mut_ptr()).errno_if_m1()?;
                    for &signal in mask {
                        libc::sigaddset(raw_mask.as_mut_ptr(), signal.as_raw()).errno_if_m1()?;
                    }

                    (how, Some(raw_mask))
                }
            };
            let mut old_mask_pair = match old_mask {
                None => None,
                Some(old_mask) => {
                    let mut raw_old_mask = MaybeUninit::<libc::sigset_t>::uninit();
                    // POSIX requires *all* sigset_t objects to be initialized before use.
                    libc::sigemptyset(raw_old_mask.as_mut_ptr()).errno_if_m1()?;
                    Some((old_mask, raw_old_mask))
                }
            };

            let raw_set_ptr = raw_mask
                .as_ref()
                .map_or(std::ptr::null(), |raw_set| raw_set.as_ptr());
            let raw_old_set_ptr = old_mask_pair
                .as_mut()
                .map_or(std::ptr::null_mut(), |(_, raw_old_mask)| {
                    raw_old_mask.as_mut_ptr()
                });
            let result = libc::sigprocmask(how, raw_set_ptr, raw_old_set_ptr);
            result.errno_if_m1().map(drop)?;

            if let Some((old_mask, raw_old_mask)) = old_mask_pair {
                old_mask.clear();
                signal::sigset_to_vec(raw_old_mask.as_ptr(), old_mask);
            }

            Ok(())
        })())
    }
}

impl GetSigaction for RealSystem {
    fn get_sigaction(&self, signal: signal::Number) -> Result<Disposition> {
        sigaction_impl(signal, None)
    }
}

impl Sigaction for RealSystem {
    fn sigaction(&self, signal: signal::Number, handling: Disposition) -> Result<Disposition> {
        sigaction_impl(signal, Some(handling))
    }
}

impl CaughtSignals for RealSystem {
    fn caught_signals(&self) -> Vec<signal::Number> {
        let mut signals = Vec::new();
        for slot in &CAUGHT_SIGNALS {
            // Need a fence to ensure we examine the slots in order.
            compiler_fence(Ordering::Acquire);

            let number = slot.swap(0, Ordering::Relaxed);
            let Some(number) = NonZero::new(number as signal::RawNumber) else {
                // The `catch_signal` function always fills the first unused
                // slot, so there is no more slot filled with a signal.
                break;
            };
            signals.push(signal::Number::from_raw_unchecked(number));
        }
        signals
    }
}

impl SendSignal for RealSystem {
    fn kill(
        &self,
        target: Pid,
        signal: Option<signal::Number>,
    ) -> impl Future<Output = Result<()>> + use<> {
        let raw = signal.map_or(0, signal::Number::as_raw);
        let result = unsafe { libc::kill(target.0, raw) }.errno_if_m1().map(drop);
        ready(result)
    }

    fn raise(&self, signal: signal::Number) -> impl Future<Output = Result<()>> + use<> {
        let raw = signal.as_raw();
        let result = unsafe { libc::raise(raw) }.errno_if_m1().map(drop);
        ready(result)
    }
}

impl Select for RealSystem {
    fn select<'a>(
        &self,
        readers: &'a mut Vec<Fd>,
        writers: &'a mut Vec<Fd>,
        timeout: Option<Duration>,
        signal_mask: Option<&[signal::Number]>,
    ) -> impl Future<Output = Result<c_int>> + use<'a> {
        ready((|| {
            use std::ptr::{null, null_mut};

            let max_fd = readers.iter().chain(writers.iter()).max();
            let nfds = max_fd
                .map(|fd| fd.0.checked_add(1).ok_or(Errno::EBADF))
                .transpose()?
                .unwrap_or(0);

            fn to_raw_fd_set(fds: &[Fd]) -> MaybeUninit<libc::fd_set> {
                let mut raw_fds = MaybeUninit::<libc::fd_set>::uninit();
                unsafe {
                    libc::FD_ZERO(raw_fds.as_mut_ptr());
                    for fd in fds {
                        libc::FD_SET(fd.0, raw_fds.as_mut_ptr());
                    }
                }
                raw_fds
            }
            let mut raw_readers = to_raw_fd_set(readers);
            let mut raw_writers = to_raw_fd_set(writers);
            let readers_ptr = raw_readers.as_mut_ptr();
            let writers_ptr = raw_writers.as_mut_ptr();
            let errors = null_mut();

            let timeout_spec = to_timespec(timeout.unwrap_or_default());
            let timeout_ptr = if timeout.is_some() {
                timeout_spec.as_ptr()
            } else {
                null()
            };

            let mut raw_mask = MaybeUninit::<libc::sigset_t>::uninit();
            let raw_mask_ptr = match signal_mask {
                None => null(),
                Some(signal_mask) => {
                    unsafe { libc::sigemptyset(raw_mask.as_mut_ptr()) }.errno_if_m1()?;
                    for &signal in signal_mask {
                        unsafe { libc::sigaddset(raw_mask.as_mut_ptr(), signal.as_raw()) }
                            .errno_if_m1()?;
                    }
                    raw_mask.as_ptr()
                }
            };

            let count = unsafe {
                libc::pselect(
                    nfds,
                    readers_ptr,
                    writers_ptr,
                    errors,
                    timeout_ptr,
                    raw_mask_ptr,
                )
            }
            .errno_if_m1()?;

            readers.retain(|fd| unsafe { libc::FD_ISSET(fd.0, readers_ptr) });
            writers.retain(|fd| unsafe { libc::FD_ISSET(fd.0, writers_ptr) });

            Ok(count)
        })())
    }
}

impl Isatty for RealSystem {
    fn isatty(&self, fd: Fd) -> bool {
        (unsafe { libc::isatty(fd.0) } != 0)
    }
}

impl TcGetPgrp for RealSystem {
    fn tcgetpgrp(&self, fd: Fd) -> Result<Pid> {
        unsafe { libc::tcgetpgrp(fd.0) }.errno_if_m1().map(Pid)
    }
}

impl TcSetPgrp for RealSystem {
    fn tcsetpgrp(&self, fd: Fd, pgid: Pid) -> impl Future<Output = Result<()>> + use<> {
        let result = unsafe { libc::tcsetpgrp(fd.0, pgid.0) };
        ready(result.errno_if_m1().map(drop))
    }
}

impl Fork for RealSystem {
    /// Creates a new child process.
    ///
    /// This implementation calls the `fork` system call and returns both in the
    /// parent and child process. In the parent, the returned
    /// `ChildProcessStarter` ignores any arguments and returns the child
    /// process ID. In the child, the starter runs the task and exits the
    /// process.
    fn new_child_process(&self) -> Result<ChildProcessStarter<Self>> {
        let raw_pid = unsafe { libc::fork() }.errno_if_m1()?;
        if raw_pid != 0 {
            // Parent process
            return Ok(Box::new(move |_env, _task| Pid(raw_pid)));
        }

        // Child process
        Ok(Box::new(|env, task| {
            let system = Rc::clone(&env.system);
            match system.run_real(task(env)) {}
        }))
    }
}

impl Wait for RealSystem {
    fn wait(&self, target: Pid) -> Result<Option<(Pid, ProcessState)>> {
        let mut status = 0;
        let options = libc::WUNTRACED | libc::WCONTINUED | libc::WNOHANG;
        match unsafe { libc::waitpid(target.0, &mut status, options) } {
            -1 => Err(Errno::last()),
            0 => Ok(None),
            pid => {
                let state = if libc::WIFCONTINUED(status) {
                    ProcessState::Running
                } else if libc::WIFEXITED(status) {
                    let exit_status = libc::WEXITSTATUS(status);
                    ProcessState::exited(exit_status)
                } else if libc::WIFSIGNALED(status) {
                    let signal = libc::WTERMSIG(status);
                    let core_dump = libc::WCOREDUMP(status);
                    // SAFETY: The signal number is always a valid signal number, which is non-zero.
                    let raw_number = unsafe { NonZero::new_unchecked(signal) };
                    let signal = signal::Number::from_raw_unchecked(raw_number);
                    let process_result = ProcessResult::Signaled { signal, core_dump };
                    process_result.into()
                } else if libc::WIFSTOPPED(status) {
                    let signal = libc::WSTOPSIG(status);
                    // SAFETY: The signal number is always a valid signal number, which is non-zero.
                    let raw_number = unsafe { NonZero::new_unchecked(signal) };
                    let signal = signal::Number::from_raw_unchecked(raw_number);
                    ProcessState::stopped(signal)
                } else {
                    unreachable!()
                };
                Ok(Some((Pid(pid), state)))
            }
        }
    }
}

impl Exec for RealSystem {
    fn execve(
        &self,
        path: &CStr,
        args: &[CString],
        envs: &[CString],
    ) -> impl Future<Output = Result<Infallible>> + use<> {
        fn to_pointer_array<S: AsRef<CStr>>(strs: &[S]) -> Vec<*const libc::c_char> {
            strs.iter()
                .map(|s| s.as_ref().as_ptr())
                .chain(std::iter::once(std::ptr::null()))
                .collect()
        }
        // TODO Uncomment when upgrading to libc 1.0
        // // This function makes mutable char pointers from immutable string
        // // slices since `execve` requires mutable pointers.
        // fn to_pointer_array<S: AsRef<CStr>>(strs: &[S]) -> Vec<*mut libc::c_char> {
        //     strs.iter()
        //         .map(|s| s.as_ref().as_ptr().cast_mut())
        //         .chain(std::iter::once(std::ptr::null_mut()))
        //         .collect()
        // }

        let args = to_pointer_array(args);
        let envs = to_pointer_array(envs);
        loop {
            let _ = unsafe { libc::execve(path.as_ptr(), args.as_ptr(), envs.as_ptr()) };
            let errno = Errno::last();
            if errno != Errno::EINTR {
                return ready(Err(errno));
            }
        }
    }
}

impl Exit for RealSystem {
    #[allow(unreachable_code)]
    fn exit(&self, exit_status: ExitStatus) -> impl Future<Output = Infallible> + use<> {
        ready(unsafe { libc::_exit(exit_status.0) })
    }
}

impl GetUid for RealSystem {
    fn getuid(&self) -> Uid {
        Uid(unsafe { libc::getuid() })
    }

    fn geteuid(&self) -> Uid {
        Uid(unsafe { libc::geteuid() })
    }

    fn getgid(&self) -> Gid {
        Gid(unsafe { libc::getgid() })
    }

    fn getegid(&self) -> Gid {
        Gid(unsafe { libc::getegid() })
    }
}

impl GetPw for RealSystem {
    fn getpwnam_dir(&self, name: &CStr) -> Result<Option<PathBuf>> {
        Errno::clear();
        let passwd = unsafe { libc::getpwnam(name.as_ptr()) };
        if passwd.is_null() {
            let errno = Errno::last();
            return if errno == Errno::NO_ERROR {
                Ok(None)
            } else {
                Err(errno)
            };
        }

        let dir = unsafe { CStr::from_ptr((*passwd).pw_dir) };
        Ok(Some(UnixString::from_vec(dir.to_bytes().to_vec()).into()))
    }
}

impl Sysconf for RealSystem {
    fn confstr_path(&self) -> Result<UnixString> {
        // TODO Support other platforms
        #[cfg(any(
            target_os = "linux",
            target_os = "macos",
            target_os = "ios",
            target_os = "tvos",
            target_os = "watchos"
        ))]
        unsafe {
            let size = libc::confstr(libc::_CS_PATH, std::ptr::null_mut(), 0);
            if size == 0 {
                return Err(Errno::last());
            }
            let mut buffer = Vec::<u8>::with_capacity(size);
            let final_size = libc::confstr(libc::_CS_PATH, buffer.as_mut_ptr() as *mut _, size);
            if final_size == 0 {
                return Err(Errno::last());
            }
            if final_size > size {
                return Err(Errno::ERANGE);
            }
            buffer.set_len(final_size - 1); // The last byte is a null terminator.
            return Ok(UnixString::from_vec(buffer));
        }

        #[allow(unreachable_code)]
        Err(Errno::ENOSYS)
    }
}

impl ShellPath for RealSystem {
    /// Returns the path to the shell.
    ///
    /// On Linux, this function returns `/proc/self/exe`. On other platforms, it
    /// searches for an executable `sh` from the default PATH returned by
    /// [`confstr_path`](Self::confstr_path).
    fn shell_path(&self) -> CString {
        #[cfg(any(target_os = "linux", target_os = "android"))]
        if self.is_executable_file(c"/proc/self/exe") {
            return c"/proc/self/exe".to_owned();
        }
        // TODO Add optimization for other targets

        // Find an executable "sh" from the default PATH
        if let Ok(path) = self.confstr_path() {
            if let Some(full_path) = path
                .as_bytes()
                .split(|b| *b == b':')
                .map(|dir| Path::new(UnixStr::from_bytes(dir)).join("sh"))
                .filter(|full_path| full_path.is_absolute())
                .filter_map(|full_path| CString::new(full_path.into_unix_string().into_vec()).ok())
                .find(|full_path| self.is_executable_file(full_path))
            {
                return full_path;
            }
        }

        // The last resort
        c"/bin/sh".to_owned()
    }
}

impl GetRlimit for RealSystem {
    fn getrlimit(&self, resource: Resource) -> Result<LimitPair> {
        let raw_resource = resource.as_raw_type().ok_or(Errno::EINVAL)?;

        let mut limits = MaybeUninit::<libc::rlimit>::uninit();
        unsafe { libc::getrlimit(raw_resource as _, limits.as_mut_ptr()) }.errno_if_m1()?;

        // SAFETY: These two fields of `limits` have been initialized by `getrlimit`.
        // (But that does not mean *all* fields are initialized,
        // so we cannot use `assume_init` here.)
        Ok(LimitPair {
            soft: unsafe { (*limits.as_ptr()).rlim_cur },
            hard: unsafe { (*limits.as_ptr()).rlim_max },
        })
    }
}

impl SetRlimit for RealSystem {
    fn setrlimit(&self, resource: Resource, limits: LimitPair) -> Result<()> {
        let raw_resource = resource.as_raw_type().ok_or(Errno::EINVAL)?;

        let mut rlimit = MaybeUninit::<libc::rlimit>::uninit();
        unsafe {
            (&raw mut (*rlimit.as_mut_ptr()).rlim_cur).write(limits.soft);
            (&raw mut (*rlimit.as_mut_ptr()).rlim_max).write(limits.hard);
        }

        unsafe { libc::setrlimit(raw_resource as _, rlimit.as_ptr()) }.errno_if_m1()?;
        Ok(())
    }
}

/// Implementor of [`Dir`] that iterates on a real directory
#[derive(Debug)]
struct RealDir(NonNull<DIR>);

impl Drop for RealDir {
    fn drop(&mut self) {
        unsafe {
            libc::closedir(self.0.as_ptr());
        }
    }
}

impl Dir for RealDir {
    fn next(&mut self) -> Result<Option<DirEntry<'_>>> {
        Errno::clear();
        let entry = unsafe { libc::readdir(self.0.as_ptr()) };
        let errno = Errno::last();
        if entry.is_null() {
            if errno == Errno::NO_ERROR {
                Ok(None)
            } else {
                Err(errno)
            }
        } else {
            // TODO Use as_ptr rather than cast when array_ptr_get is stabilized
            let name = unsafe { CStr::from_ptr((&raw const (*entry).d_name).cast()) };
            let name = UnixStr::from_bytes(name.to_bytes());
            Ok(Some(DirEntry { name }))
        }
    }
}

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

    #[test]
    fn real_system_directory_entries() {
        let system = unsafe { RealSystem::new() };
        let mut dir = system.opendir(c".").unwrap();
        let mut count = 0;
        while dir.next().unwrap().is_some() {
            count += 1;
        }
        assert!(count > 0);
    }

    // This test depends on static variables.
    #[test]
    fn real_system_caught_signals() {
        unsafe {
            let system = RealSystem::new();
            let result = system.caught_signals();
            assert_eq!(result, []);

            catch_signal(libc::SIGINT);
            catch_signal(libc::SIGTERM);
            catch_signal(libc::SIGTERM);
            catch_signal(libc::SIGCHLD);

            let sigint = signal::Number::from_raw_unchecked(NonZero::new(libc::SIGINT).unwrap());
            let sigterm = signal::Number::from_raw_unchecked(NonZero::new(libc::SIGTERM).unwrap());
            let sigchld = signal::Number::from_raw_unchecked(NonZero::new(libc::SIGCHLD).unwrap());

            let result = system.caught_signals();
            assert_eq!(result, [sigint, sigterm, sigchld]);
            let result = system.caught_signals();
            assert_eq!(result, []);
        }
    }
}