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
//! Data structures for passing application memory to the kernel.
//!
//! A Tock process can pass read-write or read-only buffers into the
//! kernel for it to use. The kernel checks that read-write buffers
//! exist within a process's RAM address space, and that read-only
//! buffers exist either within its RAM or flash address space. These
//! buffers are shared with the allow_read_write() and
//! allow_read_only() system calls.
//!
//! A read-write and read-only call is mapped to the high-level Rust
//! types [`ReadWriteAppSlice`] and [`ReadOnlyAppSlice`]
//! respectively. The memory regions can be accessed through the
//! [`Read`] and [`ReadWrite`] traits, implemented on the
//! AppSlice-structs.

use crate::capabilities;
use crate::process::ProcessId;

/// Convert an AppSlice's internal representation to a Rust slice.
///
/// This function will automatically convert zero-length AppSlices
/// into valid zero-sized Rust slices regardless of the value of
/// `ptr`.
///
/// # Safety requirements
///
/// In the case of `len != 0`, the memory `[ptr; ptr + len)` must be
/// within a single process' address space, and `ptr` must be
/// nonzero. This memory region must be mapped as _readable_, and
/// optionally _writable_ and _executable_. It must be allocated
/// within a single process' address space for the entire lifetime
/// `'a`. No mutable slice pointing to an overlapping memory region
/// may exist over the entire lifetime `'a`.
unsafe fn raw_appslice_to_slice<'a>(ptr: *const u8, len: usize) -> &'a [u8] {
    use core::ptr::NonNull;
    use core::slice::from_raw_parts;

    // Rust has very strict requirements on pointer validity[1] which
    // also in part apply to accesses of length 0. We allow an
    // application to supply arbitrary pointers if the buffer length is
    // 0, but this is not allowed for Rust slices. For instance, a null
    // pointer is _never_ valid, not even for accesses of size zero.
    //
    // To get a pointer which does not point to valid (allocated) memory, but
    // is safe to construct for accesses of size zero, we must call
    // NonNull::dangling(). The resulting pointer is guaranteed to be well-aligned
    // and uphold the guarantees required for accesses of size zero.
    //
    // [1]: https://doc.rust-lang.org/core/ptr/index.html#safety
    match len {
        0 => from_raw_parts(NonNull::<u8>::dangling().as_ptr(), 0),
        _ => from_raw_parts(ptr, len),
    }
}

/// Convert an AppSlice's internal representation to a mutable Rust
/// slice.
///
/// This function will automatically convert zero-length appslices
/// into valid zero-sized Rust slices regardless of the value of
/// `ptr`.
///
/// # Safety requirements
///
/// In the case of `len != 0`, the memory `[ptr; ptr + len)` must be
/// within a single process' address space, and `ptr` must be
/// nonzero. This memory region must be mapped as _readable_ and
/// _writable_, and optionally _executable_. It must be allocated
/// within a single process' address space for the entire lifetime
/// `'a`. No other mutable or immutable slice pointing to an
/// overlapping memory region may exist over the entire lifetime `'a`.
unsafe fn raw_appslice_to_slice_mut<'a>(ptr: *mut u8, len: usize) -> &'a mut [u8] {
    use core::ptr::NonNull;
    use core::slice::from_raw_parts_mut;

    // See documentation on [`raw_appslice_to_slice`] for Rust slice &
    // pointer validity requirements
    match len {
        0 => from_raw_parts_mut(NonNull::<u8>::dangling().as_ptr(), 0),
        _ => from_raw_parts_mut(ptr, len),
    }
}

/// A readable region of userspace memory.
///
/// This trait can be used to gain read-only access to memory regions
/// wrapped in an AppSlice type.
pub trait Read {
    /// Length of the memory region.
    ///
    /// If the process is no longer alive and the memory has been
    /// reclaimed, this method must return 0.
    ///
    /// # Default AppSlice
    ///
    /// A default instance of an AppSlice must return 0.
    fn len(&self) -> usize;

