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
//! The calling thread: its identity, its name, yielding the processor, and
//! how many processors there are to share.
//!
//! Everything portable here acts on the thread that calls it. What the
//! systems do differently is in the extension modules `linux`, `macos` and
//! `windows`, each present on its own system only: processor affinity
//! (Linux and Windows, in different shapes; macOS has none), how urgent a
//! thread is (a nice value, a quality of service class, a priority: three
//! scales with no meaning in common), where the stack of the thread is
//! (macOS and Windows; Linux keeps no such record), and creating threads.
//!
//! The processor time a thread has used is a clock:
//! [`Clock::ThreadCpu`](crate::time::Clock::ThreadCpu).
//!
//! # Creating threads
//!
//! There is no portable function for it, and the reason is Linux.
//!
//! A thread needs more than a stack: the *runtime* of the program keeps a
//! block of memory per thread (thread-local storage, and what it hangs
//! there: its allocator's caches, the identity of the thread, the state of
//! a panic), found through a register the thread is created with.
//!
//! - On **macOS** and **Windows** the runtime is the system's.
//!   `pthread_create` and `CreateThread` make threads that are complete,
//!   whoever calls them, and `std` adopts a thread it did not create the
//!   first time one asks it something. `macos::spawn` and `windows::spawn`
//!   are safe, and their threads may do anything.
//! - On **Linux** the kernel knows nothing of that block: `clone` makes a
//!   thread with a stack and no more, and the block is made by whatever
//!   runtime the program has: glibc, musl, or the `std` of fullrust, none
//!   of which offers to make one for a thread it did not create (fullrust
//!   exports nothing of the kind; a C library offers `pthread_create`
//!   itself). oscall calls no library on Linux: that is what lets it work
//!   under fullrust and in a program with no runtime at all, and a
//!   function that imported `pthread_create` where there is a C library
//!   would not exist where there is none, which is not a portable function
//!   either. What oscall can make there is `linux::spawn_raw`, an
//!   `unsafe` function whose thread may only run code that needs no
//!   runtime: no `std`, no allocation, no thread-local variable, no panic.
//!
//! A portable `spawn` would have to hold to the contract of the weakest of
//! the three, and would then be `linux::spawn_raw` under another name:
//! safe code could not call it and its thread could not allocate. A
//! program that wants threads everywhere uses `std::thread`, which is the
//! runtime's own way in; the functions here are for programs that have no
//! `std`, or that want what `std` does not offer.

use crate::sys;
use crate::{ErrorKind, Result};

#[cfg(any(windows, target_os = "macos"))]
pub(crate) mod spawn;

/// The identifier the system gives the calling thread.
///
/// It is unique among the threads that exist at the same time, in the whole
/// system on Linux, macOS and Windows; the system may give it to a new
/// thread once this one has exited. It is the number the system's own tools
/// show (`ps -L`, `/proc/<pid>/task/<tid>`, debuggers, Process Explorer).
///
/// Linux: `gettid`, which is the process id in the first thread of a
/// process. macOS: `pthread_threadid_np`. Windows: `GetCurrentThreadId`.
/// WebAssembly has one thread, and the identifier is always 1.
///
/// This is a system call on Linux: keep the result rather than asking in a
/// loop.
#[must_use]
pub fn id() -> u64 {
    sys::thread::id()
}

/// Offers the processor to another thread that is ready to run. Returns at
/// once if there is none.
///
/// This is a hint to the scheduler, and useful only for spinning a few
/// times before blocking: to wait for something, block on it
/// ([`sync::wait`](crate::sync::wait)).
///
/// Linux, macOS and WASI: `sched_yield`. Windows: `SwitchToThread`. Does
/// nothing on WebAssembly without WASI.
pub fn yield_now() {
    sys::thread::yield_now();
}

/// The number of threads that can run at the same time: the count of
/// logical processors available.
///
/// Linux: the processors the calling thread is allowed to run on
/// (`sched_getaffinity`), which accounts for `taskset` and for the CPU sets
/// of containers, but not for CPU-time quotas (cgroup `cpu.max`), which
/// `std::thread::available_parallelism` also reads. macOS: the processors
/// currently active (`sysctl hw.activecpu`). Windows: the active processors
/// of all processor groups (`GetActiveProcessorCount`), whatever the
/// affinity of the process. WebAssembly: 1.
///
/// The result is at least 1.
pub fn available_parallelism() -> Result<usize> {
    match sys::thread::available_parallelism()? {
        0 => Err(ErrorKind::Other.into()),
        count => Ok(count),
    }
}

