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
//! Threads: the calling one, and creating others where oscall can.

mod common;

use oscall::{ErrorKind, thread};

/// Runs `f` on a new thread, so that what it does to its thread (name,
/// affinity) does not leak into the other tests. On WASI, which has no
/// threads, it runs in place.
#[cfg_attr(target_family = "wasm", allow(dead_code))]
fn on_new_thread<T: Send>(f: impl FnOnce() -> T + Send) -> T {
    if cfg!(target_os = "wasi") {
        f()
    } else {
        std::thread::scope(|s| s.spawn(f).join().unwrap())
    }
}

#[test]
fn id() {
    let mine = thread::id();
    assert_ne!(mine, 0);
    assert_eq!(thread::id(), mine);
    if cfg!(target_family = "wasm") {
        assert_eq!(mine, 1);
        return; // no other threads
    }

    // Threads alive at the same time have different ids.
    let barrier = std::sync::Barrier::new(4);
    let mut ids = std::thread::scope(|s| {
        let threads: Vec<_> = (0..4)
            .map(|_| {
                s.spawn(|| {
                    let id = thread::id();
                    barrier.wait();
                    assert_eq!(thread::id(), id);
                    id
                })
            })
            .collect();
        threads
            .into_iter()
            .map(|t| t.join().unwrap())
            .collect::<Vec<_>>()
    });
    ids.push(mine);
    assert!(ids.iter().all(|&id| id != 0));
    ids.sort_unstable();
    ids.dedup();
    assert_eq!(ids.len(), 5);
}

// The system's own view of the thread id: the entries of the task directory
// of the process. Not under an emulator, whose /proc is the host's.
#[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86")))]
#[test]
fn id_is_the_systems() {
    on_new_thread(|| {
        let id = thread::id();
        assert_ne!(id, u64::from(std::process::id()), "not the first thread");
        let task = format!("/proc/self/task/{id}/comm");
        if std::path::Path::new("/proc/self/task").exists() {
            assert!(std::path::Path::new(&task).exists(), "{task}");
        }
    });
}

#[test]
fn yield_now() {
    for _ in 0..1000 {
        thread::yield_now();
    }
}

#[test]
fn available_parallelism() {
    let count = thread::available_parallelism().unwrap();
    assert!(count >= 1);
    if cfg!(target_family = "wasm") {
        assert_eq!(count, 1);
    }
    // std counts the same processors, less what a CPU quota takes away (on
    // Linux), or those of one processor group only (on Windows).
    if let Ok(std_count) = std::thread::available_parallelism() {
        assert!(count >= std_count.get(), "{count} < {std_count}");
        if cfg!(target_os = "macos") {
            assert_eq!(count, std_count.get());
        }
    }
}

#[cfg(not(target_family = "wasm"))]
#[test]
fn name() {
    on_new_thread(|| {
        let mut buf = [0u8; 256];
        thread::set_name("oscall-worker").unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), "oscall-worker");

        // Renaming, to something shorter, and to nothing.
        thread::set_name("é").unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), "é");
        thread::set_name("").unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), "");

        // A buffer of exactly the size, and one byte short.
        thread::set_name("exact").unwrap();
        assert_eq!(thread::name(&mut buf[..5]).unwrap(), "exact");
        assert_eq!(
            thread::name(&mut buf[..4]).unwrap_err(),
            ErrorKind::BufferTooSmall
        );
        assert_eq!(
            thread::name(&mut []).unwrap_err(),
            ErrorKind::BufferTooSmall
        );

        // A NUL is refused, and the name stays.
        assert_eq!(
            thread::set_name("a\0b").unwrap_err(),
            ErrorKind::InvalidInput
        );
        assert_eq!(thread::name(&mut buf).unwrap(), "exact");
    });
}

#[cfg(not(target_family = "wasm"))]
#[test]
fn name_is_cut_at_the_limit() {
    // The limit in bytes, with two-byte characters: the cut falls on a
    // character boundary, one byte below an odd limit.
    let limit = if cfg!(windows) {
        255
    } else if cfg!(target_os = "macos") {
        63
    } else {
        15
    };
    on_new_thread(|| {
        let mut buf = [0u8; 256];
        let long = "é".repeat(200);
        thread::set_name(&long).unwrap();
        let name = thread::name(&mut buf).unwrap();
        assert_eq!(name, "é".repeat(limit / 2));

        // And a name of exactly the limit is kept whole.
        let exact = "x".repeat(limit);
        thread::set_name(&exact).unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), exact);
        let over = "x".repeat(limit + 1);
        thread::set_name(&over).unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), exact);
    });
}

