oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
//! Tests of `oscall::io::macos`: POSIX asynchronous I/O.
//!
//! A process has few operations at a time (16 by default), and the tests of
//! one file run in threads of one process: each test takes a lock, so that
//! one test's operations are not refused for another's.
#![cfg(target_os = "macos")]

mod common;

/// Says what a test found: on the standard error output itself, which the
/// test harness does not capture.
macro_rules! note {
    ($($arg:tt)*) => {
        crate::common::note(&format!($($arg)*))
    };
}

use std::sync::{Mutex, MutexGuard};

use oscall::io::macos;

static SERIAL: Mutex<()> = Mutex::new(());

/// One test at a time. A test that failed has released what it held when
/// its operations were dropped.
fn serial() -> MutexGuard<'static, ()> {
    SERIAL
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

#[test]
fn limits() {
    let _serial = serial();
    let limits = macos::limits().unwrap();
    note!("io::macos: {limits:?}");
    assert!(limits.process >= 1, "{limits:?}");
    assert!(limits.system >= limits.process, "{limits:?}");
    assert!(limits.threads >= 1, "{limits:?}");
    assert_eq!(limits, macos::limits().unwrap());
    // What sysctl(8) says.
    let said = std::process::Command::new("sysctl")
        .args(["-n", "kern.aiomax", "kern.aioprocmax", "kern.aiothreads"])
        .output()
        .unwrap();
    let said: Vec<u32> = String::from_utf8(said.stdout)
        .unwrap()
        .lines()
        .map(|line| line.trim().parse().unwrap())
        .collect();
    assert_eq!(said, [limits.system, limits.process, limits.threads]);
}

#[cfg(feature = "alloc")]
mod operation {
    use std::time::{Duration, Instant};

    use oscall::event::{Event, Poller};
    use oscall::io::macos::{self, Batch, Operation};
    use oscall::process::unix::SignalExt;
    use oscall::process::{Signal, Signals};
    use oscall::{ErrorKind, fs, io};

    use super::{common, serial};

    /// A wait that is never meant to end by itself.
    const LONG: Duration = Duration::from_secs(60);

    /// Waits for the operation and returns its outcome.
    fn finish(operation: &Operation) -> oscall::Result<usize> {
        assert_eq!(macos::wait(&[operation], Some(LONG)).unwrap(), Some(0));
        assert!(!operation.is_pending());
        operation.result().expect("the operation is over")
    }

    fn open(path: &std::path::Path, options: &fs::OpenOptions) -> oscall::OwnedHandle {
        fs::open(path, options).unwrap()
    }

    /// A FIFO open for reading and for writing, which is what holds an
    /// operation in flight for as long as a test likes: a read of it waits
    /// until something is written. (Pipes and sockets are refused, and a
    /// file is read at once.)
    struct Fifo(oscall::OwnedHandle);

    impl Fifo {
        fn new(name: &str) -> Self {
            let path = common::tmp_dir(name).join("fifo");
            fs::unix::mkfifo(&path, 0o600).unwrap();
            Self::open(&path)
        }

        fn open(path: &std::path::Path) -> Self {
            Self(open(path, &fs::OpenOptions::new().read(true).write(true)))
        }
    }

    impl Drop for Fifo {
        /// Closing a handle waits for the operations that run on it, and
        /// a read of a FIFO runs until it has a byte: a test that fails
        /// with reads in flight would never end. Every read of these
        /// tests is one of a single byte, and none has more than a few
        /// dozen.
        fn drop(&mut self) {
            let _ = io::set_nonblocking(&self.0, true);
            let _ = io::write(&self.0, &[b'!'; 256]);
        }
    }

    /// Asserts that a submission was refused for the reason `kind`. Before
    /// macOS 26 the kernel says `EAGAIN` whatever the reason.
    #[track_caller]
    fn assert_refused(error: oscall::Error, kind: ErrorKind) {
        if error.kind() != ErrorKind::WouldBlock {
            assert_eq!(error.kind(), kind, "{error:?}");
        }
    }

    fn read_write() -> fs::OpenOptions {
        fs::OpenOptions::new().read(true).write(true).create(true)
    }

    #[test]
    fn nothing_started() {
        let _serial = serial();
        let mut operation = Operation::new();
        assert!(format!("{operation:?}").starts_with("Operation"));
        assert!(!operation.is_pending());
        assert_eq!(operation.result(), None);
        assert_eq!(operation.cancel(), Ok(false));
        assert_eq!(operation.take_buffer(), None);
        // Nothing to wait for.
        let err = macos::wait(&[&operation], Some(Duration::ZERO)).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = macos::wait(&[], Some(Duration::ZERO)).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        drop(Operation::default());
    }

