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
//! Encapsulation for system call arguments and return values.
//!
//! The inline-asm and outline-asm code paths do some amount of reordering
//! of arguments; to ensure that we don't accidentally misroute an argument
//! or return value, we use distinct types for each argument index and
//! return value.
//!
//! # Safety
//!
//! The `ToAsm` and `FromAsm` traits are unsafe to use; they should only be
//! used by the syscall code which executes actual syscall machine
//! instructions.

#![allow(unsafe_code)]

use super::c;
use super::fd::RawFd;
use core::marker::PhantomData;
use core::ops::Range;

pub(super) trait ToAsm: private::Sealed {
    /// Convert `self` to a `usize` ready to be passed to a syscall
    /// machine instruction.
    ///
    /// # Safety
    ///
    /// This should be used immediately before the syscall instruction, and
    /// the returned value shouldn't be used for any other purpose.
    #[must_use]
    unsafe fn to_asm(self) -> *mut Opaque;
}

pub(super) trait FromAsm: private::Sealed {
    /// Convert `raw` from a value produced by a syscall machine instruction
    /// into a `Self`.
    ///
    /// # Safety
    ///
    /// This should be used immediately after the syscall instruction, and
    /// the operand value shouldn't be used for any other purpose.
    #[must_use]
    unsafe fn from_asm(raw: *mut Opaque) -> Self;
}

/// To preserve provenance, syscall arguments and return values are passed as
/// pointer types. They need a type to point to, so we define a custom private
/// type, to prevent it from being used for anything else.
#[repr(transparent)]
pub(super) struct Opaque(c::c_void);

// Argument numbers.
pub(super) struct A0(());
pub(super) struct A1(());
pub(super) struct A2(());
pub(super) struct A3(());
pub(super) struct A4(());
pub(super) struct A5(());
#[cfg(target_arch = "mips")]
pub(super) struct A6(());
#[cfg(target_arch = "x86")]
pub(super) struct SocketArg;

pub(super) trait ArgNumber: private::Sealed {}
impl ArgNumber for A0 {}
impl ArgNumber for A1 {}
impl ArgNumber for A2 {}
impl ArgNumber for A3 {}
impl ArgNumber for A4 {}
impl ArgNumber for A5 {}
#[cfg(target_arch = "mips")]
impl ArgNumber for A6 {}
#[cfg(target_arch = "x86")]
impl ArgNumber for SocketArg {}

// Return value numbers.
pub(super) struct R0(());

pub(super) trait RetNumber: private::Sealed {}
impl RetNumber for R0 {}

/// Syscall arguments use register-sized types. We use a newtype to
/// discourage accidental misuse of the raw integer values.
///
/// This type doesn't implement `Clone` or `Copy`; it should be used exactly
/// once. And it has a lifetime to ensure that it doesn't outlive any resources
/// it might be pointing to.
#[repr(transparent)]
#[must_use]
pub(super) struct ArgReg<'a, Num: ArgNumber> {
    raw: *mut Opaque,
    _phantom: PhantomData<(&'a (), Num)>,
}

impl<'a, Num: ArgNumber> ToAsm for ArgReg<'a, Num> {
    #[inline]
    unsafe fn to_asm(self) -> *mut Opaque {
        self.raw
    }
}

/// Syscall return values use register-sized types. We use a newtype to
/// discourage accidental misuse of the raw integer values.
///
/// This type doesn't implement `Clone` or `Copy`; it should be used exactly
/// once.
#[repr(transparent)]
#[must_use]
pub(super) struct RetReg<Num: RetNumber> {
    raw: *mut Opaque,
    _phantom: PhantomData<Num>,
}

impl<Num: RetNumber> RetReg<Num> {
    #[inline]
    pub(super) fn decode_usize(self) -> usize {
        debug_assert!(!(-4095..0).contains(&(self.raw as isize)));
        self.raw as usize
    }

    #[inline]
    pub(super) fn decode_raw_fd(self) -> RawFd {
        let bits = self.decode_usize();
        let raw_fd = bits as RawFd;

        // Converting `raw` to `RawFd` should be lossless.
        debug_assert_eq!(raw_fd as usize, bits);

        raw_fd
    }

