Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/object/buffer.rs

kernel/object/
buffer.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14use core::cmp::min;
15use core::ptr::NonNull;
16
17use memory_config::MemoryRegionType;
18use pw_status::{Error, Result};
19use vectored_buffer::{Slice, vectored_buffer_copy};
20
21use crate::Kernel;
22use crate::scheduler::{ProcessHandle, SchedulerState};
23use crate::sync::spinlock::SpinLockGuard;
24
25/// A `Buffer` represents a buffer or vector of buffers in a user process.
26pub enum Buffer {
27    Flat(Slice<u8>),
28    Vector(Slice<Slice<u8>>),
29}
30
31// SAFETY: Buffer's slice contains pointers which are not Send.  However the
32// kernel has access to the globally fixed address space so these pointers will
33// remain valid.   Additionally, the syscall interface contract is that userspace
34// must not access these underlying pointers and they remain valid for the lifetime
35// of the syscall (or async operation).  If userspace violates this contract,
36// it only affects the soundness of userspace, not the kernel.
37unsafe impl Send for Buffer {}
38
39impl Buffer {
40    fn new(address: usize, length: isize) -> Result<Self> {
41        let Some(address) = NonNull::<u8>::new(core::ptr::with_exposed_provenance_mut(address))
42        else {
43            return Err(Error::InvalidArgument);
44        };
45        if length >= 0 {
46            Ok(Buffer::Flat(Slice {
47                addr: address,
48                length: length.cast_unsigned(),
49            }))
50        } else {
51            Ok(Buffer::Vector(Slice {
52                addr: address.cast(),
53                length: (-length).cast_unsigned(),
54            }))
55        }
56    }
57
58    fn _check_access_locked<K: Kernel>(
59        sched: &SpinLockGuard<'_, K, SchedulerState<K>>,
60        start: usize,
61        size: usize,
62        access_type: MemoryRegionType,
63        process_handle: &ProcessHandle<K>,
64    ) -> Result<usize> {
65        if size > 0 {
66            // We only need to check if the size is greater than zero.
67            // The pointer for zero-sized objects will be invalid, so
68            // we shouldn't check access.
69            if !process_handle.range_has_access_locked(sched, access_type, start..(start + size)) {
70                return Err(Error::PermissionDenied);
71            }
72        }
73        Ok(size)
74    }
75    fn check_access_locked<K: Kernel>(
76        &self,
77        sched: &SpinLockGuard<'_, K, SchedulerState<K>>,
78        access_type: MemoryRegionType,
79        process_handle: &ProcessHandle<K>,
80    ) -> Result<usize> {
81        let total_size = match self {
82            Buffer::Flat(buf) => Self::_check_access_locked(
83                sched,
84                buf.addr.as_ptr().addr(),
85                buf.length,
86                access_type,
87                process_handle,
88            )?,
89
90            Buffer::Vector(vec) => {
91                let mut sum = 0;
92                // First make sure we can access the vector of slices.
93                let _ = Self::_check_access_locked(
94                    sched,
95                    vec.addr.as_ptr().addr(),
96                    vec.length * core::mem::size_of::<Slice<u8>>(),
97                    access_type,
98                    process_handle,
99                )?;
100                // Then check each item in the vector and sum up the total size in bytes.
101                for item in vec.as_slice() {
102                    sum += Self::_check_access_locked(
103                        sched,
104                        item.addr.as_ptr().addr(),
105                        item.length,
106                        access_type,
107                        process_handle,
108                    )?;
109                }
110                sum
111            }
112        };
113        Ok(total_size)
114    }
115
116    #[must_use]
117    fn as_slices(&self) -> &[Slice<u8>] {
118        match self {
119            Buffer::Flat(buf) => core::slice::from_ref(buf),
120            Buffer::Vector(vec) => vec.as_slice(),
121        }
122    }
123}
124
125// A buffer that resides in a process
126//
127// INVARIANTS:
128// * All access to the underlying memory is done through the `UserBuffer`. The
129//  `UserBuffer` will never expose a pointer or reference to the underlying memory.
130//  Additionally `UserBuffer` is in its own leaf module to guard against other
131//  code having access to its private fields.
132// * Operation on the buffer always respects the access rights of the process to which
133//   it is bound.
134pub struct SyscallBuffer {
135    // Pointer to the user buffer.
136    buffer: Buffer,
137    // The sum of the sizes of all the buffers in the iovec.
138    size: usize,
139    access_type: MemoryRegionType,
140}
141
142impl SyscallBuffer {
143    /// Create a new buffer with access rights bound to the current process.
144    pub fn new_in_current_process<K: Kernel>(
145        kernel: K,
146        access_type: MemoryRegionType,
147        address: usize,
148        length: isize,
149    ) -> Result<Self> {
150        let sched = kernel.get_scheduler().lock(kernel);
151        let process_handle = sched.current_thread().process();
152        let buffer = Buffer::new(address, length)?;
153
154        // SAFETY: Since there is no dynamic memory and processes can not be
155        // terminated and restarted, the access check can happen at buffer creates
156        // and still uphold the invariant that the processes access rights are respected.
157        //
158        // TODO: https://pwbug.dev/442660183 - Handle access checks with process termination.
159        let size = buffer.check_access_locked(&sched, access_type, &process_handle)?;
160        Ok(Self {
161            buffer,
162            size,
163            access_type,
164        })
165    }
166
167    /// Returns the size of the buffer.
168    #[must_use]
169    pub fn size(&self) -> usize {
170        self.size
171    }
172
173    /// Reduce the size of the buffer
174    ///
175    /// # Panics
176    /// Panics if new_len is greater than the current buffer length.
177    pub fn truncate(&mut self, new_size: usize) {
178        pw_assert::assert!(new_size <= self.size);
179        self.size = new_size;
180    }
181
182    /// Copy from this buffer into another.
183    ///
184    /// Copies data from this buffer into `into_buffer`, starting at `offset` bytes
185    /// from the beginning of this buffer.  Will copy maximum number of bytes
186    /// that exist and this buffer and will fit into `into_buffer`
187    ///
188    /// # Returns
189    /// - Ok(0): No data was copied.  This can occur if `offset` is equal to the
190    ///   size of the buffer or `into_buffer is of size zero.
191    /// - Ok(len): Returns the number of bytes copied.
192    /// - Error::PermissionDenied: Either this buffer is not readable or `into_buffer`
193    ///   is not writeable
194    /// - Error::OutOfRange: `offset` is larger than the size of the buffer.
195    pub fn copy_into(&self, offset: usize, into_buffer: &mut SyscallBuffer) -> Result<usize> {
196        if !self.access_type.is_readable() || !into_buffer.access_type.is_writeable() {
197            return Err(Error::PermissionDenied);
198        }
199
200        if offset > self.size {
201            return Err(Error::OutOfRange);
202        }
203
204        let available_bytes = self.size - offset;
205        let copy_len = min(available_bytes, into_buffer.size);
206
207        // SAFETY: The access right invariant is upheld at buffer creation time
208        // where the addr and size fields are validated.
209        let copied = vectored_buffer_copy(
210            offset,
211            copy_len,
212            self.buffer.as_slices(),
213            into_buffer.buffer.as_slices(),
214        );
215        Ok(copied)
216    }
217
218    #[must_use]
219    pub fn as_slices(&self) -> &[&[u8]] {
220        unsafe {
221            // Safety: Address and size are checked and validated in `new()`.
222            // The `Slice` type is isomorphic to the underlying rust representation of a slice.
223            core::mem::transmute(self.buffer.as_slices())
224        }
225    }
226}