/// Names the calling thread, for debuggers, profilers and the system's
/// process listings.
///
/// The systems keep names of different lengths: 15 bytes on Linux, 63 on
/// macOS, and oscall passes at most 255 on Windows. A longer name is cut to
/// the limit, at a character boundary. A name with a NUL character in it
/// fails with [`InvalidInput`](ErrorKind::InvalidInput).
///
/// Linux: `prctl(PR_SET_NAME)`; in the first thread of a process this also
/// changes the name of the process that `ps` and `top` show (`comm`).
/// macOS: `pthread_setname_np`. Windows: `SetThreadDescription`, which
/// Windows 10 has since version 1607; before that the call fails with
/// [`Unsupported`](ErrorKind::Unsupported).
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly.
pub fn set_name(name: &str) -> Result<()> {
    if name.as_bytes().contains(&0) {
        return Err(ErrorKind::InvalidInput.into());
    }
    let end = name.floor_char_boundary(sys::thread::NAME_MAX);
    sys::thread::set_name(&name[..end])
}

/// Reads the name of the calling thread into `buf`, and returns it.
///
/// A thread that was never named has the name the system gave it: that of
/// the program on Linux, none (an empty string) on macOS and Windows.
///
/// If `buf` is too small for the name the call fails with
/// [`BufferTooSmall`](ErrorKind::BufferTooSmall); 64 bytes are enough on Linux
/// and macOS, and 256 for any name set through [`set_name`]. A name that
/// is not valid UTF-8, which only another library can have set, is returned
/// up to its first invalid byte.
///
/// Linux: `prctl(PR_GET_NAME)`. macOS: `pthread_getname_np`. Windows:
/// `GetThreadDescription`, with the same condition as [`set_name`].
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly.
pub fn name(buf: &mut [u8]) -> Result<&str> {
    let len = sys::thread::name(buf)?;
    let bytes = buf.get(..len).ok_or(ErrorKind::Other)?;
    Ok(match core::str::from_utf8(bytes) {
        Ok(name) => name,
        Err(error) => {
            let valid = &bytes[..error.valid_up_to()];
            // SAFETY: `valid_up_to` bytes were just checked to be UTF-8.
            unsafe { core::str::from_utf8_unchecked(valid) }
        }
    })
}

