rust: replace kernel::str::CStr w/ core::ffi::CStr
Subsystems (6)
v14 cover rust: replace kernel::str::CStr w/ core::ffi::CStr
This picks up from Michal Rostecki's work[0]. Per Michal's guidance I have omitted Co-authored tags, as the end result is quite different.
This series is intended to be taken through rust-next. The final patch in the series requires some other subsystems' Acked-bys:
- rust/kernel/device.rs: driver-core. Already acked by gregkh.
- rust/kernel/firmware.rs: driver-core. Danilo, could you take a look?
- rust/kernel/seq_file.rs: vfs, I think? missing MAINTAINERS entry. Christian Brauner <[email protected]>, perhaps?
- rust/kernel/sync/*: no clear owner, probably doesn't need any.
This series depends on steps 2a[1] and 2b[2] which both depend on step 1[3].
---
Changes in v14:
- Break the change into multiple series.
- Move CStr reexport to kernel::ffi. (Alice Ryhl)
- pub use core::fmt::{....} in kernel/fmt.rs. (Benno Lossin)
- Avoid unnecessary binding to first_lit in fmt!. (Benno Lossin)
- Add comment to identifier-extracting loop. (Benno Lossin)
- Change quote_spanned! formatting. (Benno Lossin)
- Link to v13: https://lore.kernel.org/r/[email protected]
Changes in v13:
- Rebase on v6.16-rc4.
- Link to v12: https://lore.kernel.org/r/[email protected]
Changes in v12:
- Introduce kernel::fmt::Display to allow implementations on foreign types.
- Tidy up doc comment on str_to_cstr. (Alice Ryhl).
- Link to v11: https://lore.kernel.org/r/[email protected]
Changes in v11:
- Use quote_spanned! to avoid use<'a, T> and generally reduce manual token construction.
- Add a commit to simplify quote_spanned!.
- Drop first commit in favor of
https://lore.kernel.org/rust-for-linux/[email protected]/.
(Miguel Ojeda)
- Correctly handle expressions such as pr_info!("{a}", a = a = a). (Benno Lossin)
- Avoid dealing with }} escapes, which is not needed. (Benno Lossin)
- Revert some unnecessary changes. (Benno Lossin)
- Rename c_str_avoid_literals! to str_to_cstr!. (Benno Lossin &
Alice Ryhl).
- Link to v10: https://lore.kernel.org/r/[email protected]
Changes in v10:
- Rebase on cbeaa41dfe26b72639141e87183cb23e00d4b0dd.
- Implement Alice's suggestion to use a proc macro to work around orphan rules otherwise preventing core::ffi::CStr to be directly printed with {}.
- Link to v9: https://lore.kernel.org/r/[email protected]
Changes in v9:
- Rebase on rust-next.
- Restore impl Display for BStr which exists upstream[1].
- Link: https://doc.rust-lang.org/nightly/std/bstr/struct.ByteStr.html#impl-Display-for-ByteStr [1]
- Link to v8: https://lore.kernel.org/r/[email protected]
Changes in v8:
- Move {from,as}_char_ptr back to CStrExt. This reduces the diff some.
- Restore from_bytes_with_nul_unchecked_mut, to_cstring.
- Link to v7: https://lore.kernel.org/r/[email protected]
Changes in v7:
- Rebased on mainline.
- Restore functionality added in commit a321f3ad0a5d ("rust: str: add {make,to}_{upper,lower}case() to CString").
- Used diff.algorithm patience to improve diff readability.
- Link to v6: https://lore.kernel.org/r/[email protected]
Changes in v6:
- Split the work into several commits for ease of review.
- Restore {from,as}_char_ptr to allow building on ARM (see commit message).
- Add CStrExt to kernel::prelude. (Alice Ryhl)
- Remove CStrExt::from_bytes_with_nul_unchecked_mut and restore DerefMut for CString. (Alice Ryhl)
- Rename and hide kernel::c_str! to encourage use of C-String literals.
- Drop implementation and invocation changes in kunit.rs. (Trevor Gross)
- Drop docs on Display impl. (Trevor Gross)
- Rewrite docs in the style of the standard library.
- Restore the test_cstr_debug unit tests to demonstrate that the implementation has changed.
Changes in v5:
- Keep the test_cstr_display* unit tests.
Changes in v4:
- Provide the CStrExt trait with display() method, which returns a CStrDisplay wrapper with Display implementation. This addresses the lack of Display implementation for core::ffi::CStr.
- Provide from_bytes_with_nul_unchecked_mut() method in CStrExt, which might be useful and is going to prevent manual, unsafe casts.
- Fix a typo (s/preffered/prefered/).
Changes in v3:
- Fix the commit message.
- Remove redundant braces in use, when only one item is imported.
Changes in 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.
---
Tamir Duberstein (3):
rust: macros: reduce collections in quote! macro
rust: support formatting of foreign types
rust: replace CStr with core::ffi::CStr
rust/ffi.rs | 2 + rust/kernel/device.rs | 1 + rust/kernel/error.rs | 2 + rust/kernel/firmware.rs | 9 +- rust/kernel/fmt.rs | 87 ++++++++- rust/kernel/prelude.rs | 7 +- rust/kernel/seq_file.rs | 2 +- rust/kernel/str.rs | 395 +++++++++------------------------------- rust/kernel/sync/condvar.rs | 2 +- rust/kernel/sync/lock.rs | 2 +- rust/kernel/sync/lock/global.rs | 2 +- rust/macros/fmt.rs | 94 ++++++++++ rust/macros/lib.rs | 19 ++ rust/macros/quote.rs | 111 +++++------ 14 files changed, 362 insertions(+), 373 deletions(-)
---
base-commit: 769e324b66b0d92d04f315d0c45a0f72737c7494
change-id: 20250201-cstr-core-d4b9b69120cf
prerequisite-change-id: 20250704-core-cstr-prepare-9b9e6a7bd57e:v1
prerequisite-patch-id: 83b1239d1805f206711a5a936bbb61c83227d573
prerequisite-patch-id: a0355dd0efcc945b0565dc4e5a0f42b5a3d29c7e
prerequisite-patch-id: 8585bf441cfab705181f5606c63483c2e88d25aa
prerequisite-patch-id: 04ec344c0bc23f90dbeac10afe26df1a86ce53ec
prerequisite-patch-id: a2fc6cd05fce6d6da8d401e9f8a905bb5c0b2f27
prerequisite-patch-id: f14c099c87562069f25fb7aea6d9aae4086c49a8
prerequisite-message-id: [email protected]
prerequisite-patch-id: fa79c5d8fd2762b5e488ba017e13a5774d933f81
prerequisite-patch-id: c338aa49e1319e9e802de2ad8bb0fa688bce9d9c
prerequisite-patch-id: 589a352ba7f7c9aefefd84dfd3b6b20e290b0d14
prerequisite-patch-id: 29fc25261295349f6747d1bb409cf18130e9aa69
prerequisite-patch-id: 3d89601bba1fb01d190b0ba415b28ad9cbf1e209
prerequisite-patch-id: 10923aebf24011b727f60496c0f9e0ad57e0a967
prerequisite-patch-id: 56583fd829951fb4fac843c6b1874c643b726de0
prerequisite-patch-id: 9a7e8ba460358985147efd347658be31fbc78ba2
prerequisite-patch-id: 5821a23334e317cd0351b8e4404b9e3b36b72d67
prerequisite-message-id: [email protected]
prerequisite-patch-id: 0ccc3545ff9bf22a67b79a944705cef2fb9c2bbf
prerequisite-patch-id: b1866166714606d5c11a4d7506abe4c2f86dac8d
prerequisite-patch-id: 163b8ff1edaf8e48976fd5de3f64e68fc38c7277
prerequisite-patch-id: 8fee5e2daf0749362331dad4fc63d907a01b14e9
prerequisite-patch-id: 366ef1f93fb40b1d039768f2041ff79995e7e228
prerequisite-patch-id: 1d350291f9292f910081856d8f7d5e4d9545cfd1
prerequisite-patch-id: 9a6a60bd2b209126de64c16a77a3a1d229dd898c
prerequisite-patch-id: 08ae5855768ec3b4c68272b86d2a0e0667c9aa47
prerequisite-patch-id: f15b54927660a03b52ffb34fb7943ac3228b7803
prerequisite-patch-id: f0dbf0a55a27fe8e199e242d1f79ea800d1ddb66
Best regards,
Signature · 1 line
Tamir Duberstein <[email protected]>
PATCH v14 1/3 rust: macros: reduce collections in `quote!` macro
Remove a handful of unncessary intermediate vectors and token streams; mainly the top-level stream can be directly extended with the notable exception of groups.
Remove an unnecessary #[allow(dead_code)] added in commit dbd5058ba60c ("rust: make pin-init its own crate").
--- rust/macros/quote.rs | 104 ++++++++++++++++++++++++--------------------------- 1 file changed, 49 insertions(+), 55 deletions(-)
rust/macros/quote.rs +49 -55
@@ -2,7 +2,6 @@use proc_macro::{TokenStream ,TokenTree }; -#[allow(dead_code)] pub (crate )trait ToTokens {fn to_tokens (&self, tokens: &mut TokenStream ); }
@@ -47,121 +46,116 @@ fn to_tokens(&self, tokens: &mut TokenStream) {/// `quote` crate but provides only just enough functionality needed by the current `macros` crate. macro_rules! quote_spanned { ($span:expr => $($tt:tt)*) => {{ -let mut tokens: ::std::vec::Vec <::proc_macro::TokenTree >; -#[allow(clippy::vec_init_then_push)] +let mut tokens = ::proc_macro::TokenStream ::new (); { - tokens = ::std::vec::Vec ::new ();let span = $span;quote_spanned! (@proc tokensspan $($tt)*); } - ::proc_macro::TokenStream ::from_iter (tokens) + tokens }}; (@proc $v:ident $span:ident) => {}; (@proc $v:ident $span:ident #$id:ident $($tt:tt)*) => { -let mut ts = ::proc_macro::TokenStream ::new (); - $crate::quote::ToTokens ::to_tokens (&$id, &mut ts); - $v.extend (ts); + $crate::quote::ToTokens ::to_tokens (&$id, &mut $v);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident #(#$id:ident)* $($tt:tt)*) => {for tokenin $id { -let mut ts = ::proc_macro::TokenStream ::new (); - $crate::quote::ToTokens ::to_tokens (&token, &mut ts); - $v.extend (ts); + $crate::quote::ToTokens ::to_tokens (&token, &mut $v); }quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident ( $($inner:tt)* ) $($tt:tt)*) => {#[allow(unused_mut)] -let mut tokens = ::std::vec::Vec ::<::proc_macro::TokenTree >::new (); +let mut tokens = ::proc_macro::TokenStream ::new ();quote_spanned! (@proc tokens $span $($inner)*); - $v.push (::proc_macro::TokenTree ::Group (::proc_macro::Group ::new ( + $v.extend ([::proc_macro::TokenTree ::Group (::proc_macro::Group ::new ( ::proc_macro::Delimiter ::Parenthesis , - ::proc_macro::TokenStream ::from_iter (tokens) - ))); + tokens, + ))]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident [ $($inner:tt)* ] $($tt:tt)*) => { -let mut tokens = ::std::vec::Vec ::new (); +let mut tokens = ::proc_macro::TokenStream ::new ();quote_spanned! (@proc tokens $span $($inner)*); - $v.push (::proc_macro::TokenTree ::Group (::proc_macro::Group ::new ( + $v.extend ([::proc_macro::TokenTree ::Group (::proc_macro::Group ::new ( ::proc_macro::Delimiter ::Bracket , - ::proc_macro::TokenStream ::from_iter (tokens) - ))); + tokens, + ))]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident { $($inner:tt)* } $($tt:tt)*) => { -let mut tokens = ::std::vec::Vec ::new (); +let mut tokens = ::proc_macro::TokenStream ::new ();quote_spanned! (@proc tokens $span $($inner)*); - $v.push (::proc_macro::TokenTree ::Group (::proc_macro::Group ::new ( + $v.extend ([::proc_macro::TokenTree ::Group (::proc_macro::Group ::new ( ::proc_macro::Delimiter ::Brace , - ::proc_macro::TokenStream ::from_iter (tokens) - ))); + tokens, + ))]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident :: $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new (':' , ::proc_macro::Spacing ::Joint ) - )); - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new (':' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::Spacing ::Joint , ::proc_macro::Spacing ::Alone ].map (|spacing| { + ::proc_macro::TokenTree ::Punct (::proc_macro::Punct ::new (':' , spacing)) + }));quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident : $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new (':' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new (':' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident , $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new (',' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new (',' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident @ $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new ('@' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new ('@' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident ! $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new ('!' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new ('!' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident ; $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new (';' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new (';' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident + $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new ('+' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new ('+' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident = $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new ('=' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new ('=' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident # $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Punct ( - ::proc_macro::Punct ::new ('#' , ::proc_macro::Spacing ::Alone ) - )); + $v.extend ([::proc_macro::TokenTree ::Punct ( + ::proc_macro::Punct ::new ('#' , ::proc_macro::Spacing ::Alone ), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident _ $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Ident (::proc_macro::Ident ::new ("_" , $span))); + $v.extend ([::proc_macro::TokenTree ::Ident ( + ::proc_macro::Ident ::new ("_" , $span), + )]);quote_spanned! (@proc $v $span $($tt)*); }; (@proc $v:ident $span:ident $id:ident $($tt:tt)*) => { - $v.push (::proc_macro::TokenTree ::Ident (::proc_macro::Ident ::new (stringify! ($id), $span))); + $v.extend ([::proc_macro::TokenTree ::Ident ( + ::proc_macro::Ident ::new (stringify! ($id), $span), + )]);quote_spanned! (@proc $v $span $($tt)*); }; }
Signature · 1 line
2.50.0
PATCH v14 2/3 rust: support formatting of foreign types
In reply to Tamir DubersteinIntroduce a fmt! macro which wraps all arguments in kernel::fmt::Adapter and a kernel::fmt::Display trait. This enables formatting of foreign types (like core::ffi::CStr) that do not implement core::fmt::Display due to concerns around lossy conversions which do not apply in the kernel.
--- rust/kernel/fmt.rs | 87 +++++++++++++++++++++++++++++++++++++++++++++- rust/kernel/prelude.rs | 3 +- rust/macros/fmt.rs | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 19 ++++++++++ rust/macros/quote.rs | 7 ++++ 5 files changed, 207 insertions(+), 3 deletions(-)
rust/kernel/fmt.rs +86 -1
@@ -4,4 +4,89 @@//! //! This module is intended to be used in place of `core::fmt` in kernel code. -pub use core::fmt::{Arguments ,Debug ,Display ,Error ,Formatter ,Result ,Write }; +pub use core::fmt::{Arguments ,Debug ,Error ,Formatter ,Result ,Write }; + +/// Internal adapter used to route allow implementations of formatting traits for foreign types. +/// +/// It is inserted automatically by the [`fmt!`] macro and is not meant to be used directly. +/// +/// [`fmt!`]: crate::prelude::fmt! +#[doc(hidden)] +pub struct Adapter <T >(pub T ); + +macro_rules! impl_fmt_adapter_forward { + ($($trait:ident),* $(,)?) => { + $( +impl <T : $trait> $traitfor Adapter <T > { +fn fmt (&self, f: &mut Formatter <'_>) ->Result { +let Self (t) = self; + $trait::fmt (t, f) + } + } + )* + }; +} + +use core::fmt::{Binary ,LowerExp ,LowerHex ,Octal ,Pointer ,UpperExp ,UpperHex }; +impl_fmt_adapter_forward! (Debug ,LowerHex ,UpperHex ,Octal ,Binary ,Pointer ,LowerExp ,UpperExp ); + +/// A copy of [`core::fmt::Display`] that allows us to implement it for foreign types. +/// +/// Types should implement this trait rather than [`core::fmt::Display`]. Together with the +/// [`Adapter`] type and [`fmt!`] macro, it allows for formatting foreign types (e.g. types from +/// core) which do not implement [`core::fmt::Display`] directly. +/// +/// [`fmt!`]: crate::prelude::fmt! +pub trait Display { +/// Same as [`core::fmt::Display::fmt`]. +fn fmt (&self, f: &mut Formatter <'_>) ->Result ; +} + +impl <T : ?Sized +Display >Display for &T { +fn fmt (&self, f: &mut Formatter <'_>) ->Result { +Display ::fmt (*self, f) + } +} + +impl <T : ?Sized +Display > core::fmt::Display for Adapter <&T > { +fn fmt (&self, f: &mut Formatter <'_>) ->Result { +let Self (t) = self; +Display ::fmt (t, f) + } +} + +macro_rules! impl_display_forward { + ($( + $( { $($generics:tt)* } )? $ty:ty $( {where $($where:tt)* } )? + ),* $(,)?) => { + $( + impl$($($generics)*)? Display for $ty $(where $($where)*)? { +fn fmt (&self, f: &mut Formatter <'_>) ->Result { + core::fmt::Display ::fmt (self, f) + } + } + )* + }; +} + +impl_display_forward! ( +bool , +char , + core::panic::PanicInfo <'_>, +Arguments <'_>, +i128 , +i16 , +i32 , +i64 , +i8 , +isize , +str , +u128 , +u16 , +u32 , +u64 , +u8 , +usize , + {<T : ?Sized >}crate ::sync::Arc <T > {where crate ::sync::Arc <T >: core::fmt::Display }, + {<T : ?Sized >}crate ::sync::UniqueArc <T > {where crate ::sync::UniqueArc <T >: core::fmt::Display }, +);
rust/kernel/prelude.rs +1 -2
@@ -22,7 +22,7 @@pub use crate ::alloc::{flags::*,Box ,KBox ,KVBox ,KVVec ,KVec ,VBox ,VVec ,Vec };#[doc(no_inline)] -pub use macros::{export, kunit_tests, module, vtable}; +pub use macros::{export, fmt, kunit_tests, module, vtable};pub use pin_init::{init, pin_data, pin_init, pinned_drop,InPlaceWrite ,Init ,PinInit ,Zeroable };
@@ -33,7 +33,6 @@pub use super ::dbg;pub use super ::{dev_alert, dev_crit, dev_dbg, dev_emerg, dev_err, dev_info, dev_notice, dev_warn};pub use super ::{pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; -pub use core::format_argsas fmt;pub use super ::{try_init, try_pin_init};
rust/macros/fmt.rs new file +94 -0
94 lines not on this page · raw message
rust/macros/lib.rs +19 -0
@@ -15,6 +15,7 @@mod quote;mod concat_idents;mod export; +mod fmt;mod helpers;mod kunit;mod module;
@@ -201,6 +202,24 @@ pub fn export(attr: TokenStream, ts: TokenStream) -> TokenStream { export::export (attr, ts) } +/// Like [`core::format_args!`], but automatically wraps arguments in [`kernel::fmt::Adapter`]. +/// +/// This macro allows generating `fmt::Arguments` while ensuring that each argument is wrapped with +/// `::kernel::fmt::Adapter`, which customizes formatting behavior for kernel logging. +/// +/// Named arguments used in the format string (e.g. `{foo}`) are detected and resolved from local +/// bindings. All positional and named arguments are automatically wrapped. +/// +/// This macro is an implementation detail of other kernel logging macros like [`pr_info!`] and +/// should not typically be used directly. +/// +/// [`kernel::fmt::Adapter`]: ../kernel/fmt/struct.Adapter.html +/// [`pr_info!`]: ../kernel/macro.pr_info.html +#[proc_macro] +pub fn fmt (input:TokenStream ) ->TokenStream { + fmt::fmt (input) +} +/// Concatenate two identifiers. /// /// This is useful in macros that need to declare or reference items with names
rust/macros/quote.rs +7 -0
@@ -48,6 +48,7 @@ macro_rules! quote_spanned { ($span:expr => $($tt:tt)*) => {{let mut tokens = ::proc_macro::TokenStream ::new (); { +#[allow(unused_variables)] let span = $span;quote_spanned! (@proc tokensspan $($tt)*); }
@@ -146,6 +147,12 @@ macro_rules! quote_spanned { )]);quote_spanned! (@proc $v $span $($tt)*); }; + (@proc $v:ident $span:ident & $($tt:tt)*) => { + $v.extend([::proc_macro::TokenTree::Punct( + ::proc_macro::Punct::new('&', ::proc_macro::Spacing::Alone), + )]); + quote_spanned!(@proc $v $span $($tt)*); + }; (@proc $v:ident $span:ident _ $($tt:tt)*) => { $v.extend([::proc_macro::TokenTree::Ident( ::proc_macro::Ident::new("_", $span),
Signature · 1 line
2.50.0
Re: [PATCH v14 2/3] rust: support formatting of foreign types
Quoted 11 lines · Tamir Duberstein
Introduce a
fmt!macro which wraps all arguments inkernel::fmt::Adapterand akernel::fmt::Displaytrait. This enables formatting of foreign types (likecore::ffi::CStr) that do not implementcore::fmt::Displaydue to concerns around lossy conversions which do not apply in the kernel.
I'm not 100% sure we need to always use first_span, but it's probably fine.
---
Cheers,
Benno
Quoted 7 lines
--- rust/kernel/fmt.rs | 87 +++++++++++++++++++++++++++++++++++++++++++++- rust/kernel/prelude.rs | 3 +- rust/macros/fmt.rs | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 19 ++++++++++ rust/macros/quote.rs | 7 ++++ 5 files changed, 207 insertions(+), 3 deletions(-)
PATCH v14 3/3 rust: replace `CStr` with `core::ffi::CStr`
In reply to Tamir Dubersteinkernel::ffi::CStr was introduced in commit d126d2380131 ("rust: str:
add CStr type") in November 2022 as an upstreaming of earlier work that was done in May 2021[0]. That earlier work, having predated the inclusion of CStr in core, largely duplicated the implementation of std::ffi::CStr.
std::ffi::CStr was moved to core::ffi::CStr in Rust 1.64 in September 2022. Hence replace kernel::str::CStr with core::ffi::CStr to reduce our custom code footprint, and retain needed custom functionality through an extension trait.
Add CStr to ffi and the kernel prelude.
--- rust/ffi.rs | 2 + rust/kernel/device.rs | 1 + rust/kernel/error.rs | 2 + rust/kernel/firmware.rs | 9 +- rust/kernel/prelude.rs | 4 +- rust/kernel/seq_file.rs | 2 +- rust/kernel/str.rs | 395 +++++++++------------------------------- rust/kernel/sync/condvar.rs | 2 +- rust/kernel/sync/lock.rs | 2 +- rust/kernel/sync/lock/global.rs | 2 +- 10 files changed, 106 insertions(+), 315 deletions(-)
rust/ffi.rs +2 -0
@@ -46,3 +46,5 @@ macro_rules! alias { }pub use core::ffi::c_void; + +pub use core::ffi::CStr ;
rust/kernel/device.rs +1 -0
@@ -13,6 +13,7 @@#[cfg( CONFIG_PRINTK )] use crate ::c_str; +use crate ::str::CStrExt as _;/// A reference-counted device. ///
rust/kernel/error.rs +2 -0
@@ -164,6 +164,8 @@ pub fn name(&self) -> Option<&'static CStr> {if ptr.is_null () {None }else { +use crate ::str::CStrExt as _; +// SAFETY: The string returned by `errname` is static and `NUL`-terminated. Some (unsafe {CStr ::from_char_ptr (ptr) }) }
rust/kernel/firmware.rs +8 -1
@@ -4,7 +4,14 @@//! //! C header: [`include/linux/firmware.h`](srctree/include/linux/firmware.h) -use crate ::{bindings, device::Device , error::Error , error::Result , ffi, str::CStr }; +use crate ::{ + bindings, + device::Device , + error::Error , + error::Result , + ffi, + str::{CStr ,CStrExt as _}, +};use core::ptr::NonNull ;/// # Invariants
rust/kernel/prelude.rs +2 -2
@@ -16,7 +16,7 @@pub use ::ffi::{ c_char, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong, c_ulonglong, - c_ushort, c_void, + c_ushort, c_void,CStr , };pub use crate ::alloc::{flags::*,Box ,KBox ,KVBox ,KVVec ,KVec ,VBox ,VVec ,Vec };
@@ -40,7 +40,7 @@pub use super ::error::{code::*,Error ,Result }; -pub use super ::{str::CStr ,ThisModule }; +pub use super ::{str::CStrExt as _,ThisModule };pub use super ::init::InPlaceInit ;
rust/kernel/seq_file.rs +1 -1
@@ -4,7 +4,7 @@//! //! C header: [`include/linux/seq_file.h`](srctree/include/linux/seq_file.h) -use crate ::{bindings, c_str, fmt, types::NotThreadSafe , types::Opaque }; +use crate ::{bindings, c_str, fmt, str::CStrExt as _, types::NotThreadSafe , types::Opaque };/// A utility for generating the contents of a seq file. #[repr(transparent)]
rust/kernel/str.rs +87 -308
513 lines not on this page · raw message
rust/kernel/sync/condvar.rs +1 -1
@@ -8,7 +8,7 @@use super ::{lock::Backend , lock::Guard ,LockClassKey };use crate ::{ ffi::{c_int, c_long}, - str::CStr , + str::{CStr ,CStrExt as _}, task::{MAX_SCHEDULE_TIMEOUT ,TASK_FREEZABLE ,TASK_INTERRUPTIBLE ,TASK_NORMAL ,TASK_UNINTERRUPTIBLE , },
rust/kernel/sync/lock.rs +1 -1
@@ -7,7 +7,7 @@use super ::LockClassKey ;use crate ::{ - str::CStr , + str::{CStr ,CStrExt as _}, types::{NotThreadSafe ,Opaque ,ScopeGuard }, };use core::{cell::UnsafeCell , marker::PhantomPinned , pin::Pin };
rust/kernel/sync/lock/global.rs +1 -1
@@ -5,7 +5,7 @@//! Support for defining statics containing locks. use crate ::{ - str::CStr , + str::{CStr ,CStrExt as _}, sync::lock::{Backend ,Guard ,Lock }, sync::{LockClassKey ,LockedBy }, types::Opaque ,
Signature · 1 line
2.50.0
Re: [PATCH v14 3/3] rust: replace `CStr` with `core::ffi::CStr`
Quoted 11 lines · Tamir Duberstein
kernel::ffi::CStrwas introduced in commitd126d2380131("rust: str:
addCStrtype") in November 2022 as an upstreaming of earlier work that was done in May 2021[0]. That earlier work, having predated the inclusion ofCStrincore, largely duplicated the implementation ofstd::ffi::CStr.
std::ffi::CStrwas moved tocore::ffi::CStrin Rust 1.64 in September 2022. Hence replacekernel::str::CStrwithcore::ffi::CStrto reduce our custom code footprint, and retain needed custom functionality through an extension trait.
Quoted 6 lines
Add
CStrtoffiand the kernel prelude.
Quoted 13 lines
--- rust/ffi.rs | 2 + rust/kernel/device.rs | 1 + rust/kernel/error.rs | 2 + rust/kernel/firmware.rs | 9 +- rust/kernel/prelude.rs | 4 +- rust/kernel/seq_file.rs | 2 +- rust/kernel/str.rs | 395 +++++++++------------------------------- rust/kernel/sync/condvar.rs | 2 +- rust/kernel/sync/lock.rs | 2 +- rust/kernel/sync/lock/global.rs | 2 +- 10 files changed, 106 insertions(+), 315 deletions(-)
rust/kernel/str.rs macro_rules! b_str { · line 190
Quoted 2 lines
rust/kernel/str.rs +2
-0+/// Extensions to [`CStr`]. +pub trait CStrExt {
Should we make this trait sealed?
---
Cheers,
Benno
Quoted 3 lines
/// Wraps a raw C string pointer.
///
/// # SafetyRe: [PATCH v14 3/3] rust: replace `CStr` with `core::ffi::CStr`
Quoted 13 lines · Benno Lossin
Quoted 11 lines · Tamir Duberstein
kernel::ffi::CStrwas introduced in commitd126d2380131("rust: str:
addCStrtype") in November 2022 as an upstreaming of earlier work that was done in May 2021[0]. That earlier work, having predated the inclusion ofCStrincore, largely duplicated the implementation ofstd::ffi::CStr.
std::ffi::CStrwas moved tocore::ffi::CStrin Rust 1.64 in September 2022. Hence replacekernel::str::CStrwithcore::ffi::CStrto reduce our custom code footprint, and retain needed custom functionality through an extension trait.
Quoted 8 lines
Quoted 6 lines
Add
CStrtoffiand the kernel prelude.Reviewed-by Benno Lossin <[email protected]>
Thanks!
Quoted 13 lines
Quoted 12 lines
--- rust/ffi.rs | 2 + rust/kernel/device.rs | 1 + rust/kernel/error.rs | 2 + rust/kernel/firmware.rs | 9 +- rust/kernel/prelude.rs | 4 +- rust/kernel/seq_file.rs | 2 +- rust/kernel/str.rs | 395 +++++++++------------------------------- rust/kernel/sync/condvar.rs | 2 +- rust/kernel/sync/lock.rs | 2 +- rust/kernel/sync/lock/global.rs | 2 +- 10 files changed, 106 insertions(+), 315 deletions(-)
Quoted 4 lines
rust/kernel/str.rs macro_rules! b_str { · line 190
Quoted 2 lines
rust/kernel/str.rs +2
-0+/// Extensions to [`CStr`]. +pub trait CStrExt {Should we make this trait sealed?
We can -- but is it harmful for someone to implement? I think probably not.
Quoted 8 lines
---
Cheers,
BennoQuoted 3 lines
/// Wraps a raw C string pointer. /// /// # Safety
Benno Lossin
reviewerRe: [PATCH v14 3/3] rust: replace `CStr` with `core::ffi::CStr`
Quoted 8 lines · Tamir Duberstein
Quoted 5 lines · Benno Lossin
rust/kernel/str.rs macro_rules! b_str { · line 190
Quoted 2 lines · Tamir Duberstein
rust/kernel/str.rs +2
-0+/// Extensions to [`CStr`]. +pub trait CStrExt {Should we make this trait sealed?
We can -- but is it harmful for someone to implement? I think probably not.
I don't think anything aside from CStr should implement it, so I'd say we make it sealed. There are also safe functions that return raw pointers & an implementation could just return a bogus pointer...
---
Cheers,
Benno
Re: [PATCH v14 3/3] rust: replace `CStr` with `core::ffi::CStr`
Quoted 9 lines · Benno Lossin
Quoted 7 lines · Tamir Duberstein
Quoted 5 lines · Benno Lossin
rust/kernel/str.rs macro_rules! b_str { · line 190
Quoted 2 lines · Tamir Duberstein
rust/kernel/str.rs +2
-0+/// Extensions to [`CStr`]. +pub trait CStrExt {Should we make this trait sealed?
Quoted 5 lines
Quoted 1 line
We can -- but is it harmful for someone to implement? I think probably not.
I don't think anything aside from
CStrshould implement it, so I'd say we make it sealed. There are also safe functions that return raw pointers & an implementation could just return a bogus pointer...
Done in v15.
Quoted 2 lines · Tamir Duberstein
This picks up from Michal Rostecki's work[0]. Per Michal's guidance I have omitted Co-authored tags, as the end result is quite different.
For device and firmware,