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
//! What the process was started with: its arguments and its environment.

use core::iter::FusedIterator;

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

/// Where a backend writes a list of strings: each one followed by a NUL,
/// in the caller's buffer.
pub(crate) struct Writer<'a> {
    buf: &'a mut [u8],
    len: usize,
}

#[allow(dead_code)]
impl<'a> Writer<'a> {
    pub(crate) fn new(buf: &'a mut [u8]) -> Self {
        Self { buf, len: 0 }
    }

    /// Appends bytes to the string being written.
    pub(crate) fn push(&mut self, bytes: &[u8]) -> Result<()> {
        let end = self
            .len
            .checked_add(bytes.len())
            .ok_or(ErrorKind::BufferTooSmall)?;
        self.buf
            .get_mut(self.len..end)
            .ok_or(ErrorKind::BufferTooSmall)?
            .copy_from_slice(bytes);
        self.len = end;
        Ok(())
    }

    /// Ends the string being written.
    pub(crate) fn end(&mut self) -> Result<()> {
        self.push(&[0])
    }

    /// The number of bytes written.
    pub(crate) fn len(&self) -> usize {
        self.len
    }
}

/// A [`Writer`] of UTF-16: what Windows has, written as WTF-8 (UTF-8 that
/// can also say a surrogate that has no pair, as the paths of oscall do).
#[cfg(any(windows, test))]
pub(crate) struct WideWriter<'a> {
    out: Writer<'a>,
    /// A leading surrogate that waits for the unit after it.
    pending: Option<u16>,
}

#[cfg(any(windows, test))]
impl<'a> WideWriter<'a> {
    pub(crate) fn new(buf: &'a mut [u8]) -> Self {
        Self {
            out: Writer::new(buf),
            pending: None,
        }
    }

    fn flush(&mut self) -> Result<()> {
        if let Some(unit) = self.pending.take() {
            self.code_point(unit.into())?;
        }
        Ok(())
    }

    fn code_point(&mut self, cp: u32) -> Result<()> {
        let mut bytes = [0u8; 4];
        let len = match cp {
            0..0x80 => {
                bytes[0] = cp as u8;
                1
            }
            0x80..0x800 => {
                bytes[0] = 0xc0 | (cp >> 6) as u8;
                bytes[1] = 0x80 | (cp & 0x3f) as u8;
                2
            }
            0x800..0x1_0000 => {
                bytes[0] = 0xe0 | (cp >> 12) as u8;
                bytes[1] = 0x80 | (cp >> 6 & 0x3f) as u8;
                bytes[2] = 0x80 | (cp & 0x3f) as u8;
                3
            }
            _ => {
                bytes[0] = 0xf0 | (cp >> 18) as u8;
                bytes[1] = 0x80 | (cp >> 12 & 0x3f) as u8;
                bytes[2] = 0x80 | (cp >> 6 & 0x3f) as u8;
                bytes[3] = 0x80 | (cp & 0x3f) as u8;
                4
            }
        };
        self.out.push(&bytes[..len])
    }

    /// Appends one unit to the string being written.
    pub(crate) fn push(&mut self, unit: u16) -> Result<()> {
        if let Some(high) = self.pending
            && (0xdc00..0xe000).contains(&unit)
        {
            self.pending = None;
            let cp = 0x1_0000 + ((u32::from(high) - 0xd800) << 10 | (u32::from(unit) - 0xdc00));
            return self.code_point(cp);
        }
        self.flush()?;
        if (0xd800..0xdc00).contains(&unit) {
            self.pending = Some(unit);
            Ok(())
        } else {
            self.code_point(unit.into())
        }
    }

    /// Ends the string being written.
    pub(crate) fn end(&mut self) -> Result<()> {
        self.flush()?;
        self.out.end()
    }

    /// The number of bytes written.
    pub(crate) fn len(&self) -> usize {
        self.out.len()
    }
}

