r-linux 0.1.0

Capability-based Linux Runtime
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
//! Raw System Calls
//!
//! This module provides raw and direct access to system calls on linux
//! platforms. It exports 7 different functions, one for each possible number
//! of arguments you can pass to a syscall (`syscall0` through `syscall6`). It
//! is always safe to use `syscall6()` and set unused arguments to any value.
//! For performance reasons, you might want to prefer the matching call,
//! though.
//!
//! This implementation is optimized to allow inlining of the system-call
//! invocation into the calling function. That is, when xLTO is used, the
//! syscall setup and instruction will be inlined into the caller, and thus
//! allows fast and efficient kernel calls. On common architectures, the inline
//! assembly is now stable rust, so no cross-language LTO is needed, anyway.
//!
//! Linux system calls take between 0 and 6 arguments, each argument is passed
//! as a native integer. Furthermore, every system call has a return value,
//! which also is a native integer. Depending on the platform you run on, the
//! actual underlying datatype will have different size constraints (e.g., on
//! 32bit machines all arguments are usually 32bit integers, but on 64bit
//! machines you pass 64bit integers). You should consult the documentation of
//! each system call to understand how individual arguments are passed. Be
//! warned, there are even system calls that flip argument order depending on
//! the architecture (for historical reasons, trying to provide binary
//! compatibility to existing platforms). Use the wrapper definitions to get a
//! verified function prototype for each system call.
//!
//! The return value of a system call is limited to a native integer.
//! Furthermore, 4096 values are reserved for error codes. For most syscalls
//! it is enough to interpret the return value as signed integer and consider
//! any negative value as error. However, in some special cases this is not
//! correct. Therefore, the `Retval` type provides small accessors to check
//! whether the return value is an error code or not. If performance is not
//! a concern, it also provides a conversion to `Result`.

/// System Call Return Value
///
/// On linux platforms, system calls return native integers as result. A
/// special range is used for errors. This type wraps this result type and
/// provides accessors to its underlying values.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Retval(usize);

impl Retval {
    /// Create a new return-value from raw data
    pub const fn from_usize(v: usize) -> Retval {
        Retval(v)
    }

    /// Return raw underlying data of a return-value
    pub const fn as_usize(self) -> usize {
        self.0
    }

    /// Check whether this is an error-return
    pub const fn is_error(self) -> bool {
        self.0 > core::usize::MAX - 4096
    }

    /// Check whether this is a success-return
    pub const fn is_success(self) -> bool {
        !self.is_error()
    }

    /// Return the error-code unchecked
    ///
    /// # Safety
    ///
    /// This does not verify that `self` is actually an error-return. It
    /// assumes the caller verified it.
    pub unsafe fn error_unchecked(self) -> usize {
        !self.0 + 1
    }

    /// Return the error-code
    ///
    /// If `self` is not actually an error-return, this will panic.
    pub fn error(self) -> usize {
        if self.is_error() {
            unsafe { self.error_unchecked() }
        } else {
            panic!("called `r_linux::syscall::raw::Retval::error()` on a success value")
        }
    }

    /// Return the success-value unchecked
    ///
    /// # Safety
    ///
    /// This does not verify that `self` is actually a success-return. It
    /// assumes the caller verified it.
    pub unsafe fn unwrap_unchecked(self) -> usize {
        self.0
    }

    /// Return the success value
    ///
    /// If `self` is not a success-return, this will panic.
    pub fn unwrap(self) -> usize {
        if self.is_success() {
            unsafe { self.unwrap_unchecked() }
        } else {
            panic!("called `r_linux::syscall::raw::Retval::unwrap()` on an error value")
        }
    }

    /// Convert into a Result
    ///
    /// This converts the return value into a rust-native Result type. This
    /// maps the error-return to `Err(code)` and the success-return
    /// to `Ok(usize)`. This allows using the rich convenience library of the
    /// `Result` type, rather than re-implementing them for this native type.
    pub fn to_result(self) -> Result<usize, usize> {
        if self.is_error() {
            Err(!self.0 + 1)
        } else {
            Ok(self.0)
        }
    }
}

/// Invoke System Call With 0 Arguments
///
/// This invokes the system call with the specified system-call-number. No
/// arguments are passed to the system call.
///
/// # Safety
///
/// * System calls can have arbitrary side-effects. It is the responsibility of
///   the caller to consider all effects of a system call and take required
///   precautions.
pub unsafe fn syscall0(
    nr: usize,
) -> Retval {
    Retval::from_usize(
        super::arch::native::syscall::syscall0(
            nr,
        )
    )
}

