From patchwork Sun Jul 14 16:02:19 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Michal Rostecki X-Patchwork-Id: 13732741 Received: from mail-oi1-f194.google.com (mail-oi1-f194.google.com [209.85.167.194]) (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 9E332171BB; Sun, 14 Jul 2024 16:02:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.194 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1720972968; cv=none; b=DIqvfvqm6ACzUlicy5sabQ55sO9O1Fp4oeLZjZMphhX92knio7git5gIKkEi7Nk9q7IIQZGIb/WH+hLaHMYxkfBwu32tuHNUL7OSHOrfE2Qa56u504qNWqPAu9jGiwZ0JtfUUijKfuoRlEh+54loBtp+jZ3lrCXboWrEt34eJVw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1720972968; c=relaxed/simple; bh=JK5CLW/aIZ84XUM/4CQx9DwLVq4SKC7xt14Rv+O7IY8=; h=From:To:Cc:Subject:Date:Message-ID:MIME-Version:Content-Type; b=UCJo3o6KwIWlNw/rKi3s+CB6YbWZSH0SYekKd6lTK+0Db4U5FOEiTb2EnV4zSbCeNULu5j/Cl+EjeJnn3qOsI/jy23d8p9Gx4qjC/Po0z/6uBCScTy7w2iaUnkEeJaUvNvDMYMOFoZBEVOpH9kdQ0TK+UWpvEtf/Z2m8fW8+WTg= 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=iK9RIOBu; arc=none smtp.client-ip=209.85.167.194 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="iK9RIOBu" Received: by mail-oi1-f194.google.com with SMTP id 5614622812f47-3dab349467dso762794b6e.1; Sun, 14 Jul 2024 09:02:45 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1720972965; x=1721577765; 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=QC04o2Oc39KDZ+EJDTk3+OtuWSzsHOXwGAlbi4rw6ck=; b=iK9RIOBuhsFcoe1ftLsFjH3d8oGwzIMeWl8yz0d9in+k8whYQVUwAIik4Aq32bg9M6 rcgoo/dg8jRWgN/Bl6qu8bdhtaGxsfXtRTB7oBOsbV28VrgzTHpc+7O2i8aJ1Q5Fp49Q 6N/pDT0AzwlQ8jwOrC3SzpmSgrqlRJrsEQmaLRjdq7PKNc0YqyR2dpCbLAvAOGBKN2nk 1FZHSjQkUhcJteT2FBmzXRo6L1cYPq/iBjs3bfRNKx60vH7mf2wvHcHHHhIR2JbEJyBn VMSjo6OVlXCBx/YWklUZtbkYOC1sanYozcW2BNgj24HP563OOhUSMVaCMTUAbv+pdw9/ 8rUQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1720972965; x=1721577765; 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=QC04o2Oc39KDZ+EJDTk3+OtuWSzsHOXwGAlbi4rw6ck=; b=kx7/DOm6cGtXnOnE4tD3ATqEcEZKQ0fzf1Rw5+Dx7sBFOfrJKCYlsikPOIu3dOQzAi NwtFZTCNsUMZn/0WOZ7AtIuoS11H36hB716ptj3eWH80sIE/7VXR77ai76RojBGtGRLe P+2FuDDxmYYEYpv9ke5vTUXMXpF3Y6jTjsGKAplaLajPoo6RwdVGvMu5qGLjImt+dOXt ifAKH7MrHe8W+SGT9nPpKpkFUygFafXvHC5O+h/4HCxmDwMJxrbTQM4k06RGvRG0rHQ2 dPkmNgheVs3vTnENjEVARwhC6pTXWCbjn85xY/2l1EWRp87BW6ndjyiRB3hkiozgEnFN Rt+g== X-Forwarded-Encrypted: i=1; AJvYcCX4VCAMv3KC/Hsl/ktoYOBa6h+aZ+i/NOtQkb9pkmmMpH+ZUkVqiBnltrqUOOGZol6mhkOlzRtFHzHqFgwoDoTBNXeV30IEGLTtFyHxXcGoMdH9W1a44TZEyPUMYk86DoeSMYCHuuh7KixGsC8y+UTn/8R4ydonGrOdGLKcBiRtc9W0rwRrHOmW5luBZaXyqq4oS+FwrS2Zou+hlBKPUi9KPjnY3lo= X-Gm-Message-State: AOJu0YyHkxcaPaHc1qeIRpnYO1U5+gYC1HSRFIvSAot32rE9T/nHeqp/ U8AaX/2c5hgPJwkfC24gq8fMNL8HJOszN89alT1fmhcyiWq9GGe0 X-Google-Smtp-Source: AGHT+IHJs/7FdElGIO/Zgf0ElR99qNvty5EJddX01vOD2HNkiMp/pAeUblyMUM+sL6Xzrs51bo4ndA== X-Received: by 2002:a05:6808:118c:b0:3d5:5d4c:d15a with SMTP id 5614622812f47-3d93c0bf841mr14989295b6e.55.1720972964277; Sun, 14 Jul 2024 09:02:44 -0700 (PDT) Received: from vadorovsky-macbookpro.. ([207.35.255.94]) by smtp.gmail.com with ESMTPSA id 6a1803df08f44-6b7619789aesm14010566d6.33.2024.07.14.09.02.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 14 Jul 2024 09:02:43 -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 , Laine Taffin Altman , Danilo Krummrich , Yutaro Ohno , Tiago Lam , Charalampos Mitrodimas , Ben Gooding , 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] rust: str: Use `core::CStr`, remove the custom `CStr` implementation Date: Sun, 14 Jul 2024 18:02:19 +0200 Message-ID: <20240714160238.238708-1-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, therefore there is 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`). - It does not provide `from_bytes_with_nul_unchecked_mut` method. - It was used only in `DerefMut` implementation for `CString`. This change replaces it with a manual cast to `&mut CStr`. - Otherwise, having such a method is not really desirable. `CStr` is a reference type or `str` are usually not supposed to be modified. - It has `as_ptr()` method instead of `as_char_ptr()`, which also returns `*const c_char`. Rust also introduces C literals (`c""`), so the `c_str` macro is removed here as well. Signed-off-by: Michal Rostecki --- rust/kernel/error.rs | 7 +- rust/kernel/init.rs | 8 +- rust/kernel/kunit.rs | 16 +- rust/kernel/net/phy.rs | 2 +- rust/kernel/prelude.rs | 4 +- rust/kernel/str.rs | 490 +----------------------------------- rust/kernel/sync.rs | 13 +- rust/kernel/sync/condvar.rs | 5 +- rust/kernel/sync/lock.rs | 6 +- rust/kernel/workqueue.rs | 10 +- scripts/rustdoc_test_gen.rs | 4 +- 11 files changed, 57 insertions(+), 508 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/init.rs b/rust/kernel/init.rs index 68605b633e73..af0017e56c0e 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -46,7 +46,7 @@ //! } //! //! let foo = pin_init!(Foo { -//! a <- new_mutex!(42, "Foo::a"), +//! a <- new_mutex!(42, c"Foo::a"), //! b: 24, //! }); //! ``` @@ -65,7 +65,7 @@ //! # b: u32, //! # } //! # let foo = pin_init!(Foo { -//! # a <- new_mutex!(42, "Foo::a"), +//! # a <- new_mutex!(42, c"Foo::a"), //! # b: 24, //! # }); //! let foo: Result>> = Box::pin_init(foo, GFP_KERNEL); @@ -81,7 +81,7 @@ //! ```rust //! # use kernel::sync::{new_mutex, Arc, Mutex}; //! let mtx: Result>> = -//! Arc::pin_init(new_mutex!(42, "example::mtx"), GFP_KERNEL); +//! Arc::pin_init(new_mutex!(42, c"example::mtx"), GFP_KERNEL); //! ``` //! //! To declare an init macro/function you just return an [`impl PinInit`]: @@ -99,7 +99,7 @@ //! impl DriverData { //! fn new() -> impl PinInit { //! try_pin_init!(Self { -//! status <- new_mutex!(0, "DriverData::status"), +//! status <- new_mutex!(0, c"DriverData::status"), //! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?, //! }) //! } diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 0ba77276ae7e..6da0d5e237b6 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -56,9 +56,13 @@ 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 = unsafe { + core::ffi::CStr::from_bytes_with_nul_unchecked( + core::concat!(stringify!($condition), "\0").as_bytes() + ) + }; // SAFETY: FFI call without safety requirements. let kunit_test = unsafe { $crate::bindings::kunit_get_current_test() }; @@ -71,11 +75,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 +102,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..d1e6335a02a3 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, DerefMut}; 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!("