oscall 0.1.0

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
//! Clocks and sleeping.

use std::time::{Duration, Instant, SystemTime};

use oscall::ErrorKind;
use oscall::time::{self, Clock, Timestamp};

/// Burns processor time until `clock` has visibly advanced.
fn spin_until_advanced(clock: Clock) -> (Duration, Duration) {
    let start = clock.now().unwrap();
    let mut value = 1u64;
    loop {
        for i in 0..100_000u64 {
            value = std::hint::black_box(value.wrapping_mul(6364136223846793005).wrapping_add(i));
        }
        let now = clock.now().unwrap();
        assert!(now >= start);
        if now > start {
            return (start, now);
        }
    }
}

#[test]
fn timestamp_arithmetic() {
    let epoch = Timestamp::UNIX_EPOCH;
    assert_eq!(epoch, Timestamp::default());
    let t = Timestamp {
        secs: 10,
        nanos: 900_000_000,
    };
    let later = t.checked_add(Duration::new(1, 200_000_000)).unwrap();
    assert_eq!(
        later,
        Timestamp {
            secs: 12,
            nanos: 100_000_000
        }
    );
    assert_eq!(later.checked_sub(Duration::new(1, 200_000_000)), Some(t));
    assert_eq!(later.duration_since(t), Some(Duration::new(1, 200_000_000)));
    assert_eq!(t.duration_since(later), None);
    assert_eq!(t.duration_since(t), Some(Duration::ZERO));
    assert!(t < later);

    // Before the epoch: `nanos` still counts forwards from `secs`.
    let before = epoch.checked_sub(Duration::new(1, 250_000_000)).unwrap();
    assert_eq!(
        before,
        Timestamp {
            secs: -2,
            nanos: 750_000_000
        }
    );
    assert_eq!(before.to_unix(), None);
    assert_eq!(
        epoch.duration_since(before),
        Some(Duration::new(1, 250_000_000))
    );
    assert_eq!(
        before.checked_add(Duration::new(1, 250_000_000)),
        Some(epoch)
    );

    assert_eq!(
        Timestamp::from_unix(Duration::new(10, 900_000_000)),
        Some(t)
    );
    assert_eq!(t.to_unix(), Some(Duration::new(10, 900_000_000)));

    // The limits.
    let max = Timestamp {
        secs: i64::MAX,
        nanos: 999_999_999,
    };
    let min = Timestamp {
        secs: i64::MIN,
        nanos: 0,
    };
    assert_eq!(max.checked_add(Duration::from_nanos(1)), None);
    assert_eq!(max.checked_add(Duration::ZERO), Some(max));
    assert_eq!(min.checked_sub(Duration::from_nanos(1)), None);
    assert_eq!(epoch.checked_add(Duration::MAX), None);
    assert_eq!(epoch.checked_sub(Duration::MAX), None);
    assert_eq!(Timestamp::from_unix(Duration::MAX), None);
    assert_eq!(
        max.duration_since(min),
        Some(Duration::new(u64::MAX, 999_999_999))
    );
    assert_eq!(min.duration_since(max), None);
}

/// The fields are public: `nanos` may be anything. Such a value is not a
/// time, and no method computes with it (which would overflow).
#[test]
fn timestamp_out_of_range() {
    let t = Timestamp {
        secs: 10,
        nanos: 900_000_000,
    };
    for nanos in [1_000_000_000, 1_500_000_000, u32::MAX - 1, u32::MAX] {
        let invalid = Timestamp { secs: 10, nanos };
        for duration in [
            Duration::ZERO,
            Duration::from_nanos(1),
            Duration::new(1, 999_999_999),
            Duration::MAX,
        ] {
            assert_eq!(invalid.checked_add(duration), None);
            assert_eq!(invalid.checked_sub(duration), None);
        }
        assert_eq!(invalid.duration_since(t), None);
        assert_eq!(t.duration_since(invalid), None);
        assert_eq!(invalid.duration_since(invalid), None);
        assert_eq!(invalid.duration_since(Timestamp::UNIX_EPOCH), None);
        assert_eq!(invalid.to_unix(), None);
        #[cfg(feature = "std")]
        assert_eq!(
            SystemTime::try_from(invalid).unwrap_err(),
            ErrorKind::InvalidInput
        );
    }
}