/// Invoke System Call With 1 Argument
///
/// This invokes the system call with the specified system-call-number. The
/// provided argument is passed to the system call unmodified.
///
/// # Safety
///
/// * System calls can have arbitrary side-effects. It is the responsibility of
///   the caller to consider all effects of a system call and take required
///   precautions.
pub unsafe fn syscall1(
    nr: usize,
    arg0: usize,
) -> Retval {
    Retval::from_usize(
        super::arch::native::syscall::syscall1(
            nr,
            arg0,
        )
    )
}

/// Invoke System Call With 2 Arguments
///
/// This invokes the system call with the specified system-call-number. The
/// provided arguments are passed to the system call unmodified.
///
/// # Safety
///
/// * System calls can have arbitrary side-effects. It is the responsibility of
///   the caller to consider all effects of a system call and take required
///   precautions.
pub unsafe fn syscall2(
    nr: usize,
    arg0: usize,
    arg1: usize,
) -> Retval {
    Retval::from_usize(
        super::arch::native::syscall::syscall2(
            nr,
            arg0,
            arg1,
        )
    )
}

/// Invoke System Call With 3 Arguments
///
/// This invokes the system call with the specified system-call-number. The
/// provided arguments are passed to the system call unmodified.
///
/// # Safety
///
/// * System calls can have arbitrary side-effects. It is the responsibility of
///   the caller to consider all effects of a system call and take required
///   precautions.
pub unsafe fn syscall3(
    nr: usize,
    arg0: usize,
    arg1: usize,
    arg2: usize,
) -> Retval {
    Retval::from_usize(
        super::arch::native::syscall::syscall3(
            nr,
            arg0,
            arg1,
            arg2,
        )
    )
}

/// Invoke System Call With 4 Arguments
///
/// This invokes the system call with the specified system-call-number. The
/// provided arguments are passed to the system call unmodified.
///
/// # Safety
///
/// * System calls can have arbitrary side-effects. It is the responsibility of
///   the caller to consider all effects of a system call and take required
///   precautions.
pub unsafe fn syscall4(
    nr: usize,
    arg0: usize,
    arg1: usize,
    arg2: usize,
    arg3: usize,
) -> Retval {
    Retval::from_usize(
        super::arch::native::syscall::syscall4(
            nr,
            arg0,
            arg1,
            arg2,
            arg3,
        )
    )
}

/// Invoke System Call With 5 Arguments
///
/// This invokes the system call with the specified system-call-number. The
/// provided arguments are passed to the system call unmodified.
///
/// # Safety
///
/// * System calls can have arbitrary side-effects. It is the responsibility of
///   the caller to consider all effects of a system call and take required
///   precautions.
pub unsafe fn syscall5(
    nr: usize,
    arg0: usize,
    arg1: usize,
    arg2: usize,
    arg3: usize,
    arg4: usize,
) -> Retval {
    Retval::from_usize(
        super::arch::native::syscall::syscall5(
            nr,
            arg0,
            arg1,
            arg2,
            arg3,
            arg4,
        )
    )
}

