oscall 0.0.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
//! `process` on macOS.

use core::ffi::{c_char, c_int};

pub(crate) mod signal;

use core::time::Duration;

use crate::path::with_cstr;
use crate::process::ResourceUsage;
use crate::process::unix::{Limit, Resource};
use crate::sys::{cvt, errno};
use crate::{Error, ErrorKind, Result};

const SIGKILL: c_int = 9;
pub(crate) const SIGSTOP: i32 = 17;
pub(crate) const SIGCONT: i32 = 19;
pub(crate) const SIGCHLD: i32 = 20;
pub(crate) const SIGUSR1: i32 = 30;
pub(crate) const SIGUSR2: i32 = 31;

unsafe extern "C" {
    fn getpid() -> c_int;
    fn getppid() -> c_int;
    fn getpgid(pid: c_int) -> c_int;
    fn getsid(pid: c_int) -> c_int;
    #[link_name = "kill"]
    fn c_kill(pid: c_int, signal: c_int) -> c_int;
    fn faccessat(dir: c_int, path: *const c_char, mode: c_int, flags: c_int) -> c_int;
    fn getrusage(who: c_int, usage: *mut RUsage) -> c_int;
    fn getrlimit(resource: c_int, limit: *mut [u64; 2]) -> c_int;
    fn setrlimit(resource: c_int, limit: *const [u64; 2]) -> c_int;
    fn _exit(code: c_int) -> !;
    #[link_name = "abort"]
    fn c_abort() -> !;
}

pub(crate) fn id() -> u32 {
    // SAFETY: no argument, and the call cannot fail.
    unsafe { getpid() as u32 }
}

pub(crate) fn parent_id() -> u32 {
    // SAFETY: no argument, and the call cannot fail.
    unsafe { getppid() as u32 }
}

pub(crate) fn exit(code: i32) -> ! {
    // SAFETY: terminates the process without running anything of it.
    unsafe { _exit(code) }
}

pub(crate) fn abort() -> ! {
    // SAFETY: raises SIGABRT until the process dies of it.
    unsafe { c_abort() }
}

pub(crate) const HAS_PROCESSES: bool = true;
/// What separates the directories of a search path.
pub(crate) const SEARCH_SEPARATOR: u8 = b':';
/// What goes between a directory and a name.
pub(crate) const DIR_SEPARATOR: &[u8] = b"/";
/// What a program's name ends with when it has no extension.
pub(crate) const PROGRAM_SUFFIX: &[u8] = b"";

/// An entry of a search path, as the directory it names.
pub(crate) fn search_dir(entry: &[u8]) -> &[u8] {
    entry
}

/// Whether `name` is a name to search for, and not a path.
pub(crate) fn is_bare_name(name: &[u8]) -> bool {
    !name.contains(&b'/')
}

/// Whether `path` is a regular file the caller may execute.
pub(crate) fn is_program(path: &[u8]) -> bool {
    const AT_FDCWD: c_int = -2;
    const X_OK: c_int = 1;
    const AT_EACCESS: c_int = 0x0010;

    if !crate::sys::fs::metadata(path, true).is_ok_and(|metadata| metadata.is_file()) {
        return false;
    }
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        cvt(unsafe { faccessat(AT_FDCWD, path.as_ptr(), X_OK, AT_EACCESS) })
    })
    .is_ok()
}

/// `kill`: `pid` may be negative, for a process group.
pub(crate) fn send_signal(pid: i32, signal: i32) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe { c_kill(pid, signal) }).map(drop)
}

pub(crate) fn exists(pid: u32) -> Result<bool> {
    match send_signal(pid as i32, 0) {
        Ok(()) => Ok(true),
        Err(error) => exists_from(error),
    }
}

/// What a failure to send signal 0 says.
fn exists_from(error: Error) -> Result<bool> {
    match error.raw_os_error() {
        errno::ESRCH => Ok(false),
        // It is there, and someone else's.
        errno::EPERM => Ok(true),
        _ => Err(error),
    }
}