    #[inline]
    pub(super) fn decode_c_int(self) -> c::c_int {
        let bits = self.decode_usize();
        let c_int_ = bits as c::c_int;

        // Converting `raw` to `c_int` should be lossless.
        debug_assert_eq!(c_int_ as usize, bits);

        c_int_
    }

    #[inline]
    pub(super) fn decode_c_uint(self) -> c::c_uint {
        let bits = self.decode_usize();
        let c_uint_ = bits as c::c_uint;

        // Converting `raw` to `c_uint` should be lossless.
        debug_assert_eq!(c_uint_ as usize, bits);

        c_uint_
    }

    #[inline]
    pub(super) fn decode_void_star(self) -> *mut c::c_void {
        self.raw.cast()
    }

    #[cfg(target_pointer_width = "64")]
    #[inline]
    pub(super) fn decode_u64(self) -> u64 {
        self.decode_usize() as u64
    }

    #[inline]
    pub(super) fn decode_void(self) {
        let ignore = self.decode_usize();
        debug_assert_eq!(ignore, 0);
    }

    #[inline]
    pub(super) fn decode_error_code(self) -> u16 {
        let bits = self.raw as usize;

        // `raw` must be in `-4095..0`. Linux always returns errors in
        // `-4095..0`, and we double-check it here.
        debug_assert!((-4095..0).contains(&(bits as isize)));

        bits as u16
    }

    #[inline]
    pub(super) fn is_nonzero(&self) -> bool {
        !self.raw.is_null()
    }

    #[inline]
    pub(super) fn is_negative(&self) -> bool {
        (self.raw as isize) < 0
    }

    #[inline]
    pub(super) fn is_in_range(&self, range: Range<isize>) -> bool {
        range.contains(&(self.raw as isize))
    }
}

impl<Num: RetNumber> FromAsm for RetReg<Num> {
    #[inline]
    unsafe fn from_asm(raw: *mut Opaque) -> Self {
        Self {
            raw,
            _phantom: PhantomData,
        }
    }
}

#[repr(transparent)]
pub(super) struct SyscallNumber<'a> {
    nr: usize,
    _phantom: PhantomData<&'a ()>,
}

impl<'a> ToAsm for SyscallNumber<'a> {
    #[inline]
    unsafe fn to_asm(self) -> *mut Opaque {
        self.nr as usize as *mut Opaque
    }
}

/// Encode a system call argument as an `ArgReg`.
#[inline]
pub(super) fn raw_arg<'a, Num: ArgNumber>(raw: *mut Opaque) -> ArgReg<'a, Num> {
    ArgReg {
        raw,
        _phantom: PhantomData,
    }
}

/// Encode a system call number (a `__NR_*` constant) as a `SyscallNumber`.
#[inline]
pub(super) const fn nr<'a>(nr: u32) -> SyscallNumber<'a> {
    SyscallNumber {
        nr: nr as usize,
        _phantom: PhantomData,
    }
}

/// Seal our various traits using the technique documented [here].
///
/// [here]: https://rust-lang.github.io/api-guidelines/future-proofing.html
mod private {
    pub trait Sealed {}

    // Implement for those same types, but no others.
    impl<'a, Num: super::ArgNumber> Sealed for super::ArgReg<'a, Num> {}
    impl<Num: super::RetNumber> Sealed for super::RetReg<Num> {}
    impl<'a> Sealed for super::SyscallNumber<'a> {}
    impl Sealed for super::A0 {}
    impl Sealed for super::A1 {}
    impl Sealed for super::A2 {}
    impl Sealed for super::A3 {}
    impl Sealed for super::A4 {}
    impl Sealed for super::A5 {}
    #[cfg(target_arch = "mips")]
    impl Sealed for super::A6 {}
    #[cfg(target_arch = "x86")]
    impl Sealed for super::SocketArg {}
    impl Sealed for super::R0 {}
}