#[cfg(feature = "std")]
#[test]
fn timestamp_system_time() {
    let epoch = SystemTime::UNIX_EPOCH;
    assert_eq!(Timestamp::from(epoch), Timestamp::UNIX_EPOCH);
    assert_eq!(SystemTime::try_from(Timestamp::UNIX_EPOCH).unwrap(), epoch);

    // 100 ns is the unit of Windows' SystemTime: these convert exactly.
    let after = epoch + Duration::new(1_700_000_000, 123_456_700);
    let t = Timestamp::from(after);
    assert_eq!(
        t,
        Timestamp {
            secs: 1_700_000_000,
            nanos: 123_456_700
        }
    );
    assert_eq!(SystemTime::try_from(t).unwrap(), after);

    // Before the epoch, where std's SystemTime reaches there (fullrust's
    // does not: the conversion to it is then refused).
    let t = Timestamp {
        secs: -2,
        nanos: 750_000_000,
    };
    match epoch.checked_sub(Duration::new(1, 250_000_000)) {
        Some(before) => {
            assert_eq!(Timestamp::from(before), t);
            assert_eq!(SystemTime::try_from(t).unwrap(), before);
        }
        None => assert_eq!(
            SystemTime::try_from(t).unwrap_err(),
            ErrorKind::InvalidInput
        ),
    }

    let now = SystemTime::now();
    assert_eq!(
        Timestamp::from(now).to_unix(),
        Some(now.duration_since(epoch).unwrap())
    );

    // Not a time: `nanos` out of range.
    let invalid = Timestamp {
        secs: 0,
        nanos: 1_000_000_000,
    };
    assert_eq!(
        SystemTime::try_from(invalid).unwrap_err(),
        ErrorKind::InvalidInput
    );
}

#[test]
fn now_matches_std() {
    let before = SystemTime::now();
    let now = time::now().unwrap();
    let after = SystemTime::now();
    assert!(now.nanos < 1_000_000_000);
    let now = SystemTime::UNIX_EPOCH + now.to_unix().unwrap();

    // The same clock, read in order; two seconds of slack for a clock being
    // stepped under the test, and for the 100 ns truncation of Windows.
    let slack = Duration::from_secs(2);
    assert!(now + slack >= before, "{now:?} < {before:?}");
    assert!(now <= after + slack, "{now:?} > {after:?}");
}

#[test]
fn monotonic_clocks() {
    for clock in [Clock::Monotonic, Clock::Boottime] {
        // WebAssembly has one monotonic clock only.
        if cfg!(target_family = "wasm") && clock == Clock::Boottime {
            assert_eq!(clock.now().unwrap_err(), ErrorKind::Unsupported);
            assert_eq!(clock.resolution().unwrap_err(), ErrorKind::Unsupported);
            continue;
        }
        let mut last = clock.now().unwrap();
        for _ in 0..1000 {
            let now = clock.now().unwrap();
            assert!(now >= last, "{clock:?} went backwards");
            last = now;
        }

        let pause = Duration::from_millis(20);
        let std_start = Instant::now();
        let start = clock.now().unwrap();
        std::thread::sleep(pause);
        let elapsed = clock.now().unwrap() - start;
        let std_elapsed = std_start.elapsed();
        // `std` slept for at least `pause` by its own clock, which is not
        // exactly this one: allow a millisecond between the two.
        assert!(
            elapsed + Duration::from_millis(1) >= pause,
            "{clock:?}: {elapsed:?}"
        );
        // Read inside std's interval, so no longer than it, give or take the
        // rate difference of two clocks.
        assert!(
            elapsed <= std_elapsed + Duration::from_millis(50),
            "{clock:?}: {elapsed:?} > {std_elapsed:?}"
        );
    }
}

/// A tight loop of readings: on Linux they come from the vDSO, where a
/// reading takes a few nanoseconds and consecutive ones are often equal.
#[test]
fn clocks_never_go_backwards() {
    for clock in [Clock::Monotonic, Clock::Boottime] {
        // WebAssembly has one monotonic clock only.
        if cfg!(target_family = "wasm") && clock == Clock::Boottime {
            continue;
        }
        let mut last = clock.now().unwrap();
        for _ in 0..200_000 {
            let now = clock.now().unwrap();
            assert!(
                now >= last,
                "{clock:?} went backwards: {last:?} then {now:?}"
            );
            last = now;
        }
    }
    // The CPU clocks count time spent, which only grows.
    for clock in [Clock::ProcessCpu, Clock::ThreadCpu] {
        // WASI hosts need not have these clocks: wasmtime does not.
        if cfg!(target_os = "wasi") && clock.now().is_err() {
            continue;
        }
        let mut last = clock.now().unwrap();
        for _ in 0..2_000 {
            let now = clock.now().unwrap();
            assert!(
                now >= last,
                "{clock:?} went backwards: {last:?} then {now:?}"
            );
            last = now;
        }
    }
}

#[test]
fn monotonic_matches_boottime_rate() {
    if cfg!(target_family = "wasm") {
        return; // no Boottime
    }
    // The clocks differ by the time spent suspended, which only grows.
    let monotonic = Clock::Monotonic.now().unwrap();
    let boottime = Clock::Boottime.now().unwrap();
    assert!(
        boottime + Duration::from_millis(100) >= monotonic,
        "{boottime:?} < {monotonic:?}"
    );
}

#[test]
fn cpu_clocks() {
    for clock in [Clock::ProcessCpu, Clock::ThreadCpu] {
        // WASI hosts need not have these clocks: wasmtime does not.
        if cfg!(target_os = "wasi") && clock.now().is_err() {
            continue;
        }
        let wall = Instant::now();
        let (start, end) = spin_until_advanced(clock);
        let wall = wall.elapsed();
        assert!(end > start);
        // One thread cannot use more processor time than time has passed;
        // the process has other threads (the other tests), so allow many.
        if clock == Clock::ThreadCpu {
            assert!(
                end - start <= wall + Duration::from_millis(100),
                "{:?} > {wall:?}",
                end - start
            );
        }
    }
}