pub(crate) fn kill(pid: u32) -> Result<()> {
    send_signal(pid as i32, SIGKILL)
}

/// `struct timeval`: the microseconds are an `int`, padded.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct TimeVal {
    seconds: i64,
    micros: i32,
}

/// `struct rusage`: two `timeval`s and fourteen `long`s, the first of
/// which is the peak resident set size in bytes.
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct RUsage {
    user: TimeVal,
    system: TimeVal,
    max_rss: i64,
    others: [i64; 13],
}

const _: () = assert!(size_of::<RUsage>() == 144);

pub(crate) fn usage_from(usage: &RUsage) -> ResourceUsage {
    let time = |time: TimeVal| {
        Duration::new(time.seconds.max(0) as u64, 0)
            + Duration::from_micros(time.micros.clamp(0, 999_999) as u64)
    };
    ResourceUsage {
        user_time: time(usage.user),
        system_time: time(usage.system),
        max_resident_memory: usage.max_rss.max(0) as u64,
    }
}

pub(crate) fn resource_usage() -> Result<ResourceUsage> {
    const RUSAGE_SELF: c_int = 0;
    let mut usage = RUsage::default();
    // SAFETY: the system writes one `struct rusage`.
    cvt(unsafe { getrusage(RUSAGE_SELF, &raw mut usage) })?;
    Ok(usage_from(&usage))
}

/// `RLIM_INFINITY`.
const UNLIMITED: u64 = 0x7fff_ffff_ffff_ffff;

/// The `RLIMIT_*` number, from `<sys/resource.h>`.
fn resource_number(resource: Resource) -> c_int {
    match resource {
        Resource::CpuTime => 0,
        Resource::FileSize => 1,
        Resource::Data => 2,
        Resource::Stack => 3,
        Resource::CoreSize => 4,
        Resource::AddressSpace => 5,
        Resource::LockedMemory => 6,
        Resource::Processes => 7,
        Resource::OpenFiles => 8,
    }
}

pub(crate) fn limit(resource: Resource) -> Result<Limit> {
    // `struct rlimit`: the soft limit, then the hard one, as `rlim_t`.
    let mut old = [0u64; 2];
    // SAFETY: the system writes one `struct rlimit`.
    cvt(unsafe { getrlimit(resource_number(resource), &raw mut old) })?;
    let value = |raw: u64| (raw < UNLIMITED).then_some(raw);
    Ok(Limit {
        soft: value(old[0]),
        hard: value(old[1]),
    })
}

pub(crate) fn set_limit(resource: Resource, limit: Limit) -> Result<()> {
    let raw = |value: Option<u64>| match value {
        None => Ok(UNLIMITED),
        Some(value) if value >= UNLIMITED => Err(Error::from(ErrorKind::InvalidInput)),
        Some(value) => Ok(value),
    };
    let new = [raw(limit.soft)?, raw(limit.hard)?];
    // SAFETY: the system reads one `struct rlimit`.
    cvt(unsafe { setrlimit(resource_number(resource), &raw const new) }).map(drop)
}

pub(crate) fn process_group(pid: u32) -> Result<u32> {
    // SAFETY: no memory is involved.
    cvt(unsafe { getpgid(pid as c_int) }).map(|pgid| pgid as u32)
}

pub(crate) fn session(pid: u32) -> Result<u32> {
    // SAFETY: no memory is involved.
    cvt(unsafe { getsid(pid as c_int) }).map(|sid| sid as u32)
}

#[cfg(feature = "alloc")]
pub(crate) use spawn::{Child, spawn};

#[cfg(feature = "alloc")]
mod spawn {
    use core::ffi::{c_char, c_int, c_short, c_void};
    use core::ptr;
    use core::sync::atomic::{AtomicBool, Ordering};