/// Invoke System Call With 6 Arguments
///
/// This invokes the system call with the specified system-call-number. The
/// provided arguments are passed to the system call unmodified.
///
/// # Safety
///
/// * System calls can have arbitrary side-effects. It is the responsibility of
///   the caller to consider all effects of a system call and take required
///   precautions.
pub unsafe fn syscall6(
    nr: usize,
    arg0: usize,
    arg1: usize,
    arg2: usize,
    arg3: usize,
    arg4: usize,
    arg5: usize,
) -> Retval {
    Retval::from_usize(
        super::arch::native::syscall::syscall6(
            nr,
            arg0,
            arg1,
            arg2,
            arg3,
            arg4,
            arg5,
        )
    )
}

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

    #[test]
    fn retval_check() {
        //
        // Check basic functionality of the `Retval` type and verify it has
        // the same semantics as the system call ABI.
        //

        let success_values = [
            0, 1, 2, 3,
            254, 255, 256, 257,
            65534, 65535, 65536, 65537,
            core::usize::MAX / 2,
            core::usize::MAX / 2 + 1,
            core::usize::MAX - 4097,
            core::usize::MAX - 4096,
        ];

        for v in &success_values {
            let r = Retval::from_usize(*v);

            assert_eq!(r, Retval(*v));
            assert_eq!(r.as_usize(), *v);
            assert_eq!(r.is_success(), true);
            assert_eq!(r.is_error(), false);
            assert_eq!(unsafe { r.unwrap_unchecked() }, *v);
            assert_eq!(r.unwrap(), *v);
            assert_eq!(r.to_result(), Ok(*v));
        }

        let error_values = [
            (4096, core::usize::MAX - 4095),
            (4095, core::usize::MAX - 4094),
            (4094, core::usize::MAX - 4093),
            (4093, core::usize::MAX - 4092),
            (4, core::usize::MAX - 3),
            (3, core::usize::MAX - 2),
            (2, core::usize::MAX - 1),
            (1, core::usize::MAX),
        ];

        for (c, v) in &error_values {
            let r = Retval::from_usize(*v);

            assert_eq!(r, Retval(*v));
            assert_eq!(r.as_usize(), *v);
            assert_eq!(r.is_success(), false);
            assert_eq!(r.is_error(), true);
            assert_eq!(unsafe { r.error_unchecked() }, *c);
            assert_eq!(r.error(), *c);
            assert_eq!(r.to_result(), Err(*c));
        }

        let r = Retval::from_usize(71);

        // verify copy behavior
        let copy = r;
        assert_ne!(&copy as *const _, &r as *const _);
        assert_eq!(copy, r);

        // verify clone support
        let clone = r.clone();
        assert_ne!(&clone as *const _, &r as *const _);
        assert_eq!(clone, r);

        // verify comparisons
        let (com1, com2) = (Retval::from_usize(71), Retval::from_usize(72));
        assert_eq!(r, com1);
        assert_ne!(r, com2);
    }

    #[test]
    #[should_panic]
    fn retval_error_panic() {
        //
        // Verify `Retval::error()` panics on success-values.
        //

        Retval::from_usize(0).error();
    }

    #[test]
    #[should_panic]
    fn retval_unwrap_panic() {
        //
        // Verify `Retval::unwrap()` panics on error-values.
        //

        Retval::from_usize(core::usize::MAX).unwrap();
    }

    #[test]
    fn syscall0_check() {
        //
        // Test validity of `syscall0()`.
        //
        // Tested syscall: GETPID
        //

        let r0 = unsafe { syscall0(crate::syscall::arch::native::nr::GETPID) };
        assert_eq!(r0.unwrap() as u32, std::process::id());
    }

    #[test]
    fn syscall1_check() {
        //
        // Test validity of `syscall1()`.
        //
        // Tested syscall: CLOSE
        //
        // We run `pipe2()` and verify the `close()` syscall accepts the values
        // without complaint.
        //

        let mut p0: [u32; 2] = [0, 0];

        let r0 = unsafe {
            syscall2(
                crate::syscall::arch::native::nr::PIPE2,
                p0.as_mut_ptr() as usize,
                0,
            ).unwrap()
        };
        assert_eq!(r0, 0);
        assert!(p0[0] > 2);
        assert!(p0[1] > 2);
        assert_ne!(p0[0], p0[1]);

        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                p0[0] as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);
        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                p0[1] as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);
    }

    #[test]
    fn syscall2_check() {
        //
        // Test validity of `syscall2()`.
        //
        // Tested syscall: PIPE2
        //
        // We run `pipe2()` and verify the `close()` syscall accepts the values
        // without complaint.
        //

        let mut p0: [u32; 2] = [0, 0];

        let r0 = unsafe {
            syscall2(
                crate::syscall::arch::native::nr::PIPE2,
                p0.as_mut_ptr() as usize,
                0,
            ).unwrap()
        };
        assert_eq!(r0, 0);
        assert!(p0[0] > 2);
        assert!(p0[1] > 2);
        assert_ne!(p0[0], p0[1]);

        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                p0[0] as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);
        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                p0[1] as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);
    }

    #[test]
    fn syscall3_check() {
        //
        // Test validity of `syscall3()`.
        //
        // Tested syscall: WRITE / READ
        //
        // We create a pipe, write to one end and verify we can read the same
        // data from the other end.
        //

        let mut p0: [u32; 2] = [0, 0];
        let mut b0: [u8; 16] = [0; 16];

        let r0 = unsafe {
            syscall2(
                crate::syscall::arch::native::nr::PIPE2,
                p0.as_mut_ptr() as usize,
                0,
            ).unwrap()
        };
        assert_eq!(r0, 0);
        assert!(p0[0] > 2);
        assert!(p0[1] > 2);
        assert_ne!(p0[0], p0[1]);

        let r0 = unsafe {
            syscall3(
                crate::syscall::arch::native::nr::WRITE,
                p0[1] as usize,
                "foobar".as_ptr() as usize,
                6 as usize,
            )
            .unwrap()
        };
        assert_eq!(r0, 6);

        let r0 = unsafe {
            syscall3(
                crate::syscall::arch::native::nr::READ,
                p0[0] as usize,
                b0.as_mut_ptr() as usize,
                6 as usize,
            )
            .unwrap()
        };
        assert_eq!(r0, 6);
        assert_eq!(core::str::from_utf8(&b0[..6]), Ok("foobar"));

        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                p0[0] as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);
        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                p0[1] as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);
    }

    #[test]
    fn syscall4_check() {
        //
        // Test validity of `syscall4()`.
        //
        // Tested syscall: READLINKAT
        //
        // We create a memfd and then query `/proc` for the link-value of the
        // memfd. This is ABI and needs to be the (annotated) name that we
        // passed to `memfd_create()`.
        //

        let mut b0: [u8; 128] = [0; 128];

        let f0 = unsafe {
            syscall2(
                crate::syscall::arch::native::nr::MEMFD_CREATE,
                "foobar\x00".as_ptr() as usize,
                0,
            ).unwrap()
        };
        assert!(f0 > 2);

        let r0 = unsafe {
            syscall4(
                crate::syscall::arch::native::nr::READLINKAT,
                core::usize::MAX - 100 + 1, // AT_FDCWD
                format!("/proc/self/fd/{}\x00", f0).as_str().as_ptr() as usize,
                b0.as_mut_ptr() as usize,
                128 - 1,
            )
            .unwrap()
        };
        assert_eq!(r0, 23);
        assert_eq!(
            core::str::from_utf8(&b0[..23]).unwrap(),
            "/memfd:foobar (deleted)",
        );

        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                f0,
            ).unwrap()
        };
        assert_eq!(r0, 0);
    }

    #[test]
    fn syscall5_check() {
        //
        // Test validity of `syscall5()`.
        //
        // Tested syscall: STATX
        //
        // Run `statx()` on `STDIN`, but pass `AT_SYMLINK_NOFOLLOW`. This
        // means we instead get information on the symlink in `/proc`. Check
        // that this was correctly interpreted by the kernel and verify the
        // `S_IFLNK` flag is set on the result.
        //

        let mut b0: [u32; 1024] = [0; 1024];

        let r0 = unsafe {
            syscall5(
                crate::syscall::arch::native::nr::STATX,
                core::usize::MAX - 100 + 1, // AT_FDCWD
                "/proc/self/fd/0".as_ptr() as usize,
                0x100, // AT_SYMLINK_NOFOLLOW
                0x1,   // STATX_TYPE
                b0.as_mut_ptr() as usize,
            )
            .unwrap()
        };
        assert_eq!(r0, 0);
        assert_ne!(b0[0] & 0x1, 0);
        assert_eq!(
            unsafe {
                core::ptr::read_unaligned(
                    (b0.as_ptr() as *const u16).offset(14)
                )
            } & 0o170000, // S_IFMT
            0o120000, // S_IFLNK
        );
    }

    #[test]
    fn syscall6_check() {
        //
        // Test validity of `syscall6()`.
        //
        // Tested syscall: COPY_FILE_RANGE
        //
        // Create two memfd instances, write a text into the first one. Use
        // the `copy_file_range()` syscall to copy the data over into the other
        // memfd and then verify via `read()`. Use `lseek()` to reset the file
        // position between calls.
        //

        let mut b0: [u8; 128] = [0; 128];

        let f0 = unsafe {
            syscall2(
                crate::syscall::arch::native::nr::MEMFD_CREATE,
                "foobar\x00".as_ptr() as usize,
                0,
            ).unwrap()
        };
        let f1 = unsafe {
            syscall2(
                crate::syscall::arch::native::nr::MEMFD_CREATE,
                "foobar\x00".as_ptr() as usize,
                0,
            ).unwrap()
        };
        assert!(f0 > 2);
        assert!(f1 > 2);
        assert_ne!(f0, f1);

        let r0 = unsafe {
            syscall3(
                crate::syscall::arch::native::nr::WRITE,
                f0 as usize,
                "foobar".as_ptr() as usize,
                6 as usize,
            )
            .unwrap()
        };
        assert_eq!(r0, 6);

        let r0 = unsafe {
            syscall3(
                crate::syscall::arch::native::nr::LSEEK,
                f0 as usize,
                0 as usize,
                0 as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);

        let r0 = unsafe {
            syscall6(
                crate::syscall::arch::native::nr::COPY_FILE_RANGE,
                f0 as usize,
                0 as usize,
                f1 as usize,
                0 as usize,
                6 as usize,
                0 as usize,
            )
            .unwrap()
        };
        assert_eq!(r0, 6);

        let r0 = unsafe {
            syscall3(
                crate::syscall::arch::native::nr::LSEEK,
                f1 as usize,
                0 as usize,
                0 as usize,
            ).unwrap()
        };
        assert_eq!(r0, 0);

        let r0 = unsafe {
            syscall3(
                crate::syscall::arch::native::nr::READ,
                f1 as usize,
                b0.as_mut_ptr() as usize,
                6 as usize,
            )
            .unwrap()
        };
        assert_eq!(r0, 6);
        assert_eq!(core::str::from_utf8(&b0[..6]), Ok("foobar"));

        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                f1,
            ).unwrap()
        };
        assert_eq!(r0, 0);
        let r0 = unsafe {
            syscall1(
                crate::syscall::arch::native::nr::CLOSE,
                f0,
            ).unwrap()
        };
        assert_eq!(r0, 0);
    }
}