oscall 0.0.2

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
//! `oscall::io`: reading and writing on handles, pipes, standard handles.

mod common;

use std::fs::File;
use std::io::{Read, Seek, Write};

use oscall::io::{self, IoSlice, IoSliceMut, SeekFrom};
use oscall::{AsHandle, BorrowedHandle, ErrorKind, RawHandle};

use common::handle_of;

/// Opens `path` for reading and writing with `std`, creating it empty.
fn create(path: &std::path::Path) -> File {
    File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)
        .unwrap()
}

fn write_all(handle: impl AsHandle, mut buf: &[u8]) {
    while !buf.is_empty() {
        let n = io::write(handle.as_handle(), buf).unwrap();
        assert!(n > 0 && n <= buf.len());
        buf = &buf[n..];
    }
}

/// Reads until `buf` is full or the end is reached.
fn read_full(handle: impl AsHandle, buf: &mut [u8]) -> usize {
    let mut done = 0;
    while done < buf.len() {
        match io::read(handle.as_handle(), &mut buf[done..]).unwrap() {
            0 => break,
            n => done += n,
        }
    }
    done
}

/// A handle value that is never open.
fn invalid_handle() -> BorrowedHandle<'static> {
    // A WASI descriptor is unsigned: take one that is merely not open.
    #[cfg(target_os = "wasi")]
    let raw: RawHandle = 123_456;
    // On Windows -1 is a pseudo-handle, of the current process: take a
    // value no handle of a test process has.
    #[cfg(windows)]
    let raw = 0x7ffc_0000usize as RawHandle;
    #[cfg(not(any(windows, target_os = "wasi")))]
    let raw: RawHandle = -1;
    // SAFETY: the value is not an open handle, and is only used to check
    // that the system refuses it.
    unsafe { BorrowedHandle::borrow_raw(raw) }
}

#[test]
fn read_write() {
    let dir = common::tmp_dir("io-read-write");
    let path = dir.join("file");

    // Written by oscall, read by std.
    let mut file = create(&path);
    write_all(handle_of(&file), b"hello, ");
    write_all(handle_of(&file), b"world");
    assert_eq!(io::write(handle_of(&file), b"").unwrap(), 0);
    assert_eq!(std::fs::read(&path).unwrap(), b"hello, world");

    // The position is the handle's own, shared with std.
    assert_eq!(file.stream_position().unwrap(), 12);
    file.rewind().unwrap();

    // Written by std (above, in effect) and read by oscall.
    let mut buf = [0u8; 5];
    assert_eq!(read_full(handle_of(&file), &mut buf), 5);
    assert_eq!(&buf, b"hello");
    let mut rest = [0u8; 64];
    assert_eq!(read_full(handle_of(&file), &mut rest), 7);
    assert_eq!(&rest[..7], b", world");
    // At the end of the file, and with an empty buffer.
    assert_eq!(io::read(handle_of(&file), &mut rest).unwrap(), 0);
    assert_eq!(io::read(handle_of(&file), &mut []).unwrap(), 0);

    file.write_all(b"!").unwrap();
    file.rewind().unwrap();
    let mut all = Vec::new();
    file.read_to_end(&mut all).unwrap();
    assert_eq!(all, b"hello, world!");
}

#[test]
fn bad_handle() {
    let bad = invalid_handle();
    let mut buf = [0u8; 4];
    assert_eq!(io::read(bad, &mut buf).unwrap_err(), ErrorKind::BadHandle);
    assert_eq!(io::write(bad, b"x").unwrap_err(), ErrorKind::BadHandle);
    assert_eq!(
        io::read_at(bad, &mut buf, 0).unwrap_err(),
        ErrorKind::BadHandle
    );
    assert_eq!(
        io::write_at(bad, b"x", 0).unwrap_err(),
        ErrorKind::BadHandle
    );
    assert_eq!(
        io::seek(bad, SeekFrom::Start(0)).unwrap_err(),
        ErrorKind::BadHandle
    );
    assert_eq!(
        io::write_vectored(bad, &[IoSlice::new(b"x")]).unwrap_err(),
        ErrorKind::BadHandle
    );
    assert_eq!(
        io::read_vectored(bad, &mut [IoSliceMut::new(&mut buf)]).unwrap_err(),
        ErrorKind::BadHandle
    );
    assert!(!io::is_terminal(bad));
    // WASI can neither duplicate nor pass on a handle: see `unsupported`.
    #[cfg(not(target_os = "wasi"))]
    {
        assert_eq!(io::duplicate(bad).unwrap_err(), ErrorKind::BadHandle);
        assert_eq!(io::is_inheritable(bad).unwrap_err(), ErrorKind::BadHandle);
        assert_eq!(
            io::set_inheritable(bad, true).unwrap_err(),
            ErrorKind::BadHandle
        );
    }
}