/// Splits a Windows command line into the arguments a program started
/// with it sees, by the rules of the C runtime of Microsoft since 2008,
/// which are also those of `std`: the inverse of what
/// [`Command`](super::Command) writes.
///
/// `line` ends at its first NUL, or with the iterator. An empty line has no
/// arguments at all: the caller gives the name of the program then.
#[cfg(any(windows, test))]
pub(crate) fn split_command_line(
    line: impl Iterator<Item = u16>,
    out: &mut WideWriter<'_>,
) -> Result<()> {
    const QUOTE: u16 = b'"' as u16;
    const BACKSLASH: u16 = b'\\' as u16;
    let is_space = |unit: u16| unit == b' ' as u16 || unit == b'\t' as u16;

    let mut line = line.take_while(|&unit| unit != 0).peekable();
    if line.peek().is_none() {
        return Ok(());
    }

    // The name of the program: a quote opens and closes, nothing escapes
    // anything, and the first space or tab outside quotes ends it.
    let mut in_quotes = false;
    for unit in line.by_ref() {
        match unit {
            QUOTE => in_quotes = !in_quotes,
            unit if is_space(unit) && !in_quotes => break,
            unit => out.push(unit)?,
        }
    }
    out.end()?;
    while line.next_if(|&unit| is_space(unit)).is_some() {}

    // The arguments. Backslashes mean themselves unless a quote follows
    // them: then half of them are backslashes, and the quote is one too if
    // their number was odd. Within quotes, two quotes are one.
    let mut in_quotes = false;
    let mut empty = true;
    while let Some(unit) = line.next() {
        match unit {
            unit if is_space(unit) && !in_quotes => {
                out.end()?;
                empty = true;
                while line.next_if(|&unit| is_space(unit)).is_some() {}
                continue;
            }
            BACKSLASH => {
                let mut count = 1usize;
                while line.next_if_eq(&BACKSLASH).is_some() {
                    count += 1;
                }
                if line.peek() == Some(&QUOTE) {
                    for _ in 0..count / 2 {
                        out.push(BACKSLASH)?;
                    }
                    if count % 2 == 1 {
                        line.next();
                        out.push(QUOTE)?;
                    }
                } else {
                    for _ in 0..count {
                        out.push(BACKSLASH)?;
                    }
                }
            }
            QUOTE if in_quotes => match line.peek() {
                Some(&QUOTE) => {
                    line.next();
                    out.push(QUOTE)?;
                }
                Some(_) => in_quotes = false,
                // The line ends within quotes: that is an argument, also
                // when it is empty.
                None => break,
            },
            QUOTE => in_quotes = true,
            unit => out.push(unit)?,
        }
        empty = false;
    }
    if !empty || in_quotes {
        out.end()?;
    }
    Ok(())
}

/// The arguments of the process, as [`args`] found them.
///
/// An iterator of byte strings, in order: the first is the name the
/// program was started under.
#[derive(Clone, Debug)]
pub struct Args<'a> {
    rest: &'a [u8],
}

impl<'a> Iterator for Args<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<&'a [u8]> {
        if self.rest.is_empty() {
            return None;
        }
        let (item, rest) = match self.rest.iter().position(|&byte| byte == 0) {
            Some(end) => (&self.rest[..end], &self.rest[end + 1..]),
            None => (self.rest, &[][..]),
        };
        self.rest = rest;
        Some(item)
    }
}

impl FusedIterator for Args<'_> {}

/// The environment of the process, as [`vars`] found it.
///
/// An iterator of names and values, in the order the system has them.
#[derive(Clone, Debug)]
pub struct Vars<'a> {
    entries: Args<'a>,
}

impl<'a> Iterator for Vars<'a> {
    type Item = (&'a [u8], &'a [u8]);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let entry = self.entries.next()?;
            // A name may start with `=`: Windows has such variables, one
            // per drive that has a current directory (`=C:`).
            let split = entry.iter().skip(1).position(|&byte| byte == b'=');
            if let Some(at) = split {
                return Some((&entry[..=at], &entry[at + 2..]));
            }
        }
    }
}

impl FusedIterator for Vars<'_> {}

/// Reads the arguments the process was started with into `buf`, and
/// returns an iterator over them.
///
/// The strings are bytes, as [`Command::args`](super::Command::args)
/// takes them: whatever the parent gave on Linux, macOS and WASI, and on
/// Windows the arguments of the command line converted from UTF-16 (UTF-8,
/// or WTF-8 for a line with a surrogate that has no pair).
///
/// If `buf` is too small the call fails with
/// [`BufferTooSmall`](ErrorKind::BufferTooSmall): the arguments take their
/// length, a byte each, and on WASI four more bytes each.
///
/// Where they come from, since a library without a runtime was not handed
/// them:
///
/// - Linux: the file `/proc/self/cmdline`, which is the kernel reading the
///   memory the arguments were put in when the program started. The call
///   fails where `/proc` is not mounted
///   ([`NotFound`](ErrorKind::NotFound)), or is that of another process
///   namespace. A program that wrote over that memory to change what `ps`
///   shows of it gets what it wrote.
/// - macOS: `_NSGetArgv`.
/// - Windows: `GetCommandLineW`, split by the rules of Microsoft's C
///   runtime, which are those `std` applies. A process started with an
///   empty command line has one argument, the path of its program
///   (`GetModuleFileNameW`).
/// - WASI: `args_get`.
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly
/// without WASI.
pub fn args(buf: &mut [u8]) -> Result<Args<'_>> {
    let len = sys::env::args(buf)?;
    let rest = buf.get(..len).ok_or(ErrorKind::Other)?;
    Ok(Args { rest })
}

