diff --git a/README.md b/README.md index c61cc66..8b1ecdb 100644 --- a/README.md +++ b/README.md @@ -54,3 +54,4 @@ If you want to check it out, you can opt into it with `-Dklint::atomic_context`. * [`build_error` checks](doc/build_error.md) * [Stack frame size check](doc/stack_size.md) * [Prelude check](doc/not_using_prelude.md) +* [Device logging](doc/prefer_device_logging.md) diff --git a/doc/prefer_device_logging.md b/doc/prefer_device_logging.md new file mode 100644 index 0000000..cd14eac --- /dev/null +++ b/doc/prefer_device_logging.md @@ -0,0 +1,35 @@ +# Device logging + +The `klint::prefer_device_logging` lint warns about kernel `pr_*` macros when a +shared device reference is in scope. Device logging includes information about +the device, which helps identify the source of a message on systems with more +than one device of the same kind. + +For example, instead of: + +```rust,ignore +fn probe(dev: &kernel::device::Device) { + kernel::pr_info!("starting device\n"); +} +``` + +prefer: + +```rust,ignore +fn probe(dev: &kernel::device::Device) { + kernel::dev_info!(dev, "starting device\n"); +} +``` + +The check recognizes the kernel's exported logging macros, including renamed +imports. It also recognizes shared references to types implementing +`AsRef>`, such as bus-specific device wrappers. +Lexical scopes and shadowing are respected. + +This lint is advisory: the presence of a device does not prove that a particular +message is about that device, so no automatic fix is offered. If generic logging +is intentional, allow the lint on the enclosing function or block. + +The initial implementation does not look for devices in fields, owned values, +mutable references, or declarations without initializers. It does not inspect +logging generated by other macros, `pr_cont!`, or the `pr_*_once!` macros. diff --git a/src/hir_lints/mod.rs b/src/hir_lints/mod.rs index f185189..c8559b0 100644 --- a/src/hir_lints/mod.rs +++ b/src/hir_lints/mod.rs @@ -1,2 +1,3 @@ pub(crate) mod c_str_literal; pub(crate) mod not_using_prelude; +pub(crate) mod prefer_device_logging; diff --git a/src/hir_lints/prefer_device_logging.rs b/src/hir_lints/prefer_device_logging.rs new file mode 100644 index 0000000..a3380c4 --- /dev/null +++ b/src/hir_lints/prefer_device_logging.rs @@ -0,0 +1,218 @@ +use rustc_data_structures::fx::FxHashSet; +use rustc_hir::def_id::{DefId, LOCAL_CRATE}; +use rustc_hir::{BinOpKind, Expr, ExprKind, HirId, Node, Pat, StmtKind}; +use rustc_infer::infer::TyCtxtInferExt; +use rustc_lint::{LateContext, LateLintPass, LintContext, declare_tool_lint, impl_lint_pass}; +use rustc_middle::middle::resolve::ModChild; +use rustc_middle::ty::{self, Ty}; +use rustc_span::{Ident, Span, Symbol, sym}; +use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; +use rustc_trait_selection::traits::{Obligation, ObligationCause}; + +declare_tool_lint! { + /// The `prefer_device_logging` lint detects kernel `pr_*` calls made with a device in scope. + pub klint::PREFER_DEVICE_LOGGING, + Warn, + "generic kernel logging used when a device is available" +} + +#[derive(Default)] +pub struct PreferDeviceLogging { + checked: FxHashSet, +} + +impl_lint_pass!(PreferDeviceLogging => [PREFER_DEVICE_LOGGING]); + +#[derive(Diagnostic)] +#[diag("`{$print}!` is used while a device reference is in scope")] +#[help("consider using `{$device_print}!` with `{$device}` to include device information")] +struct PreferDeviceLoggingLint { + print: Symbol, + device_print: &'static str, + device: Symbol, +} + +fn module_children<'tcx>(cx: &LateContext<'tcx>, module: DefId) -> &'tcx [ModChild] { + if let Some(local) = module.as_local() { + cx.tcx.module_children_local(local) + } else { + cx.tcx.module_children(module) + } +} + +/// Look up the actual kernel type, so unrelated types named `Device` do not trigger the lint. +fn kernel_device(cx: &LateContext<'_>) -> Option { + let krate = cx + .tcx + .crates(()) + .iter() + .copied() + .chain(std::iter::once(LOCAL_CRATE)) + .find(|&krate| cx.tcx.crate_name(krate) == crate::symbol::kernel)?; + let module = module_children(cx, krate.as_def_id()) + .iter() + .find(|child| child.ident.name.as_str() == "device")? + .res + .opt_def_id()?; + module_children(cx, module) + .iter() + .find(|child| child.ident.name.as_str() == "Device")? + .res + .opt_def_id() +} + +fn is_device_reference(cx: &LateContext<'_>, binding: HirId, device: DefId) -> bool { + let typeck = cx.tcx.typeck(binding.owner.def_id); + let ty = typeck.node_type(binding); + // Shared references remain available even if previously passed by value. Restrict the first + // version to these rather than suggesting an owned or mutable device that may have been moved. + let ty::Ref(_, _, rustc_hir::Mutability::Not) = ty.kind() else { + return false; + }; + let Some(as_ref) = cx.tcx.get_diagnostic_item(sym::AsRef) else { + return false; + }; + let infcx = cx.tcx.infer_ctxt().build(cx.typing_mode()); + let args = infcx.fresh_args_for_item(cx.tcx.hir_span(binding), device); + let device_ty = Ty::new_adt(cx.tcx, cx.tcx.adt_def(device), args); + let obligation = Obligation::new( + cx.tcx, + ObligationCause::dummy(), + cx.param_env, + ty::TraitRef::new(cx.tcx, as_ref, [ty, device_ty]), + ); + infcx.predicate_must_hold_modulo_regions(&obligation) +} + +fn add_bindings(pat: &Pat<'_>, bindings: &mut Vec<(HirId, Ident)>) { + pat.each_binding(|_, id, _, ident| { + if !ident.span.from_expansion() { + bindings.push((id, ident)); + } + }); +} + +fn condition_bindings(expr: &Expr<'_>, bindings: &mut Vec<(HirId, Ident)>) { + match expr.kind { + ExprKind::Let(let_expr) => add_bindings(let_expr.pat, bindings), + ExprKind::Binary(op, left, right) if op.node == BinOpKind::And => { + condition_bindings(right, bindings); + condition_bindings(left, bindings); + } + _ => (), + } +} + +/// Walk outwards, visiting inner declarations first so shadowed device references are ignored. +fn device_in_scope(cx: &LateContext<'_>, expr: &Expr<'_>, device: DefId) -> Option { + let mut bindings = Vec::new(); + let mut uninitialized = FxHashSet::default(); + let mut child = expr.hir_id; + for (id, node) in cx.tcx.hir_parent_iter(expr.hir_id) { + match node { + Node::Block(block) => { + let preceding = block + .stmts + .iter() + .take_while(|stmt| stmt.hir_id != child) + .collect::>(); + for stmt in preceding.into_iter().rev() { + if let StmtKind::Let(local) = stmt.kind { + add_bindings(local.pat, &mut bindings); + if local.init.is_none() { + local.pat.each_binding(|_, id, _, _| { + uninitialized.insert(id); + }); + } + } + } + } + Node::Arm(arm) => add_bindings(arm.pat, &mut bindings), + Node::Expr(parent) => match parent.kind { + ExprKind::If(cond, then, _) if then.hir_id == child => { + condition_bindings(cond, &mut bindings); + } + ExprKind::Binary(op, left, right) + if op.node == BinOpKind::And && right.hir_id == child => + { + condition_bindings(left, &mut bindings); + } + ExprKind::Closure(closure) => { + for param in cx.tcx.hir_body(closure.body).params { + add_bindings(param.pat, &mut bindings); + } + } + _ => (), + }, + Node::Item(_) | Node::ImplItem(_) | Node::TraitItem(_) => { + if let Some(body) = cx.tcx.hir_maybe_body_owned_by(id.owner.def_id) { + for param in body.params { + add_bindings(param.pat, &mut bindings); + } + } + // Nested functions cannot capture their enclosing function's locals. + break; + } + _ => (), + } + child = id; + } + + let mut seen = FxHashSet::default(); + bindings.into_iter().find_map(|(id, ident)| { + (seen.insert(ident.name) + && !uninitialized.contains(&id) + && is_device_reference(cx, id, device)) + .then_some(ident.name) + }) +} + +impl<'tcx> LateLintPass<'tcx> for PreferDeviceLogging { + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { + for expansion in expr.span.macro_backtrace() { + let Some(def_id) = expansion.macro_def_id else { + continue; + }; + if cx.tcx.crate_name(def_id.krate) != crate::symbol::kernel { + continue; + } + let print = cx.tcx.item_name(def_id); + let device_print = match print.as_str() { + "pr_emerg" => "dev_emerg", + "pr_alert" => "dev_alert", + "pr_crit" => "dev_crit", + "pr_err" => "dev_err", + "pr_warn" => "dev_warn", + "pr_notice" => "dev_notice", + "pr_info" => "dev_info", + "pr_debug" => "dev_dbg", + _ => continue, + }; + if !module_children(cx, def_id.krate.as_def_id()) + .iter() + .any(|child| child.ident.name == print && child.res.opt_def_id() == Some(def_id)) + { + continue; + } + // Only diagnose directly written invocations, not logging inside another macro. + let span = expansion.call_site; + if span.from_expansion() || !self.checked.insert(span) { + return; + } + if let Some(device_type) = kernel_device(cx) + && let Some(device) = device_in_scope(cx, expr, device_type) + { + cx.emit_span_lint( + PREFER_DEVICE_LOGGING, + span, + PreferDeviceLoggingLint { + print, + device_print, + device, + }, + ); + } + return; + } + } +} diff --git a/src/main.rs b/src/main.rs index 5a86f2a..3cc739a 100755 --- a/src/main.rs +++ b/src/main.rs @@ -117,6 +117,7 @@ impl Callbacks for MyCallbacks { binary_analysis::stack_size::STACK_FRAME_TOO_LARGE, hir_lints::c_str_literal::C_STR_LITERAL, hir_lints::not_using_prelude::NOT_USING_PRELUDE, + hir_lints::prefer_device_logging::PREFER_DEVICE_LOGGING, ]); lint_store.register_late_lint_pass(Box::new(|tcx| { @@ -131,6 +132,10 @@ impl Callbacks for MyCallbacks { }) })); + lint_store.register_late_lint_pass(Box::new(|_| { + Box::new(hir_lints::prefer_device_logging::PreferDeviceLogging::default()) + })); + // lint_store // .register_late_lint_pass(Box::new(|_| Box::new(infallible_allocation::InfallibleAllocation))); lint_store.register_late_lint_pass(Box::new(|tcx| { diff --git a/tests/ui/auxiliary/kernel.rs b/tests/ui/auxiliary/kernel.rs new file mode 100644 index 0000000..94bc2fa --- /dev/null +++ b/tests/ui/auxiliary/kernel.rs @@ -0,0 +1,43 @@ +// no-prefer-dynamic +// compile-flags: --emit=link + +pub mod device { + pub struct Device(pub C); + + impl AsRef> for Device { + fn as_ref(&self) -> &Self { + self + } + } +} + +pub struct PciDevice(pub device::Device); + +impl AsRef for PciDevice { + fn as_ref(&self) -> &device::Device { + &self.0 + } +} + +#[macro_export] +macro_rules! pr_info { + ($($arg:tt)*) => {{ + let _ = ::core::format_args!($($arg)*); + let _ = 0; + }}; +} + +#[macro_export] +macro_rules! pr_err { + ($($arg:tt)*) => {{ let _ = ::core::format_args!($($arg)*); }}; +} + +#[macro_export] +macro_rules! pr_debug { + ($($arg:tt)*) => {{ let _ = ::core::format_args!($($arg)*); }}; +} + +#[macro_export] +macro_rules! pr_cont { + ($($arg:tt)*) => {{ let _ = ::core::format_args!($($arg)*); }}; +} diff --git a/tests/ui/prefer_device_logging.rs b/tests/ui/prefer_device_logging.rs new file mode 100644 index 0000000..f1baeef --- /dev/null +++ b/tests/ui/prefer_device_logging.rs @@ -0,0 +1,137 @@ +// aux-build: kernel.rs +// compile-flags: --extern kernel +#![deny(klint::prefer_device_logging)] +#![allow(unused_variables, dead_code)] +#![deny(unfulfilled_lint_expectations)] + +use kernel::device::Device; +use kernel::{pr_debug, pr_err, pr_info}; + +fn parameter(dev: &Device) { + pr_info!("probe {}\n", 1); + pr_err!("failure\n"); + pr_debug!("debug\n"); +} + +fn wrapper(dev: &kernel::PciDevice) { + pr_info!("wrapper\n"); +} + +fn generic_context(dev: &Device) { + pr_info!("generic context\n"); +} + +fn generic_wrapper>(dev: &T) { + pr_info!("generic wrapper\n"); +} + +fn local() { + let backing = Device(()); + pr_info!("no reference yet\n"); // No warning for the owned value. + let dev = &backing; + pr_info!("local\n"); + let dev = 123; + pr_info!("shadowed\n"); // No warning for the shadowed reference. +} + +fn scopes() { + let backing = Device(()); + { + let dev = &backing; + pr_info!("inner\n"); + } + pr_info!("out of scope\n"); + let dev = &backing; + fn nested() { + pr_info!("cannot capture dev\n"); + } + pr_info!("outer\n"); +} + +fn patterns(value: Option<&Device>) { + match value { + Some(dev) => pr_info!("match\n"), + None => pr_info!("no device\n"), + } + if let Some(dev) = value { + pr_info!("if let\n"); + } else { + pr_info!("else\n"); + } + while let Some(dev) = value { + pr_info!("while let\n"); + break; + } +} + +#[allow(klint::prefer_device_logging)] +fn suppressed(dev: &Device) { + pr_info!("allowed\n"); +} + +#[expect(klint::prefer_device_logging)] +fn expected(dev: &Device) { + pr_info!("expected\n"); +} + +fn alias(device: &Device) { + use kernel::pr_info as info; + info!("renamed macro\n"); +} + +macro_rules! wrapper_macro { + () => { kernel::pr_info!("generated\n") }; +} + +fn generated(dev: &Device) { + wrapper_macro!(); // Leave logging inside another macro alone. + kernel::pr_cont!("continued\n"); // No direct dev_* equivalent. +} + +fn unrelated(dev: &u32) { + pr_info!("not a device\n"); +} + +fn unrelated_macro(dev: &Device) { + macro_rules! pr_info { + ($($arg:tt)*) => { let _ = ::core::format_args!($($arg)*); }; + } + pr_info!("unrelated macro\n"); +} + +fn initializer(dev: &Device) { + let dev = { pr_info!("old binding still visible\n"); 1 }; + pr_info!("new binding is not a device\n"); +} + +fn closures(dev: &Device) { + let _ = || pr_info!("outer device can be captured\n"); + let _ = |dev: u32| pr_info!("closure shadows outer device\n"); + let _ = |device: &Device| pr_info!("closure argument\n"); +} + +fn let_chain(value: Option<&Device>) { + if let Some(dev) = value && { pr_info!("condition\n"); true } { + pr_info!("then branch\n"); + } else { + pr_info!("else branch\n"); + } +} + +fn non_reference(mut dev: Device) { + pr_info!("owned device\n"); + let raw = &raw const dev; + pr_info!("raw device pointer\n"); + let dev = &mut dev; + pr_info!("mutable reference may have been moved\n"); +} + +fn uninitialized() { + let dev: &Device; + pr_info!("not initialized\n"); +} + +fn not_declared_yet(backing: Device) { + pr_info!("not declared yet\n"); + let dev = &backing; +} diff --git a/tests/ui/prefer_device_logging.stderr b/tests/ui/prefer_device_logging.stderr new file mode 100644 index 0000000..bd41958 --- /dev/null +++ b/tests/ui/prefer_device_logging.stderr @@ -0,0 +1,151 @@ +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:11:5 + | +11 | pr_info!("probe {}/n", 1); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information +note: the lint level is defined here + --> $DIR/prefer_device_logging.rs:3:9 + | + 3 | #![deny(klint::prefer_device_logging)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: `pr_err!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:12:5 + | +12 | pr_err!("failure/n"); + | ^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_err!` with `dev` to include device information + +error: `pr_debug!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:13:5 + | +13 | pr_debug!("debug/n"); + | ^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_dbg!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:17:5 + | +17 | pr_info!("wrapper/n"); + | ^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:21:5 + | +21 | pr_info!("generic context/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:25:5 + | +25 | pr_info!("generic wrapper/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:32:5 + | +32 | pr_info!("local/n"); + | ^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:41:9 + | +41 | pr_info!("inner/n"); + | ^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:48:5 + | +48 | pr_info!("outer/n"); + | ^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:53:22 + | +53 | Some(dev) => pr_info!("match/n"), + | ^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:57:9 + | +57 | pr_info!("if let/n"); + | ^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:62:9 + | +62 | pr_info!("while let/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:79:5 + | +79 | info!("renamed macro/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `device` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:103:17 + | +103 | let dev = { pr_info!("old binding still visible/n"); 1 }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:108:16 + | +108 | let _ = || pr_info!("outer device can be captured/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:110:31 + | +110 | let _ = |device: &Device| pr_info!("closure argument/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `device` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:114:35 + | +114 | if let Some(dev) = value && { pr_info!("condition/n"); true } { + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging.rs:115:9 + | +115 | pr_info!("then branch/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information + +error: aborting due to 18 previous errors + diff --git a/tests/ui/prefer_device_logging_local.rs b/tests/ui/prefer_device_logging_local.rs new file mode 100644 index 0000000..12d2f73 --- /dev/null +++ b/tests/ui/prefer_device_logging_local.rs @@ -0,0 +1,22 @@ +// compile-flags: --crate-name kernel +#![deny(klint::prefer_device_logging)] +#![allow(unused_variables)] + +pub mod device { + pub struct Device; + + impl AsRef for Device { + fn as_ref(&self) -> &Self { + self + } + } +} + +#[macro_export] +macro_rules! pr_info { + ($($arg:tt)*) => {{ let _ = ::core::format_args!($($arg)*); }}; +} + +pub fn probe(dev: &device::Device) { + pr_info!("local kernel crate\n"); +} diff --git a/tests/ui/prefer_device_logging_local.stderr b/tests/ui/prefer_device_logging_local.stderr new file mode 100644 index 0000000..cb7b1f1 --- /dev/null +++ b/tests/ui/prefer_device_logging_local.stderr @@ -0,0 +1,15 @@ +error: `pr_info!` is used while a device reference is in scope + --> $DIR/prefer_device_logging_local.rs:21:5 + | +21 | pr_info!("local kernel crate/n"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using `dev_info!` with `dev` to include device information +note: the lint level is defined here + --> $DIR/prefer_device_logging_local.rs:2:9 + | + 2 | #![deny(klint::prefer_device_logging)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error +