From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from mail-yw1-f175.google.com (mail-yw1-f175.google.com [209.85.128.175]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E583F3CF42 for ; Thu, 1 Feb 2024 05:04:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.175 ARC-Seal:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1706763849; cv=none; b=EBJNMqvtaeA8OdY9RglYJ/JgzTg3xSiNH4JXOFE+rP8lNwY8ovt/GaifIMWbCN0cxmDf4tIlQ9ghG0BpMEflk3WdWeu6hOrT/RGC7DIZLE30QsJAIoCL5TjHy5Io1ArVh+D/6qqCm++6xSc+2RFU1MIm8erpUrhmRagKw1YnWzc= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1706763849; c=relaxed/simple; bh=ca3ZQXP1dL7eczqFKqszekfUTYSiz0egHoKp0V5UWhI=; h=MIME-Version:References:In-Reply-To:From:Date:Message-ID:Subject: To:Cc:Content-Type; b=mVK2mQLJeqohGpO734ErPOHeZ1h28dv7CmhmDPqAq+2S8fhzgkso76bp6Novs3w/d5lCdG3rN56zHolPOyPWTTucGVKldOYEKqrd9NCM1SvGcZAcT+xqCirF3o04DwpoUAV1qHVIKh+MeKBPMP1vY9Ph+pWWDPJglN2Pgpj9wQI= ARC-Authentication-Results:i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=umich.edu; spf=pass smtp.mailfrom=umich.edu; dkim=pass (2048-bit key) header.d=umich.edu header.i=@umich.edu header.b=OMrGJSN4; arc=none smtp.client-ip=209.85.128.175 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=umich.edu Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=umich.edu Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=umich.edu header.i=@umich.edu header.b="OMrGJSN4" Received: by mail-yw1-f175.google.com with SMTP id 00721157ae682-604059403e9so5291567b3.3 for ; Wed, 31 Jan 2024 21:04:05 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=umich.edu; s=google-2016-06-03; t=1706763845; x=1707368645; darn=vger.kernel.org; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:from:to:cc:subject:date :message-id:reply-to; bh=fIVlKOR+0dK11siwWLke6mXGwWm4TuJ6szHx+WxrPIU=; b=OMrGJSN4+Cb4zSHCNFl4bn0sT9wsSZl16aTZxa0dUXPoacuv3xvQF2zTyzhHG/M2N8 Rwn4KomNF0OxPoVhpnK4ljSEtj+ZtYE7lqTsmbMCWzNzUS3Iliuq7HIUJdBbuBf3pJNT rPFqVm19Jh+Tyr/RChKYIWUWMFpizP87tb38oubnvl+qM+eqt7r6+h6bcISqsHCmCHaQ uUwDpet+dOF8ep1fH+JjfW2MQGnOxt72nKmHFjAsDE9ubdRqgafMSO74cl+u4IQh8rb5 66GkcGPj6Drl4A907VJVHE0a6VhgS/RdLg2NW/WoyvvtrjLU9k2rWqcXLMcwb/4bibvp xJ7Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1706763845; x=1707368645; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=fIVlKOR+0dK11siwWLke6mXGwWm4TuJ6szHx+WxrPIU=; b=gJ76ixvFZp//ufugI5iTbGJKJyVkSd+mvQwmGbyFyYzyk8HSnR9rj031c10BHnAul5 xNcYiORk8aC4aOBHKwJtcoQEjPWPTiyyYFTRrcx0fNjZrcFphDimks9oZDii8sy7Gb6n zWcIcRGDrcFZFMeHSPtx4ci5U5DSzUqyEFaxk0ikd0WxWV1KEQe2xNOjOArmT2Ejrebr NH/yUjrAiR04KLKref+CPLo/cS4TUv0eRoa/hfMY4KLxsGhVJEh2GuzBke7wieqxpqUu KA17+rRDLmeDK4Aqyt8rgkjJqegou7RS9JM9t4AWHbq3zDbKPlczafgbeuUtwkyT5ldz mJYw== X-Gm-Message-State: AOJu0YyIKVXX5JZSIPvCZqRv8Mn7UXTy0nLP9Cxc6L0gyf+0HEByl/QK dTYgnWUlRLO0OicR8yHWUFW+hZMl2PmpSeqqgFe6vHs5X1F0fIlALoV1U88W3yhWl9zKWQJ5puY J4zSvE5bzTRa7WZ1TPPX6JosMuRtSDKKLAwgViA== X-Google-Smtp-Source: AGHT+IFBz1YTkrf/qhzCgZIqKfossW9Ek9i6uJcsPLXTqKzNstEFU4dmZO6iv8Nqu4nRoYfb+44TKDCWKyYKEI3eeIo= X-Received: by 2002:a05:690c:82d:b0:5f0:e95f:5ad8 with SMTP id by13-20020a05690c082d00b005f0e95f5ad8mr1327057ywb.19.1706763844706; Wed, 31 Jan 2024 21:04:04 -0800 (PST) Precedence: bulk X-Mailing-List: rust-for-linux@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 References: <20240124-alice-mm-v1-0-d1abcec83c44@google.com> <20240124-alice-mm-v1-2-d1abcec83c44@google.com> In-Reply-To: <20240124-alice-mm-v1-2-d1abcec83c44@google.com> From: Trevor Gross Date: Thu, 1 Feb 2024 00:03:53 -0500 Message-ID: Subject: Re: [PATCH 2/3] rust: add typed accessors for userspace pointers To: Alice Ryhl Cc: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?Q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Kees Cook , Al Viro , Andrew Morton , Greg Kroah-Hartman , =?UTF-8?B?QXJ2ZSBIasO4bm5ldsOlZw==?= , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Christian Brauner Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable On Wed, Jan 24, 2024 at 6:21=E2=80=AFAM Alice Ryhl w= rote: I see this patch answers some of my naming questions from 1/3, sorry for not reading all the way through. > diff --git a/rust/kernel/user_ptr.rs b/rust/kernel/user_ptr.rs > index 00aa26aa6a83..daa46abe5525 100644 > --- a/rust/kernel/user_ptr.rs > +++ b/rust/kernel/user_ptr.rs > @@ -11,6 +11,7 @@ > use crate::{bindings, error::code::*, error::Result}; > use alloc::vec::Vec; > use core::ffi::{c_ulong, c_void}; > +use core::mem::{size_of, MaybeUninit}; > > /// The maximum length of a operation using `copy_[from|to]_user`. > /// > @@ -151,6 +152,36 @@ pub unsafe fn read_raw(&mut self, out: *mut u8, len:= usize) -> Result { > Ok(()) > } > > + /// Reads a value of the specified type. > + /// > + /// Fails with `EFAULT` if the read encounters a page fault. > + pub fn read(&mut self) -> Result { I think that `T: Copy` is required here, or for Copy to be a supertrait of ReadableBytes, since the data in the buffer is being duplicated from a reference. Send is probably also a reasonable bound to have . > + if size_of::() > self.1 || size_of::() > MAX_USER_OP_LEN { > + return Err(EFAULT); > + } > + let mut out: MaybeUninit =3D MaybeUninit::uninit(); > + // SAFETY: The local variable `out` is valid for writing `size_o= f::()` bytes. > + let res =3D unsafe { > + bindings::copy_from_user_unsafe_skip_check_object_size( > + out.as_mut_ptr().cast::(), > + self.0, > + size_of::() as c_ulong, As with the other patch, I think it would be more clear to use `c_ulong::try_from(...)` rather than comparing against `MAX_USER_OP_LEN ` and later casting. Possibly just in a helper function. > + ) > + }; > + if res !=3D 0 { > + return Err(EFAULT); > + } > + // Since this is not a pointer to a valid object in our program, > + // we cannot use `add`, which has C-style rules for defined > + // behavior. > + self.0 =3D self.0.wrapping_add(size_of::()); There are now methods `wrapping_byte_add` (since 1.75). Doesn't make much of a difference since the pointer is c_void anyway, but it does make the unit more clear. > + self.1 -=3D size_of::(); > + > + // SAFETY: The read above has initialized all bytes in `out`, an= d since > + // `T` implements `ReadableFromBytes`, any bit-pattern is a vali= d value > + // for this type. > + Ok(unsafe { out.assume_init() }) > + } > + > /// Reads all remaining data in the buffer into a vector. > /// > /// Fails with `EFAULT` if the read encounters a page fault. > @@ -219,4 +250,98 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result= { > // `len`, so the pointer is valid for reading `len` bytes. > unsafe { self.write_raw(ptr, len) } > } > + > + /// Writes the provided Rust value to this userspace pointer. > + /// > + /// Fails with `EFAULT` if the write encounters a page fault. > + pub fn write(&mut self, value: &T) -> Result { Send + Copy are also needed here, or supertraits of WritableToBytes. > + if size_of::() > self.1 || size_of::() > MAX_USER_OP_LEN { > + return Err(EFAULT); > + } > + // SAFETY: The reference points to a value of type `T`, so it is= valid > + // for reading `size_of::()` bytes. > + let res =3D unsafe { > + bindings::copy_to_user_unsafe_skip_check_object_size( > + self.0, > + (value as *const T).cast::(), > + size_of::() as c_ulong, > + ) > + }; > + if res !=3D 0 { > + return Err(EFAULT); > + } > + // Since this is not a pointer to a valid object in our program, > + // we cannot use `add`, which has C-style rules for defined > + // behavior. > + self.0 =3D self.0.wrapping_add(size_of::()); > + self.1 -=3D size_of::(); > + Ok(()) > + } > } > + > +/// Specifies that a type is safely readable from bytes. > +/// > +/// Not all types are valid for all values. For example, a `bool` must b= e either > +/// zero or one, so reading arbitrary bytes into something that contains= a > +/// `bool` is not okay. > +/// > +/// It's okay for the type to have padding, as initializing those bytes = has no > +/// effect. > +/// > +/// # Safety > +/// > +/// All bit-patterns must be valid for this type. > +pub unsafe trait ReadableFromBytes {} > + > +// SAFETY: All bit patterns are acceptable values of the types below. > +unsafe impl ReadableFromBytes for u8 {} > +unsafe impl ReadableFromBytes for u16 {} > +unsafe impl ReadableFromBytes for u32 {} > +unsafe impl ReadableFromBytes for u64 {} > +unsafe impl ReadableFromBytes for usize {} > +unsafe impl ReadableFromBytes for i8 {} > +unsafe impl ReadableFromBytes for i16 {} > +unsafe impl ReadableFromBytes for i32 {} > +unsafe impl ReadableFromBytes for i64 {} > +unsafe impl ReadableFromBytes for isize {} > +// SAFETY: If all bit patterns are acceptable for individual values in a= n array, > +// then all bit patterns are also acceptable for arrays of that type. > +unsafe impl ReadableFromBytes for [T] {} > +unsafe impl ReadableFromBytes for = [T; N] {} > + > +/// Specifies that a type is safely writable to bytes. > +/// > +/// If a struct implements this trait, then it is okay to copy it byte-f= or-byte > +/// to userspace. This means that it should not have any padding, as pad= ding > +/// bytes are uninitialized. Reading uninitialized memory is not just un= defined > +/// behavior, it may even lead to leaking sensitive information on the s= tack to > +/// userspace. > +/// > +/// The struct should also not hold kernel pointers, as kernel pointer a= ddresses > +/// are also considered sensitive. However, leaking kernel pointers is n= ot > +/// considered undefined behavior by Rust, so this is a correctness requ= irement, > +/// but not a safety requirement. > +/// > +/// # Safety > +/// > +/// Values of this type may not contain any uninitialized bytes. > +pub unsafe trait WritableToBytes {} > + > +// SAFETY: Instances of the following types have no uninitialized portio= ns. > +unsafe impl WritableToBytes for u8 {} > +unsafe impl WritableToBytes for u16 {} > +unsafe impl WritableToBytes for u32 {} > +unsafe impl WritableToBytes for u64 {} > +unsafe impl WritableToBytes for usize {} > +unsafe impl WritableToBytes for i8 {} > +unsafe impl WritableToBytes for i16 {} > +unsafe impl WritableToBytes for i32 {} > +unsafe impl WritableToBytes for i64 {} > +unsafe impl WritableToBytes for isize {} > +unsafe impl WritableToBytes for bool {} > +unsafe impl WritableToBytes for char {} > +unsafe impl WritableToBytes for str {} > +// SAFETY: If individual values in an array have no uninitialized portio= ns, then > +// the the array itself does not have any uninitialized portions either. > +unsafe impl WritableToBytes for [T] {} > +unsafe impl WritableToBytes for [T; = N] {} > > -- > 2.43.0.429.g432eaa2c6b-goog > > These traits are probably usable in a lot of other places (e.g. packets, GPU), so could you put them in a separate module? The patterns here are pretty similar to what the bytemuck crate does [1]. Since that crate is well established and open licensed, I think it makes sense to keep their naming or possibly even vendor a portion in. In particular, this would likely include the traits: - AnyBitPattern, which is roughly ReadableFromBytes here - NoUninit, which is roughly WritableToBytes here - Optionally Pod (plain old data), a supertrait of both AnyBitPattern and NoUninit just used to simplify trait implementation (impl Pod and you get the other two). And the functions: - from_bytes to turn &[u8] into &T for use in `read`. Needs `T: Copy` to return an owned value, as noted above. - bytes_of to turn &T into &[u8], for use in `write` The derive macros would also be nice to have down the line, though bytemuck's unfortunately relies on syn. - Trevor [1]: https://docs.rs/bytemuck/latest/bytemuck/