// std names the thread with the same system call: each sees the other's.
// (fullrust's std keeps thread names to itself.)
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
#[test]
fn name_matches_std() {
    std::thread::Builder::new()
        .name("oscall-by-std".into())
        .spawn(|| {
            let mut buf = [0u8; 64];
            assert_eq!(thread::name(&mut buf).unwrap(), "oscall-by-std");
        })
        .unwrap()
        .join()
        .unwrap();
}

#[cfg(target_family = "wasm")]
#[test]
fn name_is_unsupported() {
    let mut buf = [0u8; 64];
    assert_eq!(
        thread::set_name("name").unwrap_err(),
        ErrorKind::Unsupported
    );
    assert_eq!(thread::name(&mut buf).unwrap_err(), ErrorKind::Unsupported);
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_affinity() {
    use oscall::thread::linux;

    const WORDS: usize = 8192 / usize::BITS as usize;
    on_new_thread(|| {
        let mut mask = [usize::MAX; WORDS];
        linux::affinity(&mut mask).unwrap();
        let count: usize = mask.iter().map(|w| w.count_ones() as usize).sum();
        assert_eq!(count, thread::available_parallelism().unwrap());

        // An empty set is refused.
        assert_eq!(
            linux::set_affinity(&[0; WORDS]).unwrap_err(),
            ErrorKind::InvalidInput
        );
        assert_eq!(
            linux::set_affinity(&[]).unwrap_err(),
            ErrorKind::InvalidInput
        );

        // Pin the thread to the last processor it is allowed.
        let word = mask.iter().rposition(|&w| w != 0).unwrap();
        let bit = usize::BITS - 1 - mask[word].leading_zeros();
        let mut one = [0usize; WORDS];
        one[word] = 1 << bit;
        // A short mask is enough to set, if it reaches the processor.
        linux::set_affinity(&one[..=word]).unwrap();

        let mut now = [usize::MAX; WORDS];
        linux::affinity(&mut now).unwrap();
        assert_eq!(now, one);
        assert_eq!(thread::available_parallelism().unwrap(), 1);

        // Threads created from here inherit the mask.
        let inherited = std::thread::scope(|s| {
            s.spawn(|| {
                let mut mask = [0usize; WORDS];
                linux::affinity(&mut mask).unwrap();
                mask
            })
            .join()
            .unwrap()
        });
        assert_eq!(inherited, one);

        // And back to the whole set.
        linux::set_affinity(&mask).unwrap();
        linux::affinity(&mut now).unwrap();
        assert_eq!(now, mask);
    });
}

#[cfg(windows)]
#[test]
fn windows_affinity() {
    use oscall::thread::windows;

    on_new_thread(|| {
        let mask = windows::affinity().unwrap();
        assert_ne!(mask, 0);
        assert!(mask.count_ones() as usize <= thread::available_parallelism().unwrap());

        // An empty set is refused.
        assert_eq!(
            windows::set_affinity(0).unwrap_err(),
            ErrorKind::InvalidInput
        );

        // Pin the thread to the last processor it is allowed.
        let one = 1 << (usize::BITS - 1 - mask.leading_zeros());
        windows::set_affinity(one).unwrap();
        assert_eq!(windows::affinity().unwrap(), one);

        // And back to the whole set.
        windows::set_affinity(mask).unwrap();
        assert_eq!(windows::affinity().unwrap(), mask);
    });
}

/// The nice value is the thread's own: one thread raises its value, and
/// the others keep theirs.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_nice() {
    let before = thread::linux::nice().unwrap();
    assert!((-20..=19).contains(&before), "{before}");
    if before < 19 {
        on_new_thread(|| {
            assert_eq!(thread::linux::nice().unwrap(), before);
            thread::linux::set_nice(before + 1).unwrap();
            assert_eq!(thread::linux::nice().unwrap(), before + 1);
            // A thread created by this one starts with its value.
            assert_eq!(on_new_thread(thread::linux::nice).unwrap(), before + 1);
            // Going back takes a privilege, or a limit that allows it.
            match thread::linux::set_nice(before) {
                Ok(()) => assert_eq!(thread::linux::nice().unwrap(), before),
                Err(error) => assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error}"),
            }
            // Beyond the scale is its end.
            thread::linux::set_nice(100).unwrap();
            assert_eq!(thread::linux::nice().unwrap(), 19);
        });
    }
    assert_eq!(thread::linux::nice().unwrap(), before);
}