    #[test]
    fn file_read_and_write() {
        let _serial = serial();
        let dir = common::tmp_dir("io_macos_file");
        let path = dir.join("data");
        let file = open(&path, &read_write());

        // A write, and what it leaves in the file.
        let mut operation = Operation::new();
        operation.write(&file, b"0123456789".to_vec(), 0).unwrap();
        assert_eq!(finish(&operation), Ok(10));
        // The outcome stays until something else is started.
        assert_eq!(operation.result(), Some(Ok(10)));
        assert_eq!(operation.cancel(), Ok(false));
        assert_eq!(operation.take_buffer().as_deref(), Some(&b"0123456789"[..]));
        assert_eq!(operation.take_buffer(), None);
        assert_eq!(operation.result(), Some(Ok(10)));
        assert_eq!(std::fs::read(&path).unwrap(), b"0123456789");

        // In the middle, and past the end: the gap reads as zeroes.
        operation.write(&file, b"abc".to_vec(), 4).unwrap();
        assert_eq!(finish(&operation), Ok(3));
        operation.write(&file, b"xy".to_vec(), 12).unwrap();
        assert_eq!(finish(&operation), Ok(2));
        assert_eq!(std::fs::read(&path).unwrap(), b"0123abc789\0\0xy");

        // The position of the handle is neither used nor moved.
        assert_eq!(io::seek(&file, io::SeekFrom::Current(0)), Ok(0));

        // A read fills the buffer up to its capacity, whatever it held.
        let mut buf = Vec::with_capacity(5);
        buf.extend_from_slice(b"??");
        let capacity = buf.capacity();
        operation.read(&file, buf, 2).unwrap();
        assert_eq!(finish(&operation), Ok(capacity.min(12)));
        let buf = operation.take_buffer().unwrap();
        assert_eq!(buf, &b"23abc789\0\0xy"[..capacity.min(12)]);
        assert_eq!(buf.capacity(), capacity);

        // Across the end: what there is. At the end and after it: nothing,
        // which is not an error.
        operation.read(&file, Vec::with_capacity(64), 10).unwrap();
        assert_eq!(finish(&operation), Ok(4));
        assert_eq!(operation.take_buffer().unwrap(), b"\0\0xy");
        for offset in [14, 15, 1 << 40] {
            operation
                .read(&file, Vec::with_capacity(64), offset)
                .unwrap();
            assert_eq!(finish(&operation), Ok(0), "at {offset}");
            assert_eq!(operation.take_buffer().unwrap(), b"");
        }

        // A buffer with no room reads nothing.
        operation.read(&file, Vec::new(), 0).unwrap();
        assert_eq!(finish(&operation), Ok(0));
        assert_eq!(operation.take_buffer().unwrap(), b"");
        operation.write(&file, Vec::new(), 0).unwrap();
        assert_eq!(finish(&operation), Ok(0));

        // The same as the synchronous functions read.
        let mut expected = [0u8; 14];
        assert_eq!(io::read_at(&file, &mut expected, 0), Ok(14));
        operation.read(&file, Vec::with_capacity(14), 0).unwrap();
        assert_eq!(finish(&operation), Ok(14));
        assert_eq!(operation.take_buffer().unwrap(), expected);
    }

    #[test]
    fn large_transfers() {
        let _serial = serial();
        let dir = common::tmp_dir("io_macos_large");
        let path = dir.join("data");
        let file = open(&path, &read_write());
        let data: Vec<u8> = (0..(8usize << 20)).map(|i| ((i * 31) >> 3) as u8).collect();

        // Several at once, each on its own part of the file.
        let part = data.len() / 4;
        let mut writes: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
        for (i, write) in writes.iter_mut().enumerate() {
            let chunk = data[i * part..(i + 1) * part].to_vec();
            write.write(&file, chunk, (i * part) as u64).unwrap();
        }
        let mut left: Vec<&Operation> = writes.iter().collect();
        while !left.is_empty() {
            let index = macos::wait(&left, Some(LONG)).unwrap().expect("a write");
            assert_eq!(left[index].result(), Some(Ok(part)));
            left.remove(index);
        }
        let mut sync = Operation::new();
        sync.sync(&file, false).unwrap();
        assert_eq!(finish(&sync), Ok(0));
        assert_eq!(sync.take_buffer(), None);
        sync.sync(&file, true).unwrap();
        assert_eq!(finish(&sync), Ok(0));
        assert!(std::fs::read(&path).unwrap() == data);

        let mut reads: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
        for (i, read) in reads.iter_mut().enumerate() {
            read.read(&file, Vec::with_capacity(part), (i * part) as u64)
                .unwrap();
        }
        for (i, read) in reads.iter_mut().enumerate() {
            assert_eq!(finish(read), Ok(part));
            assert!(read.take_buffer().unwrap() == data[i * part..(i + 1) * part]);
        }
    }

