Skip to content

Commit 3505691

Browse files
committed
rust: macros: Fix macro referencing core and kernel crates v2
Update macros to always use absolute paths for crates `core` and `kernel`. This guarantees that macros will not pick up user-defined crates `core` or `kernel` by accident. Changes since v1: - Fixed paths in auto-generated code. Suggested-by: Benno Lossin <[email protected]> Closes: Rust-for-Linux#1150 Signed-off-by: Igor Korotin <[email protected]>
1 parent 28bb48c commit 3505691

11 files changed

+54
-50
lines changed

rust/ffi.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ macro_rules! alias {
1717

1818
// Check size compatibility with `core`.
1919
const _: () = assert!(
20-
core::mem::size_of::<$name>() == core::mem::size_of::<core::ffi::$name>()
20+
::core::mem::size_of::<$name>() == ::core::mem::size_of::<::core::ffi::$name>()
2121
);
2222
)*}
2323
}

rust/kernel/device.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ unsafe impl Sync for Device {}
214214
macro_rules! dev_printk {
215215
($method:ident, $dev:expr, $($f:tt)*) => {
216216
{
217-
($dev).$method(core::format_args!($($f)*));
217+
($dev).$method(::core::format_args!($($f)*));
218218
}
219219
}
220220
}

rust/kernel/device_id.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ macro_rules! module_device_table {
159159
"_", line!(),
160160
"_", stringify!($table_name))
161161
]
162-
static $module_table_name: [core::mem::MaybeUninit<u8>; $table_name.raw_ids().size()] =
163-
unsafe { core::mem::transmute_copy($table_name.raw_ids()) };
162+
static $module_table_name: [::core::mem::MaybeUninit<u8>; $table_name.raw_ids().size()] =
163+
unsafe { ::core::mem::transmute_copy($table_name.raw_ids()) };
164164
};
165165
}

rust/kernel/kunit.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ macro_rules! kunit_assert {
5959
}
6060

6161
static FILE: &'static $crate::str::CStr = $crate::c_str!($file);
62-
static LINE: i32 = core::line!() as i32 - $diff;
62+
static LINE: i32 = ::core::line!() as i32 - $diff;
6363
static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition));
6464