/// Threads made with `clone`. What they run keeps to the contract: `core`,
/// atomics and oscall, and nothing of `std`, not even an assertion; they
/// leave what they saw in statics for the test to check.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod linux_raw {
    use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
    use core::time::Duration;

    use oscall::thread::linux::spawn_raw;
    use oscall::{sync, thread, time};

    /// What one thread reports. (No 64-bit atomics: riscv32 has none.)
    struct Report {
        id: AtomicU32,
        sum: [AtomicU32; 2],
        text: AtomicUsize,
        done: AtomicU32,
        release: AtomicU32,
    }

    impl Report {
        const fn new() -> Self {
            Self {
                id: AtomicU32::new(0),
                sum: [AtomicU32::new(0), AtomicU32::new(0)],
                text: AtomicUsize::new(0),
                done: AtomicU32::new(0),
                release: AtomicU32::new(0),
            }
        }
    }

    /// Uses `depth` frames of a kilobyte each, which the optimiser cannot
    /// fold away.
    fn deep(depth: u32, seed: u64) -> u64 {
        let mut frame = [0u64; 128];
        for (i, slot) in frame.iter_mut().enumerate() {
            *slot = seed.wrapping_mul(i as u64 + 1);
        }
        let frame = core::hint::black_box(&mut frame);
        if depth == 0 {
            frame[127]
        } else {
            deep(depth - 1, seed + 1).wrapping_add(frame[depth as usize % 128])
        }
    }

    /// The same computation without the stack.
    fn deep_expected(depth: u32, seed: u64) -> u64 {
        let mut total = (seed + u64::from(depth)).wrapping_mul(128);
        for level in 1..=depth {
            let seed = seed + u64::from(depth - level);
            total = total.wrapping_add(seed.wrapping_mul(u64::from(level % 128) + 1));
        }
        total
    }

    fn work(arg: usize) {
        // SAFETY: the test gives the address of a `Report` that outlives
        // the thread, which only has atomics.
        let report = unsafe { &*(arg as *const Report) };
        report.id.store(thread::id() as u32, Ordering::Release);
        // Floating point and 128-bit arithmetic, formatted by `core`: code
        // that wants its stack aligned as the convention says.
        let mut text = Text {
            buf: [0; 64],
            len: 0,
        };
        let value = core::hint::black_box(1.5f64) * core::hint::black_box(2.25f64);
        let wide = core::hint::black_box(u128::MAX / 3) / core::hint::black_box(7u128);
        let _ = core::fmt::write(&mut text, format_args!("{value:.3} {wide}"));
        report.text.store(
            text.matches(b"3.375 16203922234330403022065457496750867212"),
            Ordering::Release,
        );
        // 200 KiB of stack.
        let sum = deep(200, 3);
        report.sum[0].store(sum as u32, Ordering::Release);
        report.sum[1].store((sum >> 32) as u32, Ordering::Release);
        let _ = time::sleep(Duration::from_millis(1));
        thread::yield_now();
        report.done.store(1, Ordering::Release);
        sync::wake_all(&report.done);
        // Stay until the test lets go, if it wants that.
        while report.release.load(Ordering::Acquire) == 1 {
            let _ = sync::wait(&report.release, 1, Some(Duration::from_millis(50)));
        }
    }

    struct Text {
        buf: [u8; 64],
        len: usize,
    }

    impl Text {
        fn matches(&self, expected: &[u8]) -> usize {
            usize::from(&self.buf[..self.len] == expected)
        }
    }

    impl core::fmt::Write for Text {
        fn write_str(&mut self, s: &str) -> core::fmt::Result {
            let end = self.len + s.len();
            self.buf
                .get_mut(self.len..end)
                .ok_or(core::fmt::Error)?
                .copy_from_slice(s.as_bytes());
            self.len = end;
            Ok(())
        }
    }

    fn wait_done(report: &Report) {
        let start = std::time::Instant::now();
        while report.done.load(Ordering::Acquire) == 0 {
            assert!(
                start.elapsed() < Duration::from_secs(60),
                "the thread never ran"
            );
            let _ = sync::wait(&report.done, 0, Some(Duration::from_millis(100)));
        }
    }

    fn check(report: &Report, id: u32) {
        assert_eq!(report.id.load(Ordering::Acquire), id);
        assert_eq!(report.text.load(Ordering::Acquire), 1);
        let sum = u64::from(report.sum[0].load(Ordering::Acquire))
            | u64::from(report.sum[1].load(Ordering::Acquire)) << 32;
        assert_eq!(sum, deep_expected(200, 3));
    }

    #[test]
    fn join() {
        static REPORT: Report = Report::new();
        assert_eq!(deep(200, 3), deep_expected(200, 3));
        REPORT.release.store(1, Ordering::Release);
        // SAFETY: `work` keeps to the contract, and the report is static.
        let thread = unsafe { spawn_raw(256 * 1024, work, &raw const REPORT as usize) }.unwrap();
        let id = thread.id();
        assert_ne!(u64::from(id), thread::id());
        assert_ne!(id, 0);
        wait_done(&REPORT);
        // It waits for the test: it has not ended.
        assert!(!thread.is_finished());
        assert!(format!("{thread:?}").contains(&id.to_string()));
        // A thread of the process, as the system sees it.
        if !super::emulated() {
            let task = format!("/proc/self/task/{id}");
            assert!(std::path::Path::new(&task).exists(), "{task}");
        }
        REPORT.release.store(0, Ordering::Release);
        sync::wake_all(&REPORT.release);
        thread.join().unwrap();
        check(&REPORT, id);
    }

    /// Many at once, each on its own stack, joined in another order than
    /// they end in.
    #[test]
    fn several() {
        const COUNT: usize = 16;
        static REPORTS: [Report; COUNT] = [const { Report::new() }; COUNT];
        let threads: Vec<_> = REPORTS
            .iter()
            .map(|report| {
                // SAFETY: as in `join`.
                unsafe { spawn_raw(256 * 1024, work, core::ptr::from_ref(report) as usize) }
                    .unwrap()
            })
            .collect();
        let mut ids: Vec<u32> = threads.iter().map(|thread| thread.id()).collect();
        for (thread, report) in threads.into_iter().zip(&REPORTS).rev() {
            let id = thread.id();
            thread.join().unwrap();
            check(report, id);
        }
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), COUNT);
    }

    /// A thread nobody joins unmaps its own stack: many of them leave the
    /// address space as it was, give or take what else the process does.
    #[test]
    fn detached() {
        const ROUNDS: usize = 64;
        const STACK: usize = 8 << 20;
        static REPORT: Report = Report::new();
        for round in 0..ROUNDS {
            REPORT.done.store(0, Ordering::Release);
            // SAFETY: as in `join`.
            let thread = unsafe { spawn_raw(STACK, work, &raw const REPORT as usize) }.unwrap();
            let id = thread.id();
            if round % 2 == 0 {
                // Detached while it runs.
                drop(thread);
                wait_done(&REPORT);
            } else {
                // Detached when it may be over already.
                wait_done(&REPORT);
                thread.detach();
            }
            check(&REPORT, id);
        }
        // Each stack was 8 MiB of address space: had none been unmapped,
        // the process would hold half a gigabyte more of them. The last
        // threads may still be on their way out.
        if !super::emulated() {
            let start = std::time::Instant::now();
            loop {
                let stacks = std::fs::read_to_string("/proc/self/maps")
                    .unwrap()
                    .lines()
                    .filter(|line| {
                        let range = line.split(' ').next().unwrap();
                        let (low, high) = range.split_once('-').unwrap();
                        let low = usize::from_str_radix(low, 16).unwrap();
                        let high = usize::from_str_radix(high, 16).unwrap();
                        (STACK..STACK + (1 << 20)).contains(&(high - low))
                            && line.contains(" rw-p ")
                    })
                    .count();
                if stacks < ROUNDS / 4 {
                    break;
                }
                assert!(
                    start.elapsed() < Duration::from_secs(30),
                    "{stacks} stacks are still mapped"
                );
                std::thread::sleep(Duration::from_millis(20));
            }
        }
    }

    /// A stack that cannot be mapped is an error, not a thread.
    #[test]
    fn errors() {
        fn nothing(_: usize) {}
        // SAFETY: `nothing` does nothing.
        let error = unsafe { spawn_raw(usize::MAX, nothing, 0) }.unwrap_err();
        assert_eq!(error.kind(), oscall::ErrorKind::InvalidInput, "{error}");
        // SAFETY: as above.
        let error = unsafe { spawn_raw(usize::MAX - (64 << 20), nothing, 0) }.unwrap_err();
        assert_eq!(error.kind(), oscall::ErrorKind::OutOfMemory, "{error}");
        // The least stack there is does for a function that does nothing.
        // SAFETY: as above.
        unsafe { spawn_raw(0, nothing, 0) }.unwrap().join().unwrap();
    }
}