#[test]
fn positional() {
    let dir = common::tmp_dir("io-positional");
    let path = dir.join("file");
    let mut file = create(&path);
    file.write_all(b"0123456789").unwrap();

    let mut buf = [0u8; 4];
    assert_eq!(io::read_at(handle_of(&file), &mut buf, 3).unwrap(), 4);
    assert_eq!(&buf, b"3456");
    // A short read at the end, then nothing at and after it.
    assert_eq!(io::read_at(handle_of(&file), &mut buf, 8).unwrap(), 2);
    assert_eq!(&buf[..2], b"89");
    assert_eq!(io::read_at(handle_of(&file), &mut buf, 10).unwrap(), 0);
    assert_eq!(io::read_at(handle_of(&file), &mut buf, 1000).unwrap(), 0);

    assert_eq!(io::write_at(handle_of(&file), b"ab", 2).unwrap(), 2);
    // Past the end: the gap is zeroes.
    assert_eq!(io::write_at(handle_of(&file), b"z", 12).unwrap(), 1);
    assert_eq!(std::fs::read(&path).unwrap(), b"01ab456789\0\0z");

    // Everywhere but on Windows, the position did not move.
    #[cfg(not(windows))]
    assert_eq!(file.stream_position().unwrap(), 10);
}

/// Marks a file sparse on Windows, where a file is not unless asked: the
/// gap before a far offset would otherwise be written out as zeroes.
#[cfg(windows)]
fn make_sparse(file: &File) {
    use std::os::windows::io::AsRawHandle;

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn DeviceIoControl(
            handle: *mut core::ffi::c_void,
            code: u32,
            input: *const core::ffi::c_void,
            input_len: u32,
            output: *mut core::ffi::c_void,
            output_len: u32,
            returned: *mut u32,
            overlapped: *mut core::ffi::c_void,
        ) -> i32;
    }
    const FSCTL_SET_SPARSE: u32 = 0x000900c4;
    let mut returned = 0;
    // SAFETY: the request takes no buffer when it sets the flag.
    let ok = unsafe {
        DeviceIoControl(
            file.as_raw_handle(),
            FSCTL_SET_SPARSE,
            std::ptr::null(),
            0,
            std::ptr::null_mut(),
            0,
            &mut returned,
            std::ptr::null_mut(),
        )
    };
    assert_ne!(ok, 0, "{}", std::io::Error::last_os_error());
}

#[cfg(not(windows))]
fn make_sparse(_: &File) {}

/// Offsets that do not fit in 32 bits, to prove the 64-bit paths of 32-bit
/// targets. The file is sparse: it takes no room.
#[test]
fn large_offsets() {
    const FAR: u64 = (5 << 30) + 3; // 5 GiB and a bit.

    let dir = common::tmp_dir("io-large-offsets");
    let path = dir.join("file");
    let mut file = create(&path);
    make_sparse(&file);

    assert_eq!(io::write_at(handle_of(&file), b"far", FAR).unwrap(), 3);
    assert_eq!(file.metadata().unwrap().len(), FAR + 3);

    let mut buf = [0u8; 8];
    assert_eq!(io::read_at(handle_of(&file), &mut buf, FAR - 2).unwrap(), 5);
    assert_eq!(&buf[..5], b"\0\0far");
    assert_eq!(io::read_at(handle_of(&file), &mut buf, FAR + 3).unwrap(), 0);
    // The low 32 bits alone would land here.
    assert_eq!(io::read_at(handle_of(&file), &mut buf, 3).unwrap(), 8);
    assert_eq!(buf, [0; 8]);

    // Seeking: to a far offset, relative to it, and from the end.
    let h = handle_of(&file);
    assert_eq!(io::seek(h, SeekFrom::Start(FAR)).unwrap(), FAR);
    assert_eq!((&file).stream_position().unwrap(), FAR);
    assert_eq!(io::seek(h, SeekFrom::Current(1)).unwrap(), FAR + 1);
    assert_eq!(io::read(h, &mut buf).unwrap(), 2);
    assert_eq!(&buf[..2], b"ar");
    assert_eq!(io::seek(h, SeekFrom::End(0)).unwrap(), FAR + 3);
    assert_eq!(io::seek(h, SeekFrom::End(-3)).unwrap(), FAR);
    assert_eq!(io::seek(h, SeekFrom::Current(-(FAR as i64))).unwrap(), 0);
    assert_eq!(
        io::seek(h, SeekFrom::Current((6 << 30) + 1)).unwrap(),
        (6 << 30) + 1
    );
    // Sequential I/O at a far position.
    assert_eq!(io::seek(h, SeekFrom::Start(FAR + 3)).unwrap(), FAR + 3);
    write_all(h, b"ther");
    file.seek(std::io::SeekFrom::Start(FAR)).unwrap();
    let mut end = Vec::new();
    file.read_to_end(&mut end).unwrap();
    assert_eq!(end, b"farther");

    drop(file);
    std::fs::remove_file(&path).unwrap();
}

