transmuting_null: Check const integer casts (#16227)

Additionally removed the comment about MIR const propagation as it is
now outdated

changelog: [`transmuting_null`]: now checks const integers being casted
to pointers
This commit is contained in:
dswij
2025-12-18 15:43:05 +00:00
committed by GitHub
3 changed files with 17 additions and 8 deletions
@@ -1,6 +1,6 @@
use clippy_utils::consts::{ConstEvalCtxt, Constant};
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_integer_literal;
use clippy_utils::is_integer_const;
use clippy_utils::res::{MaybeDef, MaybeResPath};
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
@@ -27,7 +27,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arg: &'t
// Catching:
// `std::mem::transmute(0 as *const i32)`
if let ExprKind::Cast(inner_expr, _cast_ty) = arg.kind
&& is_integer_literal(inner_expr, 0)
&& is_integer_const(cx, inner_expr, 0)
{
span_lint(cx, TRANSMUTING_NULL, expr.span, LINT_MSG);
return true;
@@ -42,10 +42,5 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arg: &'t
return true;
}
// FIXME:
// Also catch transmutations of variables which are known nulls.
// To do this, MIR const propagation seems to be the better tool.
// Whenever MIR const prop routines are more developed, this will
// become available. As of this writing (25/03/19) it is not yet.
false
}
+8
View File
@@ -30,7 +30,15 @@ fn transmute_const() {
}
}
fn transmute_const_int() {
unsafe {
let _: &u64 = std::mem::transmute(u64::MIN as *const u64);
//~^ transmuting_null
}
}
fn main() {
one_liners();
transmute_const();
transmute_const_int();
}
+7 -1
View File
@@ -19,5 +19,11 @@ error: transmuting a known null pointer into a reference
LL | let _: &u64 = std::mem::transmute(ZPTR);
| ^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to 3 previous errors
error: transmuting a known null pointer into a reference
--> tests/ui/transmuting_null.rs:35:23
|
LL | let _: &u64 = std::mem::transmute(u64::MIN as *const u64);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to 4 previous errors