    #[test]
    fn what_fails() {
        let _serial = serial();
        let dir = common::tmp_dir("io_macos_fails");
        let path = dir.join("data");
        std::fs::write(&path, b"0123456789").unwrap();
        let mut operation = Operation::new();

        // An offset the system cannot hold: nothing is started.
        let file = open(&path, &read_write());
        let err = operation
            .read(&file, Vec::with_capacity(4), u64::MAX)
            .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert!(!operation.is_pending());
        assert_eq!(operation.result(), None);

        // The wrong way round: the system tells when the operation is
        // submitted, and the buffer is there to take back.
        let read_only = open(&path, &fs::OpenOptions::new().read(true));
        let err = operation
            .write(&read_only, b"nothing".to_vec(), 0)
            .unwrap_err();
        assert_refused(err, ErrorKind::BadHandle);
        assert_eq!(operation.result(), None);
        assert_eq!(operation.take_buffer().as_deref(), Some(&b"nothing"[..]));
        let write_only = open(&path, &fs::OpenOptions::new().write(true));
        let err = operation
            .read(&write_only, Vec::with_capacity(4), 0)
            .unwrap_err();
        assert_refused(err, ErrorKind::BadHandle);
        assert_eq!(std::fs::read(&path).unwrap(), b"0123456789");

        // What has no positions is refused: pipes, and sockets.
        let (reader, writer) = io::pipe().unwrap();
        let err = operation
            .read(&reader, Vec::with_capacity(4), 0)
            .unwrap_err();
        assert_refused(err, ErrorKind::NotSeekable);
        let err = operation.write(&writer, b"x".to_vec(), 0).unwrap_err();
        assert_refused(err, ErrorKind::NotSeekable);
        note!("io::macos: a pipe is refused with {err:?}");

        // A directory is opened, and not read: the operation tells.
        let directory = open(&dir, &fs::OpenOptions::new().read(true));
        operation
            .read(&directory, Vec::with_capacity(4), 0)
            .unwrap();
        let err = finish(&operation).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::IsADirectory);
        assert_eq!(operation.take_buffer().unwrap(), b"");
    }

    #[test]
    fn in_flight() {
        let _serial = serial();
        let fifo = Fifo::new("io_macos_in_flight");
        let fifo = &fifo.0;
        let mut read = Operation::new();
        read.read(fifo, Vec::with_capacity(16), 0).unwrap();

        // Nothing to read: the operation is in flight, and stays so.
        assert!(read.is_pending());
        assert_eq!(read.result(), None);
        assert_eq!(read.take_buffer(), None);
        let err = read.read(fifo, Vec::new(), 0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::ResourceBusy);
        let err = read.sync(fifo, false).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::ResourceBusy);
        assert_eq!(macos::wait(&[&read], Some(Duration::ZERO)), Ok(None));
        let start = Instant::now();
        assert_eq!(
            macos::wait(&[&read], Some(Duration::from_millis(60))),
            Ok(None)
        );
        assert!(start.elapsed() >= Duration::from_millis(60));
        assert!(read.is_pending());

        // A wait ends when the operation does.
        let start = Instant::now();
        std::thread::scope(|scope| {
            scope.spawn(|| {
                std::thread::sleep(Duration::from_millis(100));
                io::write(fifo, b"hello").unwrap();
            });
            assert_eq!(macos::wait(&[&read], Some(LONG)), Ok(Some(0)));
            assert!(start.elapsed() >= Duration::from_millis(100));
            assert!(start.elapsed() < LONG);
        });
        assert_eq!(read.result(), Some(Ok(5)));
        // A complete operation is told again, as long as it is listed.
        assert_eq!(macos::wait(&[&read], None), Ok(Some(0)));
        assert_eq!(read.take_buffer().unwrap(), b"hello");
    }

    #[test]
    fn wait_for_one_of_several() {
        let _serial = serial();
        let fifos: Vec<_> = (0..3)
            .map(|i| Fifo::new(&format!("io_macos_several_{i}")))
            .collect();
        let fifos: Vec<_> = fifos.iter().map(|fifo| &fifo.0).collect();
        let mut reads: Vec<Operation> = (0..3).map(|_| Operation::new()).collect();
        for (read, fifo) in reads.iter_mut().zip(&fifos) {
            read.read(*fifo, Vec::with_capacity(8), 0).unwrap();
        }
        let idle = Operation::new();
        // An operation that started nothing is passed over.
        let list = [&idle, &reads[0], &reads[1], &reads[2]];
        assert_eq!(
            macos::wait(&list, Some(Duration::from_millis(20))),
            Ok(None)
        );

        io::write(fifos[1], b"one").unwrap();
        assert_eq!(macos::wait(&list, Some(LONG)), Ok(Some(2)));
        assert_eq!(reads[1].result(), Some(Ok(3)));
        // Without it, the others are still waited for.
        let list = [&reads[0], &idle, &reads[2]];
        assert_eq!(
            macos::wait(&list, Some(Duration::from_millis(20))),
            Ok(None)
        );
        io::write(fifos[2], b"two!").unwrap();
        assert_eq!(macos::wait(&list, Some(LONG)), Ok(Some(2)));
        assert_eq!(reads[2].result(), Some(Ok(4)));
        io::write(fifos[0], b"three").unwrap();
        assert_eq!(macos::wait(&[&reads[0]], None), Ok(Some(0)));
        assert_eq!(reads[0].take_buffer().unwrap(), b"three");
        assert_eq!(reads[1].take_buffer().unwrap(), b"one");
        assert_eq!(reads[2].take_buffer().unwrap(), b"two!");
    }

    #[test]
    fn moved_to_another_thread() {
        let _serial = serial();
        let fifo = Fifo::new("io_macos_moved");
        let fifo = &fifo.0;
        // Started by a thread that ends: the operation goes on.
        let mut read = std::thread::scope(|scope| {
            scope
                .spawn(|| {
                    let mut read = Operation::new();
                    read.read(fifo, Vec::with_capacity(8), 0).unwrap();
                    read
                })
                .join()
                .unwrap()
        });
        assert!(read.is_pending());
        io::write(fifo, b"late").unwrap();
        assert_eq!(finish(&read), Ok(4));
        assert_eq!(read.take_buffer().unwrap(), b"late");
    }

    /// Starts a read of one byte of `fifo` that a thread of the kernel has
    /// started on: it waits for a byte, and cannot be cancelled.
    fn running_read(fifo: &oscall::OwnedHandle) -> Operation {
        for _ in 0..200 {
            let mut read = Operation::new();
            read.read(fifo, Vec::with_capacity(1), 0).unwrap();
            std::thread::sleep(Duration::from_millis(20));
            // Still in the queue: taken out of it, and tried again.
            if !read.cancel().unwrap() {
                assert!(read.is_pending());
                return read;
            }
        }
        panic!("the kernel started on none of 200 reads in 20 ms each");
    }

    /// Starts reads of one byte of `fifo` until the process may have no
    /// more, and returns them with the refusal.
    fn fill(fifo: &oscall::OwnedHandle, limit: usize) -> (Vec<Operation>, oscall::Error) {
        let mut reads = Vec::new();
        loop {
            let mut read = Operation::new();
            match read.read(fifo, Vec::with_capacity(1), 0) {
                Ok(()) => reads.push(read),
                Err(error) => return (reads, error),
            }
            assert!(reads.len() <= limit, "more operations than the limit");
        }
    }

    /// Ends the reads of one byte that are in flight: those the kernel
    /// gives up are cancelled, and the others are given their byte.
    fn release(fifo: &oscall::OwnedHandle, reads: &[Operation]) {
        let mut running = 0;
        for read in reads {
            if read.is_pending() && !read.cancel().unwrap() {
                running += 1;
            }
        }
        // A read that ended in between leaves its byte to nobody.
        assert_eq!(io::write(fifo, &vec![b'r'; running]), Ok(running));
        for read in reads {
            if read.result().is_none() {
                finish(read).unwrap();
            }
        }
    }

    #[test]
    fn limit_of_the_process() {
        let _serial = serial();
        let limit = macos::limits().unwrap().process as usize;
        let fifo = Fifo::new("io_macos_limit");
        let fifo = &fifo.0;
        let dir = common::tmp_dir("io_macos_limit_file");
        let file = open(&dir.join("data"), &read_write());

        let (mut reads, refused) = fill(fifo, limit);
        assert_eq!(refused.kind(), ErrorKind::WouldBlock, "{refused:?}");
        assert_eq!(reads.len(), limit);
        // Whatever the operation, and whatever the handle.
        let mut other = Operation::new();
        let err = other.write(&file, b"refused".to_vec(), 0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::WouldBlock);
        assert_eq!(other.result(), None);
        assert_eq!(other.take_buffer().as_deref(), Some(&b"refused"[..]));
        let err = other.sync(&file, false).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::WouldBlock);

        // One of the reads gets a byte. Over or not, it holds its place
        // until its outcome is taken, which the wait does.
        io::write(fifo, b"1").unwrap();
        std::thread::sleep(Duration::from_millis(200));
        let mut another = Operation::new();
        let err = another.read(fifo, Vec::with_capacity(1), 0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::WouldBlock);
        let list: Vec<&Operation> = reads.iter().collect();
        let over = macos::wait(&list, Some(LONG)).unwrap().expect("a read");
        assert_eq!(reads[over].result(), Some(Ok(1)));
        assert_eq!(reads[over].take_buffer().unwrap(), b"1");
        another.read(fifo, Vec::with_capacity(1), 0).unwrap();
        let err = other.sync(&file, true).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::WouldBlock);

        // Dropped, they give their places back: as many can be started
        // again.
        reads[over] = another;
        release(fifo, &reads);
        drop(reads);
        let (reads, refused) = fill(fifo, limit);
        assert_eq!(refused.kind(), ErrorKind::WouldBlock);
        assert_eq!(reads.len(), limit);
        release(fifo, &reads);
    }

    #[test]
    fn cancel() {
        let _serial = serial();
        let limit = macos::limits().unwrap().process as usize;
        let fifo = Fifo::new("io_macos_cancel");
        let fifo = &fifo.0;

        // The kernel starts on as many reads as it has threads for, and
        // those wait; the others are queued, and can be given up.
        let mut reads = vec![running_read(fifo)];
        reads.extend(fill(fifo, limit).0);
        assert_eq!(reads.len(), limit);
        std::thread::sleep(Duration::from_millis(200));
        let cancelled: Vec<bool> = reads.iter().map(|read| read.cancel().unwrap()).collect();
        let given_up = cancelled.iter().filter(|&&cancelled| cancelled).count();
        note!(
            "io::macos: of {limit} reads that wait, {given_up} were cancelled and {} run",
            limit - given_up
        );
        let mut running = Vec::new();
        for (mut read, cancelled) in reads.into_iter().zip(cancelled) {
            if cancelled {
                // Over at once, and nothing more to cancel.
                assert!(!read.is_pending());
                let err = read.result().expect("it is over").unwrap_err();
                assert_eq!(err.kind(), ErrorKind::Canceled);
                assert_eq!(read.cancel(), Ok(false));
                assert_eq!(macos::wait(&[&read], Some(Duration::ZERO)), Ok(Some(0)));
                assert_eq!(read.take_buffer().unwrap(), b"");
            } else {
                // It runs, and goes on running.
                assert!(read.is_pending());
                assert_eq!(read.cancel(), Ok(false));
                running.push(read);
            }
        }
        assert!(!running.is_empty());
        assert_eq!(
            io::write(fifo, &vec![b'c'; running.len()]),
            Ok(running.len())
        );
        for mut read in running {
            assert_eq!(finish(&read), Ok(1));
            assert_eq!(read.take_buffer().unwrap(), b"c");
        }
    }

    #[test]
    fn cancel_at_once() {
        let _serial = serial();
        let dir = common::tmp_dir("io_macos_cancel_at_once");
        let path = dir.join("data");
        let file = open(&path, &read_write());
        // A write that is cancelled was not made, and one that is not was
        // made whole: which of the two is the kernel's to say.
        const LEN: usize = 1 << 20;
        let mut write = Operation::new();
        let mut given_up = 0;
        for round in 0..32u8 {
            let offset = round as u64 * LEN as u64;
            write.write(&file, vec![round + 1; LEN], offset).unwrap();
            let cancelled = write.cancel().unwrap();
            let outcome = finish(&write);
            let mut written = vec![0u8; LEN];
            let read = io::read_at(&file, &mut written, offset).unwrap();
            if cancelled {
                given_up += 1;
                assert_eq!(outcome.unwrap_err().kind(), ErrorKind::Canceled);
                // Nothing of it is in the file, which may end before it.
                assert!(written[..read].iter().all(|&byte| byte == 0));
            } else {
                assert_eq!(outcome, Ok(LEN));
                assert_eq!(read, LEN);
                assert!(written.iter().all(|&byte| byte == round + 1));
            }
            assert_eq!(write.take_buffer().unwrap().len(), LEN);
        }
        note!("io::macos: of 32 writes cancelled at once, {given_up} were not made");
        // A thread of the kernel has to wake up to start on a write, and
        // the cancellation comes from the thread that submitted it: all
        // 32 were given up on the two systems this was run on. That none
        // is would mean the cancellation is not tested here, and on
        // macOS 26 nowhere (see `cancel`).
        assert!(given_up > 0, "none of 32 writes was cancelled");
    }

    #[test]
    fn dropped_in_flight() {
        let _serial = serial();
        let limit = macos::limits().unwrap().process as usize;
        let fifo = Fifo::new("io_macos_dropped");
        let fifo = &fifo.0;

        // An operation that runs is waited for, and has written to memory
        // that was still there: it took the byte.
        let read = running_read(fifo);
        let start = Instant::now();
        std::thread::scope(|scope| {
            scope.spawn(|| {
                std::thread::sleep(Duration::from_millis(150));
                io::write(fifo, b"d").unwrap();
            });
            drop(read);
        });
        let waited = start.elapsed();
        assert!(waited >= Duration::from_millis(150), "{waited:?}");
        assert!(waited < Duration::from_secs(4), "{waited:?}");
        let again = running_read(fifo);
        assert!(again.is_pending(), "the byte was not read");
        io::write(fifo, b"e").unwrap();
        assert_eq!(finish(&again), Ok(1));

        // Operations on a file, dropped as soon as they are started:
        // cancelled or run to their end, as the kernel has it.
        let dir = common::tmp_dir("io_macos_dropped_file");
        let path = dir.join("data");
        std::fs::write(&path, vec![5u8; 1 << 20]).unwrap();
        let file = open(&path, &read_write());
        for round in 0..100 {
            let mut operation = Operation::new();
            match round % 3 {
                0 => operation.read(&file, Vec::with_capacity(1 << 20), 0),
                1 => operation.write(&file, vec![5u8; 1 << 20], 0),
                _ => operation.sync(&file, round % 2 == 0),
            }
            .unwrap();
        }
        assert!(std::fs::read(&path).unwrap() == vec![5u8; 1 << 20]);

        // Each gave its place back.
        let (reads, refused) = fill(fifo, limit);
        assert_eq!(refused.kind(), ErrorKind::WouldBlock);
        assert_eq!(reads.len(), limit);
        release(fifo, &reads);
    }

    #[test]
    fn kept_memory() {
        let _serial = serial();
        let dir = common::tmp_dir("io_macos_kept");
        let path = dir.join("data");
        let file = open(&path, &read_write());
        let mut operation = Operation::new();

        // Written from memory that is not a `Vec`, and read into the
        // middle of an array.
        static DATA: [u8; 12] = *b"kept memory!";
        // SAFETY: a static lives, and nothing writes it.
        unsafe { operation.write_kept(&file, DATA.as_ptr(), DATA.len(), 3) }.unwrap();
        assert_eq!(finish(&operation), Ok(12));
        // There is no buffer to hand back.
        assert_eq!(operation.take_buffer(), None);
        assert_eq!(std::fs::read(&path).unwrap(), b"\0\0\0kept memory!");

        let mut array = [b'.'; 16];
        // SAFETY: the array outlives the operation, which is waited for
        // before the array is looked at.
        unsafe { operation.read_kept(&file, array[2..].as_mut_ptr(), 8, 3) }.unwrap();
        assert_eq!(finish(&operation), Ok(8));
        assert_eq!(operation.take_buffer(), None);
        assert_eq!(&array, b"..kept mem......");
        // The end of the file is a short count, and nothing past it is
        // touched.
        // SAFETY: as above.
        unsafe { operation.read_kept(&file, array.as_mut_ptr(), 16, 11) }.unwrap();
        assert_eq!(finish(&operation), Ok(4));
        assert_eq!(&array, b"ory!pt mem......");
        // No byte of it.
        // SAFETY: nothing is read or written.
        unsafe { operation.read_kept(&file, array.as_mut_ptr(), 0, 0) }.unwrap();
        assert_eq!(finish(&operation), Ok(0));
        assert_eq!(&array, b"ory!pt mem......");
        // And no memory at all, which the kernel refuses whatever the
        // length.
        // SAFETY: nothing is read or written.
        let err = unsafe { operation.read_kept(&file, std::ptr::null_mut(), 0, 0) }.unwrap_err();
        note!("io::macos: a read into no memory at all: {err:?}");
        assert_refused(err, ErrorKind::InvalidInput);
        assert_eq!(operation.result(), None);

        // Refused, nothing is kept.
        let read_only = open(&path, &fs::OpenOptions::new().read(true));
        // SAFETY: a static.
        let err = unsafe { operation.write_kept(&read_only, DATA.as_ptr(), 12, 0) }.unwrap_err();
        assert_refused(err, ErrorKind::BadHandle);
        assert_eq!(operation.result(), None);

        // In flight, the kernel writes when it comes to it: the memory
        // has to be there until then.
        let fifo = Fifo::new("io_macos_kept_fifo");
        let fifo = &fifo.0;
        let mut late = Box::new([0u8; 4]);
        // SAFETY: the box is kept until the operation is over.
        unsafe { operation.read_kept(fifo, late.as_mut_ptr(), 4, 0) }.unwrap();
        assert!(operation.is_pending());
        // SAFETY: a static; nothing is started.
        let err = unsafe { operation.write_kept(&file, DATA.as_ptr(), 12, 0) }.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::ResourceBusy);
        io::write(fifo, b"late").unwrap();
        assert_eq!(finish(&operation), Ok(4));
        assert_eq!(&*late, b"late");
    }

    #[test]
    fn batch() {
        let _serial = serial();
        let dir = common::tmp_dir("io_macos_batch");
        let path = dir.join("data");
        let file = open(&path, &read_write());
        assert_eq!(macos::BATCH_MAX, 16);

        // Nothing to submit.
        let batch = Batch::new();
        assert!(batch.is_empty());
        assert!(format!("{batch:?}").starts_with("Batch"));
        let err = batch.submit(None).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = Batch::default().submit_and_wait().unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);

        // Four writes, started and waited for by one call.
        const PART: usize = 100_000;
        let data: Vec<u8> = (0..4 * PART).map(|i| (i / 7) as u8).collect();
        let mut writes: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
        let mut batch = Batch::new();
        for (i, write) in writes.iter_mut().enumerate() {
            let chunk = data[i * PART..(i + 1) * PART].to_vec();
            batch.write(write, &file, chunk, (i * PART) as u64).unwrap();
        }
        assert_eq!(batch.len(), 4);
        batch.submit_and_wait().unwrap();
        for write in &mut writes {
            // Over: nothing is asked of the kernel but the outcome.
            assert_eq!(write.result(), Some(Ok(PART)));
            assert_eq!(write.take_buffer().unwrap().len(), PART);
        }
        assert!(std::fs::read(&path).unwrap() == data);

        // Four reads, started by one call and waited for one by one;
        // two of them into memory that is kept.
        let mut reads: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
        let mut kept = vec![0u8; 2 * PART];
        let mut batch = Batch::new();
        for (i, read) in reads.iter_mut().enumerate() {
            let offset = (i * PART) as u64;
            if i < 2 {
                batch
                    .read(read, &file, Vec::with_capacity(PART), offset)
                    .unwrap();
            } else {
                // SAFETY: `kept` outlives the operations, which are
                // waited for before it is looked at.
                unsafe {
                    let ptr = kept.as_mut_ptr().add((i - 2) * PART);
                    batch.read_kept(read, &file, ptr, PART, offset).unwrap();
                }
            }
        }
        batch.submit(None).unwrap();
        for (i, read) in reads.iter_mut().enumerate() {
            assert_eq!(finish(read), Ok(PART));
            if i < 2 {
                assert!(read.take_buffer().unwrap() == data[i * PART..(i + 1) * PART]);
            } else {
                assert_eq!(read.take_buffer(), None);
            }
        }
        assert!(kept == data[2 * PART..]);
        // And a write from memory that is kept.
        let mut batch = Batch::new();
        // SAFETY: `kept` outlives the operation.
        unsafe { batch.write_kept(&mut reads[0], &file, kept.as_ptr(), 10, 0) }.unwrap();
        batch.submit_and_wait().unwrap();
        assert_eq!(reads[0].result(), Some(Ok(10)));
        assert_eq!(&std::fs::read(&path).unwrap()[..10], &kept[..10]);

        // A batch that is dropped has started nothing, and the buffers
        // are there to take back.
        let mut batch = Batch::new();
        let [first, second, ..] = &mut writes[..] else {
            unreachable!()
        };
        batch
            .write(first, &file, b"never written".to_vec(), 0)
            .unwrap();
        // What cannot be added: an offset the system cannot hold.
        let err = batch.read(second, &file, Vec::new(), u64::MAX).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert_eq!(batch.len(), 1);
        assert_eq!(writes[0].result(), None);
        assert!(!writes[0].is_pending());
        assert_eq!(
            writes[0].take_buffer().as_deref(),
            Some(&b"never written"[..])
        );
        assert_eq!(&std::fs::read(&path).unwrap()[..10], &kept[..10]);

        // No more than sixteen, and none that is in flight.
        let mut many: Vec<Operation> = (0..17).map(|_| Operation::new()).collect();
        let (last, many) = many.split_last_mut().unwrap();
        let mut batch = Batch::new();
        for operation in many.iter_mut() {
            batch
                .read(operation, &file, Vec::with_capacity(8), 0)
                .unwrap();
        }
        let err = batch
            .read(last, &file, Vec::with_capacity(8), 0)
            .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert_eq!(batch.len(), 16);
        // All sixteen at once is what a process has.
        batch.submit_and_wait().unwrap();
        for operation in many.iter_mut() {
            assert_eq!(operation.result(), Some(Ok(8)));
        }
        let fifo = Fifo::new("io_macos_batch_fifo");
        let fifo = &fifo.0;
        let mut busy = Operation::new();
        busy.read(fifo, Vec::with_capacity(1), 0).unwrap();
        let mut batch = Batch::new();
        let err = batch.read(&mut busy, &file, Vec::new(), 0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::ResourceBusy);
        io::write(fifo, b"b").unwrap();
        assert_eq!(finish(&busy), Ok(1));
    }

    /// Which of `operations` the kernel has, or had: those that were
    /// started. One that was not has nothing to tell, and is not in
    /// flight.
    ///
    /// In that order: an operation that is in flight at the first look
    /// was started, and one that is not is either over, and stays so, or
    /// was never started. Looked at the other way round, an operation
    /// that ends between the two looks is neither over at the first nor
    /// in flight at the second (which is what this did at first, and
    /// failed for about once in thirty runs).
    fn started(operations: &[Operation]) -> Vec<usize> {
        (0..operations.len())
            .filter(|&i| operations[i].is_pending() || operations[i].result().is_some())
            .collect()
    }

    /// What becomes of a batch the kernel refuses a part of.
    #[test]
    fn batch_refused_in_part() {
        let _serial = serial();
        let limit = macos::limits().unwrap().process as usize;
        let dir = common::tmp_dir("io_macos_batch_refused");
        let path = dir.join("data");
        std::fs::write(&path, b"0123456789").unwrap();
        let file = open(&path, &read_write());
        let read_only = open(&path, &fs::OpenOptions::new().read(true));

        // One operation the kernel refuses, between two it would take:
        // whether the call returns at once or waits.
        for wait in [false, true] {
            let mut operations: Vec<Operation> = (0..3).map(|_| Operation::new()).collect();
            let [first, second, third] = &mut operations[..] else {
                unreachable!()
            };
            let mut batch = Batch::new();
            batch.read(first, &file, Vec::with_capacity(4), 0).unwrap();
            batch
                .write(second, &read_only, b"refused".to_vec(), 0)
                .unwrap();
            batch.read(third, &file, Vec::with_capacity(4), 6).unwrap();
            let refusal = if wait {
                batch.submit_and_wait()
            } else {
                batch.submit(None)
            };
            let started = started(&operations);
            note!(
                "io::macos: a batch with a write to a handle open for reading, waited for: \
                 {wait}: {refusal:?}, and started: {started:?}"
            );
            assert_refused(refusal.unwrap_err(), ErrorKind::BadHandle);
            // The one that was refused has started nothing, and its
            // buffer is there to take back.
            assert!(!started.contains(&1));
            assert_eq!(
                operations[1].take_buffer().as_deref(),
                Some(&b"refused"[..])
            );
            // Nor have the others: the kernel looks at the whole batch
            // before it starts any of it.
            assert_eq!(started, []);
            for i in [0, 2] {
                assert!(operations[i].take_buffer().unwrap().is_empty());
            }
            assert_eq!(std::fs::read(&path).unwrap(), b"0123456789");
        }

        // An operation that fails by itself is not a refusal: the batch
        // was started, and waited for.
        let mut operations: Vec<Operation> = (0..2).map(|_| Operation::new()).collect();
        let directory = open(&dir, &fs::OpenOptions::new().read(true));
        let [first, second] = &mut operations[..] else {
            unreachable!()
        };
        let mut batch = Batch::new();
        batch.read(first, &file, Vec::with_capacity(4), 2).unwrap();
        batch
            .read(second, &directory, Vec::with_capacity(4), 0)
            .unwrap();
        let waited = batch.submit_and_wait();
        note!(
            "io::macos: a batch one read of which fails, waited for: {waited:?}, \
             and started: {:?}",
            started(&operations)
        );
        waited.unwrap();
        assert_eq!(operations[0].result(), Some(Ok(4)));
        let err = operations[1].result().expect("it is over").unwrap_err();
        assert_eq!(err.kind(), ErrorKind::IsADirectory);

        // More than the process has places left: the first ones of the
        // batch are started, as many as there are places, and the call
        // says that not all of it was.
        let fifo = Fifo::new("io_macos_batch_limit");
        let fifo = &fifo.0;
        let mut held = Vec::new();
        for _ in 0..limit - 2 {
            let mut read = Operation::new();
            read.read(fifo, Vec::with_capacity(1), 0).unwrap();
            held.push(read);
        }
        let mut four: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
        let mut batch = Batch::new();
        for (i, operation) in four.iter_mut().enumerate() {
            batch
                .read(operation, &file, Vec::with_capacity(2), 2 * i as u64)
                .unwrap();
        }
        let refusal = batch.submit(None);
        let over_limit = started(&four);
        note!(
            "io::macos: a batch of 4 with 2 places left: {refusal:?}, and started: {over_limit:?}"
        );
        // The reads of the file wait their turn behind those of the
        // FIFO, on a system that runs few at a time.
        release(fifo, &held);
        drop(held);
        for &i in &over_limit {
            assert_eq!(finish(&four[i]), Ok(2));
        }
        assert_eq!(refusal.unwrap_err().kind(), ErrorKind::WouldBlock);
        assert_eq!(over_limit, [0, 1]);
        for (i, operation) in four.iter_mut().enumerate() {
            if !over_limit.contains(&i) {
                assert!(operation.take_buffer().unwrap().is_empty());
            }
        }
        // With room for all of it, the same batch is taken whole.
        let mut batch = Batch::new();
        for (i, operation) in four.iter_mut().enumerate() {
            batch
                .read(operation, &file, Vec::with_capacity(2), 2 * i as u64)
                .unwrap();
        }
        batch.submit(None).unwrap();
        assert_eq!(started(&four), [0, 1, 2, 3]);
        for operation in &four {
            assert_eq!(finish(operation), Ok(2));
        }
    }

    /// The signal of the notices, as a `Signal`.
    fn sigio() -> Signal {
        Signal::from_raw(macos::SIGIO)
    }

    /// Waits for events of the poller, through the signals that
    /// interrupt the wait: the one a notice sends may land in this
    /// thread.
    fn poll(poller: &Poller, timeout: Duration) -> Vec<usize> {
        let mut events = [Event::EMPTY; 8];
        loop {
            match poller.wait(&mut events, Some(timeout)) {
                Ok(count) => return events[..count].iter().map(Event::token).collect(),
                Err(error) if error.kind() == ErrorKind::Interrupted => {}
                Err(error) => panic!("{error:?}"),
            }
        }
    }

    /// As [`finish`], through the signals that interrupt the wait.
    fn finish_through_signals(operation: &Operation) -> oscall::Result<usize> {
        loop {
            match macos::wait(&[operation], Some(LONG)) {
                Ok(over) => {
                    assert_eq!(over, Some(0));
                    return operation.result().expect("the operation is over");
                }
                Err(error) if error.kind() == ErrorKind::Interrupted => {}
                Err(error) => panic!("{error:?}"),
            }
        }
    }

    /// Takes what the subscription has: how many signals.
    fn drain(signals: &Signals) -> usize {
        let mut count = 0;
        while let Some(signal) = signals.try_next() {
            assert_eq!(signal, sigio());
            count += 1;
        }
        count
    }

    #[test]
    fn notice_by_signal() {
        let _serial = serial();
        let dir = common::tmp_dir("io_macos_notice");
        let path = dir.join("data");
        let file = open(&path, &read_write());
        let fifo = Fifo::new("io_macos_notice_fifo");
        let fifo = &fifo.0;
        let signals = Signals::new(&[sigio()]).unwrap();
        let poller = Poller::new().unwrap();
        poller.register_signals(&signals, 7).unwrap();
        const QUIET: Duration = Duration::from_millis(150);

        // An operation in flight tells nothing; over, it is told of by
        // the signal, which the poller waits for.
        let mut read = Operation::new();
        read.set_notice(Some(sigio()));
        read.read(fifo, Vec::with_capacity(4), 0).unwrap();
        assert_eq!(poll(&poller, QUIET), []);
        assert_eq!(signals.try_next(), None);
        io::write(fifo, b"told").unwrap();
        assert_eq!(poll(&poller, LONG), [7]);
        // The outcome is there when the signal is.
        let over = read.result();
        note!("io::macos: when the signal of a notice is told, the outcome is {over:?}");
        assert_eq!(over, Some(Ok(4)));
        assert_eq!(drain(&signals), 1);
        assert_eq!(read.take_buffer().unwrap(), b"told");
        assert_eq!(poll(&poller, QUIET), []);

        // The notice is the operation's: it tells of the next one too,
        // until it is taken away.
        read.read(&file, Vec::with_capacity(4), 0).unwrap();
        assert_eq!(poll(&poller, LONG), [7]);
        assert_eq!(drain(&signals), 1);
        assert_eq!(finish_through_signals(&read), Ok(0));
        read.set_notice(None);
        read.write(&file, b"quiet".to_vec(), 0).unwrap();
        assert_eq!(finish_through_signals(&read), Ok(5));
        assert_eq!(poll(&poller, QUIET), []);
        assert_eq!(signals.try_next(), None);

        // Several that end together: one signal or more, and every
        // outcome is there once the last was told.
        let mut writes: Vec<Operation> = (0..8).map(|_| Operation::new()).collect();
        for (i, write) in writes.iter_mut().enumerate() {
            write.set_notice(Some(sigio()));
            write
                .write(&file, vec![i as u8; 1000], i as u64 * 1000)
                .unwrap();
        }
        let (mut events, mut told) = (0, 0);
        let deadline = Instant::now() + LONG;
        while writes.iter().any(|write| write.result().is_none()) {
            events += poll(&poller, Duration::from_millis(100)).len();
            told += drain(&signals);
            assert!(Instant::now() < deadline);
        }
        // Those that were still on their way.
        std::thread::sleep(QUIET);
        events += poll(&poller, Duration::ZERO).len();
        told += drain(&signals);
        note!(
            "io::macos: 8 writes with a notice: {events} events of the poller, \
             {told} signals taken"
        );
        assert!((1..=8).contains(&told), "{told} signals for 8 operations");
        for write in &writes {
            assert_eq!(write.result(), Some(Ok(1000)));
        }

        // A batch is told of once, when the last of it is over, whatever
        // its operations were set to do.
        let mut reads: Vec<Operation> = (0..3).map(|_| Operation::new()).collect();
        let mut batch = Batch::new();
        for read in reads.iter_mut() {
            read.set_notice(Some(sigio()));
            batch.read(read, fifo, Vec::with_capacity(1), 0).unwrap();
        }
        batch.submit(Some(sigio())).unwrap();
        assert_eq!(poll(&poller, QUIET), []);
        io::write(fifo, b"12").unwrap();
        let deadline = Instant::now() + LONG;
        while reads.iter().filter(|read| read.result().is_some()).count() < 2 {
            std::thread::sleep(Duration::from_millis(5));
            assert!(Instant::now() < deadline);
        }
        let early = poll(&poller, QUIET);
        note!("io::macos: with 2 of the 3 reads of a batch over, the poller has {early:?}");
        assert_eq!(early, []);
        assert_eq!(signals.try_next(), None);
        io::write(fifo, b"3").unwrap();
        assert_eq!(poll(&poller, LONG), [7]);
        assert_eq!(drain(&signals), 1);
        for read in &reads {
            assert_eq!(read.result(), Some(Ok(1)));
        }
        // And without a notice, of nothing.
        let mut batch = Batch::new();
        for read in reads.iter_mut() {
            batch.read(read, &file, Vec::with_capacity(1), 0).unwrap();
        }
        batch.submit(None).unwrap();
        for read in &reads {
            assert_eq!(finish_through_signals(read), Ok(1));
        }
        assert_eq!(poll(&poller, QUIET), []);
        assert_eq!(signals.try_next(), None);

        // What is no signal for a notice is refused with the operation.
        for number in [0, -1, 1000, oscall::process::unix::SIGKILL] {
            let mut refused = Operation::new();
            refused.set_notice(Some(Signal::from_raw(number)));
            match refused.read(&file, Vec::with_capacity(1), 0) {
                Err(error) => {
                    note!("io::macos: a notice by the signal {number} is refused: {error:?}");
                    assert_refused(error, ErrorKind::InvalidInput);
                }
                Ok(()) => panic!("a notice by the signal {number} was taken"),
            }
            assert_eq!(refused.result(), None);
        }

        // With nobody listening any more, the signal of a notice is
        // discarded: the process goes on.
        poller.deregister_signals(&signals).unwrap();
        drop(signals);
        let mut last = Operation::new();
        last.set_notice(Some(sigio()));
        last.write(&file, b"nobody listens".to_vec(), 0).unwrap();
        assert_eq!(finish_through_signals(&last), Ok(14));
        std::thread::sleep(QUIET);
    }

    /// The name of the variable that makes this program the helper of
    /// [`dropped_and_never_over`]: the path of its FIFO.
    const HELPER: &str = "OSCALL_IO_MACOS_HELPER";

    /// An operation that never ends is given up after a few seconds, and
    /// its place with it. That is for a process of its own: the place is
    /// lost for good.
    #[test]
    fn dropped_and_never_over() {
        let _serial = serial();
        let path = common::tmp_dir("io_macos_never_over").join("fifo");
        fs::unix::mkfifo(&path, 0o600).unwrap();
        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["--exact", "operation::helper", "--nocapture"])
            .env(HELPER, &path)
            .status()
            .unwrap();
        assert!(status.success(), "{status:?}");
    }

    #[test]
    fn helper() {
        let Some(path) = std::env::var_os(HELPER) else {
            return;
        };
        let limit = macos::limits().unwrap().process as usize;
        let fifo = Fifo::open(std::path::Path::new(&path));
        let fifo = &fifo.0;
        let read = running_read(fifo);
        let start = Instant::now();
        drop(read);
        let waited = start.elapsed();
        assert!(waited >= Duration::from_secs(4), "{waited:?}");
        assert!(waited < Duration::from_secs(30), "{waited:?}");

        // The kernel still has the operation, which holds its place.
        let (reads, refused) = fill(fifo, limit);
        assert_eq!(refused.kind(), ErrorKind::WouldBlock);
        assert_eq!(reads.len(), limit - 1);
        // The byte for the read that was given up, which the kernel
        // writes to the memory left to it; without it the process would
        // not end.
        let mut running = 1;
        for read in &reads {
            if !read.cancel().unwrap() {
                running += 1;
            }
        }
        assert_eq!(io::write(fifo, &vec![b'h'; running]), Ok(running));
        for read in &reads {
            if read.result().is_none() {
                assert_eq!(finish(read), Ok(1));
            }
        }
        // And over, it holds its place still: nothing takes its outcome.
        std::thread::sleep(Duration::from_millis(200));
        drop(reads);
        let (reads, _) = fill(fifo, limit);
        assert_eq!(reads.len(), limit - 1);
        release(fifo, &reads);
    }
}