    use super::{RUsage, SIGKILL, SIGSTOP, c_kill, usage_from};
    use crate::process::{CStrings, Command, ExitStatus, ResourceUsage, Stdio};
    use crate::sys::io::fcntl;
    use crate::sys::{cvt, errno};
    use crate::{Error, ErrorKind, OwnedHandle, Result};

    /// `posix_spawnattr_t` and `posix_spawn_file_actions_t` are both a
    /// pointer to something `libSystem` allocates.
    type Opaque = *mut c_void;
    /// `sigset_t`: one bit per signal, 1 to 32.
    type SigSet = u32;

    unsafe extern "C" {
        fn posix_spawn(
            pid: *mut c_int,
            path: *const c_char,
            file_actions: *const Opaque,
            attributes: *const Opaque,
            argv: *const *const c_char,
            envp: *const *const c_char,
        ) -> c_int;
        fn posix_spawnattr_init(attributes: *mut Opaque) -> c_int;
        fn posix_spawnattr_destroy(attributes: *mut Opaque) -> c_int;
        fn posix_spawnattr_setflags(attributes: *mut Opaque, flags: c_short) -> c_int;
        fn posix_spawnattr_setsigdefault(attributes: *mut Opaque, set: *const SigSet) -> c_int;
        fn posix_spawnattr_setsigmask(attributes: *mut Opaque, set: *const SigSet) -> c_int;
        fn posix_spawnattr_setpgroup(attributes: *mut Opaque, group: c_int) -> c_int;
        fn posix_spawn_file_actions_init(actions: *mut Opaque) -> c_int;
        fn posix_spawn_file_actions_destroy(actions: *mut Opaque) -> c_int;
        fn posix_spawn_file_actions_addopen(
            actions: *mut Opaque,
            fd: c_int,
            path: *const c_char,
            flags: c_int,
            mode: u16,
        ) -> c_int;
        fn posix_spawn_file_actions_adddup2(actions: *mut Opaque, fd: c_int, new: c_int) -> c_int;
        fn posix_spawn_file_actions_addinherit_np(actions: *mut Opaque, fd: c_int) -> c_int;
        // macOS 10.15.
        fn posix_spawn_file_actions_addchdir_np(actions: *mut Opaque, path: *const c_char)
        -> c_int;
        /// The address of `environ`, which a dynamic library cannot name.
        fn _NSGetEnviron() -> *mut *const *const c_char;
        fn wait4(pid: c_int, status: *mut c_int, options: c_int, usage: *mut RUsage) -> c_int;
    }

    const POSIX_SPAWN_SETPGROUP: c_short = 0x0002;
    /// macOS 10.15.
    const POSIX_SPAWN_SETSID: c_short = 0x0400;

    const POSIX_SPAWN_SETSIGDEF: c_short = 0x0004;
    const POSIX_SPAWN_SETSIGMASK: c_short = 0x0008;
    /// Every descriptor is closed in the child, except those the file
    /// actions create or mark as inherited.
    const POSIX_SPAWN_CLOEXEC_DEFAULT: c_short = 0x4000;

    const O_RDWR: c_int = 2;
    const F_GETFD: c_int = 1;
    const F_DUPFD_CLOEXEC: c_int = 67;
    const WNOHANG: c_int = 1;

    /// The functions of the `posix_spawn` family return the error number
    /// instead of setting `errno`.
    fn check(ret: c_int) -> Result<()> {
        if ret == 0 {
            Ok(())
        } else {
            Err(Error::from_raw_os_error(ret))
        }
    }

    struct Attributes(Opaque);

    impl Drop for Attributes {
        fn drop(&mut self) {
            // SAFETY: initialised, and not used afterwards.
            unsafe { posix_spawnattr_destroy(&raw mut self.0) };
        }
    }

    struct FileActions(Opaque);

    impl Drop for FileActions {
        fn drop(&mut self) {
            // SAFETY: initialised, and not used afterwards.
            unsafe { posix_spawn_file_actions_destroy(&raw mut self.0) };
        }
    }