/// What Linux alone offers for threads.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub mod linux {
    use crate::Result;
    use crate::sys;

    /// Reads the set of processors the calling thread may run on
    /// (`sched_getaffinity`).
    ///
    /// The set is a bit mask: processor `n` is bit `n % usize::BITS` of
    /// `mask[n / usize::BITS]`. The whole of `mask` is written, with zeros
    /// beyond the processors the system has.
    ///
    /// Fails with [`InvalidInput`](crate::ErrorKind::InvalidInput) if `mask`
    /// has fewer bits than the system has possible processors: 1024 bits
    /// (`[usize; 1024 / usize::BITS as usize]`) suit all but the largest
    /// machines, and 8192 any kernel.
    pub fn affinity(mask: &mut [usize]) -> Result<()> {
        sys::thread::affinity(mask)
    }

    /// Restricts the calling thread to the processors of `mask`
    /// (`sched_setaffinity`), in the layout [`affinity`] describes. The
    /// thread moves to one of them if it is running on another.
    ///
    /// Bits for processors the system does not have are ignored. Fails with
    /// [`InvalidInput`](crate::ErrorKind::InvalidInput) if the mask has none
    /// of the processors the thread is permitted (by its cgroup's CPU set,
    /// among others).
    ///
    /// Threads created afterwards by this one inherit the mask.
    pub fn set_affinity(mask: &[usize]) -> Result<()> {
        sys::thread::set_affinity(mask)
    }

    /// The nice value of the calling thread: from -20, which the scheduler
    /// favours most, to 19; 0 unless something changed it
    /// (`getpriority(PRIO_PROCESS, 0)`).
    ///
    /// Linux keeps the value per thread, where POSIX has one for the whole
    /// process: this is the calling thread's, which a thread it creates
    /// inherits.
    pub fn nice() -> Result<i32> {
        sys::thread::nice()
    }

    /// Sets the nice value of the calling thread
    /// (`setpriority(PRIO_PROCESS, 0, nice)`). A value outside -20 to 19
    /// is brought to the nearest end.
    ///
    /// Any thread may raise its value. Lowering it, even back to what it
    /// was, takes `CAP_SYS_NICE` or a limit that allows it
    /// (`RLIMIT_NICE`); otherwise the call fails with
    /// [`PermissionDenied`](crate::ErrorKind::PermissionDenied).
    pub fn set_nice(nice: i32) -> Result<()> {
        sys::thread::set_nice(nice)
    }

    /// A thread created by [`spawn_raw`].
    ///
    /// Dropping it detaches the thread: it runs to its end on its own, and
    /// unmaps its stack as it leaves.
    pub struct RawThread(sys::thread::spawn::RawThread);

    impl RawThread {
        /// The identifier of the thread: what [`id`](crate::thread::id)
        /// returns in it, and what `clone` returned.
        #[inline]
        #[must_use]
        pub fn id(&self) -> u32 {
            self.0.id()
        }

        /// Whether the thread has ended, and no longer uses its stack: the
        /// kernel has cleared the word it was asked to clear
        /// (`CLONE_CHILD_CLEARTID`).
        #[inline]
        #[must_use]
        pub fn is_finished(&self) -> bool {
            self.0.is_finished()
        }

        /// Waits until the thread has ended (a `futex` wait on that word),
        /// and unmaps its stack.
        pub fn join(self) -> Result<()> {
            self.0.join()
        }

        /// Lets the thread run on its own, which dropping the value does
        /// too.
        #[inline]
        pub fn detach(self) {}
    }

    impl core::fmt::Debug for RawThread {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("RawThread").field("id", &self.id()).finish()
        }
    }

    /// Creates a thread with `clone`, on a stack of its own, that calls
    /// `f(arg)` and ends when `f` returns.
    ///
    /// The stack is a mapping of `stack_size` bytes rounded up to whole
    /// pages, with a page below it that nothing may touch: a stack that
    /// overflows ends the process with `SIGSEGV`. The thread shares
    /// everything with its creator, as any thread does (`CLONE_VM | CLONE_FS
    /// | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM`), and
    /// starts with every signal blocked.
    ///
    /// **No runtime knows this thread** (see [the module](crate::thread)).
    /// It has no thread-local storage of its own: the register that points
    /// to it has the value it had in the creator, so that what reads
    /// thread-local storage finds the *creator's*, at the same time as the
    /// creator. The thread is not in the C library's list either: what a
    /// library does to every thread (`setuid`, which tells each of them;
    /// cancellation) does not reach it.
    ///
    /// # Safety
    ///
    /// From the call of `f` to its return, the thread must run nothing
    /// that depends on the runtime of the program. That is:
    ///
    /// - nothing of `std`, which keeps the current thread, the state of
    ///   panics and its output capture in thread-local storage;
    /// - no thread-local variable (`thread_local!`, `#[thread_local]`,
    ///   C's `errno`), and no function of a C library;
    /// - no use of the global allocator, unless the program has given
    ///   itself one that keeps nothing per thread: the system's keep
    ///   caches there, and the `std` of fullrust a whole heap;
    /// - no panic, and so nothing that unwinds out of `f`.
    ///
    /// What it may run: `core`, atomics, and the Linux backend of oscall,
    /// which makes system calls and keeps nothing per thread. `arg` is the
    /// function's business; if it is the address of something, that thing
    /// must stay valid for as long as the thread uses it, and be safe to
    /// use from another thread.
    pub unsafe fn spawn_raw(stack_size: usize, f: fn(usize), arg: usize) -> Result<RawThread> {
        // SAFETY: the caller's contract.
        unsafe { sys::thread::spawn::spawn_raw(stack_size, f, arg) }.map(RawThread)
    }
}

/// What macOS alone offers for threads.
#[cfg(target_os = "macos")]
pub mod macos {
    use core::ops::Range;

    use crate::sys;
    use crate::{ErrorKind, Result};

    pub use super::spawn::{Builder, Thread, spawn_fn};
    #[cfg(feature = "alloc")]
    pub use super::spawn::{JoinHandle, spawn};

    /// The memory the calling thread's stack is in: from its lowest
    /// address to one past its highest, where it starts
    /// (`pthread_get_stackaddr_np`, `pthread_get_stacksize_np`).
    ///
    /// For the first thread of a process the size is the limit the stack
    /// may grow to, not what is mapped.
    #[must_use]
    pub fn stack_bounds() -> Range<usize> {
        sys::thread::stack_bounds()
    }