/// Reads the environment of the process into `buf`, and returns an
/// iterator over its variables: a name and a value each, as bytes.
///
/// An entry with no `=` in it, which only a parent that writes the block
/// by hand can produce, is left out. On Windows the names come as the
/// system has them, which compares them without regard to case, and
/// include its hidden variables, whose names start with `=` and which
/// the system writes itself (`=C:` is the current directory of that
/// drive, and appears when something asks for it).
///
/// If `buf` is too small the call fails with
/// [`BufferTooSmall`](ErrorKind::BufferTooSmall).
///
/// **Which environment** differs, and could not be made the same:
///
/// - Linux: the one the process was *started with*, from the file
///   `/proc/self/environ`. The environment a program changes afterwards
///   (`std::env::set_var`, `setenv`) is a copy its runtime keeps, which
///   nothing outside that runtime can find: such changes do not show
///   here. The call fails where `/proc` is not mounted
///   ([`NotFound`](ErrorKind::NotFound)), and in a process that is not
///   root and has made itself not dumpable
///   ([`PermissionDenied`](ErrorKind::PermissionDenied): the file then
///   belongs to root).
/// - macOS: the one the process has *now* (`_NSGetEnviron`), with the
///   changes made through the C library, which `std` uses.
/// - Windows: the one the process has now (`GetEnvironmentStringsW`).
/// - WASI: the one the module was started with (`environ_get`).
///
/// So the result is the same everywhere for a program that does not
/// change its own environment, which is also the only kind that may read
/// it from several threads: on macOS, this reads the memory `setenv`
/// writes, with no lock, exactly as `getenv` does. That is why
/// `std::env::set_var` is `unsafe`, and why oscall has no function that
/// sets a variable: the C library gives no way to do so that is safe with
/// respect to its other users, and on Linux there is no environment to
/// set without one. A child is given its environment by
/// [`Command::env`](super::Command::env).
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly
/// without WASI.
pub fn vars(buf: &mut [u8]) -> Result<Vars<'_>> {
    let len = sys::env::vars(buf)?;
    let rest = buf.get(..len).ok_or(ErrorKind::Other)?;
    Ok(Vars {
        entries: Args { rest },
    })
}

/// Calls `f` with larger and larger buffers until what it writes fits.
#[cfg(feature = "alloc")]
fn to_vec(f: impl Fn(&mut [u8]) -> Result<usize>) -> Result<alloc::vec::Vec<u8>> {
    // More than a system lets a process be started with: Linux stops at 6 MiB
    // by default, and Windows at 32767 characters for either.
    const MAX: usize = 1 << 28;

    let mut buf = alloc::vec::Vec::new();
    let mut size = 4096;
    loop {
        buf.try_reserve_exact(size - buf.len())
            .map_err(|_| ErrorKind::OutOfMemory)?;
        buf.resize(size, 0);
        match f(&mut buf) {
            Ok(len) => {
                buf.truncate(len);
                return Ok(buf);
            }
            Err(error) if error.kind() == ErrorKind::BufferTooSmall && size < MAX => size *= 2,
            Err(error) => return Err(error),
        }
    }
}

#[cfg(feature = "alloc")]
fn owned(bytes: &[u8]) -> Result<alloc::vec::Vec<u8>> {
    let mut vec = alloc::vec::Vec::new();
    vec.try_reserve_exact(bytes.len())
        .map_err(|_| ErrorKind::OutOfMemory)?;
    vec.extend_from_slice(bytes);
    Ok(vec)
}

/// As [`args`], returning the arguments in a `Vec` each.
#[cfg(feature = "alloc")]
pub fn args_vec() -> Result<alloc::vec::Vec<alloc::vec::Vec<u8>>> {
    let buf = to_vec(sys::env::args)?;
    let mut list = alloc::vec::Vec::new();
    for arg in (Args { rest: &buf }) {
        list.try_reserve(1).map_err(|_| ErrorKind::OutOfMemory)?;
        list.push(owned(arg)?);
    }
    Ok(list)
}

/// A name and a value of the environment, as [`vars_vec`] returns them.
#[cfg(feature = "alloc")]
pub type Var = (alloc::vec::Vec<u8>, alloc::vec::Vec<u8>);

