Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: uaccess: add typed accessors for userspace pointers

Add safe methods for reading and writing Rust values to and from
userspace pointers.

The C methods for copying to/from userspace use a function called
`check_object_size` to verify that the kernel pointer is not dangling.
However, this check is skipped when the length is a compile-time
constant, with the assumption that such cases trivially have a correct
kernel pointer.

In this patch, we apply the same optimization to the typed accessors.
For both methods, the size of the operation is known at compile time to
be size_of of the type being read or written. Since the C side doesn't
provide a variant that skips only this check, we create custom helpers
for this purpose.

The majority of reads and writes to userspace pointers in the Rust
Binder driver uses these accessor methods. Benchmarking has found that
skipping the `check_object_size` check makes a big difference for the
cases being skipped here. (And that the check doesn't make a difference
for the cases that use the raw read/write methods.)

This code is based on something that was originally written by Wedson on
the old rust branch. It was modified by Alice to skip the
`check_object_size` check, and to update various comments, including the
notes about kernel pointers in `WritableToBytes`.

Co-developed-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240528-alice-mm-v7-3-78222c31b8f4@google.com
[ Wrapped docs to 100 and added a few intra-doc links. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>

authored by

Alice Ryhl and committed by
Miguel Ojeda
b33bf37a 1f9a8286

+141 -2
+64
rust/kernel/types.rs
··· 409 409 /// Constructs an instance of [`Either`] containing a value of type `R`. 410 410 Right(R), 411 411 } 412 + 413 + /// Types for which any bit pattern is valid. 414 + /// 415 + /// Not all types are valid for all values. For example, a `bool` must be either zero or one, so 416 + /// reading arbitrary bytes into something that contains a `bool` is not okay. 417 + /// 418 + /// It's okay for the type to have padding, as initializing those bytes has no effect. 419 + /// 420 + /// # Safety 421 + /// 422 + /// All bit-patterns must be valid for this type. This type must not have interior mutability. 423 + pub unsafe trait FromBytes {} 424 + 425 + // SAFETY: All bit patterns are acceptable values of the types below. 426 + unsafe impl FromBytes for u8 {} 427 + unsafe impl FromBytes for u16 {} 428 + unsafe impl FromBytes for u32 {} 429 + unsafe impl FromBytes for u64 {} 430 + unsafe impl FromBytes for usize {} 431 + unsafe impl FromBytes for i8 {} 432 + unsafe impl FromBytes for i16 {} 433 + unsafe impl FromBytes for i32 {} 434 + unsafe impl FromBytes for i64 {} 435 + unsafe impl FromBytes for isize {} 436 + // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit 437 + // patterns are also acceptable for arrays of that type. 438 + unsafe impl<T: FromBytes> FromBytes for [T] {} 439 + unsafe impl<T: FromBytes, const N: usize> FromBytes for [T; N] {} 440 + 441 + /// Types that can be viewed as an immutable slice of initialized bytes. 442 + /// 443 + /// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This 444 + /// means that it should not have any padding, as padding bytes are uninitialized. Reading 445 + /// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive 446 + /// information on the stack to userspace. 447 + /// 448 + /// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered 449 + /// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so 450 + /// this is a correctness requirement, but not a safety requirement. 451 + /// 452 + /// # Safety 453 + /// 454 + /// Values of this type may not contain any uninitialized bytes. This type must not have interior 455 + /// mutability. 456 + pub unsafe trait AsBytes {} 457 + 458 + // SAFETY: Instances of the following types have no uninitialized portions. 459 + unsafe impl AsBytes for u8 {} 460 + unsafe impl AsBytes for u16 {} 461 + unsafe impl AsBytes for u32 {} 462 + unsafe impl AsBytes for u64 {} 463 + unsafe impl AsBytes for usize {} 464 + unsafe impl AsBytes for i8 {} 465 + unsafe impl AsBytes for i16 {} 466 + unsafe impl AsBytes for i32 {} 467 + unsafe impl AsBytes for i64 {} 468 + unsafe impl AsBytes for isize {} 469 + unsafe impl AsBytes for bool {} 470 + unsafe impl AsBytes for char {} 471 + unsafe impl AsBytes for str {} 472 + // SAFETY: If individual values in an array have no uninitialized portions, then the array itself 473 + // does not have any uninitialized portions either. 474 + unsafe impl<T: AsBytes> AsBytes for [T] {} 475 + unsafe impl<T: AsBytes, const N: usize> AsBytes for [T; N] {}
+77 -2
rust/kernel/uaccess.rs
··· 4 4 //! 5 5 //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) 6 6 7 - use crate::{alloc::Flags, bindings, error::Result, prelude::*}; 7 + use crate::{ 8 + alloc::Flags, 9 + bindings, 10 + error::Result, 11 + prelude::*, 12 + types::{AsBytes, FromBytes}, 13 + }; 8 14 use alloc::vec::Vec; 9 15 use core::ffi::{c_ulong, c_void}; 10 - use core::mem::MaybeUninit; 16 + use core::mem::{size_of, MaybeUninit}; 11 17 12 18 /// The type used for userspace addresses. 13 19 pub type UserPtr = usize; ··· 253 247 self.read_raw(out) 254 248 } 255 249 250 + /// Reads a value of the specified type. 251 + /// 252 + /// Fails with [`EFAULT`] if the read happens on a bad address, or if the read goes out of 253 + /// bounds of this [`UserSliceReader`]. 254 + pub fn read<T: FromBytes>(&mut self) -> Result<T> { 255 + let len = size_of::<T>(); 256 + if len > self.length { 257 + return Err(EFAULT); 258 + } 259 + let Ok(len_ulong) = c_ulong::try_from(len) else { 260 + return Err(EFAULT); 261 + }; 262 + let mut out: MaybeUninit<T> = MaybeUninit::uninit(); 263 + // SAFETY: The local variable `out` is valid for writing `size_of::<T>()` bytes. 264 + // 265 + // By using the _copy_from_user variant, we skip the check_object_size check that verifies 266 + // the kernel pointer. This mirrors the logic on the C side that skips the check when the 267 + // length is a compile-time constant. 268 + let res = unsafe { 269 + bindings::_copy_from_user( 270 + out.as_mut_ptr().cast::<c_void>(), 271 + self.ptr as *const c_void, 272 + len_ulong, 273 + ) 274 + }; 275 + if res != 0 { 276 + return Err(EFAULT); 277 + } 278 + self.ptr = self.ptr.wrapping_add(len); 279 + self.length -= len; 280 + // SAFETY: The read above has initialized all bytes in `out`, and since `T` implements 281 + // `FromBytes`, any bit-pattern is a valid value for this type. 282 + Ok(unsafe { out.assume_init() }) 283 + } 284 + 256 285 /// Reads the entirety of the user slice, appending it to the end of the provided buffer. 257 286 /// 258 287 /// Fails with [`EFAULT`] if the read happens on a bad address. ··· 344 303 // SAFETY: `data_ptr` points into an immutable slice of length `len_ulong`, so we may read 345 304 // that many bytes from it. 346 305 let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len_ulong) }; 306 + if res != 0 { 307 + return Err(EFAULT); 308 + } 309 + self.ptr = self.ptr.wrapping_add(len); 310 + self.length -= len; 311 + Ok(()) 312 + } 313 + 314 + /// Writes the provided Rust value to this userspace pointer. 315 + /// 316 + /// Fails with [`EFAULT`] if the write happens on a bad address, or if the write goes out of 317 + /// bounds of this [`UserSliceWriter`]. This call may modify the associated userspace slice even 318 + /// if it returns an error. 319 + pub fn write<T: AsBytes>(&mut self, value: &T) -> Result { 320 + let len = size_of::<T>(); 321 + if len > self.length { 322 + return Err(EFAULT); 323 + } 324 + let Ok(len_ulong) = c_ulong::try_from(len) else { 325 + return Err(EFAULT); 326 + }; 327 + // SAFETY: The reference points to a value of type `T`, so it is valid for reading 328 + // `size_of::<T>()` bytes. 329 + // 330 + // By using the _copy_to_user variant, we skip the check_object_size check that verifies the 331 + // kernel pointer. This mirrors the logic on the C side that skips the check when the length 332 + // is a compile-time constant. 333 + let res = unsafe { 334 + bindings::_copy_to_user( 335 + self.ptr as *mut c_void, 336 + (value as *const T).cast::<c_void>(), 337 + len_ulong, 338 + ) 339 + }; 347 340 if res != 0 { 348 341 return Err(EFAULT); 349 342 }