#[test]
fn seek() {
    let dir = common::tmp_dir("io-seek");
    let mut file = create(&dir.join("file"));
    file.write_all(b"0123456789").unwrap();
    let h = handle_of(&file);

    assert_eq!(io::seek(h, SeekFrom::Current(0)).unwrap(), 10);
    assert_eq!(io::seek(h, SeekFrom::Start(4)).unwrap(), 4);
    assert_eq!((&file).stream_position().unwrap(), 4);
    assert_eq!(io::seek(h, SeekFrom::Current(-3)).unwrap(), 1);
    assert_eq!(io::seek(h, SeekFrom::End(-1)).unwrap(), 9);
    let mut buf = [0u8; 4];
    assert_eq!(io::read(h, &mut buf).unwrap(), 1);
    assert_eq!(buf[0], b'9');
    // After the end is a valid position.
    assert_eq!(io::seek(h, SeekFrom::End(5)).unwrap(), 15);
    assert_eq!(io::read(h, &mut buf).unwrap(), 0);

    // Before the start is not, nor is an offset no file can have.
    assert_eq!(
        io::seek(h, SeekFrom::Current(-16)).unwrap_err(),
        ErrorKind::InvalidInput
    );
    assert_eq!(
        io::seek(h, SeekFrom::End(-11)).unwrap_err(),
        ErrorKind::InvalidInput
    );
    assert_eq!(
        io::seek(h, SeekFrom::Start(u64::MAX)).unwrap_err(),
        ErrorKind::InvalidInput
    );
    assert_eq!(io::seek(h, SeekFrom::Current(0)).unwrap(), 15);
}

#[test]
fn vectored() {
    let dir = common::tmp_dir("io-vectored");
    let path = dir.join("file");
    let mut file = create(&path);

    // Windows writes one buffer per call: go on until everything is out.
    let parts: [&[u8]; 4] = [b"", b"one ", b"two ", b"three"];
    let total: usize = parts.iter().map(|p| p.len()).sum();
    let mut done = 0;
    while done < total {
        // The slices that remain after `done` bytes.
        let mut skip = done;
        let mut slices = Vec::new();
        for part in parts {
            let cut = skip.min(part.len());
            skip -= cut;
            slices.push(IoSlice::new(&part[cut..]));
        }
        let n = io::write_vectored(handle_of(&file), &slices).unwrap();
        assert!(n > 0 && done + n <= total);
        // So does wasmtime. Elsewhere, one call writes it all.
        #[cfg(not(any(windows, target_os = "wasi")))]
        assert_eq!(n, total);
        done += n;
    }
    assert_eq!(std::fs::read(&path).unwrap(), b"one two three");
    assert_eq!(io::write_vectored(handle_of(&file), &[]).unwrap(), 0);
    assert_eq!(
        io::write_vectored(handle_of(&file), &[IoSlice::new(b"")]).unwrap(),
        0
    );

    file.rewind().unwrap();
    let mut a = [0u8; 4];
    let mut b = [0u8; 0];
    let mut c = [0u8; 20];
    let n = {
        let mut bufs = [
            IoSliceMut::new(&mut a),
            IoSliceMut::new(&mut b),
            IoSliceMut::new(&mut c),
        ];
        io::read_vectored(handle_of(&file), &mut bufs).unwrap()
    };
    #[cfg(not(any(windows, target_os = "wasi")))]
    {
        assert_eq!(n, 13);
        assert_eq!(&c[..9], b"two three");
    }
    // Windows reads into the first buffer only, and a WASI host may.
    #[cfg(windows)]
    assert_eq!(n, 4);
    assert!(n == 4 || n == 13);
    assert_eq!(&a, b"one ");
    assert_eq!(io::read_vectored(handle_of(&file), &mut []).unwrap(), 0);
}

#[test]
fn io_slices() {
    let data = *b"abc";
    let slice = IoSlice::new(&data);
    assert_eq!(slice.as_slice(), b"abc");
    assert_eq!(&*slice, b"abc");
    assert_eq!(slice.len(), 3);
    let copy = slice;
    assert_eq!(format!("{copy:?}"), format!("{:?}", b"abc"));
    // The slice outlives the `IoSlice`.
    let inner: &[u8] = IoSlice::new(&data).as_slice();
    assert_eq!(inner, b"abc");

    let mut buf = *b"xyz";
    let mut slice = IoSliceMut::new(&mut buf);
    assert_eq!(slice.as_slice(), b"xyz");
    slice.as_mut_slice()[0] = b'X';
    slice[1] = b'Y';
    assert_eq!(&*slice, b"XYz");
    assert_eq!(format!("{slice:?}"), format!("{:?}", b"XYz"));
    assert_eq!(&buf, b"XYz");

    // They are laid out as the system's own vectored I/O structure.
    #[cfg(not(windows))]
    assert_eq!(size_of::<IoSlice<'_>>(), size_of::<std::io::IoSlice<'_>>());
    assert_eq!(
        size_of::<IoSliceMut<'_>>(),
        size_of::<std::io::IoSliceMut<'_>>()
    );

    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<IoSlice<'_>>();
    assert_send_sync::<IoSliceMut<'_>>();
}