/// As [`vars`], returning each name and value in a `Vec`.
#[cfg(feature = "alloc")]
pub fn vars_vec() -> Result<alloc::vec::Vec<Var>> {
    let buf = to_vec(sys::env::vars)?;
    let mut list = alloc::vec::Vec::new();
    let vars = Vars {
        entries: Args { rest: &buf },
    };
    for (name, value) in vars {
        list.try_reserve(1).map_err(|_| ErrorKind::OutOfMemory)?;
        list.push((owned(name)?, owned(value)?));
    }
    Ok(list)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn split(line: &str) -> ([u8; 256], usize) {
        let mut buf = [0u8; 256];
        let mut out = WideWriter::new(&mut buf);
        split_command_line(line.encode_utf16(), &mut out).unwrap();
        let len = out.len();
        (buf, len)
    }

    fn check(line: &str, expected: &[&str]) {
        let (buf, len) = split(line);
        let mut args = Args { rest: &buf[..len] };
        for (i, expected) in expected.iter().enumerate() {
            assert_eq!(
                args.next().map(|arg| core::str::from_utf8(arg).unwrap()),
                Some(*expected),
                "argument {i} of {line:?}"
            );
        }
        assert_eq!(args.next(), None, "{line:?}");
    }

    /// The cases of `std`'s own tests of the same rules, and of Microsoft's
    /// documentation.
    #[test]
    fn command_lines() {
        check("", &[]);
        check("EXE", &["EXE"]);
        check("EXE ", &["EXE"]);
        check("EXE \t ", &["EXE"]);
        check("\"EXE", &["EXE"]);
        check("\"EX E\" a", &["EX E", "a"]);
        check("E\"X E\"E a", &["EX EE", "a"]);
        check("EXE\\\"a b", &["EXE\\a b"]);
        check("EXE a b  c\td", &["EXE", "a", "b", "c", "d"]);
        check("EXE \"\"", &["EXE", ""]);
        check("EXE \"\" \"\"", &["EXE", "", ""]);
        check("EXE \"\"abc\"\"", &["EXE", "abc"]);
        check("EXE \"abc\"\"", &["EXE", "abc\""]);
        check("EXE \"", &["EXE", ""]);
        check("EXE \"a b\" c", &["EXE", "a b", "c"]);
        check("EXE a\"b c\"d", &["EXE", "ab cd"]);
        check("EXE \"a\"\"b\"", &["EXE", "a\"b"]);
        check("EXE \"a\"\"", &["EXE", "a\""]);
        check("EXE \"a\"\" b\" c", &["EXE", "a\" b", "c"]);
        check("EXE a\\b", &["EXE", "a\\b"]);
        check("EXE a\\\\b", &["EXE", "a\\\\b"]);
        check("EXE a\\\"b", &["EXE", "a\"b"]);
        check("EXE a\\\\\"b c\"", &["EXE", "a\\b c"]);
        check("EXE a\\\\\\\"b", &["EXE", "a\\\"b"]);
        check("EXE \"a\\\\\"", &["EXE", "a\\"]);
        check("EXE \"a b\\\\\" c", &["EXE", "a b\\", "c"]);
        check("EXE a\\", &["EXE", "a\\"]);
        check("EXE \"a\tb\"", &["EXE", "a\tb"]);
        check(
            "EXE h\u{e9}llo \u{1f600}",
            &["EXE", "h\u{e9}llo", "\u{1f600}"],
        );
        check(" a", &["", "a"]);
    }

    #[test]
    fn surrogates() {
        let mut buf = [0u8; 32];
        let mut out = WideWriter::new(&mut buf);
        // A pair, a leading one alone, a trailing one alone, a leading one
        // at the end.
        let line = [
            b'x' as u16,
            b' ' as u16,
            0xd83d,
            0xde00,
            0xd800,
            b'a' as u16,
            0xdc00,
            0xd801,
        ];
        split_command_line(line.into_iter(), &mut out).unwrap();
        let len = out.len();
        assert_eq!(
            buf[..len],
            *b"x\0\xf0\x9f\x98\x80\xed\xa0\x80a\xed\xb0\x80\xed\xa0\x81\0"
        );

        let mut small = [0u8; 3];
        let mut out = WideWriter::new(&mut small);
        let error = split_command_line("abc".encode_utf16(), &mut out).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BufferTooSmall);
    }

    #[test]
    fn iterators() {
        let args = Args { rest: b"a\0\0bc\0" };
        assert!(args.eq([&b"a"[..], b"", b"bc"]));
        // A last string that nothing ends is one all the same.
        let args = Args { rest: b"a\0b" };
        assert!(args.eq([&b"a"[..], b"b"]));
        assert_eq!(Args { rest: b"" }.next(), None);

        let vars = Vars {
            entries: Args {
                rest: b"A=1\0novalue\0=C:=C:\\x\0B=\0C=a=b\0=\0",
            },
        };
        assert!(vars.eq([
            (&b"A"[..], &b"1"[..]),
            (b"=C:", b"C:\\x"),
            (b"B", b""),
            (b"C", b"a=b"),
        ]));
    }
}