From nobody Thu Oct 9 20:21:55 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 C4E5B285CBA for ; Mon, 16 Jun 2025 12:42:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750077730; cv=none; b=fHySh5Z2UQo1jkfsp4wO8hc4Y6ac2MBbtfvXd/XO3oGUb2Hu8vEjPoU0GiKowCHuLfdaUKWA8eo1Q8hStw5sRDH5Al3OeF2oHBEdYKxrLb2mnjnVLCMMhbvP0rhKMuhTqNfS5XTQ5tuM2+zod5knA25YQ1z8ZlbXN7YjNYQNyl4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750077730; c=relaxed/simple; bh=eisJelsbzbgz5PauR9t6Qqmq85k3CBf47pI1tIcqyIU=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=VVrr6TW9eGgkMeerNF20paV5ioWKr0LVJmGvv1CrN0GwwriO5+2Soxogpw7OLj1bayg5NmgUtmR6agphEOpkL9+RAYGg2wE257+0zVBhsZlNhSos0TJMlWiTj1SI5+eKfyCN+skb86CjX0Jwq2QiBmtE1p09u3LideBmQZ7Mqwo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=Ly1dA9TS; arc=none smtp.client-ip=209.85.128.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="Ly1dA9TS" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-451d5600a54so36888735e9.2 for ; Mon, 16 Jun 2025 05:42:08 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1750077727; x=1750682527; darn=vger.kernel.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=4iPsvC3FNImEIyla9KrHgTvmi5udSzFWrqAjBfWFnic=; b=Ly1dA9TSaM/5sY/uCnMQQwNN1IeJfaBdXzrL1MtpL0eDfd1MgN3OhFVx6nFbwvHZfA G81o9Ush3IJRhQDXzUAepcJXv+r953sx+z+k7SiKU+pb8w4vo8owxio5lnT7mCwZJYbi ljMgBaRdV3UP7OYTvGJbsNWdSWZ6KppjsU7Ih9Z5y5pn+wnaxyNhM8Vk+jwGGc50fHd+ dZ//rHDSFN0t/FNbaiOJgDCjaetrOeWwarQt89+i+JM9jVRaPTcn7LtdtG8fAyANsC6k vSSzmTvQ37pm7l24gMn1kvUXx3gjCNEvkPQkZxCDTT4V0t5oz+MSKP5iQelVAsMDZBG3 hZnw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1750077727; x=1750682527; 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=4iPsvC3FNImEIyla9KrHgTvmi5udSzFWrqAjBfWFnic=; b=Pyu3CfQlOgkTnl4gEVU2jOE5bUl040jOEVG8WBJAWKMwgRdgEB3rK5mfUNdLpNr4YA BVxLhy3F9Gp2ZYA6oJDXaW9aJ6zKJ+QOO8e6KsZNMwviGYGY53tsNP+2u7jAcqFhlRUj B00mss3ZqXJM5VY9ZDhiUzgQBKPqvg2lsyFUYTZeYEIg8MaQb3KLGbzbDE93IgqQ1T6h byCwsUy8EvOY6Xn8kfOWWYbtqyX8NE4f1OLLpxQ+Ph52HP8kilbyWqW1vNGkFs5SniH9 z+PK6ZsduAAYfL4VIkEAldymOHAchPefl2oxOQJjvc94mKGrq6XT8ETw6+LVb3pMbcrp euYQ== X-Forwarded-Encrypted: i=1; AJvYcCW0XfAsNCMpXImmWA1dzuBE3sICfgbN237xcYlwgZbOdT0oifUllCT6Xy90G+sLcgBm1Hg6gmmMHpJ2+gk=@vger.kernel.org X-Gm-Message-State: AOJu0YyTB3NCGLBe5umDwGxEkMepxezIAjuw9tEbGFDdsCPBQLOPD9O7 4A9MfaIHgXZtgMuCvK7sWlHykFjy+CPE3maA4GSs4bXL9ikeksCYMFrREvyHY3aYVdG0ITOknni pGqkqWkOwcSsihn8jgw== X-Google-Smtp-Source: AGHT+IFFEgIkgx+6TKashi0el2hVGOtC2gAVnRdLv6IfE63TCVZAam6vLTu09ppRDIqAw3h1TDUJsf/jVtAg1X0= X-Received: from wmth13.prod.google.com ([2002:a05:600c:8b6d:b0:451:edc8:7816]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3584:b0:451:df07:f437 with SMTP id 5b1f17b1804b1-4533cac908fmr84778685e9.30.1750077727306; Mon, 16 Jun 2025 05:42:07 -0700 (PDT) Date: Mon, 16 Jun 2025 12:41:47 +0000 In-Reply-To: <20250616-strncpy-from-user-v5-0-2d3fb0e1f5af@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250616-strncpy-from-user-v5-0-2d3fb0e1f5af@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=2881; i=aliceryhl@google.com; h=from:subject:message-id; bh=eisJelsbzbgz5PauR9t6Qqmq85k3CBf47pI1tIcqyIU=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoUBEawPXeuRCgQ5wZKLaXtuHVvRNKHSlpd0hBk 5Vk8HVeBKeJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaFARGgAKCRAEWL7uWMY5 RlmRD/4q1ndgbZsarygiYRaLLFiGWz2nYIpLwtNtRb7vaFqFiEI/KP/W6NZx+yWhdfc9qshRXeE WjvBOCwBkezCJ9SBY+wRcl7EzEcTHBp2vXxFVRXP5h+8dY+lolSZqcoGWMUKfBtpB0NoNvFlrw6 9i5zdHF5cjt8KiXVHn1qXxB90QyYcvVMZQ4CE6HaQFYmXczn/w3OSYPrLKKaRUJSD8nSk6yoa/i nv8t29nKfTp0CD3k2AvoY1PvF3ykQHK7qcaB0n5liFITOApLSb0VFrkKvyuZ1Y4eaaC07Y9C2SJ ByMc1Kjb/thT6fcsodupNIFryztcYhauKvnGL1dvdnexrzO+plvxDTij1aV77R1UoEqmDfLUoco r3/fohtiNTJ5RpdRnxgbJ6r6AbSJWv4oYQQ8Re02eW5yhEU1eHdB+/TgPni9wi5pvVW9buYDi8P RYkzvgyhdNsffkUqv+eEHCAfoRk6n/8rQK1Qzf5ElVTSKL5fynOBl6iMI5XNGiCbSxKT3c13L1B 0oBB6nc5h4Hnte76G3pV/TeK7Jhzlu/pJbEhvb6SeVEpSHm+kouvOjadWpypYVteq1xY64EVAUW /NQE95Rje3CtXs0HOnlFybvvw84R+tjggZu9QXKQMaQXNkofAs8vZw3kY/sl4wlwL5scRn4tKI2 DILR09TojH2ZqOg== X-Mailer: b4 0.14.2 Message-ID: <20250616-strncpy-from-user-v5-1-2d3fb0e1f5af@google.com> Subject: [PATCH v5 1/2] uaccess: rust: add strncpy_from_user From: Alice Ryhl To: Miguel Ojeda , Andrew Morton , Alexander Viro , Greg Kroah-Hartman Cc: Boqun Feng , Benno Lossin , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Andreas Hindborg , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This patch adds a direct wrapper around the C function of the same name. It's not really intended for direct use by Rust code since strncpy_from_user has a somewhat unfortunate API where it only nul-terminates the buffer if there's space for the nul-terminator. This means that a direct Rust wrapper around it could not return a &CStr since the buffer may not be a cstring. However, we still add the method to build more convenient APIs on top of it, which will happen in subsequent patches. Reviewed-by: Danilo Krummrich Reviewed-by: Greg Kroah-Hartman Reviewed-by: Boqun Feng Reviewed-by: Benno Lossin Signed-off-by: Alice Ryhl --- rust/kernel/uaccess.rs | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index 6d70edd8086a9f1ce38f78d312d6a7cfc03141a1..635a03e0989f3fe99be80987aa4= 7763782de1d3f 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -8,7 +8,7 @@ alloc::{Allocator, Flags}, bindings, error::Result, - ffi::c_void, + ffi::{c_char, c_void}, prelude::*, transmute::{AsBytes, FromBytes}, }; @@ -367,3 +367,37 @@ pub fn write(&mut self, value: &T) -> Resu= lt { Ok(()) } } + +/// Reads a nul-terminated string into `dst` and returns the length. +/// +/// This reads from userspace until a NUL byte is encountered, or until `d= st.len()` bytes have been +/// read. Fails with [`EFAULT`] if a read happens on a bad address (some d= ata may have been +/// copied). When the end of the buffer is encountered, no NUL byte is add= ed, so the string is +/// *not* guaranteed to be NUL-terminated when `Ok(dst.len())` is returned. +/// +/// # Guarantees +/// +/// When this function returns `Ok(len)`, it is guaranteed that the first = `len` bytes of `dst` are +/// initialized and non-zero. Furthermore, if `len < dst.len()`, then `dst= [len]` is a NUL byte. +#[inline] +#[expect(dead_code)] +fn raw_strncpy_from_user(dst: &mut [MaybeUninit], src: UserPtr) -> Res= ult { + // CAST: Slice lengths are guaranteed to be `<=3D isize::MAX`. + let len =3D dst.len() as isize; + + // SAFETY: `dst` is valid for writing `dst.len()` bytes. + let res =3D unsafe { + bindings::strncpy_from_user(dst.as_mut_ptr().cast::(), src= as *const c_char, len) + }; + + if res < 0 { + return Err(Error::from_errno(res as i32)); + } + + #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)] + assert!(res <=3D len); + + // GUARANTEES: `strncpy_from_user` was successful, so `dst` has conten= ts in accordance with the + // guarantees of this function. + Ok(res as usize) +} --=20 2.50.0.rc2.692.g299adb8693-goog From nobody Thu Oct 9 20:21:55 2025 Received: from mail-wr1-f73.google.com (mail-wr1-f73.google.com [209.85.221.73]) (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 1C8CB292B3E for ; Mon, 16 Jun 2025 12:42:10 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750077733; cv=none; b=DgbVrWiYfsvbw9buFDCIpUeBFXQxda6+9hf3Z3g+5Ou6YpxKLWF/62l16GqTI9t1cosGWc+/TN3qtwmQljT+XrBLESz5kUla0xVISHEP+HH7Nx7zNDgPkyxcIbsiL+ry6Hd/NgWOwWI9FbT5vyL0Y3EXn45HDFKvoobX99xL4Ao= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750077733; c=relaxed/simple; bh=Y22ZxTR2DcKyT7kx2NYZr8N8bEg7nYMhhgJibMcqX0g=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=e5ztrNmd6BW2p2LRET97lx0qfSKgZJvVerMi8rQ8lPzpUOBKNwDauTqMQkwbE7dB9nA90CYgsCdcRixVQAgoCpqluenboGudTR0f1Fg6ycLmXhGbvDhPwoCy3auNjwE0RnEtuHRCBHlTzSxl+djUdRv8RBF94OgZzggL8Q6HZKo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=LHGtTA7n; arc=none smtp.client-ip=209.85.221.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="LHGtTA7n" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-3a4fac7fa27so1969290f8f.0 for ; Mon, 16 Jun 2025 05:42:10 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1750077729; x=1750682529; darn=vger.kernel.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=CuCPHidyaJNjh33RmhUzqGRp6ORq7xZF7q/o9iPn7Ss=; b=LHGtTA7n926K/gWUxflXxgrXAr4zU/wzdk02roKJBO8tDXZycQZcAqOATrVwhM+MIJ jLaptEw4iGyK5s76FpbHdNZylYPkwzcOVuoKsYilzbp/VMMrriVhScSiDs00JYDjlCMV LPnF2vRkPWxVz3QSBORIuvEEHgS5Q1LQusuh22dL1aSATPB7yfCRy5g3yeyZ4JYBb9Ix gx9BUQIwPm2LaFr9L7bxOKHd8nWk4LvbIVTnSlb9C0UDZNvogtrdeMDy/49GwGraxiNb pBICJQ60LfLVvsX9l/Y4XkSlw7gIYBH+IAdqlf9Gn47uu6Ye1H635OF5Vfc95jFg77rX f2ow== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1750077729; x=1750682529; 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=CuCPHidyaJNjh33RmhUzqGRp6ORq7xZF7q/o9iPn7Ss=; b=Jrz9W/xVV3bGJ86ojm0h+DP7aC+I5uDea4Pp7CEa2f2yDx36ZUfpAvqNEFo81eHyoe RdOQ+HavUyVqcMqtXJ1i0e+aRhql9fDwfHLzycxlW5yBPqGmN21eM92LMpGdb6DJmHEU JOobpehXVDloBT2sJ/bNqjj5zpAJTdDlQlhIA3LvcxSEVK+e6BbQyIlg0p6JwEE3qdyx 8wcancma7DIP+TYPwsUr8ykViuo5FOPlPoVhZq5HtoWhqYYju5DCYeX14pB79kVfwrJT kVfCl9NV7N3suw39cgHMuqT+JlNvWw6zJ7uIF3pzx/IRkR6vIvLIPo0UV/by8dSir4P5 jyUQ== X-Forwarded-Encrypted: i=1; AJvYcCUOA1Sj1nS7YyBn3Iuf2zCSAbMNOdVA4Gzfx2YtTqVMvdCkJCz7fMxr3hKwg0c1Z/+HP4icjoOhEIL275A=@vger.kernel.org X-Gm-Message-State: AOJu0YxVaGn+K3uv20zPEjkfOJ+Xwhl2IracJESKP+qBPSX8dZI04pRl gihOKNlvDmcquQYBjxR6pj1N4BTZCWtqqsGh+o44PPS9X4GCK4L8Mws5cBvC1ArX9nHp87KRjZn cNJ6491Khuob5LopZwA== X-Google-Smtp-Source: AGHT+IEos9wyOljUVIq90oH/1Empt3J27Zrm4ASfnekdBgunNGd+0fbNM/dRPiUIggHpq4BXdQu5iWPUfUkkAZo= X-Received: from wmbet8.prod.google.com ([2002:a05:600c:8188:b0:453:f66:5f37]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:718:b0:3a5:3b63:58f0 with SMTP id ffacd0b85a97d-3a57237178dmr6945893f8f.18.1750077729505; Mon, 16 Jun 2025 05:42:09 -0700 (PDT) Date: Mon, 16 Jun 2025 12:41:48 +0000 In-Reply-To: <20250616-strncpy-from-user-v5-0-2d3fb0e1f5af@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250616-strncpy-from-user-v5-0-2d3fb0e1f5af@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4668; i=aliceryhl@google.com; h=from:subject:message-id; bh=Y22ZxTR2DcKyT7kx2NYZr8N8bEg7nYMhhgJibMcqX0g=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoUBEaT5eIFMl7DUCzdjz0g9XIj9E+jo8Q9i1mT 2jQH/b4/1+JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaFARGgAKCRAEWL7uWMY5 Run8D/9uR2TkeeCSeYbhMCB9fnbQeEsT3DeNMpVZDAtJSqXmkusSPB+9E9qlBSNt2z604bOQ2d6 48wxi0hTUluSRGs9EvZPjIiWfjPOhGbUk/5Qc0LtNFBK/BfJ5L6DLsO4uCQK1fymL5rsNbLsNCv f2CWyKlX7IMJxE0SpDAKxH5XgBvgc2isNOZfqmI4zI1A6Dn56uUcDNqXmtyzbDys82MFrsEp1Bq C1OXgES8mm8kXQrScgmKfkQzRJwHDoFgesbx1Noc0N1NRQqnv2V3ppYjx2r/vAntVy6nqDbvXvh mubfwSFHQ0OiHxCs4SSfDURnjRPQ8iaZOwndZxNQcQf2a8Zvdu4o6CTKIud7WHIcIepCTD/HxOl 7N6EAXyssV0I7JvSxsndjQIzuTUhdcUHPt5Eaqqr1vR3zVACt21DALVD2QurJifeMHk/YgWkh4O uHLDau5USjWyVIOIxQPWjXqrnIFFuhRVrL9vrnrtNBOB4lXU6ZAH5ZBpW7nAolmHuk4ZyQXKSzR noMO7FmCgfp3x8K87IfkFeES6tLdryyIQUOcAkxIYkFBjtRXYfELrRD/CXLVYEM5Jl+uO41dUQz AolPq1W4Jx4obxS3j11PSmQfAyhV+GXTwOTqzW5kUyPiq09AWpvnLm5nI4cIYL0Lt3cLW/C/rhK LSucTuUoKNStijw== X-Mailer: b4 0.14.2 Message-ID: <20250616-strncpy-from-user-v5-2-2d3fb0e1f5af@google.com> Subject: [PATCH v5 2/2] uaccess: rust: add UserSliceReader::strcpy_into_buf From: Alice Ryhl To: Miguel Ojeda , Andrew Morton , Alexander Viro , Greg Kroah-Hartman Cc: Boqun Feng , Benno Lossin , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Andreas Hindborg , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This patch adds a more convenient method for reading C strings from userspace. Logic is added to NUL-terminate the buffer when necessary so that a &CStr can be returned. Note that we treat attempts to read past `self.length` as a fault, so this returns EFAULT if that limit is exceeded before `buf.len()` is reached. Reviewed-by: Danilo Krummrich Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin --- rust/kernel/uaccess.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index 635a03e0989f3fe99be80987aa47763782de1d3f..106aa05ea1b88868fe48f64ca9c= 86b20ad7db68e 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -291,6 +291,65 @@ pub fn read_all(mut self, buf: &mut Vec<= u8, A>, flags: Flags) -> R unsafe { buf.inc_len(len) }; Ok(()) } + + /// Read a NUL-terminated string from userspace and return it. + /// + /// The string is read into `buf` and a NUL-terminator is added if the= end of `buf` is reached. + /// Since there must be space to add a NUL-terminator, the buffer must= not be empty. The + /// returned `&CStr` points into `buf`. + /// + /// Fails with [`EFAULT`] if the read happens on a bad address (some d= ata may have been + /// copied). + #[doc(alias =3D "strncpy_from_user")] + pub fn strcpy_into_buf<'buf>(self, buf: &'buf mut [u8]) -> Result<&'bu= f CStr> { + if buf.is_empty() { + return Err(EINVAL); + } + + // SAFETY: The types are compatible and `strncpy_from_user` doesn'= t write uninitialized + // bytes to `buf`. + let mut dst =3D unsafe { &mut *(buf as *mut [u8] as *mut [MaybeUni= nit]) }; + + // We never read more than `self.length` bytes. + if dst.len() > self.length { + dst =3D &mut dst[..self.length]; + } + + let mut len =3D raw_strncpy_from_user(dst, self.ptr)?; + if len < dst.len() { + // Add one to include the NUL-terminator. + len +=3D 1; + } else if len < buf.len() { + // This implies that `len =3D=3D dst.len() < buf.len()`. + // + // This means that we could not fill the entire buffer, but we= had to stop reading + // because we hit the `self.length` limit of this `UserSliceRe= ader`. Since we did not + // fill the buffer, we treat this case as if we tried to read = past the `self.length` + // limit and received a page fault, which is consistent with o= ther `UserSliceReader` + // methods that also return page faults when you exceed `self.= length`. + return Err(EFAULT); + } else { + // This implies that `len =3D=3D buf.len()`. + // + // This means that we filled the buffer exactly. In this case,= we add a NUL-terminator + // and return it. Unlike the `len < dst.len()` branch, don't m= odify `len` because it + // already represents the length including the NUL-terminator. + // + // SAFETY: Due to the check at the beginning, the buffer is no= t empty. + unsafe { *buf.last_mut().unwrap_unchecked() =3D 0 }; + } + + // This method consumes `self`, so it can only be called once, thu= s we do not need to + // update `self.length`. This sidesteps concerns such as whether `= self.length` should be + // incremented by `len` or `len-1` in the `len =3D=3D buf.len()` c= ase. + + // SAFETY: There are two cases: + // * If we hit the `len < dst.len()` case, then `raw_strncpy_from_= user` guarantees that + // this slice contains exactly one NUL byte at the end of the st= ring. + // * Otherwise, `raw_strncpy_from_user` guarantees that the string= contained no NUL bytes, + // and we have since added a NUL byte at the end. + Ok(unsafe { CStr::from_bytes_with_nul_unchecked(&buf[..len]) }) + } } =20 /// A writer for [`UserSlice`]. @@ -380,7 +439,6 @@ pub fn write(&mut self, value: &T) -> Resul= t { /// When this function returns `Ok(len)`, it is guaranteed that the first = `len` bytes of `dst` are /// initialized and non-zero. Furthermore, if `len < dst.len()`, then `dst= [len]` is a NUL byte. #[inline] -#[expect(dead_code)] fn raw_strncpy_from_user(dst: &mut [MaybeUninit], src: UserPtr) -> Res= ult { // CAST: Slice lengths are guaranteed to be `<=3D isize::MAX`. let len =3D dst.len() as isize; --=20 2.50.0.rc2.692.g299adb8693-goog