// WASI has no pipes and cannot duplicate or pass on a handle.
#[cfg(target_os = "wasi")]
#[test]
fn unsupported() {
    let dir = common::tmp_dir("io-unsupported");
    let file = create(&dir.join("file"));
    assert_eq!(io::pipe().unwrap_err(), ErrorKind::Unsupported);
    assert_eq!(
        io::duplicate(handle_of(&file)).unwrap_err(),
        ErrorKind::Unsupported
    );
    assert_eq!(
        io::is_inheritable(handle_of(&file)).unwrap_err(),
        ErrorKind::Unsupported
    );
    assert_eq!(
        io::set_inheritable(handle_of(&file), true).unwrap_err(),
        ErrorKind::Unsupported
    );
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn pipe() {
    let (reader, writer) = io::pipe().unwrap();
    write_all(&writer, b"through the pipe");
    let mut buf = [0u8; 64];
    let n = io::read(&reader, &mut buf).unwrap();
    assert_eq!(&buf[..n], b"through the pipe");

    // Vectored I/O works on pipes too.
    let n = io::write_vectored(&writer, &[IoSlice::new(b"ab"), IoSlice::new(b"cd")]).unwrap();
    #[cfg(not(windows))]
    assert_eq!(n, 4);
    #[cfg(windows)]
    assert_eq!(n, 2);
    let mut small = [0u8; 4];
    let got = io::read_vectored(&reader, &mut [IoSliceMut::new(&mut small)]).unwrap();
    assert_eq!(got, n);
    assert_eq!(&small[..n], &b"abcd"[..n]);

    // A pipe has no position. (Windows does not always say so.)
    #[cfg(not(windows))]
    {
        assert_eq!(
            io::seek(&reader, SeekFrom::Current(0)).unwrap_err(),
            ErrorKind::NotSeekable
        );
        assert_eq!(
            io::read_at(&reader, &mut buf, 0).unwrap_err(),
            ErrorKind::NotSeekable
        );
    }
    assert!(!io::is_terminal(&reader));
    assert!(!io::is_terminal(&writer));

    // What is in the pipe can still be read once the write end is closed;
    // then comes the end.
    write_all(&writer, b"last");
    drop(writer);
    assert_eq!(read_full(&reader, &mut buf), 4);
    assert_eq!(&buf[..4], b"last");
    assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);
    assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);

    // Writing to a pipe nobody reads fails, and does not kill the process.
    let (reader, writer) = io::pipe().unwrap();
    drop(reader);
    assert_eq!(io::write(&writer, b"x").unwrap_err(), ErrorKind::BrokenPipe);
}

/// A pipe that does not wait says so instead, in both directions.
#[cfg(not(target_os = "wasi"))]
#[test]
fn nonblocking_pipe() {
    let (reader, writer) = io::pipe().unwrap();
    let mut buf = [0u8; 4096];

    // Reading.
    io::set_nonblocking(&reader, true).unwrap();
    let error = io::read(&reader, &mut buf).unwrap_err();
    assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
    let error = io::read_vectored(&reader, &mut [IoSliceMut::new(&mut buf)]).unwrap_err();
    assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
    write_all(&writer, b"some data");
    let n = io::read(&reader, &mut buf).unwrap();
    assert_eq!(&buf[..n], b"some data");
    assert_eq!(
        io::read(&reader, &mut buf).unwrap_err(),
        ErrorKind::WouldBlock
    );
    // Setting it again changes nothing; a duplicate shares the mode.
    io::set_nonblocking(&reader, true).unwrap();
    let duplicate = io::duplicate(&reader).unwrap();
    assert_eq!(
        io::read(&duplicate, &mut buf).unwrap_err(),
        ErrorKind::WouldBlock
    );
    drop(duplicate);

    // Writing: each end has its own mode, and the write end still waits.
    // Fill the pipe once it does not: what fits is written, then nothing.
    io::set_nonblocking(&writer, true).unwrap();
    let chunk = [0x5au8; 65536];
    let mut written = 0usize;
    let error = loop {
        match io::write(&writer, &chunk) {
            Ok(n) => {
                assert!(n > 0 && n <= chunk.len(), "{n} after {written}");
                written += n;
                // No pipe holds this much.
                assert!(written < 64 << 20, "the pipe never fills");
            }
            Err(error) => break error,
        }
    };
    assert_eq!(error, ErrorKind::WouldBlock, "{error:?} after {written}");
    assert!(written > 0);
    let error = io::write_vectored(&writer, &[IoSlice::new(&chunk)]).unwrap_err();
    assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
    // An empty write is not one that would wait.
    assert_eq!(io::write(&writer, &[]).unwrap(), 0);

    // Everything that went in comes out, then the pipe is empty again and
    // takes more.
    let mut read = 0usize;
    let error = loop {
        match io::read(&reader, &mut buf) {
            Ok(n) => {
                assert!(n > 0);
                assert!(buf[..n].iter().all(|&byte| byte == 0x5a));
                read += n;
            }
            Err(error) => break error,
        }
    };
    assert_eq!(error, ErrorKind::WouldBlock, "{error:?} after {read}");
    assert_eq!(read, written);
    assert_eq!(io::write(&writer, b"more").unwrap(), 4);
    let n = io::read(&reader, &mut buf).unwrap();
    assert_eq!(&buf[..n], b"more");

    // Back to waiting: a read waits for the write of another thread.
    io::set_nonblocking(&reader, false).unwrap();
    io::set_nonblocking(&writer, false).unwrap();
    std::thread::scope(|scope| {
        scope.spawn(|| {
            std::thread::sleep(std::time::Duration::from_millis(100));
            write_all(&writer, b"late");
        });
        let n = io::read(&reader, &mut buf).unwrap();
        assert_eq!(&buf[..n], b"late");
    });

    // The end of the pipe is the end, not a wait; and a pipe nobody reads
    // is broken, not full.
    io::set_nonblocking(&reader, true).unwrap();
    write_all(&writer, b"last");
    drop(writer);
    let n = io::read(&reader, &mut buf).unwrap();
    assert_eq!(&buf[..n], b"last");
    assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);
    assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);

    let (reader, writer) = io::pipe().unwrap();
    io::set_nonblocking(&writer, true).unwrap();
    drop(reader);
    let error = io::write(&writer, b"x").unwrap_err();
    assert_eq!(error, ErrorKind::BrokenPipe, "{error:?}");

    assert_eq!(
        io::set_nonblocking(invalid_handle(), true).unwrap_err(),
        ErrorKind::BadHandle
    );
}

