From patchwork Mon Jul 15 21:49:44 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Michal Rostecki X-Patchwork-Id: 13733924 Received: from mail-qv1-f66.google.com (mail-qv1-f66.google.com [209.85.219.66]) (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 790667A13A; Mon, 15 Jul 2024 22:03:25 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.66 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721081008; cv=none; b=IgW63Qp9wJWQ7/JBu0uNZ2hTyE/HrK2snmyAXkrUGBZOVf6+HucxnW+he/mhFBArHWurUliD6V/S24EmAxyKUTuDk2OGa6CGiZjGTTObUTy1fw1EKYQtL9Wmey3Jm7/KIENrgB1hrSKmZCd3emLXklmsjPidxIxrxsMPsLCwVWo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721081008; c=relaxed/simple; bh=/Dvy4oE+Y8WIl3MAp+SvReyubXBjxUrXhquUtvCJAKg=; h=From:To:Cc:Subject:Date:Message-ID:MIME-Version:Content-Type; b=LCWuCVn3fNjXEqFXvvxlY8rx9MZox19Fn7UVE84NFiLAl+XEzIES4eGUONl62N1TrlX6l8mBkCZLJ89Ts/UQ4bDluEdH9IEJYEknXQWVpN+89P/gxoX2Ukp/spwIBFetycYjFXC4nl9RUb6sIY5JgK+nwahO4mUXmLUU2AxbHp0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=WszfR+Zu; arc=none smtp.client-ip=209.85.219.66 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="WszfR+Zu" Received: by mail-qv1-f66.google.com with SMTP id 6a1803df08f44-6b5e0d881a1so43764156d6.1; Mon, 15 Jul 2024 15:03:25 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1721081004; x=1721685804; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to; bh=rA+i02ojNphWYTbFc4Klz4RzPhtEfgz33S5RLXVLUSo=; b=WszfR+ZuMAt2/MsKvXeGxNOkmu7jF7yOSOjdedmyyrRGijmCgzjSdJPGZB8Mpb0vht BpZ2R0Tz8B5XDwW0JmtfTe/yVfYu5FF+KTDEAd+kcs5CPoYbmrw3eDcTuDDMdi2mq3Ij 7JJZssJGmG7kiG3QuBnly86H0BeEwnHJ7SAgMGQeH8u4VcfZFXkKk7uRBCK8CMkkwSrJ B2N58pDhoWpscPDbOhffQ/NrWmRo9ysFTVtAft8DbN41NUkcAWX0bEgq9dZiFKlPkiJ2 YMlExYoB9TytMjBOvuzZDmBo4lQJAdg38Jf2FbNSaExs2Dffl6iO0YkkTNmDXCn6qWxL eolg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1721081004; x=1721685804; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-message-state:from:to:cc:subject:date:message-id :reply-to; bh=rA+i02ojNphWYTbFc4Klz4RzPhtEfgz33S5RLXVLUSo=; b=IJWckpu9tNEceW777Oe7qVotOMtxswU0LHB70lRnzvi91Yo9JJHBJbfOQS5qiYx0r7 hd8isnIRKVtJSTV0HxFU032G6QWAZ2vI0WSkKGj5ClTegTvnvPJvBi4Gwhh2B63Yp3QH o656g2LX6wndeZa3dhE6DIBQ3ZdfUYSB4+d1gAO1Slqd5/Wx3hFwhDxV0fDfDEZug0pW QcZS2ikin+so0x1d1e6AKhVxN1ka9BJTGcvmiz1hS+fR7FaUfoXLfU6ZmpJux9VSw5jl 3pe3buguvjdxH5xxk4nasb9SL9j3v+8Gc0mEcD5oDP4hBp1Cp9EO6i1WuGgBr++mZ1tf Wqcg== X-Forwarded-Encrypted: i=1; AJvYcCUHco2Zqcxb/317lp99A/Wdp5USL6qX2I5ITibSWI4PeHZnR8zsRCpJtFvt8MJXDW/DvLkcXSsCpS/ceD0jRHJOD2QmfmKohxVU8lUZeBfhbZ/a4qk4lP3cGXPvJj3xj32WTThjshbzQRTek/X7WMOWlhzllAjA6VIKbf7U7UJSYQZlwk5GOI+7V7+hkoeE5n/RTEkwgVwc9/RBm5oc4krxXS56xj4= X-Gm-Message-State: AOJu0Yz8vWGeyTtG0oO85zMNRFXWQK/4kbbqbZyeVPcAdci4xuCvIkvu ODsDkLBmWqTPnaykpvR1jKeHN46G71kJihygIVFtzj2Qu9jYsZfp X-Google-Smtp-Source: AGHT+IHAZkKtbRV6xgYkSDBHXku4RNgtMO2gaznfHqz60WvcBvo+PqaP04VyWr43KrU4wKeTR2vSwA== X-Received: by 2002:a05:6214:29c1:b0:6b4:f979:1e03 with SMTP id 6a1803df08f44-6b7800d1fcfmr4570596d6.25.1721081003971; Mon, 15 Jul 2024 15:03:23 -0700 (PDT) Received: from vadorovsky-macbookpro.fritz.box ([2607:fea8:fd50:8247::f272]) by smtp.gmail.com with ESMTPSA id 6a1803df08f44-6b76199f12asm25028446d6.62.2024.07.15.15.03.22 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 15 Jul 2024 15:03:23 -0700 (PDT) From: Michal Rostecki To: Cc: Michal Rostecki , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Brendan Higgins , David Gow , Rae Moar , FUJITA Tomonori , Trevor Gross , Nathan Chancellor , Nick Desaulniers , Bill Wendling , Justin Stitt , Martin Rodriguez Reboredo , Finn Behrens , Manmohan Shukla , Valentin Obst , Asahi Lina , Yutaro Ohno , Danilo Krummrich , Tiago Lam , Charalampos Mitrodimas , Ben Gooding , Tejun Heo , Roland Xu , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, netdev@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v2] rust: str: Use `core::CStr`, remove the custom `CStr` implementation Date: Mon, 15 Jul 2024 23:49:44 +0200 Message-ID: <20240715214956.401687-2-vadorovsky@gmail.com> X-Mailer: git-send-email 2.45.2 Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 `CStr` became a part of `core` library in Rust 1.75. This change replaces the custom `CStr` implementation with the one from `core`. no need to keep the custom implementation. `core::CStr` behaves generally the same as the removed implementation, with the following differences: - It does not implement `Display` (but implements `Debug`). Therefore, by switching to `core::CStr`, we lose the `Display` implementation. - Lack of `Display` implementation impacted only rust/kernel/kunit.rs. In this change, we use `Debug` format there. The only difference between the removed `Display` output and `Debug` output are quotation marks present in the latter (`foo` vs `"foo"`). - It does not provide `from_bytes_with_nul_unchecked_mut` method. - It was used only in `DerefMut` implementation for `CString`. This change removes that implementation. - Otherwise, having such a method is not desirable. The rule in Rust std is that `str` is used only as an immutable reference (`&str`), while mutating strings is done with the owned `String` type. Similarly, we can introduce the rule that `CStr` should be used only as an immutable reference (`&CStr`), while mutating is done only with the owned `CString` type. - It has `as_ptr()` method instead of `as_char_ptr()`, which also returns `*const c_char`. Signed-off-by: Michal Rostecki --- v1 -> v2: - Do not remove `c_str` macro. While it's preferred to use C-string literals, there are two cases where `c_str` is helpful: - When working with macros, which already return a Rust string literal (e.g. `stringify!`). - When building macros, where we want to take a Rust string literal as an argument (for caller's convenience), but still use it as a C-string internally. - Use Rust literals as arguments in macros (`new_mutex`, `new_condvar`, `new_mutex`). Use the `c_str` macro to convert these literals to C-string literals. - Use `c_str` in kunit.rs for converting the output of `stringify!` to a `CStr`. - Remove `DerefMut` implementation for `CString`. rust/kernel/error.rs | 7 +- rust/kernel/kunit.rs | 12 +- rust/kernel/net/phy.rs | 2 +- rust/kernel/prelude.rs | 4 +- rust/kernel/str.rs | 486 ++---------------------------------- rust/kernel/sync/condvar.rs | 5 +- rust/kernel/sync/lock.rs | 6 +- rust/kernel/workqueue.rs | 2 +- scripts/rustdoc_test_gen.rs | 4 +- 9 files changed, 44 insertions(+), 484 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 55280ae9fe40..18808b29604d 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -4,10 +4,11 @@ //! //! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h) -use crate::{alloc::AllocError, str::CStr}; +use crate::alloc::AllocError; use alloc::alloc::LayoutError; +use core::ffi::CStr; use core::fmt; use core::num::TryFromIntError; use core::str::Utf8Error; @@ -142,7 +143,7 @@ pub fn name(&self) -> Option<&'static CStr> { None } else { // SAFETY: The string returned by `errname` is static and `NUL`-terminated. - Some(unsafe { CStr::from_char_ptr(ptr) }) + Some(unsafe { CStr::from_ptr(ptr) }) } } @@ -164,7 +165,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { None => f.debug_tuple("Error").field(&-self.0).finish(), // SAFETY: These strings are ASCII-only. Some(name) => f - .debug_tuple(unsafe { core::str::from_utf8_unchecked(name) }) + .debug_tuple(unsafe { core::str::from_utf8_unchecked(name.to_bytes()) }) .finish(), } } diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 0ba77276ae7e..c08f9dddaa6f 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -56,9 +56,9 @@ macro_rules! kunit_assert { break 'out; } - static FILE: &'static $crate::str::CStr = $crate::c_str!($file); + static FILE: &'static core::ffi::CStr = $file; static LINE: i32 = core::line!() as i32 - $diff; - static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition)); + static CONDITION: &'static core::ffi::CStr = $crate::c_str!(stringify!($condition)); // SAFETY: FFI call without safety requirements. let kunit_test = unsafe { $crate::bindings::kunit_get_current_test() }; @@ -71,11 +71,11 @@ macro_rules! kunit_assert { // // This mimics KUnit's failed assertion format. $crate::kunit::err(format_args!( - " # {}: ASSERTION FAILED at {FILE}:{LINE}\n", + " # {:?}: ASSERTION FAILED at {FILE:?}:{LINE:?}\n", $name )); $crate::kunit::err(format_args!( - " Expected {CONDITION} to be true, but is false\n" + " Expected {CONDITION:?} to be true, but is false\n" )); $crate::kunit::err(format_args!( " Failure not reported to KUnit since this is a non-KUnit task\n" @@ -98,12 +98,12 @@ unsafe impl Sync for Location {} unsafe impl Sync for UnaryAssert {} static LOCATION: Location = Location($crate::bindings::kunit_loc { - file: FILE.as_char_ptr(), + file: FILE.as_ptr(), line: LINE, }); static ASSERTION: UnaryAssert = UnaryAssert($crate::bindings::kunit_unary_assert { assert: $crate::bindings::kunit_assert {}, - condition: CONDITION.as_char_ptr(), + condition: CONDITION.as_ptr(), expected_true: true, }); diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs index fd40b703d224..19f45922ec42 100644 --- a/rust/kernel/net/phy.rs +++ b/rust/kernel/net/phy.rs @@ -502,7 +502,7 @@ unsafe impl Sync for DriverVTable {} pub const fn create_phy_driver() -> DriverVTable { // INVARIANT: All the fields of `struct phy_driver` are initialized properly. DriverVTable(Opaque::new(bindings::phy_driver { - name: T::NAME.as_char_ptr().cast_mut(), + name: T::NAME.as_ptr().cast_mut(), flags: T::FLAGS, phy_id: T::PHY_DEVICE_ID.id, phy_id_mask: T::PHY_DEVICE_ID.mask_as_int(), diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index b37a0b3180fb..5efabfaa5804 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -12,7 +12,7 @@ //! ``` #[doc(no_inline)] -pub use core::pin::Pin; +pub use core::{ffi::CStr, pin::Pin}; pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt}; @@ -35,7 +35,7 @@ pub use super::error::{code::*, Error, Result}; -pub use super::{str::CStr, ThisModule}; +pub use super::{ThisModule}; pub use super::init::{InPlaceInit, Init, PinInit}; diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..e491a9803187 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -4,8 +4,9 @@ use crate::alloc::{flags::*, vec_ext::VecExt, AllocError}; use alloc::vec::Vec; +use core::ffi::CStr; use core::fmt::{self, Write}; -use core::ops::{self, Deref, DerefMut, Index}; +use core::ops::Deref; use crate::error::{code::*, Error}; @@ -41,11 +42,11 @@ impl fmt::Display for BStr { /// # use kernel::{fmt, b_str, str::{BStr, CString}}; /// let ascii = b_str!("Hello, BStr!"); /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); - /// assert_eq!(s.as_bytes(), "Hello, BStr!".as_bytes()); + /// assert_eq!(s.to_bytes(), "Hello, BStr!".as_bytes()); /// /// let non_ascii = b_str!("