/// Whether the tests run under qemu-user: see `tests/common`.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
fn emulated() -> bool {
    common::emulated()
}

/// Threads of macOS and Windows: whole threads, which may do anything.
#[cfg(any(target_os = "macos", windows))]
mod spawned {
    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

    #[cfg(target_os = "macos")]
    use oscall::thread::macos as system;
    #[cfg(windows)]
    use oscall::thread::windows as system;
    use oscall::{ErrorKind, thread};

    #[test]
    fn spawn_fn() {
        static SEEN: AtomicUsize = AtomicUsize::new(0);
        static ID: AtomicU64 = AtomicU64::new(0);
        fn work(arg: usize) {
            ID.store(thread::id(), Ordering::Release);
            // `std` is at home on this thread.
            thread_local!(static LOCAL: std::cell::Cell<usize> = const { std::cell::Cell::new(1) });
            LOCAL.set(LOCAL.get() + arg);
            let text = format!("{}", LOCAL.get());
            let _ = std::thread::current().id();
            SEEN.store(text.parse().unwrap(), Ordering::Release);
        }
        let handle = system::spawn_fn(work, 41).unwrap();
        let id = handle.id();
        assert_ne!(id, 0);
        assert_ne!(id, thread::id());
        assert!(format!("{handle:?}").contains("Thread"));
        handle.join().unwrap();
        assert_eq!(SEEN.load(Ordering::Acquire), 42);
        assert_eq!(ID.load(Ordering::Acquire), id);
    }

