rust: replace kernel::str::CStr w/ core::ffi::CStr
Subsystems (16)
v6 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.
---
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 (4):
rust: move BStr,CStr Display impls behind method
rust: replace CStr with core::ffi::CStr
rust: replace kernel::c_str! with C-Strings
rust: remove core::ffi::CStr reexport
drivers/gpu/drm/drm_panic_qr.rs | 2 +- drivers/net/phy/ax88796b_rust.rs | 7 +- drivers/net/phy/qt2025.rs | 5 +- rust/kernel/device.rs | 5 +- rust/kernel/error.rs | 10 +- rust/kernel/firmware.rs | 9 +- rust/kernel/kunit.rs | 18 +- rust/kernel/miscdevice.rs | 5 +- rust/kernel/net/phy.rs | 8 +- rust/kernel/prelude.rs | 2 +- rust/kernel/seq_file.rs | 4 +- rust/kernel/str.rs | 579 +++++++++++---------------------------- rust/kernel/sync.rs | 4 +- rust/kernel/sync/condvar.rs | 4 +- rust/kernel/sync/lock.rs | 5 +- rust/kernel/sync/lock/global.rs | 7 +- rust/kernel/sync/poll.rs | 1 + rust/kernel/workqueue.rs | 3 +- 18 files changed, 210 insertions(+), 468 deletions(-)
---
base-commit: bdf3d0e99c106932167de56141be5092762bab48
change-id: 20250201-cstr-core-d4b9b69120cf
Best regards,
Signature · 1 line
Tamir Duberstein <[email protected]>
PATCH v6 1/4 rust: move BStr,CStr Display impls behind method
There are two reasons for doing this:
- Moving the Display impl behind a display method matches the style used in the standard library for printing non-Unicode data.
- The standard library's core::ffi::CStr doesn't implement Display; moving Display to a helper struct is a necessary step toward using it.
--- rust/kernel/kunit.rs | 9 ++-- rust/kernel/str.rs | 120 +++++++++++++++++++++++++++++++++++---------------- 2 files changed, 89 insertions(+), 40 deletions(-)
rust/kernel/kunit.rs +6 -3
@@ -56,6 +56,7 @@ macro_rules! kunit_assert {break 'out; } +static NAME : &'static $crate::str::CStr = $crate::c_str!($name);static FILE : &'static $crate::str::CStr = $crate::c_str!($file);static LINE :i32 = core::line!()as i32 - $diff;static CONDITION : &'static $crate::str::CStr = $crate::c_str!(stringify! ($condition));
@@ -71,11 +72,13 @@ macro_rules! kunit_assert {// // This mimics KUnit's failed assertion format. $crate::kunit::err (format_args! ( -" # {}: ASSERTION FAILED at {FILE}:{LINE}\n" , - $name +" # {NAME}: ASSERTION FAILED at {FILE}:{LINE}\n" , +NAME =NAME .display (), +FILE =FILE .display (), )); $crate::kunit::err (format_args! ( -" Expected {CONDITION} to be true, but is false\n" +" Expected {CONDITION} to be true, but is false\n" , +CONDITION =CONDITION .display (), )); $crate::kunit::err(format_args!( " Failure not reported to KUnit since this is a non-KUnit task\n"
rust/kernel/str.rs +83 -37
196 lines not on this page · raw message
Signature · 1 line
2.48.1
PATCH v6 2/4 rust: replace `CStr` with `core::ffi::CStr`
In reply to Tamir Dubersteinstd::ffi::CStr was moved to core::ffi::CStr in Rust 1.64. Replace kernel::str::CStr with core::ffi::CStr now that we can.
kernel::str::CStr::{from,as}_char_ptr live on as free functions in kernel::str to paper over the difference between core::ffi::c_char and kernel::ffi::char; see the code comment on the latter type for details.
C-String literals were added in Rust 1.77. Opportunistically replace instances of kernel::c_str! with C-String literals where other code changes were already necessary; the rest will be done in a later commit.
--- drivers/gpu/drm/drm_panic_qr.rs | 2 +- rust/kernel/device.rs | 5 +- rust/kernel/error.rs | 4 +- rust/kernel/firmware.rs | 2 +- rust/kernel/kunit.rs | 4 +- rust/kernel/miscdevice.rs | 2 +- rust/kernel/net/phy.rs | 2 +- rust/kernel/prelude.rs | 5 +- rust/kernel/seq_file.rs | 4 +- rust/kernel/str.rs | 449 ++++++---------------------------------- rust/kernel/sync/condvar.rs | 2 +- rust/kernel/sync/lock.rs | 2 +- rust/kernel/sync/lock/global.rs | 2 +- rust/kernel/workqueue.rs | 2 +- 14 files changed, 88 insertions(+), 399 deletions(-)
drivers/gpu/drm/drm_panic_qr.rs +1 -1
@@ -958,7 +958,7 @@ fn draw_all(&mut self, data: impl Iterator<Item = u8>) { }else {// SAFETY: The caller ensures that `url` is a valid pointer to a // nul-terminated string. -let url_cstr: &CStr =unsafe {CStr ::from_char_ptr (url) }; +let url_cstr: &CStr =unsafe { kernel::str::from_char_ptr (url) };let segments = &[ &Segment ::Binary (url_cstr.as_bytes ()), &Segment::Numeric(&data_slice[0..data_len]),
rust/kernel/device.rs +1 -4
@@ -10,9 +10,6 @@ };use core::{fmt, ptr}; -#[cfg( CONFIG_PRINTK )] -use crate ::c_str; -/// A reference-counted device. /// /// This structure represents the Rust abstraction for a C `struct device`. This implementation
@@ -175,7 +172,7 @@ unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) { bindings::_dev_printk ( klevelas *const _ as *const crate ::ffi::c_char , self.as_raw (), -c_str! ("%pA" ).as_char_ptr (), +crate ::str::as_char_ptr (c"%pA" ), &msgas *const _ as *const crate ::ffi::c_void , ) };
rust/kernel/error.rs +2 -2
@@ -164,7 +164,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 {crate ::str::from_char_ptr (ptr) }) } }
@@ -187,7 +187,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Some(name) => f .debug_tuple (// SAFETY: These strings are ASCII-only. -unsafe { core::str::from_utf8_unchecked (name) }, +unsafe { core::str::from_utf8_unchecked (name.to_bytes ()) }, ) .finish(), }
rust/kernel/firmware.rs +1 -1
@@ -61,7 +61,7 @@ fn request_internal(name: &CStr, dev: &Device, func: FwFunc) -> Result<Self> {// SAFETY: `pfw` is a valid pointer to a NULL initialized `bindings::firmware` pointer. // `name` and `dev` are valid as by their type invariants. -let ret =unsafe { func.0 (pfwas _ , name.as_char_ptr (), dev.as_raw ()) }; +let ret =unsafe { func.0 (pfwas _ ,crate ::str::as_char_ptr (name), dev.as_raw ()) };if ret !=0 {return Err (Error ::from_errno (ret)); }
rust/kernel/kunit.rs +2 -2
@@ -101,12 +101,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: $crate::str::as_char_ptr (FILE ), line:LINE , });static ASSERTION :UnaryAssert =UnaryAssert ($crate::bindings::kunit_unary_assert { assert: $crate::bindings::kunit_assert {}, - condition:CONDITION .as_char_ptr (), + condition: $crate::str::as_char_ptr (CONDITION ), expected_true:true , });
rust/kernel/miscdevice.rs +1 -1
@@ -31,7 +31,7 @@ pub const fn into_raw<T: MiscDevice>(self) -> bindings::miscdevice {// SAFETY: All zeros is valid for this C type. let mut result: bindings::miscdevice =unsafe {MaybeUninit ::zeroed ().assume_init () }; result.minor = bindings::MISC_DYNAMIC_MINOR as _ ; - result.name = self.name.as_char_ptr (); + result.name =crate ::str::as_char_ptr (self.name); result.fops =create_vtable ::<T >(); result }
rust/kernel/net/phy.rs +1 -1
@@ -504,7 +504,7 @@ unsafe impl Sync for DriverVTable {}pub const fn create_phy_driver <T :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: crate::str::as_char_ptr(T::NAME), flags: T::FLAGS, phy_id: T::PHY_DEVICE_ID.id, phy_id_mask: T::PHY_DEVICE_ID.mask_as_int(),
rust/kernel/prelude.rs +4 -1
@@ -34,7 +34,10 @@pub use super ::error::{code::*,Error ,Result }; -pub use super ::{str::CStr ,ThisModule }; +pub use super ::{ + str::{CStr ,CStrExt as _}, +ThisModule , +};pub use super ::init::{InPlaceInit ,InPlaceWrite ,Init ,PinInit };
rust/kernel/seq_file.rs +2 -2
@@ -4,7 +4,7 @@//! //! C header: [`include/linux/seq_file.h`](srctree/include/linux/seq_file.h) -use crate ::{bindings, c_str, types::NotThreadSafe , types::Opaque }; +use crate ::{bindings, types::NotThreadSafe , types::Opaque };/// A utility for generating the contents of a seq file. #[repr(transparent)]
@@ -35,7 +35,7 @@ pub fn call_printf(&self, args: core::fmt::Arguments<'_>) {unsafe { bindings::seq_printf ( self.inner.get (), -c_str! ("%pA" ).as_char_ptr (), +crate ::str::as_char_ptr (c"%pA" ), &argsas *const _ as *const crate ::ffi::c_void , ); }
rust/kernel/str.rs +69 -380
546 lines not on this page · raw message
rust/kernel/sync/condvar.rs +1 -1
@@ -107,7 +107,7 @@ pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self// SAFETY: `slot` is valid while the closure is called and both `name` and `key` have // static lifetimes so they live indefinitely. wait_queue_head <-Opaque ::ffi_init (|slot|unsafe { - bindings::__init_waitqueue_head (slot, name.as_char_ptr (), key.as_ptr ()) + bindings::__init_waitqueue_head (slot,crate ::str::as_char_ptr (name), key.as_ptr ()) }), }) }
rust/kernel/sync/lock.rs +1 -1
@@ -128,7 +128,7 @@ pub fn new(t: T, name: &'static CStr, key: &'static LockClassKey) -> impl PinIni// SAFETY: `slot` is valid while the closure is called and both `name` and `key` have // static lifetimes so they live indefinitely. state <-Opaque ::ffi_init (|slot|unsafe { -B ::init (slot, name.as_char_ptr (), key.as_ptr ()) +B ::init (slot,crate ::str::as_char_ptr (name), key.as_ptr ()) }), }) }
rust/kernel/sync/lock/global.rs +1 -1
@@ -69,7 +69,7 @@ pub unsafe fn init(&'static self) {unsafe {B ::Backend ::init ( self.inner.state.get (), -B ::NAME .as_char_ptr (), +crate ::str::as_char_ptr (B ::NAME ),B ::get_lock_class ().as_ptr (), ) }
rust/kernel/workqueue.rs +1 -1
@@ -382,7 +382,7 @@ pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self slot, Some(T::Pointer::run), false, - name.as_char_ptr(), + crate::str::as_char_ptr(name), key.as_ptr(), ) }
Signature · 1 line
2.48.1
PATCH v6 3/4 rust: replace `kernel::c_str!` with C-Strings
In reply to Tamir DubersteinC-String literals were added in Rust 1.77. Replace instances of kernel::c_str! with C-String literals where possible and rename kernel::c_str! to c_str_avoid_literals to clarify its intended use.
--- drivers/net/phy/ax88796b_rust.rs | 7 +++---- drivers/net/phy/qt2025.rs | 5 ++--- rust/kernel/firmware.rs | 4 ++-- rust/kernel/kunit.rs | 7 ++++--- rust/kernel/net/phy.rs | 6 ++---- rust/kernel/str.rs | 37 ++++++++++++++++++++++++------------- rust/kernel/sync.rs | 4 ++-- rust/kernel/sync/lock/global.rs | 3 ++- 8 files changed, 41 insertions(+), 32 deletions(-)
drivers/net/phy/ax88796b_rust.rs +3 -4
@@ -5,7 +5,6 @@//! //! C version of this driver: [`drivers/net/phy/ax88796b.c`](./ax88796b.c) use kernel::{ - c_str, net::phy::{self, reg::C22 ,DeviceId ,Driver }, prelude::*, uapi,
@@ -41,7 +40,7 @@ fn asix_soft_reset(dev: &mut phy::Device) -> Result {#[vtable] impl Driver for PhyAX88772A {const FLAGS :u32 = phy::flags::IS_INTERNAL ; -const NAME : &'staticCStr =c_str! ("Asix Electronics AX88772A" ); +const NAME : &'staticCStr =c"Asix Electronics AX88772A" ;const PHY_DEVICE_ID :DeviceId =DeviceId ::new_with_exact_mask (0x003b1861 );// AX88772A is not working properly with some old switches (NETGEAR EN 108TP):
@@ -105,7 +104,7 @@ fn link_change_notify(dev: &mut phy::Device) {#[vtable] impl Driver for PhyAX88772C {const FLAGS :u32 = phy::flags::IS_INTERNAL ; -const NAME : &'staticCStr =c_str! ("Asix Electronics AX88772C" ); +const NAME : &'staticCStr =c"Asix Electronics AX88772C" ;const PHY_DEVICE_ID :DeviceId =DeviceId ::new_with_exact_mask (0x003b1881 );fn suspend (dev: &mut phy::Device ) ->Result {
@@ -125,7 +124,7 @@ fn soft_reset(dev: &mut phy::Device) -> Result {#[vtable] impl Driver for PhyAX88796B { -const NAME : &'staticCStr =c_str! ("Asix Electronics AX88796B" ); +const NAME : &'staticCStr =c"Asix Electronics AX88796B" ;const PHY_DEVICE_ID :DeviceId =DeviceId ::new_with_model_mask (0x003b1841 );fn soft_reset (dev: &mut phy::Device ) ->Result {
drivers/net/phy/qt2025.rs +2 -3
@@ -9,7 +9,6 @@//! //! The QT2025 PHY integrates an Intel 8051 micro-controller. -use kernel::c_str;use kernel::error::code;use kernel::firmware::Firmware ;use kernel::net::phy::{
@@ -36,7 +35,7 @@#[vtable] impl Driver for PhyQT2025 { -const NAME : &'staticCStr =c_str! ("QT2025 10Gpbs SFP+" ); +const NAME : &'staticCStr =c"QT2025 10Gpbs SFP+" ;const PHY_DEVICE_ID : phy::DeviceId = phy::DeviceId ::new_with_exact_mask (0x0043a400 );fn probe (dev: &mut phy::Device ) ->Result <()> {
@@ -69,7 +68,7 @@ fn probe(dev: &mut phy::Device) -> Result<()> {// The micro-controller will start running from the boot ROM. dev.write (C45 ::new (Mmd ::PCS ,0xe854 ),0x00c0 )?; -let fw =Firmware ::request (c_str! ("qt2025-2.0.3.3.fw" ), dev.as_ref ())?; +let fw =Firmware ::request (c"qt2025-2.0.3.3.fw" , dev.as_ref ())?;if fw.data ().len () >SZ_16K +SZ_8K {return Err (code::EFBIG ); }
rust/kernel/firmware.rs +2 -2
@@ -40,13 +40,13 @@ fn request_nowarn() -> Self {/// # Examples /// /// ```no_run -/// # use kernel::{c_str, device::Device, firmware::Firmware}; +/// # use kernel::{device::Device, firmware::Firmware}; /// /// # fn no_run() -> Result<(), Error> { /// # // SAFETY: *NOT* safe, just for the example to get an `ARef<Device>` instance /// # let dev = unsafe { Device::get_device(core::ptr::null_mut()) }; /// -/// let fw = Firmware::request(c_str!("path/to/firmware.bin"), &dev)?; +/// let fw = Firmware::request(c"path/to/firmware.bin", &dev)?; /// let blob = fw.data(); /// /// # Ok(())
rust/kernel/kunit.rs +4 -3
@@ -56,10 +56,11 @@ macro_rules! kunit_assert {break 'out; } -static NAME : &'static $crate::str::CStr = $crate::c_str!($name); -static FILE : &'static $crate::str::CStr = $crate::c_str!($file); +static NAME : &'static $crate::str::CStr = $crate::c_str_avoid_literals!($name); +static FILE : &'static $crate::str::CStr = $crate::c_str_avoid_literals!($file);static LINE :i32 = core::line!()as i32 - $diff; -static CONDITION : &'static $crate::str::CStr = $crate::c_str!(stringify! ($condition)); +static CONDITION : &'static $crate::str::CStr = + $crate::c_str_avoid_literals!(stringify! ($condition));// SAFETY: FFI call without safety requirements. let kunit_test =unsafe { $crate::bindings::kunit_get_current_test () };
rust/kernel/net/phy.rs +2 -4
@@ -780,7 +780,6 @@ const fn as_int(&self) -> u32 {/// /// ``` /// # mod module_phy_driver_sample { -/// use kernel::c_str; /// use kernel::net::phy::{self, DeviceId}; /// use kernel::prelude::*; ///
@@ -799,7 +798,7 @@ const fn as_int(&self) -> u32 {/// /// #[vtable] /// impl phy::Driver for PhySample { -/// const NAME: &'static CStr = c_str!("PhySample"); +/// const NAME: &'static CStr = c"PhySample"; /// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001); /// } /// # }
@@ -808,7 +807,6 @@ const fn as_int(&self) -> u32 {/// This expands to the following code: /// /// ```ignore -/// use kernel::c_str; /// use kernel::net::phy::{self, DeviceId}; /// use kernel::prelude::*; ///
@@ -828,7 +826,7 @@ const fn as_int(&self) -> u32 {/// /// #[vtable] /// impl phy::Driver for PhySample { -/// const NAME: &'static CStr = c_str!("PhySample"); +/// const NAME: &'static CStr = c"PhySample"; /// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001); /// } ///
rust/kernel/str.rs +24 -13
@@ -190,14 +190,13 @@ pub trait CStrExt {/// # Examples /// /// ``` -/// # use kernel::c_str; /// # use kernel::fmt; /// # use kernel::str::CString; -/// let penguin = c_str!("🐧"); +/// let penguin = c"🐧"; /// let s = CString::try_from_fmt(fmt!("{}", penguin.display()))?; /// assert_eq!(s.to_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes()); /// -/// let ascii = c_str!("so \"cool\""); +/// let ascii = c"so \"cool\""; /// let s = CString::try_from_fmt(fmt!("{}", ascii.display()))?; /// assert_eq!(s.to_bytes_with_nul(), "so \"cool\"\0".as_bytes()); /// # Ok::<(), kernel::error::Error>(())
@@ -250,25 +249,37 @@ pub const fn as_char_ptr(c_str: &CStr) -> *const crate::ffi::c_char { c_str.as_ptr ().cast () } -/// Creates a new [`CStr`] from a string literal. +/// Creates a static C string wrapper at compile time. /// -/// The string literal should not contain any `NUL` bytes. +/// Rust supports C string literals since Rust 1.77, and they should be used instead of this macro +/// where possible. This macro exists to allow static *non-literal* C strings to be created at +/// compile time. This is most often used in other macros. +/// +/// # Panics +/// +/// This macro panics if the operand contains an interior `NUL` byte. /// /// # Examples /// /// ``` -/// # use kernel::c_str; +/// # use kernel::c_str_avoid_literals; /// # use kernel::str::CStr; -/// const MY_CSTR: &CStr = c_str!("My awesome CStr!"); +/// const MY_CSTR: &CStr = c_str_avoid_literals!(concat!(file!(), ":", line!(), ": My CStr!")); /// ``` #[macro_export] -macro_rules! c_str { +macro_rules! c_str_avoid_literals { +// NB: we could write `($str:lit) => compile_error!("use a C string literal instead");` here but +// that would trigger when the literal is at the top of several macro expansions. That would be +// too limiting to macro authors, so we rely on the name as a hint instead. ($str:expr) => {{ -const S : &str =concat! ($str ,"\0" ); -const C : &$crate::str ::CStr =match $crate::str ::CStr ::from_bytes_with_nul (S .as_bytes ()) { -Ok (v) => v, -Err (_) =>panic! ("string contains interior NUL" ), - }; +const S : &'static str =concat! ($str ,"\0" ); +const C : &'static $crate::str ::CStr = +match $crate::str ::CStr ::from_bytes_with_nul (S .as_bytes ()) { +Ok (v) => v, +Err (core::ffi::FromBytesWithNulError { .. }) => { +panic! ("string contains interior NUL" ) + } + };C }}; }
rust/kernel/sync.rs +2 -2
@@ -61,9 +61,9 @@ macro_rules! static_lock_class {#[macro_export] macro_rules! optional_name { () => { - $crate::c_str!(::core::concat!(::core::file!(),":" , ::core::line!())) + $crate::c_str_avoid_literals!(::core::concat!(::core::file!(),":" , ::core::line!())) }; ($name:literal) => { - $crate::c_str!($name) + $crate::c_str_avoid_literals!($name) }; }
rust/kernel/sync/lock/global.rs +2 -1
@@ -266,7 +266,8 @@ macro_rules! global_lock { $pub enum $name {}impl $crate::sync::lock::GlobalLockBackend for $name { -const NAME : &'static $crate::str::CStr = $crate::c_str!(::core::stringify!($name)); +const NAME : &'static $crate::str::CStr = + $crate::c_str_avoid_literals!(::core::stringify!($name));type Item = $valuety;type Backend = $crate::global_lock_inner!(backend $kind);
Signature · 1 line
2.48.1
PATCH v6 4/4 rust: remove core::ffi::CStr reexport
In reply to Tamir DubersteinClean up references to kernel::str::CStr.
--- rust/kernel/error.rs | 6 ++---- rust/kernel/firmware.rs | 3 ++- rust/kernel/kunit.rs | 6 +++--- rust/kernel/miscdevice.rs | 3 +-- rust/kernel/prelude.rs | 5 +---- rust/kernel/str.rs | 19 +++++++++---------- rust/kernel/sync/condvar.rs | 2 +- rust/kernel/sync/lock.rs | 3 +-- rust/kernel/sync/lock/global.rs | 4 ++-- rust/kernel/sync/poll.rs | 1 + rust/kernel/workqueue.rs | 1 + 11 files changed, 24 insertions(+), 29 deletions(-)
rust/kernel/error.rs +2 -4
@@ -4,11 +4,9 @@//! //! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h) -use crate ::{ - alloc::{layout::LayoutError ,AllocError }, - str::CStr , -}; +use crate ::alloc::{layout::LayoutError ,AllocError }; +use core::ffi::CStr ;use core::fmt;use core::num::NonZeroI32 ;use core::num::TryFromIntError ;
rust/kernel/firmware.rs +2 -1
@@ -4,7 +4,8 @@//! //! C header: [`include/linux/firmware.h`](srctree/include/linux/firmware.h) -use crate ::{bindings, device::Device , error::Error , error::Result , str::CStr }; +use crate ::{bindings, device::Device , error::Error , error::Result }; +use core::ffi::CStr ;use core::ptr::NonNull ;/// # Invariants
rust/kernel/kunit.rs +3 -3
@@ -56,10 +56,10 @@ macro_rules! kunit_assert {break 'out; } -static NAME : &'static $crate::str::CStr = $crate::c_str_avoid_literals!($name); -static FILE : &'static $crate::str::CStr = $crate::c_str_avoid_literals!($file); +static NAME : &'static core::ffi::CStr = $crate::c_str_avoid_literals!($name); +static FILE : &'static core::ffi::CStr = $crate::c_str_avoid_literals!($file);static LINE :i32 = core::line!()as i32 - $diff; -static CONDITION : &'static $crate::str::CStr = +static CONDITION : &'static core::ffi::CStr = $crate::c_str_avoid_literals!(stringify! ($condition));// SAFETY: FFI call without safety requirements.
rust/kernel/miscdevice.rs +1 -2
@@ -13,10 +13,9 @@ error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR}, ffi::{c_int, c_long, c_uint, c_ulong}, prelude::*, - str::CStr, types::{ForeignOwnable, Opaque}, }; -use core::{marker::PhantomData , mem::MaybeUninit , pin::Pin }; +use core::{ffi::CStr , marker::PhantomData , mem::MaybeUninit , pin::Pin };/// Options for creating a misc device. #[derive( Copy , Clone )]
rust/kernel/prelude.rs +1 -4
@@ -34,10 +34,7 @@pub use super ::error::{code::*,Error ,Result }; -pub use super ::{ - str::{CStr ,CStrExt as _}, -ThisModule , -}; +pub use super ::{str::CStrExt as _,ThisModule };pub use super ::init::{InPlaceInit ,InPlaceWrite ,Init ,PinInit };
rust/kernel/str.rs +9 -10
@@ -3,6 +3,7 @@//! String representations. use crate ::alloc::{flags::*,AllocError ,KVec }; +use core::ffi::CStr ;use core::fmt::{self,Write };use core::ops::{Deref ,DerefMut };
@@ -176,8 +177,6 @@ macro_rules! b_str { }}; } -pub use core::ffi::CStr ; -/// Extensions to [`CStr`]. pub trait CStrExt {/// Returns an object that implements [`Display`] for safely printing a [`CStr`] that may
@@ -263,7 +262,7 @@ pub const fn as_char_ptr(c_str: &CStr) -> *const crate::ffi::c_char {/// /// ``` /// # use kernel::c_str_avoid_literals; -/// # use kernel::str::CStr; +/// # use core::ffi::CStr; /// const MY_CSTR: &CStr = c_str_avoid_literals!(concat!(file!(), ":", line!(), ": My CStr!")); /// ``` #[macro_export]
@@ -273,13 +272,13 @@ macro_rules! c_str_avoid_literals {// too limiting to macro authors, so we rely on the name as a hint instead. ($str:expr) => {{const S : &'staticstr =concat! ($str ,"\0" ); -const C : &'static $crate::str::CStr = -match $crate::str::CStr ::from_bytes_with_nul (S .as_bytes ()) { -Ok (v) => v, -Err (core::ffi::FromBytesWithNulError { .. }) => { -panic! ("string contains interior NUL" ) - } - }; +const C : &'static core::ffi::CStr =match core::ffi::CStr ::from_bytes_with_nul (S .as_bytes ()) + { +Ok (v) => v, +Err (core::ffi::FromBytesWithNulError { .. }) => { +panic! ("string contains interior NUL" ) + } + };C }}; }
rust/kernel/sync/condvar.rs +1 -1
@@ -10,11 +10,11 @@ ffi::{c_int, c_long}, init::PinInit, pin_init, - str::CStr, task::{MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE, TASK_NORMAL, TASK_UNINTERRUPTIBLE}, time::Jiffies, types::Opaque, }; +use core::ffi::CStr ;use core::marker::PhantomPinned ;use core::ptr;use macros::pin_data;
rust/kernel/sync/lock.rs +1 -2
@@ -9,10 +9,9 @@use crate ::{ init::PinInit , pin_init, - str::CStr , types::{NotThreadSafe ,Opaque ,ScopeGuard }, }; -use core::{cell::UnsafeCell , marker::PhantomPinned }; +use core::{cell::UnsafeCell , ffi::CStr , marker::PhantomPinned };use macros::pin_data;pub mod mutex;
rust/kernel/sync/lock/global.rs +2 -2
@@ -5,13 +5,13 @@//! Support for defining statics containing locks. use crate ::{ - str::CStr , sync::lock::{Backend ,Guard ,Lock }, sync::{LockClassKey ,LockedBy }, types::Opaque , };use core::{ cell::UnsafeCell , + ffi::CStr , marker::{PhantomData ,PhantomPinned }, };
@@ -266,7 +266,7 @@ macro_rules! global_lock { $pub enum $name {}impl $crate::sync::lock::GlobalLockBackend for $name { -const NAME : &'static $crate::str::CStr = +const NAME : &'static core::ffi::CStr = $crate::c_str_avoid_literals!(::core::stringify!($name));type Item = $valuety;type Backend = $crate::global_lock_inner!(backend $kind);
rust/kernel/sync/poll.rs +1 -0
@@ -11,6 +11,7 @@ sync::{CondVar, LockClassKey}, types::Opaque, }; +use core::ffi::CStr ;use core::ops::Deref ;/// Creates a [`PollCondVar`] initialiser with the given name and a newly-created lock class.
rust/kernel/workqueue.rs +1 -0
@@ -135,6 +135,7 @@use crate ::alloc::{AllocError ,Flags };use crate ::{prelude::*, sync::Arc , sync::LockClassKey , types::Opaque }; +use core::ffi::CStr ;use core::marker::PhantomData ;/// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
Signature · 1 line
2.48.1
Re: [PATCH v6 2/4] rust: replace `CStr` with `core::ffi::CStr`
In reply to Tamir Dubersteinrust/kernel/str.rs fn deref(&self) -> &Self::Target { · line 611
Quoted 10 lines · Tamir Duberstein
impl DerefMut for CString { fn deref_mut(&mut self) -> &mut Self::Target {rust/kernel/str.rs +2
-3-// SAFETY: A `CString` is always NUL-terminated and contains no other -// NUL bytes. -unsafe {CStr ::from_bytes_with_nul_unchecked_mut (self.buf.as_mut_slice ()) } +// SAFETY: Properties of `bytes` guaranteed by the safety precondition. +unsafe { &mut *(self.buf.as_mut_slice ()as *mut [u8 ]as *mut CStr ) } } }
Whoops, this safety comment is nonsense. I'll use the one from impl Deref above in v7...or just remove this impl altogether. I'm not sure what the use for &mut CStr would be.
Re: [PATCH v6 3/4] rust: replace `kernel::c_str!` with C-Strings
In reply to Tamir DubersteinHi Tamir,
Quoted 6 lines · Tamir Duberstein
C-String literals were added in Rust 1.77. Replace instances of
kernel::c_str!with C-String literals where possible and renamekernel::c_str!toc_str_avoid_literalsto clarify its intended use.
Quoted 10 lines
--- drivers/net/phy/ax88796b_rust.rs | 7 +++---- drivers/net/phy/qt2025.rs | 5 ++--- rust/kernel/firmware.rs | 4 ++-- rust/kernel/kunit.rs | 7 ++++--- rust/kernel/net/phy.rs | 6 ++---- rust/kernel/str.rs | 37 ++++++++++++++++++++++++------------- rust/kernel/sync.rs | 4 ++-- rust/kernel/sync/lock/global.rs | 3 ++- 8 files changed, 41 insertions(+), 32 deletions(-)
Have you checked samples/rust/ [1] as well?
Best regards
Dirk
[1]
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/samples/rust
Quoted 246 lines
drivers/net/phy/ax88796b_rust.rs +3
-4@@ -5,7 +5,6 @@//! //! C version of this driver: [`drivers/net/phy/ax88796b.c`](./ax88796b.c) use kernel::{ - c_str, net::phy::{self, reg::C22 ,DeviceId ,Driver }, prelude::*, uapi,@@ -41,7 +40,7 @@ fn asix_soft_reset(dev: &mut phy::Device) -> Result {#[vtable] impl Driver for PhyAX88772A {const FLAGS :u32 = phy::flags::IS_INTERNAL ; -const NAME : &'staticCStr =c_str! ("Asix Electronics AX88772A" ); +const NAME : &'staticCStr =c"Asix Electronics AX88772A" ;const PHY_DEVICE_ID :DeviceId =DeviceId ::new_with_exact_mask (0x003b1861 );// AX88772A is not working properly with some old switches (NETGEAR EN 108TP): @@ -105,7 +104,7 @@ fn link_change_notify(dev: &mut phy::Device) {#[vtable] impl Driver for PhyAX88772C {const FLAGS :u32 = phy::flags::IS_INTERNAL ; -const NAME : &'staticCStr =c_str! ("Asix Electronics AX88772C" ); +const NAME : &'staticCStr =c"Asix Electronics AX88772C" ;const PHY_DEVICE_ID :DeviceId =DeviceId ::new_with_exact_mask (0x003b1881 );fn suspend (dev: &mut phy::Device ) ->Result {@@ -125,7 +124,7 @@ fn soft_reset(dev: &mut phy::Device) -> Result {#[vtable] impl Driver for PhyAX88796B { -const NAME : &'staticCStr =c_str! ("Asix Electronics AX88796B" ); +const NAME : &'staticCStr =c"Asix Electronics AX88796B" ;const PHY_DEVICE_ID :DeviceId =DeviceId ::new_with_model_mask (0x003b1841 );fn soft_reset (dev: &mut phy::Device ) ->Result {drivers/net/phy/qt2025.rs +2
-3@@ -9,7 +9,6 @@//! //! The QT2025 PHY integrates an Intel 8051 micro-controller. -use kernel::c_str;use kernel::error::code;use kernel::firmware::Firmware ;use kernel::net::phy::{@@ -36,7 +35,7 @@#[vtable] impl Driver for PhyQT2025 { -const NAME : &'staticCStr =c_str! ("QT2025 10Gpbs SFP+" ); +const NAME : &'staticCStr =c"QT2025 10Gpbs SFP+" ;const PHY_DEVICE_ID : phy::DeviceId = phy::DeviceId ::new_with_exact_mask (0x0043a400 );fn probe (dev: &mut phy::Device ) ->Result <()> {@@ -69,7 +68,7 @@ fn probe(dev: &mut phy::Device) -> Result<()> {// The micro-controller will start running from the boot ROM. dev.write (C45 ::new (Mmd ::PCS ,0xe854 ),0x00c0 )?; -let fw =Firmware ::request (c_str! ("qt2025-2.0.3.3.fw" ), dev.as_ref ())?; +let fw =Firmware ::request (c"qt2025-2.0.3.3.fw" , dev.as_ref ())?;if fw.data ().len () >SZ_16K +SZ_8K {return Err (code::EFBIG ); }rust/kernel/firmware.rs +2
-2@@ -40,13 +40,13 @@ fn request_nowarn() -> Self {/// # Examples /// /// ```no_run -/// # use kernel::{c_str, device::Device, firmware::Firmware}; +/// # use kernel::{device::Device, firmware::Firmware}; /// /// # fn no_run() -> Result<(), Error> { /// # // SAFETY: *NOT* safe, just for the example to get an `ARef<Device>` instance /// # let dev = unsafe { Device::get_device(core::ptr::null_mut()) }; /// -/// let fw = Firmware::request(c_str!("path/to/firmware.bin"), &dev)?; +/// let fw = Firmware::request(c"path/to/firmware.bin", &dev)?; /// let blob = fw.data(); /// /// # Ok(()) rust/kernel/kunit.rs +4
-3@@ -56,10 +56,11 @@ macro_rules! kunit_assert {break 'out; } -static NAME : &'static $crate::str::CStr = $crate::c_str!($name); -static FILE : &'static $crate::str::CStr = $crate::c_str!($file); +static NAME : &'static $crate::str::CStr = $crate::c_str_avoid_literals!($name); +static FILE : &'static $crate::str::CStr = $crate::c_str_avoid_literals!($file);static LINE :i32 = core::line!()as i32 - $diff; -static CONDITION : &'static $crate::str::CStr = $crate::c_str!(stringify! ($condition)); +static CONDITION : &'static $crate::str::CStr = + $crate::c_str_avoid_literals!(stringify! ($condition));// SAFETY: FFI call without safety requirements. let kunit_test =unsafe { $crate::bindings::kunit_get_current_test () };rust/kernel/net/phy.rs +2
-4@@ -780,7 +780,6 @@ const fn as_int(&self) -> u32 {/// /// ``` /// # mod module_phy_driver_sample { -/// use kernel::c_str; /// use kernel::net::phy::{self, DeviceId}; /// use kernel::prelude::*; /// @@ -799,7 +798,7 @@ const fn as_int(&self) -> u32 {/// /// #[vtable] /// impl phy::Driver for PhySample { -/// const NAME: &'static CStr = c_str!("PhySample"); +/// const NAME: &'static CStr = c"PhySample"; /// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001); /// } /// # } @@ -808,7 +807,6 @@ const fn as_int(&self) -> u32 {/// This expands to the following code: /// /// ```ignore -/// use kernel::c_str; /// use kernel::net::phy::{self, DeviceId}; /// use kernel::prelude::*; /// @@ -828,7 +826,7 @@ const fn as_int(&self) -> u32 {/// /// #[vtable] /// impl phy::Driver for PhySample { -/// const NAME: &'static CStr = c_str!("PhySample"); +/// const NAME: &'static CStr = c"PhySample"; /// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001); /// } /// rust/kernel/str.rs +24
-13@@ -190,14 +190,13 @@ pub trait CStrExt {/// # Examples /// /// ``` -/// # use kernel::c_str; /// # use kernel::fmt; /// # use kernel::str::CString; -/// let penguin = c_str!("🐧"); +/// let penguin = c"🐧"; /// let s = CString::try_from_fmt(fmt!("{}", penguin.display()))?; /// assert_eq!(s.to_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes()); /// -/// let ascii = c_str!("so \"cool\""); +/// let ascii = c"so \"cool\""; /// let s = CString::try_from_fmt(fmt!("{}", ascii.display()))?; /// assert_eq!(s.to_bytes_with_nul(), "so \"cool\"\0".as_bytes()); /// # Ok::<(), kernel::error::Error>(()) @@ -250,25 +249,37 @@ pub const fn as_char_ptr(c_str: &CStr) -> *const crate::ffi::c_char { c_str.as_ptr ().cast () } -/// Creates a new [`CStr`] from a string literal. +/// Creates a static C string wrapper at compile time. /// -/// The string literal should not contain any `NUL` bytes. +/// Rust supports C string literals since Rust 1.77, and they should be used instead of this macro +/// where possible. This macro exists to allow static *non-literal* C strings to be created at +/// compile time. This is most often used in other macros. +/// +/// # Panics +/// +/// This macro panics if the operand contains an interior `NUL` byte. /// /// # Examples /// /// ``` -/// # use kernel::c_str; +/// # use kernel::c_str_avoid_literals; /// # use kernel::str::CStr; -/// const MY_CSTR: &CStr = c_str!("My awesome CStr!"); +/// const MY_CSTR: &CStr = c_str_avoid_literals!(concat!(file!(), ":", line!(), ": My CStr!")); /// ``` #[macro_export] -macro_rules! c_str { +macro_rules! c_str_avoid_literals { +// NB: we could write `($str:lit) => compile_error!("use a C string literal instead");` here but +// that would trigger when the literal is at the top of several macro expansions. That would be +// too limiting to macro authors, so we rely on the name as a hint instead. ($str:expr) => {{ -const S : &str =concat! ($str ,"\0" ); -const C : &$crate::str ::CStr =match $crate::str ::CStr ::from_bytes_with_nul (S .as_bytes ()) { -Ok (v) => v, -Err (_) =>panic! ("string contains interior NUL" ), - }; +const S : &'static str =concat! ($str ,"\0" ); +const C : &'static $crate::str ::CStr = +match $crate::str ::CStr ::from_bytes_with_nul (S .as_bytes ()) { +Ok (v) => v, +Err (core::ffi::FromBytesWithNulError { .. }) => { +panic! ("string contains interior NUL" ) + } + };C }}; }rust/kernel/sync.rs +2
-2@@ -61,9 +61,9 @@ macro_rules! static_lock_class {#[macro_export] macro_rules! optional_name { () => { - $crate::c_str!(::core::concat!(::core::file!(),":" , ::core::line!())) + $crate::c_str_avoid_literals!(::core::concat!(::core::file!(),":" , ::core::line!())) }; ($name:literal) => { - $crate::c_str!($name) + $crate::c_str_avoid_literals!($name) }; }rust/kernel/sync/lock/global.rs +2
-1@@ -266,7 +266,8 @@ macro_rules! global_lock { $pub enum $name {}impl $crate::sync::lock::GlobalLockBackend for $name { -const NAME : &'static $crate::str::CStr = $crate::c_str!(::core::stringify!($name)); +const NAME : &'static $crate::str::CStr = + $crate::c_str_avoid_literals!(::core::stringify!($name));type Item = $valuety;type Backend = $crate::global_lock_inner!(backend $kind);
Re: [PATCH v6 3/4] rust: replace `kernel::c_str!` with C-Strings
Quoted 22 lines · Dirk Behme
Hi Tamir,
Quoted 6 lines · Tamir Duberstein
C-String literals were added in Rust 1.77. Replace instances of
kernel::c_str!with C-String literals where possible and renamekernel::c_str!toc_str_avoid_literalsto clarify its intended use.Quoted 10 lines
--- drivers/net/phy/ax88796b_rust.rs | 7 +++---- drivers/net/phy/qt2025.rs | 5 ++--- rust/kernel/firmware.rs | 4 ++-- rust/kernel/kunit.rs | 7 ++++--- rust/kernel/net/phy.rs | 6 ++---- rust/kernel/str.rs | 37 ++++++++++++++++++++++++------------- rust/kernel/sync.rs | 4 ++-- rust/kernel/sync/lock/global.rs | 3 ++- 8 files changed, 41 insertions(+), 32 deletions(-)
Quoted 5 lines
Have you checked
samples/rust/[1] as well?Best regards
Dirk
Hi Dirk, I had, but I was working on rust-next rather than on torvalds/master. I'll update the other samples in v7.
Re: [PATCH v6 2/4] rust: replace `CStr` with `core::ffi::CStr`
In reply to Tamir DubersteinQuoted 13 lines · Tamir Duberstein
rust/kernel/str.rs fn deref(&self) -> &Self::Target { · line 611
Quoted 10 lines · Tamir Duberstein
impl DerefMut for CString { fn deref_mut(&mut self) -> &mut Self::Target {rust/kernel/str.rs +2
-3-// SAFETY: A `CString` is always NUL-terminated and contains no other -// NUL bytes. -unsafe {CStr ::from_bytes_with_nul_unchecked_mut (self.buf.as_mut_slice ()) } +// SAFETY: Properties of `bytes` guaranteed by the safety precondition. +unsafe { &mut *(self.buf.as_mut_slice ()as *mut [u8 ]as *mut CStr ) } } }
Quoted 3 lines
Whoops, this safety comment is nonsense. I'll use the one from
impl Derefabove in v7...or just remove this impl altogether. I'm not sure what the use for&mut CStrwould be.
Ah, turns out Michal's patches removed functionality added in commit a321f3ad0a5d ("rust: str: add {make,to}_{upper,lower}case() to CString") which relied on this DerefMut impl. I've restored it all in v7.