    #[derive(Debug)]
    pub(crate) struct Child {
        pid: c_int,
        /// Set when a wait found that the child is no longer ours to wait
        /// for: someone else collected it, and its identifier is free for
        /// the system to give to another process.
        gone: AtomicBool,
    }

    pub(crate) fn spawn(command: &Command<'_>) -> Result<Child> {
        let mut paths = CStrings::new();
        match command.current_dir {
            // The program is relative to the caller's directory, and the
            // child looks for it from its own.
            Some(_) if !command.program.is_empty() && !command.program.starts_with(b"/") => {
                let here = crate::fs::current_dir_vec()?;
                paths.push(&[&here, b"/", command.program])?;
            }
            _ => paths.push(&[command.program])?,
        }
        if let Some(dir) = command.current_dir {
            paths.push(&[dir])?;
        }
        let group = match command.process_group {
            None => None,
            Some(group) => Some(c_int::try_from(group).map_err(|_| ErrorKind::InvalidInput)?),
        };
        let mut argv = CStrings::new();
        argv.push(&[command.arg0.unwrap_or(command.program)])?;
        for arg in command.args.iter() {
            argv.push(&[arg])?;
        }
        let mut envp = CStrings::new();
        if let Some(vars) = command.env {
            for var in vars.iter() {
                envp.push(&[var])?;
            }
        }
        let paths = paths.pointers()?;
        let argv = argv.pointers()?;
        let envp = match command.env {
            Some(_) => envp.pointers()?.as_ptr(),
            // SAFETY: the function returns the address of `environ`.
            // Reading it races with a concurrent `setenv`, as it does for
            // everything that reads the environment.
            None => unsafe { *_NSGetEnviron() },
        };

        let mut attributes = Attributes(ptr::null_mut());
        // SAFETY: the object is written by the call.
        check(unsafe { posix_spawnattr_init(&raw mut attributes.0) })?;
        // Default dispositions for every signal that can have another, and
        // nothing blocked.
        let default: SigSet = !(1 << (SIGKILL - 1) | 1 << (SIGSTOP - 1));
        let mask: SigSet = 0;
        let mut flags =
            POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_CLOEXEC_DEFAULT;
        if command.new_session {
            flags |= POSIX_SPAWN_SETSID;
        } else if let Some(group) = group {
            flags |= POSIX_SPAWN_SETPGROUP;
            // SAFETY: the attributes are initialised.
            check(unsafe { posix_spawnattr_setpgroup(&raw mut attributes.0, group) })?;
        }
        // SAFETY: the attributes are initialised; the sets are read.
        unsafe {
            check(posix_spawnattr_setsigdefault(
                &raw mut attributes.0,
                &raw const default,
            ))?;
            check(posix_spawnattr_setsigmask(
                &raw mut attributes.0,
                &raw const mask,
            ))?;
            check(posix_spawnattr_setflags(&raw mut attributes.0, flags))?;
        }

        let mut actions = FileActions(ptr::null_mut());
        // SAFETY: the object is written by the call.
        check(unsafe { posix_spawn_file_actions_init(&raw mut actions.0) })?;
        // The actions run in order in the child: a source that sits on
        // another standard descriptor than its own would be overwritten
        // before it is used, and is moved out of the way here.
        let mut held: [Option<OwnedHandle>; 3] = [None, None, None];
        for (target, source) in command.stdio.iter().enumerate() {
            let target = target as c_int;
            // SAFETY: the actions are initialised; the path is copied.
            check(unsafe {
                match source {
                    // Inheriting a descriptor that is not open is an error
                    // for `posix_spawn`: the child simply has none either.
                    Stdio::Inherit if fcntl(target, F_GETFD) == -1 => 0,
                    Stdio::Inherit => {
                        posix_spawn_file_actions_addinherit_np(&raw mut actions.0, target)
                    }
                    Stdio::Null => posix_spawn_file_actions_addopen(
                        &raw mut actions.0,
                        target,
                        c"/dev/null".as_ptr(),
                        O_RDWR,
                        0,
                    ),
                    Stdio::Handle(handle) => {
                        let mut fd = handle.as_raw();
                        if fd == target {
                            posix_spawn_file_actions_addinherit_np(&raw mut actions.0, target)
                        } else {
                            if (0..3).contains(&fd) {
                                let min: c_int = 3;
                                fd = cvt(fcntl(fd, F_DUPFD_CLOEXEC, min))?;
                                held[target as usize] = Some(OwnedHandle::from_raw(fd));
                            }
                            posix_spawn_file_actions_adddup2(&raw mut actions.0, fd, target)
                        }
                    }
                }
            })?;
        }
        if command.current_dir.is_some() {
            // SAFETY: the actions are initialised; the path is copied.
            check(unsafe { posix_spawn_file_actions_addchdir_np(&raw mut actions.0, paths[1]) })?;
        }

        let mut pid: c_int = 0;
        // SAFETY: every pointer is valid for the call: C strings,
        // NULL-terminated arrays of them, initialised objects.
        check(unsafe {
            posix_spawn(
                &raw mut pid,
                paths[0],
                &raw const actions.0,
                &raw const attributes.0,
                argv.as_ptr(),
                envp,
            )
        })?;
        drop(held);
        Ok(Child {
            pid,
            gone: AtomicBool::new(false),
        })
    }