    #[test]
    fn builder() {
        static NAME_OK: AtomicUsize = AtomicUsize::new(0);
        static STACK: AtomicUsize = AtomicUsize::new(0);
        fn work(_: usize) {
            let mut buf = [0u8; 64];
            let name = thread::name(&mut buf).unwrap();
            NAME_OK.store(usize::from(name == "oscall worker"), Ordering::Release);
            let bounds = system::stack_bounds();
            STACK.store(bounds.end - bounds.start, Ordering::Release);
        }
        let handle = system::Builder::new()
            .name("oscall worker")
            .stack_size(3 << 20)
            .spawn_fn(work, 0)
            .unwrap();
        handle.join().unwrap();
        assert_eq!(NAME_OK.load(Ordering::Acquire), 1);
        let stack = STACK.load(Ordering::Acquire);
        assert!((3 << 20..4 << 20).contains(&stack), "{stack}");

        // The default is 2 MiB, and a small stack is a small stack.
        for (asked, range) in [(0, 2 << 20..3 << 20), (64 << 10, 64 << 10..256 << 10)] {
            STACK.store(0, Ordering::Release);
            let handle = system::Builder::new()
                .stack_size(asked)
                .spawn_fn(work, 0)
                .unwrap();
            handle.join().unwrap();
            let stack = STACK.load(Ordering::Acquire);
            assert!(range.contains(&stack), "{asked}: {stack}");
        }

        let error = system::Builder::new()
            .name("a\0b")
            .spawn_fn(work, 0)
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
        let _ = format!("{:?}", system::Builder::default().clone());
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn spawn() {
        let numbers: Vec<u64> = (1..=3).collect();
        let handle = system::spawn(move || {
            let sum: u64 = numbers.iter().sum();
            (sum, thread::id(), String::from("done"))
        })
        .unwrap();
        let id = handle.id();
        assert!(format!("{handle:?}").contains("JoinHandle"));
        let (sum, seen, text) = handle.join().unwrap();
        assert_eq!((sum, text.as_str()), (6, "done"));
        assert_eq!(seen, id);

        // Many at once, which use `std` to meet.
        let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
        let handles: Vec<_> = (0..8u64)
            .map(|i| {
                let barrier = barrier.clone();
                system::Builder::new()
                    .name("oscall many")
                    .spawn(move || {
                        barrier.wait();
                        i * i
                    })
                    .unwrap()
            })
            .collect();
        let squares: Vec<u64> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        assert_eq!(squares, [0, 1, 4, 9, 16, 25, 36, 49]);

        let error = system::Builder::new().name("a\0").spawn(|| ()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
    }

    /// A thread nobody joins runs to its end, and what it returned is
    /// dropped there.
    #[cfg(feature = "alloc")]
    #[test]
    fn detached() {
        use std::sync::mpsc;
        use std::time::Duration;

        struct Tell(mpsc::Sender<&'static str>);
        impl Drop for Tell {
            fn drop(&mut self) {
                let _ = self.0.send("dropped");
            }
        }
        let (sender, receiver) = mpsc::channel();
        let (go, wait) = mpsc::channel::<()>();
        let tell = Tell(sender.clone());
        let handle = system::spawn(move || {
            wait.recv().unwrap();
            sender.send("ran").unwrap();
            tell
        })
        .unwrap();
        drop(handle);
        go.send(()).unwrap();
        let timeout = Duration::from_secs(60);
        assert_eq!(receiver.recv_timeout(timeout), Ok("ran"));
        assert_eq!(receiver.recv_timeout(timeout), Ok("dropped"));

        let (sender, receiver) = mpsc::channel();
        system::spawn(move || sender.send(7).unwrap())
            .unwrap()
            .detach();
        assert_eq!(receiver.recv_timeout(timeout), Ok(7));
        static RAN: AtomicUsize = AtomicUsize::new(0);
        system::spawn_fn(|value| RAN.store(value, Ordering::Release), 9)
            .unwrap()
            .detach();
        let start = std::time::Instant::now();
        while RAN.load(Ordering::Acquire) != 9 {
            assert!(start.elapsed() < timeout);
            std::thread::sleep(Duration::from_millis(1));
        }
    }

    #[test]
    fn stack_bounds() {
        let check = || {
            let local = 0u8;
            let address = &raw const local as usize;
            let bounds = system::stack_bounds();
            assert!(bounds.contains(&address), "{address:#x} in {bounds:#x?}");
            bounds.end - bounds.start
        };
        // The first thread of the process is not the test's: this is one
        // `std` made, with the stack it gives (2 MiB unless told).
        let size = check();
        assert!(size >= 64 << 10, "{size}");
        let size = std::thread::Builder::new()
            .stack_size(5 << 20)
            .spawn(check)
            .unwrap()
            .join()
            .unwrap();
        assert!((5 << 20..6 << 20).contains(&size), "{size}");
    }

    #[cfg(windows)]
    #[test]
    fn windows_priority() {
        super::on_new_thread(|| {
            assert_eq!(system::priority().unwrap(), 0);
            for priority in [1, -1, 2, -2, -15, 15, 0] {
                system::set_priority(priority).unwrap();
                assert_eq!(system::priority().unwrap(), priority);
            }
            let error = system::set_priority(7).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error}");
            assert_eq!(system::priority().unwrap(), 0);
        });
        assert_eq!(system::priority().unwrap(), 0);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_qos() {
        use system::Qos;

        for class in [
            Qos::Utility,
            Qos::Background,
            Qos::Default,
            Qos::UserInitiated,
            Qos::UserInteractive,
        ] {
            super::on_new_thread(move || {
                system::set_qos(class).unwrap();
                assert_eq!(system::qos(), Some(class));
            });
        }
        // What a thread of oscall's starts with is the system's business;
        // what it sets it has.
        #[cfg(feature = "alloc")]
        {
            let class = system::spawn(|| {
                system::set_qos(Qos::Utility).unwrap();
                system::qos()
            });
            assert_eq!(class.unwrap().join().unwrap(), Some(Qos::Utility));
        }
    }
}