    /// Pointer to the first byte of the userspace memory region.
    ///
    /// If the length of the initially shared memory region
    /// (irrespective of the return value of [`len`](Read::len)) is 0,
    /// this function returns a pointer to address `0x0`. This is
    /// because processes may allow buffers with length 0 to share no
    /// no memory with the kernel. Because these buffers have zero
    /// length, they may have any pointer value. However, these
    /// _dummy addresses_ should not be leaked, so this method returns
    /// 0 for zero-length slices.
    ///
    /// # Default AppSlice
    ///
    /// A default instance of an AppSlice must return a pointer to
    /// address `0x0`.
    fn ptr(&self) -> *const u8;

    /// Applies a function to the (read only) slice reference pointed
    /// to by the AppSlice.
    ///
    /// If the process is no longer alive and the memory has been
    /// reclaimed, this method must return the default value.
    ///
    /// # Default AppSlice
    ///
    /// A default instance of an AppSlice must return the passed
    /// default value without executing the closure.
    fn map_or<F, R>(&self, default: R, fun: F) -> R
    where
        F: FnOnce(&[u8]) -> R;
}

/// A readable and writable region of userspace memory.
///
/// This trait can be used to gain read-write access to memory regions
/// wrapped in an AppSlice type.
///
/// This is a supertrait of [`Read`], which features further methods.
pub trait ReadWrite: Read {
    /// Applies a function to the mutable slice reference pointed to
    /// by the AppSlice.
    ///
    /// If the process is no longer alive and the memory has been
    /// reclaimed, this method must return the default value.
    ///
    /// # Default AppSlice
    ///
    /// A default instance of an AppSlice must return the passed
    /// default value without executing the closure.
    fn mut_map_or<F, R>(&mut self, default: R, fun: F) -> R
    where
        F: FnOnce(&mut [u8]) -> R;
}

/// Read-writable memory region of a process, shared with the kernel
pub struct ReadWriteAppSlice {
    ptr: *mut u8,
    len: usize,
    process_id: Option<ProcessId>,
}

impl ReadWriteAppSlice {
    /// Construct a new [`ReadWriteAppSlice`] over a given pointer and
    /// length.
    ///
    /// # Safety requirements
    ///
    /// Refer to the safety requirments of
    /// [`ReadWriteAppSlice::new_external`].
    pub(crate) unsafe fn new(ptr: *mut u8, len: usize, process_id: ProcessId) -> Self {
        ReadWriteAppSlice {
            ptr,
            len,
            process_id: Some(process_id),
        }
    }

    /// Construct a new [`ReadWriteAppSlice`] over a given pointer and
    /// length.
    ///
    /// Publicly accessible constructor, which requires the
    /// [`capabilities::ExternalProcessCapability`] capability. This
    /// is provided to allow implementations of the
    /// [`Process`](crate::process::Process) trait outside of
    /// the `kernel` crate.
    ///
    /// # Safety requirements
    ///
    /// In Rust, no two slices may point to the same memory location
    /// if at least one is mutable. This constructor relies on the
    /// fact that at most a single [`ReadWriteAppSlice`] or
    /// [`ReadOnlyAppSlice`] will point to the memory region of `[ptr;
    /// ptr + len)`, and no other slice in scope anywhere in the
    /// kernel points to an overlapping memory region.
    ///
    /// If the length is `0`, an arbitrary pointer may be passed into
    /// `ptr`. It does not necessarily have to point to allocated
    /// memory, nor does it have to meet [Rust's pointer validity
    /// requirements](https://doc.rust-lang.org/core/ptr/index.html#safety).
    /// [`ReadWriteAppSlice`] must ensure that all Rust slices with a
    /// length of `0` must be constructed over a valid (but not
    /// necessarily allocated) base pointer.
    ///
    /// If the length is not `0`, the memory region of `[ptr; ptr +
    /// len)` must be valid memory of the process of the given
    /// [`ProcessId`]. It must be allocated and and accessible over the
    /// entire lifetime of the [`ReadWriteAppSlice`]. It must not
    /// point to memory outside of the process' accessible memory
    /// range, or point (in part) to other processes or kernel
    /// memory. The `ptr` must meet [Rust's requirements for pointer
    /// validity](https://doc.rust-lang.org/core/ptr/index.html#safety),
    /// in particular it must have a minimum alignment of
    /// `core::mem::align_of::<u8>()` on the respective platform. It
    /// must point to memory mapped as _readable_ and _writable_ and
    /// optionally _executable_.
    pub unsafe fn new_external(
        ptr: *mut u8,
        len: usize,
        process_id: ProcessId,
        _cap: &dyn capabilities::ExternalProcessCapability,
    ) -> Self {
        Self::new(ptr, len, process_id)
    }