    impl Child {
        pub(crate) fn id(&self) -> u32 {
            self.pid as u32
        }

        /// Whether the child was found to have been collected by other
        /// code: its identifier is no longer its own.
        pub(crate) fn is_gone(&self) -> bool {
            self.gone.load(Ordering::Acquire)
        }

        pub(crate) fn wait(
            &self,
            block: bool,
        ) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
            // Not asked again: the identifier may by now be the one of
            // another child of this process, which this call would collect.
            if self.gone.load(Ordering::Acquire) {
                return Err(Error::from_raw_os_error(errno::ECHILD));
            }
            let mut status: c_int = 0;
            let mut usage = RUsage::default();
            let options = if block { 0 } else { WNOHANG };
            // SAFETY: `status` and `usage` are written by the call. The
            // process is a child that has not been waited for: the
            // identifier is its own.
            let waited = unsafe { wait4(self.pid, &raw mut status, options, &raw mut usage) };
            let pid = match cvt(waited) {
                Ok(pid) => pid,
                Err(error) => {
                    // Collected by other code, or by the system because
                    // SIGCHLD is ignored.
                    if error.raw_os_error() == errno::ECHILD {
                        self.gone.store(true, Ordering::Release);
                    }
                    return Err(error);
                }
            };
            if pid == 0 {
                return Ok(None);
            }
            // The low seven bits are the terminating signal, 0 for an exit
            // (and 0x7f for a stop, which is not asked for).
            let signal = status & 0x7f;
            let status = if signal == 0 {
                ExitStatus::exited(status >> 8 & 0xff)
            } else {
                ExitStatus::signaled(signal, status & 0x80 != 0)
            };
            Ok(Some((status, Some(usage_from(&usage)))))
        }

        pub(crate) fn kill(&self) -> Result<()> {
            if self.gone.load(Ordering::Acquire) {
                return Ok(());
            }
            self.send_signal(SIGKILL)
        }

        pub(crate) fn send_signal(&self, signal: i32) -> Result<()> {
            // The caller only gets here while the child has not been waited
            // for: the identifier is still its own.
            if self.pid <= 0 || self.gone.load(Ordering::Acquire) {
                return Err(ErrorKind::NoSuchProcess.into());
            }
            // SAFETY: no memory is involved.
            cvt(unsafe { c_kill(self.pid, signal) }).map(drop)
        }
    }
}