#[test]
fn cpu_clock_does_not_count_sleep() {
    let clock = Clock::ThreadCpu;
    if cfg!(target_os = "wasi") && clock.now().is_err() {
        return; // see cpu_clocks
    }
    let start = clock.now().unwrap();
    time::sleep(Duration::from_millis(300)).unwrap();
    let used = clock.now().unwrap() - start;
    assert!(used < Duration::from_millis(250), "{used:?}");
}

#[test]
fn thread_cpu_is_per_thread() {
    if cfg!(target_os = "wasi") {
        return; // no threads
    }
    // A thread that has just started has used less than this one, which
    // burns some first; the process has used at least as much as either.
    let (_, mine) = spin_until_advanced(Clock::ThreadCpu);
    let mut value = 0u64;
    let spin = Instant::now();
    while spin.elapsed() < Duration::from_millis(50) {
        value = std::hint::black_box(value.wrapping_add(1));
    }
    let mine = Clock::ThreadCpu.now().unwrap().max(mine);
    let other = std::thread::spawn(|| Clock::ThreadCpu.now().unwrap())
        .join()
        .unwrap();
    assert!(other < mine, "{other:?} >= {mine:?}");
    let process = Clock::ProcessCpu.now().unwrap();
    // Windows accounts process and thread times in ticks, separately.
    assert!(
        process + Duration::from_millis(50) >= mine,
        "{process:?} < {mine:?}"
    );
}

#[test]
fn resolution() {
    for clock in [
        Clock::Monotonic,
        Clock::Boottime,
        Clock::ProcessCpu,
        Clock::ThreadCpu,
    ] {
        // WASI: see monotonic_clocks and cpu_clocks.
        if cfg!(target_os = "wasi") && clock != Clock::Monotonic && clock.resolution().is_err() {
            continue;
        }
        let resolution = clock.resolution().unwrap();
        assert!(!resolution.is_zero(), "{clock:?}");
        assert!(resolution <= Duration::from_millis(100), "{clock:?}");
    }
}

#[test]
fn sleep() {
    time::sleep(Duration::ZERO).unwrap();
    for pause in [
        Duration::from_nanos(1),
        Duration::from_micros(1500),
        Duration::from_millis(30),
        Duration::from_millis(120),
    ] {
        let std_start = Instant::now();
        let start = Clock::Monotonic.now().unwrap();
        time::sleep(pause).unwrap();
        let elapsed = Clock::Monotonic.now().unwrap() - start;
        let std_elapsed = std_start.elapsed();
        assert!(elapsed >= pause, "{elapsed:?} < {pause:?}");
        // std's clock is the same one on Linux and macOS; elsewhere it is
        // another counter, read around a syscall: allow it 100 µs.
        assert!(
            std_elapsed + Duration::from_micros(100) >= pause,
            "{std_elapsed:?} < {pause:?}"
        );
    }
}

#[test]
fn sleep_until() {
    // A deadline in the past returns at once.
    time::sleep_until(Duration::ZERO).unwrap();
    let now = Clock::Monotonic.now().unwrap();
    time::sleep_until(now).unwrap();

    let pause = Duration::from_millis(40);
    let std_start = Instant::now();
    let deadline = Clock::Monotonic.now().unwrap() + pause;
    time::sleep_until(deadline).unwrap();
    assert!(Clock::Monotonic.now().unwrap() >= deadline);
    assert!(std_start.elapsed() + Duration::from_micros(100) >= pause);
    // And again, now that it has passed.
    time::sleep_until(deadline).unwrap();
}

/// Sleeps longer than any system counts (`Duration::MAX` is 584 billion
/// years) do sleep: they neither fail nor return at once. The threads are
/// left asleep, which the end of the process ends. WASI has no threads to
/// leave behind.
#[cfg(not(target_os = "wasi"))]
#[test]
fn huge_sleeps() {
    let (sender, receiver) = std::sync::mpsc::channel();
    let durations = [
        Duration::MAX,
        Duration::from_secs(u64::MAX),
        Duration::from_secs(i64::MAX as u64),
        Duration::from_nanos(u64::MAX),
        Duration::from_nanos(i64::MAX as u64),
        Duration::from_secs(u32::MAX as u64 + 1),
    ];
    for duration in durations {
        for until in [false, true] {
            let sender = sender.clone();
            std::thread::spawn(move || {
                let result = if until {
                    time::sleep_until(duration)
                } else {
                    time::sleep(duration)
                };
                let _ = sender.send((duration, until, result.map_err(|e| e.raw_os_error())));
            });
        }
    }
    drop(sender);
    match receiver.recv_timeout(Duration::from_millis(500)) {
        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
        woke => panic!("a sleep is over: {woke:?}"),
    }
}