    /// Consumes the ReadWriteAppSlice, returning its constituent
    /// pointer and size. This ensures that there cannot simultaneously
    /// be both a `ReadWriteAppSlice` and a pointer to its internal data.
    ///
    /// `consume` can be used when the kernel needs to pass the underlying
    /// values across the kernel-to-user boundary (e.g., in return values to
    /// system calls).
    pub(crate) fn consume(self) -> (*mut u8, usize) {
        (self.ptr, self.len)
    }

    /// This is a `const` version of `Default::default` with the same semantics.
    ///
    /// Having a const initializer allows initializing a fixed-size array with default values
    /// without the struct being marked `Copy` as such:
    ///
    /// ```
    /// use kernel::ReadWriteAppSlice;
    /// const DEFAULT_RWAPPSLICE_VAL: ReadWriteAppSlice = ReadWriteAppSlice::const_default();
    /// let my_array = [DEFAULT_RWAPPSLICE_VAL; 12];
    /// ```
    pub const fn const_default() -> Self {
        Self {
            ptr: 0x0 as *mut u8,
            len: 0,
            process_id: None,
        }
    }
}

impl Default for ReadWriteAppSlice {
    fn default() -> Self {
        Self::const_default()
    }
}

impl ReadWrite for ReadWriteAppSlice {
    fn mut_map_or<F, R>(&mut self, default: R, fun: F) -> R
    where
        F: FnOnce(&mut [u8]) -> R,
    {
        match self.process_id {
            None => default,
            Some(pid) => pid.kernel.process_map_or(default, pid, |_| {
                // Safety: `kernel.process_map_or()` validates that the process still exists
                // and its memory is still valid. `Process` tracks the "high water mark" of
                // memory that the process has `allow`ed to the kernel, and will not permit
                // the process to free any memory after it has been `allow`ed. This guarantees
                // that the buffer is safe to convert into a slice here.
                fun(unsafe { raw_appslice_to_slice_mut(self.ptr, self.len) })
            }),
        }
    }
}

impl Read for ReadWriteAppSlice {
    fn len(&self) -> usize {
        self.process_id
            .map_or(0, |pid| pid.kernel.process_map_or(0, pid, |_| self.len))
    }

    fn ptr(&self) -> *const u8 {
        if self.len == 0 {
            0x0 as *const u8
        } else {
            self.ptr
        }
    }

    fn map_or<F, R>(&self, default: R, fun: F) -> R
    where
        F: FnOnce(&[u8]) -> R,
    {
        match self.process_id {
            None => default,
            Some(pid) => pid.kernel.process_map_or(default, pid, |_| {
                // Safety: `kernel.process_map_or()` validates that the process still exists
                // and its memory is still valid. `Process` tracks the "high water mark" of
                // memory that the process has `allow`ed to the kernel, and will not permit
                // the process to free any memory after it has been `allow`ed. This guarantees
                // that the buffer is safe to convert into a slice here.
                fun(unsafe { raw_appslice_to_slice(self.ptr, self.len) })
            }),
        }
    }
}

/// Read-only memory region of a process, shared with the kernel
pub struct ReadOnlyAppSlice {
    ptr: *const u8,
    len: usize,
    process_id: Option<ProcessId>,
}

impl ReadOnlyAppSlice {
    /// Construct a new [`ReadOnlyAppSlice`] over a given pointer and
    /// length.
    ///
    /// # Safety requirements
    ///
    /// Refer to the safety requirments of
    /// [`ReadOnlyAppSlice::new_external`].
    pub(crate) unsafe fn new(ptr: *const u8, len: usize, process_id: ProcessId) -> Self {
        ReadOnlyAppSlice {
            ptr,
            len,
            process_id: Some(process_id),
        }
    }