/// One end that waits and one that does not still move everything from one
/// to the other, whichever is which and whatever the sizes they use.
#[cfg(not(target_os = "wasi"))]
#[test]
fn nonblocking_end_to_blocking_end() {
    use std::time::{Duration, Instant};

    const TOTAL: usize = 1 << 20;
    let data: Vec<u8> = (0..TOTAL).map(|i| (i % 253) as u8).collect();
    // The reader's buffer and the writer's chunk: smaller than a pipe,
    // larger, and one of each.
    for (read_size, write_size) in [(4096, 65536), (65536, 4096), (300, 100_000), (100_000, 300)] {
        // The writer does not wait, the reader does.
        let (reader, writer) = io::pipe().unwrap();
        io::set_nonblocking(&writer, true).unwrap();
        std::thread::scope(|scope| {
            let received = scope.spawn(|| {
                let mut all = Vec::new();
                let mut buf = vec![0u8; read_size];
                loop {
                    match io::read(&reader, &mut buf).unwrap() {
                        0 => return all,
                        n => all.extend_from_slice(&buf[..n]),
                    }
                }
            });
            let mut sent = 0;
            let mut last_progress = Instant::now();
            while sent < TOTAL {
                let end = (sent + write_size).min(TOTAL);
                match io::write(&writer, &data[sent..end]) {
                    Ok(n) => {
                        assert!(n > 0 && n <= end - sent);
                        sent += n;
                        last_progress = Instant::now();
                    }
                    Err(error) => {
                        assert_eq!(error, ErrorKind::WouldBlock, "{error:?} after {sent}");
                        assert!(
                            last_progress.elapsed() < Duration::from_secs(20),
                            "nothing written for 20 s after {sent} bytes \
                             ({read_size}, {write_size})"
                        );
                        std::thread::yield_now();
                    }
                }
            }
            drop(writer);
            assert!(
                received.join().unwrap() == data,
                "({read_size}, {write_size})"
            );
        });

        // The reader does not wait, the writer does.
        let (reader, writer) = io::pipe().unwrap();
        io::set_nonblocking(&reader, true).unwrap();
        std::thread::scope(|scope| {
            scope.spawn(|| {
                for chunk in data.chunks(write_size) {
                    write_all(&writer, chunk);
                }
                drop(writer);
            });
            let mut all = Vec::new();
            let mut buf = vec![0u8; read_size];
            let mut last_progress = Instant::now();
            loop {
                match io::read(&reader, &mut buf) {
                    Ok(0) => break,
                    Ok(n) => {
                        all.extend_from_slice(&buf[..n]);
                        last_progress = Instant::now();
                    }
                    Err(error) => {
                        assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
                        assert!(
                            last_progress.elapsed() < Duration::from_secs(20),
                            "nothing read for 20 s after {} bytes ({read_size}, {write_size})",
                            all.len()
                        );
                        std::thread::yield_now();
                    }
                }
            }
            assert!(all == data, "({read_size}, {write_size})");
        });
    }
}