    /// A quality of service class: how the system weighs the work of a
    /// thread against the rest, in processor time, in which cores run it,
    /// in timer accuracy and in I/O priority. From the most urgent to the
    /// least.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum Qos {
        /// Work the user is waiting for at this instant: drawing, input
        /// (`QOS_CLASS_USER_INTERACTIVE`).
        UserInteractive,
        /// Work the user asked for and waits to see done
        /// (`QOS_CLASS_USER_INITIATED`).
        UserInitiated,
        /// What a thread has when nothing was said (`QOS_CLASS_DEFAULT`).
        Default,
        /// Work the user does not follow closely: a long computation, a
        /// download (`QOS_CLASS_UTILITY`).
        Utility,
        /// Work the user does not see: indexing, backups
        /// (`QOS_CLASS_BACKGROUND`). On Apple silicon it runs on the
        /// efficiency cores only.
        Background,
    }

    // sys/qos.h
    const CLASSES: [(Qos, u32); 5] = [
        (Qos::UserInteractive, 0x21),
        (Qos::UserInitiated, 0x19),
        (Qos::Default, 0x15),
        (Qos::Utility, 0x11),
        (Qos::Background, 0x09),
    ];

    /// The quality of service class of the calling thread
    /// (`qos_class_self`), or `None` when it has none: a thread created
    /// without one that never chose, or one whose scheduling was set by
    /// other means.
    #[must_use]
    pub fn qos() -> Option<Qos> {
        let raw = sys::thread::qos();
        CLASSES
            .iter()
            .find(|(_, value)| *value == raw)
            .map(|(class, _)| *class)
    }

    /// Sets the quality of service class of the calling thread
    /// (`pthread_set_qos_class_self_np`).
    ///
    /// Fails with [`PermissionDenied`](ErrorKind::PermissionDenied) for a
    /// thread whose scheduling policy or priority was set through the
    /// `pthread` scheduling functions, which takes it out of the classes
    /// for good.
    pub fn set_qos(class: Qos) -> Result<()> {
        let raw = CLASSES
            .iter()
            .find(|(candidate, _)| *candidate == class)
            .map(|(_, value)| *value)
            .ok_or(ErrorKind::InvalidInput)?;
        sys::thread::set_qos(raw)
    }
}

/// What Windows alone offers for threads.
#[cfg(windows)]
pub mod windows {
    use crate::Result;
    use crate::sys;

    /// Reads the set of processors the calling thread may run on, within
    /// its processor group (`GetThreadGroupAffinity`): processor `n` of the
    /// group is bit `n`.
    ///
    /// A group has at most 64 processors (32 on 32-bit Windows); systems
    /// with more have several groups, and a thread runs in one.
    pub fn affinity() -> Result<usize> {
        sys::thread::affinity()
    }

    /// Restricts the calling thread to the processors of `mask`, within its
    /// processor group (`SetThreadAffinityMask`), in the layout
    /// [`affinity`] describes.
    ///
    /// Fails with [`InvalidInput`](crate::ErrorKind::InvalidInput) if the
    /// mask is empty or has a processor that the process may not use.
    pub fn set_affinity(mask: usize) -> Result<()> {
        sys::thread::set_affinity(mask)
    }

    pub use super::spawn::{Builder, Thread, spawn_fn};
    #[cfg(feature = "alloc")]
    pub use super::spawn::{JoinHandle, spawn};

    /// The memory reserved for the calling thread's stack: from its lowest
    /// address to one past its highest, where it starts
    /// (`GetCurrentThreadStackLimits`). Only the upper part of it is
    /// committed, and the system commits more as the stack grows.
    #[must_use]
    pub fn stack_bounds() -> core::ops::Range<usize> {
        sys::thread::stack_bounds()
    }

    /// The priority of the calling thread within the priority class of its
    /// process (`GetThreadPriority`): 0 is normal, and the values the
    /// system has names for are -2 (lowest), -1, 1, 2 (highest), -15
    /// (idle) and 15 (time critical).
    pub fn priority() -> Result<i32> {
        sys::thread::priority()
    }

    /// Sets the priority of the calling thread within the priority class
    /// of its process (`SetThreadPriority`), to one of the values
    /// [`priority`] lists. Any thread may set any of them for itself.
    ///
    /// Fails with [`InvalidInput`](crate::ErrorKind::InvalidInput) for
    /// another value.
    pub fn set_priority(priority: i32) -> Result<()> {
        sys::thread::set_priority(priority)
    }
}