6565
// SAFETY: FFI call without safety requirements.
@@ -130,11 +130,11 @@ macro_rules! kunit_assert {
130130
unsafe {
131131
$crate::bindings::__kunit_do_failed_assertion(
132132
kunit_test,
133-
core::ptr::addr_of!(LOCATION.0),
133+
::core::ptr::addr_of!(LOCATION.0),
134134
$crate::bindings::kunit_assert_type_KUNIT_ASSERTION,
135-
core::ptr::addr_of!(ASSERTION.0.assert),
135+
::core::ptr::addr_of!(ASSERTION.0.assert),
136136
Some($crate::bindings::kunit_unary_assert_format),
137-
core::ptr::null(),
137+
::core::ptr::null(),
138138
);
139139
}
140140

rust/kernel/static_assert.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
///
1717
/// ```
1818
/// static_assert!(42 > 24);
19-
/// static_assert!(core::mem::size_of::<u8>() == 1);
19+
/// static_assert!(::core::mem::size_of::<u8>() == 1);
2020
///
2121
/// const X: &[u8] = b"bar";
2222
/// static_assert!(X[1] == b'a');
@@ -29,6 +29,6 @@
2929
#[macro_export]
3030
macro_rules! static_assert {
3131
($condition:expr) => {
32-
const _: () = core::assert!($condition);
32+
const _: () = ::core::assert!($condition);
3333
};
3434
}

rust/kernel/str.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ mod tests {
595595

596596
macro_rules! format {
597597
($($f:tt)*) => ({
598-
&*String::from_fmt(kernel::fmt!($($f)*))
598+
&*String::from_fmt(::kernel::fmt!($($f)*))
599599
})
600600
}
601601

@@ -944,5 +944,5 @@ impl fmt::Debug for CString {
944944
/// A convenience alias for [`core::format_args`].
945945
#[macro_export]
946946
macro_rules! fmt {
947-
($($f:tt)*) => ( core::format_args!($($f)*) )
947+
($($f:tt)*) => ( ::core::format_args!($($f)*) )
948948
}

rust/macros/kunit.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -88,29 +88,29 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
8888
// Looks like:
8989
//
9090
// ```
91-
// unsafe extern "C" fn kunit_rust_wrapper_foo(_test: *mut kernel::bindings::kunit) { foo(); }
92-
// unsafe extern "C" fn kunit_rust_wrapper_bar(_test: *mut kernel::bindings::kunit) { bar(); }
91+
// unsafe extern "C" fn kunit_rust_wrapper_foo(_test: *mut ::kernel::bindings::kunit) { foo(); }
92+
// unsafe extern "C" fn kunit_rust_wrapper_bar(_test: *mut ::kernel::bindings::kunit) { bar(); }
9393
//
94-
// static mut TEST_CASES: [kernel::bindings::kunit_case; 3] = [
95-
// kernel::kunit::kunit_case(kernel::c_str!("foo"), kunit_rust_wrapper_foo),
96-
// kernel::kunit::kunit_case(kernel::c_str!("bar"), kunit_rust_wrapper_bar),
97-
// kernel::kunit::kunit_case_null(),
94+
// static mut TEST_CASES: [::kernel::bindings::kunit_case; 3] = [
95+
// ::kernel::kunit::kunit_case(::kernel::c_str!("foo"), kunit_rust_wrapper_foo),
96+
// ::kernel::kunit::kunit_case(::kernel::c_str!("bar"), kunit_rust_wrapper_bar),
97+
// ::kernel::kunit::kunit_case_null(),
9898
// ];
9999
//
100-
// kernel::kunit_unsafe_test_suite!(kunit_test_suit_name, TEST_CASES);
100+
// ::kernel::kunit_unsafe_test_suite!(kunit_test_suit_name, TEST_CASES);
101101
// ```
102102
let mut kunit_macros = "".to_owned();
103103
let mut test_cases = "".to_owned();
104104
for test in &tests {
105105
let kunit_wrapper_fn_name = format!("kunit_rust_wrapper_{}", test);
106106
let kunit_wrapper = format!(
107-
"unsafe extern \"C\" fn {}(_test: *mut kernel::bindings::kunit) {{ {}(); }}",
107+
"unsafe extern \"C\" fn {}(_test: *mut ::kernel::bindings::kunit) {{ {}(); }}",
108108
kunit_wrapper_fn_name, test
109109
);
110110
writeln!(kunit_macros, "{kunit_wrapper}").unwrap();
111111
writeln!(
112112
test_cases,
113-
" kernel::kunit::kunit_case(kernel::c_str!(\"{}\"), {}),",
113+
" ::kernel::kunit::kunit_case(::kernel::c_str!(\"{}\"), {}),",
114114
test, kunit_wrapper_fn_name
115115
)
116116
.unwrap();
@@ -119,14 +119,14 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
119119
writeln!(kunit_macros).unwrap();
120120
writeln!(
121121
kunit_macros,
122-
"static mut TEST_CASES: [kernel::bindings::kunit_case; {}] = [\n{test_cases} kernel::kunit::kunit_case_null(),\n];",
122+
"static mut TEST_CASES: [::kernel::bindings::kunit_case; {}] = [\n{test_cases} ::kernel::kunit::kunit_case_null(),\n];",
123123
tests.len() + 1
124124
)
125125
.unwrap();
126126

127127
writeln!(
128128
kunit_macros,
129-
"kernel::kunit_unsafe_test_suite!({attr}, TEST_CASES);"
129+
"::kernel::kunit_unsafe_test_suite!({attr}, TEST_CASES);"
130130
)
131131
.unwrap();
132132

rust/macros/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream {
283283
/// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
284284
/// macro_rules! pub_no_prefix {
285285
/// ($prefix:ident, $($newname:ident),+) => {
286-
/// kernel::macros::paste! {
286+
/// ::kernel::macros::paste! {
287287
/// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
288288
/// }
289289
/// };
@@ -340,7 +340,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream {
340340
/// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
341341
/// macro_rules! pub_no_prefix {
342342
/// ($prefix:ident, $($newname:ident),+) => {
343-
/// kernel::macros::paste! {
343+
/// ::kernel::macros::paste! {
344344
/// $(pub(crate) const fn [<$newname:lower:span>]() -> u32 { [<$prefix $newname:span>] })+
345345
/// }
346346
/// };
@@ -375,7 +375,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream {
375375
/// ```
376376
/// macro_rules! create_numbered_fn {
377377
/// ($name:literal, $val:literal) => {
378-
/// kernel::macros::paste! {
378+
/// ::kernel::macros::paste! {
379379
/// fn [<some_ $name _fn $val>]() -> u32 { $val }
380380
/// }
381381
/// };

rust/macros/module.rs

+15-15
Original file line numberDiff line numberDiff line change
@@ -224,20 +224,20 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
224224
// SAFETY: `__this_module` is constructed by the kernel at load time and will not be
225225
// freed until the module is unloaded.
226226
#[cfg(MODULE)]
227-
static THIS_MODULE: kernel::ThisModule = unsafe {{
227+
static THIS_MODULE: ::kernel::ThisModule = unsafe {{
228228
extern \"C\" {{
229-
static __this_module: kernel::types::Opaque<kernel::bindings::module>;
229+
static __this_module: ::kernel::types::Opaque<::kernel::bindings::module>;
230230
}}
231231
232-
kernel::ThisModule::from_ptr(__this_module.get())
232+
::kernel::ThisModule::from_ptr(__this_module.get())
233233
}};
234234
#[cfg(not(MODULE))]
235-
static THIS_MODULE: kernel::ThisModule = unsafe {{
236-
kernel::ThisModule::from_ptr(core::ptr::null_mut())
235+
static THIS_MODULE: ::kernel::ThisModule = unsafe {{
236+
::kernel::ThisModule::from_ptr(::core::ptr::null_mut())
237237
}};
238238
239-
impl kernel::ModuleMetadata for {type_} {{
240-
const NAME: &'static kernel::str::CStr = kernel::c_str!(\"{name}\");
239+
impl ::kernel::ModuleMetadata for {type_} {{
240+
const NAME: &'static ::kernel::str::CStr = ::kernel::c_str!(\"{name}\");
241241
}}
242242
243243
// Double nested modules, since then nobody can access the public items inside.
@@ -255,8 +255,8 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
255255
#[used]
256256
static __IS_RUST_MODULE: () = ();
257257
258-
static mut __MOD: core::mem::MaybeUninit<{type_}> =
259-
core::mem::MaybeUninit::uninit();
258+
static mut __MOD: ::core::mem::MaybeUninit<{type_}> =
259+
::core::mem::MaybeUninit::uninit();
260260
261261
// Loadable modules need to export the `{{init,cleanup}}_module` identifiers.
262262
/// # Safety
@@ -267,7 +267,7 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
267267
#[doc(hidden)]
268268
#[no_mangle]
269269
#[link_section = \".init.text\"]
270-
pub unsafe extern \"C\" fn init_module() -> kernel::ffi::c_int {{
270+
pub unsafe extern \"C\" fn init_module() -> ::kernel::ffi::c_int {{
271271
// SAFETY: This function is inaccessible to the outside due to the double
272272
// module wrapping it. It is called exactly once by the C side via its
273273
// unique name.
@@ -306,11 +306,11 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
306306
#[doc(hidden)]
307307
#[link_section = \"{initcall_section}\"]
308308
#[used]
309-
pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init;
309+
pub static __{name}_initcall: extern \"C\" fn() -> ::kernel::ffi::c_int = __{name}_init;
310310
311311
#[cfg(not(MODULE))]
312312
#[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
313-
core::arch::global_asm!(
313+
::core::arch::global_asm!(
314314
r#\".section \"{initcall_section}\", \"a\"
315315
__{name}_initcall:
316316
.long __{name}_init - .
@@ -321,7 +321,7 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
321321
#[cfg(not(MODULE))]
322322
#[doc(hidden)]
323323
#[no_mangle]
324-
pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_int {{
324+
pub extern \"C\" fn __{name}_init() -> ::kernel::ffi::c_int {{
325325
// SAFETY: This function is inaccessible to the outside due to the double
326326
// module wrapping it. It is called exactly once by the C side via its
327327
// placement above in the initcall section.
@@ -344,9 +344,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
344344
/// # Safety
345345
///
346346
/// This function must only be called once.
347-
unsafe fn __init() -> kernel::ffi::c_int {{
347+
unsafe fn __init() -> ::kernel::ffi::c_int {{
348348
let initer =
349-
<{type_} as kernel::InPlaceModule>::init(&super::super::THIS_MODULE);
349+
<{type_} as ::kernel::InPlaceModule>::init(&super::super::THIS_MODULE);
350350
// SAFETY: No data race, since `__MOD` can only be accessed by this module
351351
// and there only `__init` and `__exit` access it. These functions are only
352352
// called once and `__exit` cannot be called before or during `__init`.

scripts/rustdoc_test_builder.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ fn main() {
2828
//
2929
// ```
3030
// fn main() { #[allow(non_snake_case)] fn _doctest_main_rust_kernel_file_rs_28_0() {
31-
// fn main() { #[allow(non_snake_case)] fn _doctest_main_rust_kernel_file_rs_37_0() -> Result<(), impl core::fmt::Debug> {
31+
// fn main() { #[allow(non_snake_case)] fn _doctest_main_rust_kernel_file_rs_37_0() -> Result<(), impl ::core::fmt::Debug> {
3232
// ```
3333
//
3434
// It should be unlikely that doctest code matches such lines (when code is formatted properly).
@@ -49,8 +49,8 @@ fn main() {
4949

5050
// Qualify `Result` to avoid the collision with our own `Result` coming from the prelude.
5151
let body = body.replace(
52-
&format!("{rustdoc_function_name}() -> Result<(), impl core::fmt::Debug> {{"),
53-
&format!("{rustdoc_function_name}() -> core::result::Result<(), impl core::fmt::Debug> {{"),
52+
&format!("{rustdoc_function_name}() -> Result<(), impl ::core::fmt::Debug> {{"),
53+
&format!("{rustdoc_function_name}() -> ::core::result::Result<(), impl ::core::fmt::Debug> {{"),
5454
);
5555

5656
// For tests that get generated with `Result`, like above, `rustdoc` generates an `unwrap()` on

scripts/rustdoc_test_gen.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -167,26 +167,30 @@ fn main() {
167167
rust_tests,
168168
r#"/// Generated `{name}` KUnit test case from a Rust documentation test.
169169
#[no_mangle]
170-
pub extern "C" fn {kunit_name}(__kunit_test: *mut kernel::bindings::kunit) {{
170+
pub extern "C" fn {kunit_name}(__kunit_test: *mut ::kernel::bindings::kunit) {{
171171
/// Overrides the usual [`assert!`] macro with one that calls KUnit instead.
172172
#[allow(unused)]
173173
macro_rules! assert {{
174174
($cond:expr $(,)?) => {{{{
175-
kernel::kunit_assert!("{kunit_name}", "{real_path}", __DOCTEST_ANCHOR - {line}, $cond);
175+
::kernel::kunit_assert!(
176+
"{kunit_name}", "{real_path}", __DOCTEST_ANCHOR - {line}, $cond
177+
);
176178
}}}}
177179
}}
178180
179181
/// Overrides the usual [`assert_eq!`] macro with one that calls KUnit instead.
180182
#[allow(unused)]
181183
macro_rules! assert_eq {{
182184
($left:expr, $right:expr $(,)?) => {{{{
183-
kernel::kunit_assert_eq!("{kunit_name}", "{real_path}", __DOCTEST_ANCHOR - {line}, $left, $right);
185+
::kernel::kunit_assert_eq!(
186+
"{kunit_name}", "{real_path}", __DOCTEST_ANCHOR - {line}, $left, $right
187+
);
184188
}}}}
185189
}}
186190
187191
// Many tests need the prelude, so provide it by default.
188192
#[allow(unused)]
189-
use kernel::prelude::*;
193+
use ::kernel::prelude::*;
190194
191195
// Unconditionally print the location of the original doctest (i.e. rather than the location in
192196
// the generated file) so that developers can easily map the test back to the source code.
@@ -197,11 +201,11 @@ pub extern "C" fn {kunit_name}(__kunit_test: *mut kernel::bindings::kunit) {{
197201
// This follows the syntax for declaring test metadata in the proposed KTAP v2 spec, which may
198202
// be used for the proposed KUnit test attributes API. Thus hopefully this will make migration
199203
// easier later on.
200-
kernel::kunit::info(format_args!(" # {kunit_name}.location: {real_path}:{line}\n"));
204+
::kernel::kunit::info(format_args!(" # {kunit_name}.location: {real_path}:{line}\n"));
201205
202206
/// The anchor where the test code body starts.
203207
#[allow(unused)]
204-
static __DOCTEST_ANCHOR: i32 = core::line!() as i32 + {body_offset} + 1;
208+
static __DOCTEST_ANCHOR: i32 = ::core::line!() as i32 + {body_offset} + 1;
205209
{{
206210
{body}
207211
main();

0 commit comments

Comments
 (0)