    /// Construct a new [`ReadOnlyAppSlice`] over a given pointer and
    /// length.
    ///
    /// Publicly accessible constructor, which requires the
    /// [`capabilities::ExternalProcessCapability`] capability. This
    /// is provided to allow implementations of the
    /// [`Process`](crate::process::Process) trait outside of
    /// the `kernel` crate.
    ///
    /// # Safety requirements
    ///
    /// In Rust, no two slices may point to the same memory location
    /// if at least one is mutable. This constructor relies on the
    /// fact that at most a single [`ReadWriteAppSlice`] or
    /// [`ReadOnlyAppSlice`] will point to the memory region of `[ptr;
    /// ptr + len)`, and no other slice in scope anywhere in the
    /// kernel points to an overlapping memory region.
    ///
    /// If the length is `0`, an arbitrary pointer may be passed into
    /// `ptr`. It does not necessarily have to point to allocated
    /// memory, nor does it have to meet [Rust's pointer validity
    /// requirements](https://doc.rust-lang.org/core/ptr/index.html#safety).
    /// [`ReadOnlyAppSlice`] must ensure that all Rust slices with a
    /// length of `0` must be constructed over a valid (but not
    /// necessarily allocated) base pointer.
    ///
    /// If the length is not `0`, the memory region of `[ptr; ptr +
    /// len)` must be valid memory of the process of the given
    /// [`ProcessId`]. It must be allocated and and accessible over the
    /// entire lifetime of the [`ReadOnlyAppSlice`]. It must not point
    /// to memory outside of the process' accessible memory range, or
    /// point (in part) to other processes or kernel memory. The `ptr`
    /// must meet [Rust's requirements for pointer
    /// validity](https://doc.rust-lang.org/core/ptr/index.html#safety),
    /// in particular it must have a minimum alignment of
    /// `core::mem::align_of::<u8>()` on the respective platform. It
    /// must point to memory mapped as _readable_ and optionally
    /// _writable_ and _executable_.
    pub unsafe fn new_external(
        ptr: *const u8,
        len: usize,
        process_id: ProcessId,
        _cap: &dyn capabilities::ExternalProcessCapability,
    ) -> Self {
        Self::new(ptr, len, process_id)
    }

    /// Consumes the ReadOnlyAppSlice, returning its constituent
    /// pointer and size. This ensures that there cannot simultaneously
    /// be both a `ReadOnlyAppSlice` and a pointer to its internal data.
    ///
    /// `consume` can be used when the kernel needs to pass the underlying
    /// values across the kernel-to-user boundary (e.g., in return values to
    /// system calls).
    pub(crate) fn consume(self) -> (*const u8, usize) {
        (self.ptr, self.len)
    }
}

impl Default for ReadOnlyAppSlice {
    fn default() -> Self {
        ReadOnlyAppSlice {
            ptr: 0x0 as *mut u8,
            len: 0,
            process_id: None,
        }
    }
}

impl Read for ReadOnlyAppSlice {
    fn len(&self) -> usize {
        self.process_id
            .map_or(0, |pid| pid.kernel.process_map_or(0, pid, |_| self.len))
    }

    fn ptr(&self) -> *const u8 {
        if self.len == 0 {
            0x0 as *const u8
        } else {
            self.ptr
        }
    }

    fn map_or<F, R>(&self, default: R, fun: F) -> R
    where
        F: FnOnce(&[u8]) -> R,
    {
        match self.process_id {
            None => default,
            Some(pid) => pid.kernel.process_map_or(default, pid, |_| {
                // Safety: `kernel.process_map_or()` validates that the process still exists
                // and its memory is still valid. `Process` tracks the "high water mark" of
                // memory that the process has `allow`ed to the kernel, and will not permit
                // the process to free any memory after it has been `allow`ed. This guarantees
                // that the buffer is safe to convert into a slice here.
                fun(unsafe { raw_appslice_to_slice(self.ptr, self.len) })
            }),
        }
    }
}