Skip to content

Commit 1550b13

Browse files
committed
rust: replace kernel::c_str! with C-Strings
C-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. Closes: Rust-for-Linux#1075 Signed-off-by: Tamir Duberstein <[email protected]>
1 parent 72f0910 commit 1550b13

File tree

14 files changed

+50
-42
lines changed

14 files changed

+50
-42
lines changed

drivers/net/phy/ax88796b_rust.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
//!
66
//! C version of this driver: [`drivers/net/phy/ax88796b.c`](./ax88796b.c)
77
use kernel::{
8-
c_str,
98
net::phy::{self, reg::C22, DeviceId, Driver},
109
prelude::*,
1110
uapi,
@@ -41,7 +40,7 @@ struct PhyAX88772A;
4140
#[vtable]
4241
impl Driver for PhyAX88772A {
4342
const FLAGS: u32 = phy::flags::IS_INTERNAL;
44-
const NAME: &'static CStr = c_str!("Asix Electronics AX88772A");
43+
const NAME: &'static CStr = c"Asix Electronics AX88772A";
4544
const PHY_DEVICE_ID: DeviceId = DeviceId::new_with_exact_mask(0x003b1861);
4645

4746
// AX88772A is not working properly with some old switches (NETGEAR EN 108TP):
@@ -105,7 +104,7 @@ struct PhyAX88772C;
105104
#[vtable]
106105
impl Driver for PhyAX88772C {
107106
const FLAGS: u32 = phy::flags::IS_INTERNAL;
108-
const NAME: &'static CStr = c_str!("Asix Electronics AX88772C");
107+
const NAME: &'static CStr = c"Asix Electronics AX88772C";
109108
const PHY_DEVICE_ID: DeviceId = DeviceId::new_with_exact_mask(0x003b1881);
110109

111110
fn suspend(dev: &mut phy::Device) -> Result {
@@ -125,7 +124,7 @@ struct PhyAX88796B;
125124

126125
#[vtable]
127126
impl Driver for PhyAX88796B {
128-
const NAME: &'static CStr = c_str!("Asix Electronics AX88796B");
127+
const NAME: &'static CStr = c"Asix Electronics AX88796B";
129128
const PHY_DEVICE_ID: DeviceId = DeviceId::new_with_model_mask(0x003b1841);
130129

131130
fn soft_reset(dev: &mut phy::Device) -> Result {

drivers/net/phy/qt2025.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
//!
1010
//! The QT2025 PHY integrates an Intel 8051 micro-controller.
1111
12-
use kernel::c_str;
1312
use kernel::error::code;
1413
use kernel::firmware::Firmware;
1514
use kernel::net::phy::{
@@ -36,7 +35,7 @@ struct PhyQT2025;
3635

3736
#[vtable]
3837
impl Driver for PhyQT2025 {
39-
const NAME: &'static CStr = c_str!("QT2025 10Gpbs SFP+");
38+
const NAME: &'static CStr = c"QT2025 10Gpbs SFP+";
4039
const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x0043a400);
4140

4241
fn probe(dev: &mut phy::Device) -> Result<()> {
@@ -69,7 +68,7 @@ impl Driver for PhyQT2025 {
6968
// The micro-controller will start running from the boot ROM.
7069
dev.write(C45::new(Mmd::PCS, 0xe854), 0x00c0)?;
7170

72-
let fw = Firmware::request(c_str!("qt2025-2.0.3.3.fw"), dev.as_ref())?;
71+
let fw = Firmware::request(c"qt2025-2.0.3.3.fw", dev.as_ref())?;
7372
if fw.data().len() > SZ_16K + SZ_8K {
7473
return Err(code::EFBIG);
7574
}

rust/kernel/devres.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ struct DevresInner<T> {
4545
/// # Example
4646
///
4747
/// ```no_run
48-
/// # use kernel::{bindings, c_str, device::Device, devres::Devres, io::{Io, IoRaw}};
48+
/// # use kernel::{bindings, device::Device, devres::Devres, io::{Io, IoRaw}};
4949
/// # use core::ops::Deref;
5050
///
5151
/// // See also [`pci::Bar`] for a real example.

rust/kernel/firmware.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,13 @@ impl FwFunc {
4040
/// # Examples
4141
///
4242
/// ```no_run
43-
/// # use kernel::{c_str, device::Device, firmware::Firmware};
43+
/// # use kernel::{device::Device, firmware::Firmware};
4444
///
4545
/// # fn no_run() -> Result<(), Error> {
4646
/// # // SAFETY: *NOT* safe, just for the example to get an `ARef<Device>` instance
4747
/// # let dev = unsafe { Device::get_device(core::ptr::null_mut()) };
4848
///
49-
/// let fw = Firmware::request(c_str!("path/to/firmware.bin"), &dev)?;
49+
/// let fw = Firmware::request(c"path/to/firmware.bin", &dev)?;
5050
/// let blob = fw.data();
5151
///
5252
/// # Ok(())

rust/kernel/kunit.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,11 @@ macro_rules! kunit_assert {
5656
break 'out;
5757
}
5858

59-
static NAME: &'static $crate::str::CStr = $crate::c_str!($name);
60-
static FILE: &'static $crate::str::CStr = $crate::c_str!($file);
59+
static NAME: &'static $crate::str::CStr = $crate::c_str_avoid_literals!($name);
60+
static FILE: &'static $crate::str::CStr = $crate::c_str_avoid_literals!($file);
6161
static LINE: i32 = core::line!() as i32 - $diff;
62-
static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition));
62+
static CONDITION: &'static $crate::str::CStr =
63+
$crate::c_str_avoid_literals!(stringify!($condition));
6364

6465
// SAFETY: FFI call without safety requirements.
6566
let kunit_test = unsafe { $crate::bindings::kunit_get_current_test() };

rust/kernel/net/phy.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -780,7 +780,6 @@ impl DeviceMask {
780780
///
781781
/// ```
782782
/// # mod module_phy_driver_sample {
783-
/// use kernel::c_str;
784783
/// use kernel::net::phy::{self, DeviceId};
785784
/// use kernel::prelude::*;
786785
///
@@ -799,7 +798,7 @@ impl DeviceMask {
799798
///
800799
/// #[vtable]
801800
/// impl phy::Driver for PhySample {
802-
/// const NAME: &'static CStr = c_str!("PhySample");
801+
/// const NAME: &'static CStr = c"PhySample";
803802
/// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001);
804803
/// }
805804
/// # }
@@ -808,7 +807,6 @@ impl DeviceMask {
808807
/// This expands to the following code:
809808
///
810809
/// ```ignore
811-
/// use kernel::c_str;
812810
/// use kernel::net::phy::{self, DeviceId};
813811
/// use kernel::prelude::*;
814812
///
@@ -828,7 +826,7 @@ impl DeviceMask {
828826
///
829827
/// #[vtable]
830828
/// impl phy::Driver for PhySample {
831-
/// const NAME: &'static CStr = c_str!("PhySample");
829+
/// const NAME: &'static CStr = c"PhySample";
832830
/// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001);
833831
/// }
834832
///

rust/kernel/platform.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ macro_rules! module_platform_driver {
120120
/// # Example
121121
///
122122
///```
123-
/// # use kernel::{bindings, c_str, of, platform};
123+
/// # use kernel::{bindings, of, platform};
124124
///
125125
/// struct MyDriver;
126126
///
@@ -129,7 +129,7 @@ macro_rules! module_platform_driver {
129129
/// MODULE_OF_TABLE,
130130
/// <MyDriver as platform::Driver>::IdInfo,
131131
/// [
132-
/// (of::DeviceId::new(c_str!("test,device")), ())
132+
/// (of::DeviceId::new(c"test,device"), ())
133133
/// ]
134134
/// );
135135
///

rust/kernel/str.rs

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -273,14 +273,13 @@ pub trait CStrExt {
273273
/// # Examples
274274
///
275275
/// ```
276-
/// # use kernel::c_str;
277276
/// # use kernel::fmt;
278277
/// # use kernel::str::CString;
279-
/// let penguin = c_str!("🐧");
278+
/// let penguin = c"🐧";
280279
/// let s = CString::try_from_fmt(fmt!("{}", penguin.display()))?;
281280
/// assert_eq!(s.to_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes());
282281
///
283-
/// let ascii = c_str!("so \"cool\"");
282+
/// let ascii = c"so \"cool\"";
284283
/// let s = CString::try_from_fmt(fmt!("{}", ascii.display()))?;
285284
/// assert_eq!(s.to_bytes_with_nul(), "so \"cool\"\0".as_bytes());
286285
/// # Ok::<(), kernel::error::Error>(())
@@ -368,25 +367,37 @@ impl AsRef<BStr> for CStr {
368367
}
369368
}
370369

371-
/// Creates a new [`CStr`] from a string literal.
370+
/// Creates a static C string wrapper at compile time.
372371
///
373-
/// The string literal should not contain any `NUL` bytes.
372+
/// Rust supports C string literals since Rust 1.77, and they should be used instead of this macro
373+
/// where possible. This macro exists to allow static *non-literal* C strings to be created at
374+
/// compile time. This is most often used in other macros.
375+
///
376+
/// # Panics
377+
///
378+
/// This macro panics if the operand contains an interior `NUL` byte.
374379
///
375380
/// # Examples
376381
///
377382
/// ```
378-
/// # use kernel::c_str;
383+
/// # use kernel::c_str_avoid_literals;
379384
/// # use kernel::str::CStr;
380-
/// const MY_CSTR: &CStr = c_str!("My awesome CStr!");
385+
/// const MY_CSTR: &CStr = c_str_avoid_literals!(concat!(file!(), ":", line!(), ": My CStr!"));
381386
/// ```
382387
#[macro_export]
383-
macro_rules! c_str {
388+
macro_rules! c_str_avoid_literals {
389+
// NB: we could write `($str:lit) => compile_error!("use a C string literal instead");` here but
390+
// that would trigger when the literal is at the top of several macro expansions. That would be
391+
// too limiting to macro authors, so we rely on the name as a hint instead.
384392
($str:expr) => {{
385-
const S: &str = concat!($str, "\0");
386-
const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
387-
Ok(v) => v,
388-
Err(_) => panic!("string contains interior NUL"),
389-
};
393+
const S: &'static str = concat!($str, "\0");
394+
const C: &'static $crate::str::CStr =
395+
match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
396+
Ok(v) => v,
397+
Err(core::ffi::FromBytesWithNulError { .. }) => {
398+
panic!("string contains interior NUL")
399+
}
400+
};
390401
C
391402
}};
392403
}

rust/kernel/sync.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,9 @@ macro_rules! static_lock_class {
6262
#[macro_export]
6363
macro_rules! optional_name {
6464
() => {
65-
$crate::c_str!(::core::concat!(::core::file!(), ":", ::core::line!()))
65+
$crate::c_str_avoid_literals!(::core::concat!(::core::file!(), ":", ::core::line!()))
6666
};
6767
($name:literal) => {
68-
$crate::c_str!($name)
68+
$crate::c_str_avoid_literals!($name)
6969
};
7070
}

rust/kernel/sync/lock/global.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,8 @@ macro_rules! global_lock {
266266
$pub enum $name {}
267267

268268
impl $crate::sync::lock::GlobalLockBackend for $name {
269-
const NAME: &'static $crate::str::CStr = $crate::c_str!(::core::stringify!($name));
269+
const NAME: &'static $crate::str::CStr =
270+
$crate::c_str_avoid_literals!(::core::stringify!($name));
270271
type Item = $valuety;
271272
type Backend = $crate::global_lock_inner!(backend $kind);
272273

rust/macros/module.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
229229
}};
230230
231231
impl kernel::ModuleMetadata for {type_} {{
232-
const NAME: &'static kernel::str::CStr = kernel::c_str!(\"{name}\");
232+
const NAME: &'static kernel::str::CStr = c\"{name}\";
233233
}}
234234
235235
// Double nested modules, since then nobody can access the public items inside.

samples/rust/rust_driver_pci.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
//!
55
//! To make this driver probe, QEMU must be run with `-device pci-testdev`.
66
7-
use kernel::{bindings, c_str, devres::Devres, pci, prelude::*};
7+
use kernel::{bindings, devres::Devres, pci, prelude::*};
88

99
struct Regs;
1010

@@ -73,7 +73,7 @@ impl pci::Driver for SampleDriver {
7373
pdev.enable_device_mem()?;
7474
pdev.set_master();
7575

76-
let bar = pdev.iomap_region_sized::<{ Regs::END }>(0, c_str!("rust_driver_pci"))?;
76+
let bar = pdev.iomap_region_sized::<{ Regs::END }>(0, c"rust_driver_pci")?;
7777

7878
let drvdata = KBox::new(
7979
Self {

samples/rust/rust_driver_platform.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
//! Rust Platform driver sample.
44
5-
use kernel::{c_str, of, platform, prelude::*};
5+
use kernel::{of, platform, prelude::*};
66

77
struct SampleDriver {
88
pdev: platform::Device,
@@ -14,7 +14,7 @@ kernel::of_device_table!(
1414
OF_TABLE,
1515
MODULE_OF_TABLE,
1616
<SampleDriver as platform::Driver>::IdInfo,
17-
[(of::DeviceId::new(c_str!("test,rust-device")), Info(42))]
17+
[(of::DeviceId::new(c"test,rust-device"), Info(42))]
1818
);
1919

2020
impl platform::Driver for SampleDriver {

samples/rust/rust_misc_device.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,6 @@
9797
use core::pin::Pin;
9898

9999
use kernel::{
100-
c_str,
101100
device::Device,
102101
fs::File,
103102
ioctl::{_IO, _IOC_SIZE, _IOR, _IOW},
@@ -132,7 +131,7 @@ impl kernel::InPlaceModule for RustMiscDeviceModule {
132131
pr_info!("Initialising Rust Misc Device Sample\n");
133132

134133
let options = MiscDeviceOptions {
135-
name: c_str!("rust-misc-device"),
134+
name: c"rust-misc-device",
136135
};
137136

138137
try_pin_init!(Self {

0 commit comments

Comments
 (0)