/// On a file the mode means nothing: Linux, macOS and WASI take it and go
/// on as before, Windows refuses it.
#[test]
fn nonblocking_file() {
    let dir = common::tmp_dir("io-nonblocking-file");
    let file = create(&dir.join("file"));
    let handle = handle_of(&file);
    let result = io::set_nonblocking(handle, true);
    if cfg!(windows) {
        let error = result.unwrap_err();
        eprintln!("set_nonblocking on a file: {error:?}");
    } else {
        result.unwrap();
        io::set_nonblocking(handle, false).unwrap();
    }
    write_all(handle, b"content");
    io::seek(handle, SeekFrom::Start(0)).unwrap();
    let mut buf = [0u8; 16];
    assert_eq!(read_full(handle, &mut buf), 7);
    // The end of a file is still its end.
    assert_eq!(io::read(handle, &mut buf).unwrap(), 0);
    assert_eq!(
        io::set_nonblocking(invalid_handle(), false).unwrap_err(),
        ErrorKind::BadHandle
    );
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn pipe_between_threads() {
    let (reader, writer) = io::pipe().unwrap();
    let total = 1 << 20; // More than a pipe holds: the writer must wait.
    let thread = std::thread::spawn(move || {
        let chunk: Vec<u8> = (0..4096u32).map(|i| i as u8).collect();
        for _ in 0..total / chunk.len() {
            write_all(&writer, &chunk);
        }
    });
    let mut buf = vec![0u8; 10000];
    let mut received = 0usize;
    loop {
        let n = io::read(&reader, &mut buf).unwrap();
        if n == 0 {
            break;
        }
        for (i, &byte) in buf[..n].iter().enumerate() {
            assert_eq!(byte, ((received + i) % 4096) as u8);
        }
        received += n;
    }
    assert_eq!(received, total);
    thread.join().unwrap();
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn duplicate() {
    let dir = common::tmp_dir("io-duplicate");
    let path = dir.join("file");
    let mut file = create(&path);
    file.write_all(b"0123456789").unwrap();
    file.rewind().unwrap();

    let dup = io::duplicate(handle_of(&file)).unwrap();
    assert_ne!(dup.as_raw(), handle_of(&file).as_raw());
    assert!(!io::is_inheritable(&dup).unwrap());

    // One open file behind both: the position is shared.
    let mut buf = [0u8; 4];
    assert_eq!(io::read(&dup, &mut buf).unwrap(), 4);
    assert_eq!(file.stream_position().unwrap(), 4);
    file.seek(std::io::SeekFrom::Start(8)).unwrap();
    assert_eq!(io::read(&dup, &mut buf).unwrap(), 2);
    assert_eq!(&buf[..2], b"89");

    // Each handle is closed on its own.
    drop(file);
    write_all(&dup, b"ab");
    let again = io::duplicate(&dup).unwrap();
    drop(dup);
    assert_eq!(io::seek(&again, SeekFrom::Current(0)).unwrap(), 12);
    assert_eq!(std::fs::read(&path).unwrap(), b"0123456789ab");

    // A pipe end can be duplicated as well.
    let (reader, writer) = io::pipe().unwrap();
    let writer2 = io::duplicate(&writer).unwrap();
    drop(writer);
    write_all(&writer2, b"x");
    drop(writer2);
    assert_eq!(read_full(&reader, &mut buf), 1);
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn inheritable() {
    // What oscall creates is private to the process, and so is what std
    // opens.
    let (reader, writer) = io::pipe().unwrap();
    assert!(!io::is_inheritable(&reader).unwrap());
    assert!(!io::is_inheritable(&writer).unwrap());
    let dir = common::tmp_dir("io-inheritable");
    let file = create(&dir.join("file"));
    assert!(!io::is_inheritable(handle_of(&file)).unwrap());

    io::set_inheritable(&reader, true).unwrap();
    assert!(io::is_inheritable(&reader).unwrap());
    assert!(!io::is_inheritable(&writer).unwrap());
    // The flag belongs to the handle, not to the object behind it.
    let dup = io::duplicate(&reader).unwrap();
    assert!(!io::is_inheritable(&dup).unwrap());
    io::set_inheritable(&reader, true).unwrap();
    assert!(io::is_inheritable(&reader).unwrap());
    io::set_inheritable(&reader, false).unwrap();
    assert!(!io::is_inheritable(&reader).unwrap());
    io::set_inheritable(&reader, false).unwrap();
    assert!(!io::is_inheritable(&reader).unwrap());
}

#[test]
fn standard_handles() {
    use std::io::IsTerminal;

    // A test process has the three of them.
    let stdin = io::stdin().unwrap();
    let stdout = io::stdout().unwrap();
    let stderr = io::stderr().unwrap();
    #[cfg(not(windows))]
    {
        assert_eq!(stdin.as_raw(), 0);
        assert_eq!(stdout.as_raw(), 1);
        assert_eq!(stderr.as_raw(), 2);
    }
    #[cfg(windows)]
    {
        use std::os::windows::io::AsRawHandle;
        assert_eq!(stdin.as_raw(), std::io::stdin().as_raw_handle());
        assert_eq!(stdout.as_raw(), std::io::stdout().as_raw_handle());
        assert_eq!(stderr.as_raw(), std::io::stderr().as_raw_handle());
    }

    assert_eq!(io::is_terminal(stdin), std::io::stdin().is_terminal());
    assert_eq!(io::is_terminal(stdout), std::io::stdout().is_terminal());
    assert_eq!(io::is_terminal(stderr), std::io::stderr().is_terminal());

    // Nothing is written, but the call goes all the way to the system.
    assert_eq!(io::write(stderr, b"").unwrap(), 0);

    let dir = common::tmp_dir("io-standard-handles");
    let file = create(&dir.join("file"));
    assert!(!io::is_terminal(handle_of(&file)));
}

/// Handles open for overlapped (asynchronous) operation. oscall is given
/// them without knowing, and each of its calls must still return only when
/// its operation is complete: the system writes to the buffer until then.
#[cfg(windows)]
mod overlapped {
    use std::ffi::c_void;
    use std::fs::File;
    use std::os::windows::ffi::OsStrExt;
    use std::os::windows::fs::OpenOptionsExt;
    use std::os::windows::io::FromRawHandle;
    use std::path::PathBuf;
    use std::thread;
    use std::time::{Duration, Instant};

    use oscall::io;

    use super::common::{self, handle_of};

    const FILE_FLAG_OVERLAPPED: u32 = 0x4000_0000;
    const PIPE_ACCESS_DUPLEX: u32 = 3;
    const PIPE_TYPE_MESSAGE: u32 = 4;
    const PIPE_READMODE_MESSAGE: u32 = 2;
    const GENERIC_READ: u32 = 0x8000_0000;
    const GENERIC_WRITE: u32 = 0x4000_0000;
    const OPEN_EXISTING: u32 = 3;
    const ERROR_INVALID_PARAMETER: i32 = 87;

    /// Long enough for a thread to be waiting in its call.
    const SETTLE: Duration = Duration::from_millis(300);

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn CreateNamedPipeW(
            name: *const u16,
            open_mode: u32,
            pipe_mode: u32,
            max_instances: u32,
            out_buffer_size: u32,
            in_buffer_size: u32,
            default_timeout: u32,
            security: *const c_void,
        ) -> *mut c_void;
        fn CreateFileW(
            name: *const u16,
            access: u32,
            share: u32,
            security: *const c_void,
            creation: u32,
            flags: u32,
            template: *mut c_void,
        ) -> *mut c_void;
    }

    /// The two ends of a named pipe that goes both ways: the server end,
    /// made with `flags` and `mode`, and the client end, made with `flags`.
    fn pipe_pair(name: &str, flags: u32, mode: u32) -> (File, File) {
        let name = format!(r"\\.\pipe\oscall-test-{}-{name}", std::process::id());
        let name: Vec<u16> = std::ffi::OsStr::new(&name)
            .encode_wide()
            .chain([0])
            .collect();
        // SAFETY: the name is NUL-terminated; the handles are new.
        unsafe {
            let server = CreateNamedPipeW(
                name.as_ptr(),
                PIPE_ACCESS_DUPLEX | flags,
                mode,
                1,
                4096,
                4096,
                0,
                std::ptr::null(),
            );
            assert_ne!(server as isize, -1, "{}", std::io::Error::last_os_error());
            let server = File::from_raw_handle(server);
            let client = CreateFileW(
                name.as_ptr(),
                GENERIC_READ | GENERIC_WRITE,
                0,
                std::ptr::null(),
                OPEN_EXISTING,
                flags,
                std::ptr::null_mut(),
            );
            assert_ne!(client as isize, -1, "{}", std::io::Error::last_os_error());
            (server, File::from_raw_handle(client))
        }
    }

    fn overlapped_file(name: &str) -> (File, PathBuf) {
        let path = common::tmp_dir(name).join("file");
        let file = File::options()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .custom_flags(FILE_FLAG_OVERLAPPED)
            .open(&path)
            .unwrap();
        (file, path)
    }

    #[test]
    fn file_at_offsets() {
        let (file, path) = overlapped_file("io-overlapped-file");
        let handle = handle_of(&file);
        assert_eq!(io::write_at(handle, b"hello world", 0).unwrap(), 11);
        assert_eq!(io::write_at(handle, b"HELLO", 100).unwrap(), 5);
        let mut buf = [0xffu8; 32];
        assert_eq!(io::read_at(handle, &mut buf, 0).unwrap(), 32);
        assert_eq!(&buf[..11], b"hello world");
        assert_eq!(&buf[11..], &[0; 21]);
        assert_eq!(io::read_at(handle, &mut buf, 98).unwrap(), 7);
        assert_eq!(&buf[..7], b"\0\0HELLO");
        // The end of the file is an error of its own on such a handle.
        assert_eq!(io::read_at(handle, &mut buf, 105).unwrap(), 0);
        assert_eq!(io::read_at(handle, &mut buf, 1 << 40).unwrap(), 0);
        assert_eq!(std::fs::metadata(path).unwrap().len(), 105);
    }

    /// A file open for overlapped operation has no position: the system
    /// refuses a transfer that does not say where. What matters is that
    /// the calls come back with an answer, and that the buffer is not
    /// written afterwards.
    #[test]
    fn file_without_offset() {
        let (file, _) = overlapped_file("io-overlapped-file-no-offset");
        let handle = handle_of(&file);
        assert_eq!(io::write_at(handle, b"0123456789", 0).unwrap(), 10);
        let mut buf = [0xffu8; 4];
        let read = io::read(handle, &mut buf).map_err(|e| e.raw_os_error());
        assert_eq!(read, Err(ERROR_INVALID_PARAMETER), "read: {read:?}");
        assert_eq!(buf, [0xff; 4]);
        let written = io::write(handle, b"abcd").map_err(|e| e.raw_os_error());
        assert_eq!(written, Err(ERROR_INVALID_PARAMETER), "write: {written:?}");
        let mut buf = [0u8; 16];
        assert_eq!(io::read_at(handle, &mut buf, 0).unwrap(), 10);
        assert_eq!(&buf[..10], b"0123456789");
    }

    /// Several threads on one handle: the completion of one's operation
    /// signals the handle for all of them.
    #[test]
    fn file_from_several_threads() {
        let (file, _) = overlapped_file("io-overlapped-file-threads");
        thread::scope(|scope| {
            for thread in 0..4u8 {
                let file = &file;
                scope.spawn(move || {
                    let handle = handle_of(file);
                    let block = [b'a' + thread; 8192];
                    let mut buf = [0u8; 8192];
                    for round in 0..64u64 {
                        let offset = (round * 4 + u64::from(thread)) * 8192;
                        assert_eq!(io::write_at(handle, &block, offset).unwrap(), 8192);
                        assert_eq!(io::read_at(handle, &mut buf, offset).unwrap(), 8192);
                        assert!(buf == block, "thread {thread}, round {round}");
                        buf.fill(0);
                    }
                });
            }
        });
    }

    /// A read that the system leaves pending, and that a writer satisfies
    /// later: the call must wait for it.
    #[test]
    fn pipe_read_completes_later() {
        let (server, client) = pipe_pair("later", FILE_FLAG_OVERLAPPED, 0);
        thread::scope(|scope| {
            scope.spawn(|| {
                thread::sleep(SETTLE);
                assert_eq!(io::write(handle_of(&client), b"late").unwrap(), 4);
            });
            let start = Instant::now();
            let mut buf = [0u8; 16];
            let read = io::read(handle_of(&server), &mut buf);
            let elapsed = start.elapsed();
            let read = read.map_err(|e| e.raw_os_error());
            assert_eq!(read, Ok(4), "read: {read:?} after {elapsed:?}");
            assert_eq!(&buf[..4], b"late");
            assert!(elapsed >= SETTLE - Duration::from_millis(50), "{elapsed:?}");
        });
        // The other way, and the end of the pipe.
        assert_eq!(io::write(handle_of(&server), b"back").unwrap(), 4);
        let mut buf = [0u8; 16];
        assert_eq!(io::read(handle_of(&client), &mut buf).unwrap(), 4);
        assert_eq!(&buf[..4], b"back");
        drop(client);
        assert_eq!(io::read(handle_of(&server), &mut buf).unwrap(), 0);
    }

    /// As above, while another thread completes operations on the same
    /// handle: each signals the handle, and none of them is the read's.
    #[test]
    fn pipe_read_among_other_operations() {
        let (server, client) = pipe_pair("among", FILE_FLAG_OVERLAPPED, 0);
        thread::scope(|scope| {
            let reader = scope.spawn(|| {
                let start = Instant::now();
                let mut buf = [0u8; 16];
                let read = io::read(handle_of(&server), &mut buf);
                let elapsed = start.elapsed();
                let read = read.map_err(|e| e.raw_os_error());
                assert_eq!(read, Ok(4), "read: {read:?} after {elapsed:?}");
                assert_eq!(&buf[..4], b"done");
                elapsed
            });
            let start = Instant::now();
            let mut buf = [0u8; 16];
            while start.elapsed() < SETTLE {
                assert_eq!(io::write(handle_of(&server), b"noise").unwrap(), 5);
                assert_eq!(io::read(handle_of(&client), &mut buf).unwrap(), 5);
                assert_eq!(&buf[..5], b"noise");
                thread::sleep(Duration::from_millis(5));
            }
            assert!(!reader.is_finished());
            assert_eq!(io::write(handle_of(&client), b"done").unwrap(), 4);
            let elapsed = reader.join().unwrap();
            assert!(elapsed >= SETTLE - Duration::from_millis(50), "{elapsed:?}");
        });
    }

    /// A message longer than the buffer is read in pieces: the system
    /// reports the first ones as "more data", which is not a failure.
    #[test]
    fn message_pipe_in_pieces() {
        for (name, flags) in [("message", 0), ("message-ov", FILE_FLAG_OVERLAPPED)] {
            let mode = PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE;
            let (server, client) = pipe_pair(name, flags, mode);
            assert_eq!(io::write(handle_of(&client), b"0123456789").unwrap(), 10);
            assert_eq!(io::write(handle_of(&client), b"abc").unwrap(), 3);
            let read = |len: usize| {
                let mut buf = [0u8; 16];
                let result = io::read(handle_of(&server), &mut buf[..len]);
                let done = result.unwrap_or_else(|e| panic!("{name}: {}", e.raw_os_error()));
                buf[..done].to_vec()
            };
            assert_eq!(read(4), b"0123");
            assert_eq!(read(4), b"4567");
            assert_eq!(read(4), b"89");
            assert_eq!(read(16), b"abc");
        }
    }
}