From patchwork Thu Apr 18 08:59:17 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13634363 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 3BC97C04FFF for ; Thu, 18 Apr 2024 08:59:38 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 94FF26B0092; Thu, 18 Apr 2024 04:59:37 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 900F86B0093; Thu, 18 Apr 2024 04:59:37 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 77AED6B0095; Thu, 18 Apr 2024 04:59:37 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 4F07C6B0092 for ; Thu, 18 Apr 2024 04:59:37 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 014D7141299 for ; Thu, 18 Apr 2024 08:59:36 +0000 (UTC) X-FDA: 82022054394.26.D04E071 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) by imf09.hostedemail.com (Postfix) with ESMTP id D3749140021 for ; Thu, 18 Apr 2024 08:59:34 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=nz18jc3v; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf09.hostedemail.com: domain of 39eAgZgkKCHIQbYSUhoXbWeeWbU.SecbYdkn-ccalQSa.ehW@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=39eAgZgkKCHIQbYSUhoXbWeeWbU.SecbYdkn-ccalQSa.ehW@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1713430775; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=aOneHqkzjWbsXPBG08c1iIXkahak8VOduk+9lYv05Ps=; b=yglNFqBPbxDDnV1QxbjDC5zAdZgisuwk3JtPf8H1gRvsAGxbRRZ6iGZlpO+S7EuvKhqAnL SpxnwoHKFLDRd/jomAqllCvV24KlBtlK0Hy//K+bUIB/824UTa+NnLH5MdNjqB94S+qh/2 bj7tWCp/rpKAtTjvVN/6r0bX6R0xMnY= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=nz18jc3v; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf09.hostedemail.com: domain of 39eAgZgkKCHIQbYSUhoXbWeeWbU.SecbYdkn-ccalQSa.ehW@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=39eAgZgkKCHIQbYSUhoXbWeeWbU.SecbYdkn-ccalQSa.ehW@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1713430775; a=rsa-sha256; cv=none; b=cp9rkSrI6HbC6kvwRuOBezqmPgEOgwzcowBdlF0FU3pX+dJfxRxLXb/nJ4wQVMc0S9xIvb vYA6gvw4JAoG8J70IHB2eUoIRT6+m2y85WcW/O5gfuwcRwjfS+SkM5X9qDm6VYHZ2/6MX0 mJO4ueZaqzeLi5iguUSU4z6CXsemfok= Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-516c2460d95so434757e87.0 for ; Thu, 18 Apr 2024 01:59:34 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713430773; x=1714035573; darn=kvack.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=aOneHqkzjWbsXPBG08c1iIXkahak8VOduk+9lYv05Ps=; b=nz18jc3v91Dki/H76LC5mJyM8R8IUVrE1sctpSLfHzrUUyfO9xp4hHBWy1cG3t/8QT n/VH3P5+pnnMzzFJlwapxITPCnTpOIV0N1uGT0ggJ5/zEEDasi2wQx86glTWY0rZuNnF WSPEHTyJmuvhiZrJmjyqbcFkIoYXTFpC/c9Sce20Cy1zEjAWrd8SZmwd34s0dRXeeI0g e18BR5XyqiMEppQS5a3A3+fDuS/2fDZTnARqd2w5EPUE3GJasmaD2xpyesCuqCYdX/v5 hHkRAC6xC83TBpOTyD9zibqcPX4oWGkUPstpEfu+n2J7iHlzGOzcFeGepnRacpO70c5H XLGg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713430773; x=1714035573; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=aOneHqkzjWbsXPBG08c1iIXkahak8VOduk+9lYv05Ps=; b=byztoFzgVQDHMFdO/E/H0ikNixoifSNzIJZFgXWFtyxlnnGN50U7mXKBQCjMQWiddY NvKCGdJ1RHTXOqOR6NeJUxC+leo6nNkkg0geqIsO5mrG30nJRg1H6tVHCn9ps0ESxSqD XsDjCZshITTzaFdE6uaTrKULpo80IAVflW9Bn/fUOT4uv9C8WbgzAeDe50iZ/u7SiB6c FoEbdiEChCCT52pb5pA8g3CGyzfkQBfgCeQ7xuWw0GGgUUCdPaTcI6Ol5w1wb/sDjY0N AaHjm4UYJKd7D4kq8vuRJTX5O482UqDUhjeUA2EqGGsXd7MCCLhB1xHvtTknO4LMoXFh Vdng== X-Forwarded-Encrypted: i=1; AJvYcCXUBTfA/JAoazRw2znCmtjvH6txB4ppfg6+xdjW2jbadkHHUstTVMdhPTwiEpCn8BFudrAFYaWg0SiteFVxl1a5iyc= X-Gm-Message-State: AOJu0Yz2Keg/FG24lRJb/k7z6v1cEKUCcgs19Way8UO0RUO+lyQNxfI+ E7q8VHnUKcYEea5/EU2o5OH2Zs/VEDVkVcKh0RNFP2GrJkRovaM5eIew/veFXxJfeljmeIE8jkq u1YfOXR82Nxhmhg== X-Google-Smtp-Source: AGHT+IHAzlRE+T5ZNzdf0n0yMnp0TRPLdqGfxRE+ai5i4Jw9MhTAF5YG02+gMQDX3d5VCntdRnGFyCJrt8qMyG4= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:ac2:5f63:0:b0:518:b58c:5232 with SMTP id c3-20020ac25f63000000b00518b58c5232mr1940lfc.10.1713430773184; Thu, 18 Apr 2024 01:59:33 -0700 (PDT) Date: Thu, 18 Apr 2024 08:59:17 +0000 In-Reply-To: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> Mime-Version: 1.0 References: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15853; i=aliceryhl@google.com; h=from:subject:message-id; bh=dZfQOYQEGgz9vrwD+/QIrkBZiZV+Ak86iv4sMvdKcZY=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmIODtO+zgTchi2fWbmMoR8hezbeVKozC/rxnIH Fk8vU/95riJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZiDg7QAKCRAEWL7uWMY5 RvLND/42zY+nfrVdUZqjFKVr1NuzgOb6/IvXeHq8K+LMoavlpt6BGSIPiUfSuaEFgRDjkzDpnjt ucFzGZDWx6oCN/4lstzEucyIjWNxnR48QfRlZhM/OrvCiw2HR0yjRmKc83kWGacLIaNtQeePU+6 zwOH7xKJmrrUh/KA9KLZFOhgifzCeiRaCIqheoNh3M7q/KA8aRED9PBf6be+GRnfSlA/fdfrT9s 6UWvWZtr2ONv7R3Trh/klpANVtgEShr8lVmV5t0EQEmp+8Ni+DgpdhBn04FmrnBcSCKN1g7Dpo/ VlOlIKuleHV8Ja5xqk005npof0R1Xs9dT5lJREWO/ufD+UDt37h9CbQFbrmFG6PIC4/1vNvW5dm S6oepiulmGFRbMYLUCe3ujygDWhRct5X+VJow266U4Fvz+BbBL4YpfXpMDHCyJatO9c4+QqMv9c CjEcwZCayTr8lOF9RV10UhJ5dnJ49KLVrG8b8qCth/WADCcxVeSSKlHPWKBNgzTm75LMVpkJULF sKeTd64ya0OhpmgqM5S8jN0fmd9WrghxB12UAbY4sAYlkcvZbleRXowd9WuisyblzKNQCke5IBp YRtVnXcWpzYcAqRf7AeDVZXTxNJVCczFb7UH+M6PgYy1dktDn0ZT9mZBpjg2+LHk/eT2d/B7kRm pkb+sg3dqEm2CEg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240418-alice-mm-v6-1-cb8f3e5d688f@google.com> Subject: [PATCH v6 1/4] rust: uaccess: add userspace pointers From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , Trevor Gross , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: D3749140021 X-Rspam-User: X-Stat-Signature: jfq553ucq3pi35nbpy4wtt58jisjib1y X-HE-Tag: 1713430774-960451 X-HE-Meta: U2FsdGVkX1+QIuCpi/DJUUb0CkQguOQgeWCfs4KGqxfzAU/FEg2pB/PiQ3Sm8x3PIwWoGclaoQMLQ2jlZMUaR2jNcqSsHpTytkS9WnH5FqhtatCPoC2iOdTDtRuRt6dnkwBCbEk8o9GwRbWY3Dvrh5GROPbt1jzslMuZKwVjE0dN5j+0p9ELI2YG4N2oaou+c3BpzU1046f7pp+kDGp+mFV/7/MVsP6ootQnKZFw833biVkpKAwLUy/10shaGzk8wgUSv60XFIHy3E3/SRWGdCWF1N0BOOpOXMIVsikuPirYst16u5gKiVn2fRXW2gA4Bl5a05bDF91C9MxVBOl+shobjSdnAoDROJSmnapCzFOiK6gU5B1kKCzbY1KfDqsyZWdRSnCZvS41Jll2Xpct9ndRgAZznTvXOu3lWFFvcpJ2phEK5vWn0M48QrDj5WcO2/3b47wlSBFnQ0SVVFwOUVv79L4oX6jmy90vEvbipZXAmb69CYC8weYF3Vl5IAEnCTWCxdseXfbyjEO1aWZbIEAsxXsv8n/CWrO4dc7kn1/99bDKdShthGZmJWFqsozBVf9+JXlIlBFcb1oFCfK/AdLI7I56n0CFRE8Klr0HWFIh4oElssZyiZ4J11mLtd9C5uxAoAhgJI1kcBI/cAzDsFlLkybkeZMc/apsD1Ww+rUO5NGFeCWF5iW/eEM+mELzwly3q/Ni0fsJLxQpkZPJ4cl7VfFtgaTy8RWDi4Cl++P2scZ4+rfZJVsrMzinDQ+1MGzDpKspJvxSUIKxQzt/N2NLhClFv5VffvU2xjDefM1lGX04I/QmA+brgXkjad4JNdoZxsBLBbgusleANk6qb1VWodmoDR7GOlO9pWke10swHjTQOYacuLqLzsG04E2IzYdT+fQnLIzEyV7lGmC6sVTClSpFeYfAHpHVPaZaQXAWxcZ7A4N+wsWxRqktB5o24SGrTwMHzx8EQT2Po8o bRbmLAcc 7jSHD6plyLgtIEl+3XGaVR18EB97uMvCOi2y5JNzUUsXs4Qwce10XPFO19RNQzN03wpp6w56TkuryIFc3HyewPGOpq03tVlprnDJetFJVD11LSaUf69PF3MnFyCGgRcF2vYQ2yNcW+pTwh+MJUp26QPkoELQa4eSycyvcIox6P6tiU5VaE8Xz6ULW2XSfPUWTCdp10zBvU3W8cw1WP4xeIWDll9AGYK9/M+Bze08WMMdAuAWVTR9prZTuRDas6P9MYZ40bYJ6jWC/zmpebEMcaKwptsbY+QoPJeaZimLOnXZK45YOskERwUqRNFecKGb5NQaWFpHM1VSuKe2jhHtF6U51jY8MNXM+S603dTpnolmQrMa4R94mYNmvcmQpJXWvvUot2cKRcWiEXABNtzcRt3v5mCRA6xcdkkOXA60ZEfLSkoMdXTQxc2kwfN6/LV/U2itw7ZHCU1ZJ8aYgP1UWRUHxoZBhVZXi3pjUz4UOZ8tY/roFl+2whNNt8QH++HF7Gx+4ONU3BZ12OFm29YgOD6qxK4U/2AK8T8/NybIZyz0QKe1eCmlvvIjBJqAVp8CJHfYEKGch3cem2gLiISIEeIRXcK33QfCBUu+Q5CjO+57Ajgdr0D0MD+ZOvinT1InCBw9kU2nvFdewMSUqFe4Z0sFwRFZtCXFZYJSHC3oUPMueSKn3MAecxv1slTJGdjKUuqRiN5LOF4+3Tbr2oCIdqMuG1TuVbu+DYjlhpM65Zi/kGV+6kwfKLh00+DknzUWPy+7m1GvbbaA7ctpcNUNkF0kuiBQKTpY8f6dk X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: From: Wedson Almeida Filho A pointer to an area in userspace memory, which can be either read-only or read-write. All methods on this struct are safe: attempting to read or write on bad addresses (either out of the bound of the slice or unmapped addresses) will return `EFAULT`. Concurrent access, *including data races to/from userspace memory*, is permitted, because fundamentally another userspace thread/process could always be modifying memory at the same time (in the same way that userspace Rust's `std::io` permits data races with the contents of files on disk). In the presence of a race, the exact byte values read/written are unspecified but the operation is well-defined. Kernelspace code should validate its copy of data after completing a read, and not expect that multiple reads of the same address will return the same value. These APIs are designed to make it difficult to accidentally write TOCTOU bugs. Every time you read from a memory location, the pointer is advanced by the length so that you cannot use that reader to read the same memory location twice. Preventing double-fetches avoids TOCTOU bugs. This is accomplished by taking `self` by value to prevent obtaining multiple readers on a given `UserSlice`, and the readers only permitting forward reads. If double-fetching a memory location is necessary for some reason, then that is done by creating multiple readers to the same memory location. Constructing a `UserSlice` performs no checks on the provided address and length, it can safely be constructed inside a kernel thread with no current userspace process. Reads and writes wrap the kernel APIs `copy_from_user` and `copy_to_user`, which check the memory map of the current process and enforce that the address range is within the user range (no additional calls to `access_ok` are needed). This code is based on something that was originally written by Wedson on the old rust branch. It was modified by Alice by removing the `IoBufferReader` and `IoBufferWriter` traits, and various other changes. Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Trevor Gross Reviewed-by: Boqun Feng Signed-off-by: Alice Ryhl --- rust/helpers.c | 14 +++ rust/kernel/lib.rs | 1 + rust/kernel/uaccess.rs | 313 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 328 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 70e59efd92bc..312b6fcb49d5 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -38,6 +38,20 @@ __noreturn void rust_helper_BUG(void) } EXPORT_SYMBOL_GPL(rust_helper_BUG); +unsigned long rust_helper_copy_from_user(void *to, const void __user *from, + unsigned long n) +{ + return copy_from_user(to, from, n); +} +EXPORT_SYMBOL_GPL(rust_helper_copy_from_user); + +unsigned long rust_helper_copy_to_user(void __user *to, const void *from, + unsigned long n) +{ + return copy_to_user(to, from, n); +} +EXPORT_SYMBOL_GPL(rust_helper_copy_to_user); + void rust_helper_mutex_lock(struct mutex *lock) { mutex_lock(lock); diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 9a943d99c71a..7ee807ae4680 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,7 @@ pub mod task; pub mod time; pub mod types; +pub mod uaccess; pub mod workqueue; #[doc(hidden)] diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs new file mode 100644 index 000000000000..ee5623d7b98f --- /dev/null +++ b/rust/kernel/uaccess.rs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Slices to user space memory regions. +//! +//! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) + +use crate::{alloc::Flags, bindings, error::Result, prelude::*}; +use alloc::vec::Vec; +use core::ffi::{c_ulong, c_void}; +use core::mem::MaybeUninit; + +/// The type used for userspace addresses. +pub type UserPtr = usize; + +/// A pointer to an area in userspace memory, which can be either read-only or read-write. +/// +/// All methods on this struct are safe: attempting to read or write on bad addresses (either out of +/// the bound of the slice or unmapped addresses) will return `EFAULT`. Concurrent access, +/// *including data races to/from userspace memory*, is permitted, because fundamentally another +/// userspace thread/process could always be modifying memory at the same time (in the same way that +/// userspace Rust's [`std::io`] permits data races with the contents of files on disk). In the +/// presence of a race, the exact byte values read/written are unspecified but the operation is +/// well-defined. Kernelspace code should validate its copy of data after completing a read, and not +/// expect that multiple reads of the same address will return the same value. +/// +/// These APIs are designed to make it difficult to accidentally write TOCTOU (time-of-check to +/// time-of-use) bugs. Every time a memory location is read, the reader's position is advanced by +/// the read length and the next read will start from there. This helps prevent accidentally reading +/// the same location twice and causing a TOCTOU bug. +/// +/// Creating a [`UserSliceReader`] and/or [`UserSliceWriter`] consumes the `UserSlice`, helping +/// ensure that there aren't multiple readers or writers to the same location. +/// +/// If double-fetching a memory location is necessary for some reason, then that is done by creating +/// multiple readers to the same memory location, e.g. using [`clone_reader`]. +/// +/// # Examples +/// +/// Takes a region of userspace memory from the current process, and modify it by adding one to +/// every byte in the region. +/// +/// ```no_run +/// use alloc::vec::Vec; +/// use core::ffi::c_void; +/// use kernel::error::Result; +/// use kernel::uaccess::{UserPtr, UserSlice}; +/// +/// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> { +/// let (read, mut write) = UserSlice::new(uptr, len).reader_writer(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf, GFP_KERNEL)?; +/// +/// for b in &mut buf { +/// *b = b.wrapping_add(1); +/// } +/// +/// write.write_slice(&buf)?; +/// Ok(()) +/// } +/// ``` +/// +/// Example illustrating a TOCTOU (time-of-check to time-of-use) bug. +/// +/// ```no_run +/// use alloc::vec::Vec; +/// use core::ffi::c_void; +/// use kernel::error::{code::EINVAL, Result}; +/// use kernel::uaccess::{UserPtr, UserSlice}; +/// +/// /// Returns whether the data in this region is valid. +/// fn is_valid(uptr: UserPtr, len: usize) -> Result { +/// let read = UserSlice::new(uptr, len).reader(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf, GFP_KERNEL)?; +/// +/// todo!() +/// } +/// +/// /// Returns the bytes behind this user pointer if they are valid. +/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { +/// if !is_valid(uptr, len)? { +/// return Err(EINVAL); +/// } +/// +/// let read = UserSlice::new(uptr, len).reader(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf, GFP_KERNEL)?; +/// +/// // THIS IS A BUG! The bytes could have changed since we checked them. +/// // +/// // To avoid this kind of bug, don't call `UserSlice::new` multiple +/// // times with the same address. +/// Ok(buf) +/// } +/// ``` +/// +/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html +/// [`clone_reader`]: UserSliceReader::clone_reader +pub struct UserSlice { + ptr: UserPtr, + length: usize, +} + +impl UserSlice { + /// Constructs a user slice from a raw pointer and a length in bytes. + /// + /// Constructing a [`UserSlice`] performs no checks on the provided address and length, it can + /// safely be constructed inside a kernel thread with no current userspace process. Reads and + /// writes wrap the kernel APIs `copy_from_user` and `copy_to_user`, which check the memory map + /// of the current process and enforce that the address range is within the user range (no + /// additional calls to `access_ok` are needed). Validity of the pointer is checked when you + /// attempt to read or write, not in the call to `UserSlice::new`. + /// + /// Callers must be careful to avoid time-of-check-time-of-use (TOCTOU) issues. The simplest way + /// is to create a single instance of [`UserSlice`] per user memory block as it reads each byte + /// at most once. + pub fn new(ptr: UserPtr, length: usize) -> Self { + UserSlice { ptr, length } + } + + /// Reads the entirety of the user slice, appending it to the end of the provided buffer. + /// + /// Fails with `EFAULT` if the read happens on a bad address. + pub fn read_all(self, buf: &mut Vec, flags: Flags) -> Result { + self.reader().read_all(buf, flags) + } + + /// Constructs a [`UserSliceReader`]. + pub fn reader(self) -> UserSliceReader { + UserSliceReader { + ptr: self.ptr, + length: self.length, + } + } + + /// Constructs a [`UserSliceWriter`]. + pub fn writer(self) -> UserSliceWriter { + UserSliceWriter { + ptr: self.ptr, + length: self.length, + } + } + + /// Constructs both a [`UserSliceReader`] and a [`UserSliceWriter`]. + /// + /// Usually when this is used, you will first read the data, and then overwrite it afterwards. + pub fn reader_writer(self) -> (UserSliceReader, UserSliceWriter) { + ( + UserSliceReader { + ptr: self.ptr, + length: self.length, + }, + UserSliceWriter { + ptr: self.ptr, + length: self.length, + }, + ) + } +} + +/// A reader for [`UserSlice`]. +/// +/// Used to incrementally read from the user slice. +pub struct UserSliceReader { + ptr: UserPtr, + length: usize, +} + +impl UserSliceReader { + /// Skip the provided number of bytes. + /// + /// Returns an error if skipping more than the length of the buffer. + pub fn skip(&mut self, num_skip: usize) -> Result { + // Update `self.length` first since that's the fallible part of this operation. + self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?; + self.ptr = self.ptr.wrapping_add(num_skip); + Ok(()) + } + + /// Create a reader that can access the same range of data. + /// + /// Reading from the clone does not advance the current reader. + /// + /// The caller should take care to not introduce TOCTOU issues, as described in the + /// documentation for [`UserSlice`]. + pub fn clone_reader(&self) -> UserSliceReader { + UserSliceReader { + ptr: self.ptr, + length: self.length, + } + } + + /// Returns the number of bytes left to be read from this reader. + /// + /// Note that even reading less than this number of bytes may fail. + pub fn len(&self) -> usize { + self.length + } + + /// Returns `true` if no data is available in the io buffer. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + /// Reads raw data from the user slice into a kernel buffer. + /// + /// For a version that uses `&mut [u8]`, please see [`UserSliceReader::read_slice`]. + /// + /// Fails with `EFAULT` if the read happens on a bad address, or if the read goes out of bounds + /// of this [`UserSliceReader`]. This call may modify `out` even if it returns an error. + /// + /// # Guarantees + /// + /// After a successful call to this method, all bytes in `out` are initialized. + pub fn read_raw(&mut self, out: &mut [MaybeUninit]) -> Result { + let len = out.len(); + let out_ptr = out.as_mut_ptr().cast::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: `out_ptr` points into a mutable slice of length `len_ulong`, so we may write + // that many bytes to it. + let res = + unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_add(len); + self.length -= len; + Ok(()) + } + + /// Reads raw data from the user slice into a kernel buffer. + /// + /// Fails with `EFAULT` if the read happens on a bad address, or if the read goes out of bounds + /// of this [`UserSliceReader`]. This call may modify `out` even if it returns an error. + pub fn read_slice(&mut self, out: &mut [u8]) -> Result { + // SAFETY: The types are compatible and `read_raw` doesn't write uninitialized bytes to + // `out`. + let out = unsafe { &mut *(out as *mut [u8] as *mut [MaybeUninit]) }; + self.read_raw(out) + } + + /// Reads the entirety of the user slice, appending it to the end of the provided buffer. + /// + /// Fails with `EFAULT` if the read happens on a bad address. + pub fn read_all(mut self, buf: &mut Vec, flags: Flags) -> Result { + let len = self.length; + buf.reserve(len, flags)?; + + // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes + // long. + self.read_raw(&mut buf.spare_capacity_mut()[..len])?; + + // SAFETY: Since the call to `read_raw` was successful, so the next `len` bytes of the + // vector have been initialized. + unsafe { buf.set_len(buf.len() + len) }; + Ok(()) + } +} + +/// A writer for [`UserSlice`]. +/// +/// Used to incrementally write into the user slice. +pub struct UserSliceWriter { + ptr: UserPtr, + length: usize, +} + +impl UserSliceWriter { + /// Returns the amount of space remaining in this buffer. + /// + /// Note that even writing less than this number of bytes may fail. + pub fn len(&self) -> usize { + self.length + } + + /// Returns `true` if no more data can be written to this buffer. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + /// Writes raw data to this user pointer from a kernel buffer. + /// + /// Fails with `EFAULT` if the write happens on a bad address, or if the write goes out of bounds + /// of this [`UserSliceWriter`]. This call may modify the associated userspace slice even if it + /// returns an error. + pub fn write_slice(&mut self, data: &[u8]) -> Result { + let len = data.len(); + let data_ptr = data.as_ptr().cast::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: `data_ptr` points into an immutable slice of length `len_ulong`, so we may read + // that many bytes from it. + let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_add(len); + self.length -= len; + Ok(()) + } +}