Skip to content

Commit 7bfd952

Browse files
committed
Auto merge of #119220 - Urgau:uplift-invalid_null_ptr_usage, r=fee1-dead
Uplift `clippy::invalid_null_ptr_usage` lint as `invalid_null_arguments` This PR aims at uplifting the `clippy::invalid_null_ptr_usage` lint into rustc, this is similar to the [`clippy::invalid_utf8_in_unchecked` uplift](#111543) a few months ago, in the sense that those two lints lint on invalid parameter(s), here a null pointer where it is unexpected and UB to pass one. *For context: GitHub Search reveals that just for `slice::from_raw_parts{_mut}` [~20 invalid usages](hhttps://github.com/search?q=lang%3Arust+%2Fslice%3A%3Afrom_raw_parts%28_mut%29%3F%5C%28ptr%3A%3Anull%2F+NOT+path%3A%2F%5Eclippy_lints%5C%2Fsrc%5C%2F%2F+NOT+path%3A%2F%5Erust%5C%2Fsrc%5C%2Ftools%5C%2Fclippy%5C%2Fclippy_lints%5C%2Fsrc%5C%2F%2F+NOT+path%3A%2F%5Esrc%5C%2Ftools%5C%2Fclippy%5C%2Fclippy_lints%5C%2Fsrc%5C%2F%2F&type=code) with `ptr::null` and an additional [4 invalid usages](https://github.com/search?q=lang%3Arust+%2Fslice%3A%3Afrom_raw_parts%5C%280%28%5C%29%7C+as%29%2F+NOT+path%3A%2F%5Eclippy_lints%5C%2Fsrc%5C%2F%2F+NOT+path%3A%2F%5Erust%5C%2Fsrc%5C%2Ftools%5C%2Fclippy%5C%2Fclippy_lints%5C%2Fsrc%5C%2F%2F+NOT+path%3A%2F%5Esrc%5C%2Ftools%5C%2Fclippy%5C%2Fclippy_lints%5C%2Fsrc%5C%2F%2F+NOT+path%3A%2F%5Eutils%5C%2Ftinystr%5C%2Fsrc%5C%2F%2F+NOT+path%3A%2F%5Eutils%5C%2Fzerovec%5C%2Fsrc%5C%2F%2F+NOT+path%3A%2F%5Eprovider%5C%2Fcore%5C%2Fsrc%5C%2F%2F&type=code) with `0 as *const ...`-ish casts.* ----- ## `invalid_null_arguments` (deny-by-default) The `invalid_null_arguments` lint checks for invalid usage of null pointers. ### Example ```rust // Undefined behavior unsafe { std::slice::from_raw_parts(ptr::null(), 1); } ``` Produces: ``` error: calling this function with a null pointer is Undefined Behavior, even if the result of the function is unused --> $DIR/invalid_null_args.rs:21:23 | LL | let _: &[usize] = std::slice::from_raw_parts(ptr::null_mut(), 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------^^^^ | | | null pointer originates from here | = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> ``` ### Explanation Calling methods whose safety invariants requires non-null pointer with a null pointer is undefined behavior. ----- The lint use a list of functions to know which functions and arguments to checks, this could be improved in the future with a rustc attribute, or maybe even with a `#[diagnostic]` attribute. This PR also includes some small refactoring to avoid some ambiguities in naming, those can be done in another PR is desired. `@rustbot` label: +I-lang-nominated r? compiler
2 parents 3c0f722 + aa88480 commit 7bfd952

30 files changed

+713
-719
lines changed

compiler/rustc_lint/messages.ftl

+13-9
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,10 @@ lint_invalid_nan_comparisons_eq_ne = incorrect NaN comparison, NaN cannot be dir
456456
457457
lint_invalid_nan_comparisons_lt_le_gt_ge = incorrect NaN comparison, NaN is not orderable
458458
459+
lint_invalid_null_arguments = calling this function with a null pointer is undefined behavior, even if the result of the function is unused
460+
.origin = null pointer originates from here
461+
.doc = for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html>
462+
459463
lint_invalid_reference_casting_assign_to_ref = assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
460464
.label = casting happened here
461465
@@ -680,15 +684,6 @@ lint_private_extern_crate_reexport = extern crate `{$ident}` is private and cann
680684
lint_proc_macro_derive_resolution_fallback = cannot find {$ns} `{$ident}` in this scope
681685
.label = names from parent modules are not accessible without an explicit import
682686
683-
lint_ptr_null_checks_fn_ptr = function pointers are not nullable, so checking them for null will always return false
684-
.help = wrap the function pointer inside an `Option` and use `Option::is_none` to check for null pointer value
685-
.label = expression has type `{$orig_ty}`
686-
687-
lint_ptr_null_checks_fn_ret = returned pointer of `{$fn_name}` call is never null, so checking it for null will always return false
688-
689-
lint_ptr_null_checks_ref = references are not nullable, so checking them for null will always return false
690-
.label = expression has type `{$orig_ty}`
691-
692687
lint_query_instability = using `{$query}` can result in unstable query results
693688
.note = if you believe this case to be fine, allow this lint and add a comment explaining your rationale
694689
@@ -981,6 +976,15 @@ lint_unused_result = unused result of type `{$ty}`
981976
982977
lint_use_let_underscore_ignore_suggestion = use `let _ = ...` to ignore the expression or result
983978
979+
lint_useless_ptr_null_checks_fn_ptr = function pointers are not nullable, so checking them for null will always return false
980+
.help = wrap the function pointer inside an `Option` and use `Option::is_none` to check for null pointer value
981+
.label = expression has type `{$orig_ty}`
982+
983+
lint_useless_ptr_null_checks_fn_ret = returned pointer of `{$fn_name}` call is never null, so checking it for null will always return false
984+
985+
lint_useless_ptr_null_checks_ref = references are not nullable, so checking them for null will always return false
986+
.label = expression has type `{$orig_ty}`
987+
984988
lint_uses_power_alignment = repr(C) does not follow the power alignment rule. This may affect platform C ABI compatibility for this type
985989
986990
lint_variant_size_differences =

compiler/rustc_lint/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ mod types;
8080
mod unit_bindings;
8181
mod unqualified_local_imports;
8282
mod unused;
83+
mod utils;
8384

8485
use async_closures::AsyncClosureUsage;
8586
use async_fn_in_trait::AsyncFnInTrait;

compiler/rustc_lint/src/lints.rs

+21-5
Original file line numberDiff line numberDiff line change
@@ -591,24 +591,40 @@ pub(crate) struct ExpectationNote {
591591

592592
// ptr_nulls.rs
593593
#[derive(LintDiagnostic)]
594-
pub(crate) enum PtrNullChecksDiag<'a> {
595-
#[diag(lint_ptr_null_checks_fn_ptr)]
596-
#[help(lint_help)]
594+
pub(crate) enum UselessPtrNullChecksDiag<'a> {
595+
#[diag(lint_useless_ptr_null_checks_fn_ptr)]
596+
#[help]
597597
FnPtr {
598598
orig_ty: Ty<'a>,
599599
#[label]
600600
label: Span,
601601
},
602-
#[diag(lint_ptr_null_checks_ref)]
602+
#[diag(lint_useless_ptr_null_checks_ref)]
603603
Ref {
604604
orig_ty: Ty<'a>,
605605
#[label]
606606
label: Span,
607607
},
608-
#[diag(lint_ptr_null_checks_fn_ret)]
608+
#[diag(lint_useless_ptr_null_checks_fn_ret)]
609609
FnRet { fn_name: Ident },
610610
}
611611

612+
#[derive(LintDiagnostic)]
613+
pub(crate) enum InvalidNullArgumentsDiag {
614+
#[diag(lint_invalid_null_arguments)]
615+
#[help(lint_doc)]
616+
NullPtrInline {
617+
#[label(lint_origin)]
618+
null_span: Span,
619+
},
620+
#[diag(lint_invalid_null_arguments)]
621+
#[help(lint_doc)]
622+
NullPtrThroughBinding {
623+
#[note(lint_origin)]
624+
null_span: Span,
625+
},
626+
}
627+
612628
// for_loops_over_fallibles.rs
613629
#[derive(LintDiagnostic)]
614630
#[diag(lint_for_loops_over_fallibles)]

compiler/rustc_lint/src/ptr_nulls.rs

+114-14
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
use rustc_ast::LitKind;
22
use rustc_hir::{BinOpKind, Expr, ExprKind, TyKind};
3+
use rustc_middle::ty::RawPtr;
34
use rustc_session::{declare_lint, declare_lint_pass};
4-
use rustc_span::sym;
5+
use rustc_span::{Span, sym};
56

6-
use crate::lints::PtrNullChecksDiag;
7+
use crate::lints::{InvalidNullArgumentsDiag, UselessPtrNullChecksDiag};
8+
use crate::utils::peel_casts;
79
use crate::{LateContext, LateLintPass, LintContext};
810

911
declare_lint! {
@@ -31,17 +33,40 @@ declare_lint! {
3133
"useless checking of non-null-typed pointer"
3234
}
3335

34-
declare_lint_pass!(PtrNullChecks => [USELESS_PTR_NULL_CHECKS]);
36+
declare_lint! {
37+
/// The `invalid_null_arguments` lint checks for invalid usage of null pointers in arguments.
38+
///
39+
/// ### Example
40+
///
41+
/// ```rust,compile_fail
42+
/// # use std::{slice, ptr};
43+
/// // Undefined behavior
44+
/// # let _slice: &[u8] =
45+
/// unsafe { slice::from_raw_parts(ptr::null(), 0) };
46+
/// ```
47+
///
48+
/// {{produces}}
49+
///
50+
/// ### Explanation
51+
///
52+
/// Calling methods whos safety invariants requires non-null ptr with a null pointer
53+
/// is [Undefined Behavior](https://doc.rust-lang.org/reference/behavior-considered-undefined.html)!
54+
INVALID_NULL_ARGUMENTS,
55+
Deny,
56+
"invalid null pointer in arguments"
57+
}
58+
59+
declare_lint_pass!(PtrNullChecks => [USELESS_PTR_NULL_CHECKS, INVALID_NULL_ARGUMENTS]);
3560

3661
/// This function checks if the expression is from a series of consecutive casts,
3762
/// ie. `(my_fn as *const _ as *mut _).cast_mut()` and whether the original expression is either
3863
/// a fn ptr, a reference, or a function call whose definition is
3964
/// annotated with `#![rustc_never_returns_null_ptr]`.
4065
/// If this situation is present, the function returns the appropriate diagnostic.
41-
fn incorrect_check<'a, 'tcx: 'a>(
66+
fn useless_check<'a, 'tcx: 'a>(
4267
cx: &'a LateContext<'tcx>,
4368
mut e: &'a Expr<'a>,
44-
) -> Option<PtrNullChecksDiag<'tcx>> {
69+
) -> Option<UselessPtrNullChecksDiag<'tcx>> {
4570
let mut had_at_least_one_cast = false;
4671
loop {
4772
e = e.peel_blocks();
@@ -50,14 +75,14 @@ fn incorrect_check<'a, 'tcx: 'a>(
5075
&& cx.tcx.has_attr(def_id, sym::rustc_never_returns_null_ptr)
5176
&& let Some(fn_name) = cx.tcx.opt_item_ident(def_id)
5277
{
53-
return Some(PtrNullChecksDiag::FnRet { fn_name });
78+
return Some(UselessPtrNullChecksDiag::FnRet { fn_name });
5479
} else if let ExprKind::Call(path, _args) = e.kind
5580
&& let ExprKind::Path(ref qpath) = path.kind
5681
&& let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
5782
&& cx.tcx.has_attr(def_id, sym::rustc_never_returns_null_ptr)
5883
&& let Some(fn_name) = cx.tcx.opt_item_ident(def_id)
5984
{
60-
return Some(PtrNullChecksDiag::FnRet { fn_name });
85+
return Some(UselessPtrNullChecksDiag::FnRet { fn_name });
6186
}
6287
e = if let ExprKind::Cast(expr, t) = e.kind
6388
&& let TyKind::Ptr(_) = t.kind
@@ -73,9 +98,9 @@ fn incorrect_check<'a, 'tcx: 'a>(
7398
} else if had_at_least_one_cast {
7499
let orig_ty = cx.typeck_results().expr_ty(e);
75100
return if orig_ty.is_fn() {
76-
Some(PtrNullChecksDiag::FnPtr { orig_ty, label: e.span })
101+
Some(UselessPtrNullChecksDiag::FnPtr { orig_ty, label: e.span })
77102
} else if orig_ty.is_ref() {
78-
Some(PtrNullChecksDiag::Ref { orig_ty, label: e.span })
103+
Some(UselessPtrNullChecksDiag::Ref { orig_ty, label: e.span })
79104
} else {
80105
None
81106
};
@@ -85,6 +110,25 @@ fn incorrect_check<'a, 'tcx: 'a>(
85110
}
86111
}
87112

113+
/// Checks if the given expression is a null pointer (modulo casting)
114+
fn is_null_ptr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<Span> {
115+
let (expr, _) = peel_casts(cx, expr);
116+
117+
if let ExprKind::Call(path, []) = expr.kind
118+
&& let ExprKind::Path(ref qpath) = path.kind
119+
&& let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
120+
&& let Some(diag_item) = cx.tcx.get_diagnostic_name(def_id)
121+
{
122+
(diag_item == sym::ptr_null || diag_item == sym::ptr_null_mut).then_some(expr.span)
123+
} else if let ExprKind::Lit(spanned) = expr.kind
124+
&& let LitKind::Int(v, _) = spanned.node
125+
{
126+
(v == 0).then_some(expr.span)
127+
} else {
128+
None
129+
}
130+
}
131+
88132
impl<'tcx> LateLintPass<'tcx> for PtrNullChecks {
89133
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
90134
match expr.kind {
@@ -97,11 +141,67 @@ impl<'tcx> LateLintPass<'tcx> for PtrNullChecks {
97141
cx.tcx.get_diagnostic_name(def_id),
98142
Some(sym::ptr_const_is_null | sym::ptr_is_null)
99143
)
100-
&& let Some(diag) = incorrect_check(cx, arg) =>
144+
&& let Some(diag) = useless_check(cx, arg) =>
101145
{
102146
cx.emit_span_lint(USELESS_PTR_NULL_CHECKS, expr.span, diag)
103147
}
104148

149+
// Catching:
150+
// <path>(arg...) where `arg` is null-ptr and `path` is a fn that expect non-null-ptr
151+
ExprKind::Call(path, args)
152+
if let ExprKind::Path(ref qpath) = path.kind
153+
&& let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
154+
&& let Some(diag_name) = cx.tcx.get_diagnostic_name(def_id) =>
155+
{
156+
// `arg` positions where null would cause U.B and whenever ZST are allowed.
157+
//
158+
// We should probably have a `rustc` attribute, but checking them is costly,
159+
// maybe if we checked for null ptr first, it would be acceptable?
160+
let (arg_indices, are_zsts_allowed): (&[_], _) = match diag_name {
161+
sym::ptr_read
162+
| sym::ptr_read_unaligned
163+
| sym::ptr_read_volatile
164+
| sym::ptr_replace
165+
| sym::ptr_write
166+
| sym::ptr_write_bytes
167+
| sym::ptr_write_unaligned
168+
| sym::ptr_write_volatile => (&[0], true),
169+
sym::slice_from_raw_parts | sym::slice_from_raw_parts_mut => (&[0], false),
170+
sym::ptr_copy
171+
| sym::ptr_copy_nonoverlapping
172+
| sym::ptr_swap
173+
| sym::ptr_swap_nonoverlapping => (&[0, 1], true),
174+
_ => return,
175+
};
176+
177+
for &arg_idx in arg_indices {
178+
if let Some(arg) = args.get(arg_idx)
179+
&& let Some(null_span) = is_null_ptr(cx, arg)
180+
&& let Some(ty) = cx.typeck_results().expr_ty_opt(arg)
181+
&& let RawPtr(ty, _mutbl) = ty.kind()
182+
{
183+
// If ZST are fine, don't lint on them
184+
let typing_env = cx.typing_env();
185+
if are_zsts_allowed
186+
&& cx
187+
.tcx
188+
.layout_of(typing_env.as_query_input(*ty))
189+
.is_ok_and(|layout| layout.is_1zst())
190+
{
191+
break;
192+
}
193+
194+
let diag = if arg.span.contains(null_span) {
195+
InvalidNullArgumentsDiag::NullPtrInline { null_span }
196+
} else {
197+
InvalidNullArgumentsDiag::NullPtrThroughBinding { null_span }
198+
};
199+
200+
cx.emit_span_lint(INVALID_NULL_ARGUMENTS, expr.span, diag)
201+
}
202+
}
203+
}
204+
105205
// Catching:
106206
// (fn_ptr as *<const/mut> <ty>).is_null()
107207
ExprKind::MethodCall(_, receiver, _, _)
@@ -110,18 +210,18 @@ impl<'tcx> LateLintPass<'tcx> for PtrNullChecks {
110210
cx.tcx.get_diagnostic_name(def_id),
111211
Some(sym::ptr_const_is_null | sym::ptr_is_null)
112212
)
113-
&& let Some(diag) = incorrect_check(cx, receiver) =>
213+
&& let Some(diag) = useless_check(cx, receiver) =>
114214
{
115215
cx.emit_span_lint(USELESS_PTR_NULL_CHECKS, expr.span, diag)
116216
}
117217

118218
ExprKind::Binary(op, left, right) if matches!(op.node, BinOpKind::Eq) => {
119219
let to_check: &Expr<'_>;
120-
let diag: PtrNullChecksDiag<'_>;
121-
if let Some(ddiag) = incorrect_check(cx, left) {
220+
let diag: UselessPtrNullChecksDiag<'_>;
221+
if let Some(ddiag) = useless_check(cx, left) {
122222
to_check = right;
123223
diag = ddiag;
124-
} else if let Some(ddiag) = incorrect_check(cx, right) {
224+
} else if let Some(ddiag) = useless_check(cx, right) {
125225
to_check = left;
126226
diag = ddiag;
127227
} else {

compiler/rustc_lint/src/reference_casting.rs

+1-43
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use rustc_session::{declare_lint, declare_lint_pass};
66
use rustc_span::sym;
77

88
use crate::lints::InvalidReferenceCastingDiag;
9+
use crate::utils::peel_casts;
910
use crate::{LateContext, LateLintPass, LintContext};
1011

1112
declare_lint! {
@@ -235,46 +236,3 @@ fn is_cast_to_bigger_memory_layout<'tcx>(
235236
None
236237
}
237238
}
238-
239-
fn peel_casts<'tcx>(cx: &LateContext<'tcx>, mut e: &'tcx Expr<'tcx>) -> (&'tcx Expr<'tcx>, bool) {
240-
let mut gone_trough_unsafe_cell_raw_get = false;
241-
242-
loop {
243-
e = e.peel_blocks();
244-
// <expr> as ...
245-
e = if let ExprKind::Cast(expr, _) = e.kind {
246-
expr
247-
// <expr>.cast(), <expr>.cast_mut() or <expr>.cast_const()
248-
} else if let ExprKind::MethodCall(_, expr, [], _) = e.kind
249-
&& let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id)
250-
&& matches!(
251-
cx.tcx.get_diagnostic_name(def_id),
252-
Some(sym::ptr_cast | sym::const_ptr_cast | sym::ptr_cast_mut | sym::ptr_cast_const)
253-
)
254-
{
255-
expr
256-
// ptr::from_ref(<expr>), UnsafeCell::raw_get(<expr>) or mem::transmute<_, _>(<expr>)
257-
} else if let ExprKind::Call(path, [arg]) = e.kind
258-
&& let ExprKind::Path(ref qpath) = path.kind
259-
&& let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
260-
&& matches!(
261-
cx.tcx.get_diagnostic_name(def_id),
262-
Some(sym::ptr_from_ref | sym::unsafe_cell_raw_get | sym::transmute)
263-
)
264-
{
265-
if cx.tcx.is_diagnostic_item(sym::unsafe_cell_raw_get, def_id) {
266-
gone_trough_unsafe_cell_raw_get = true;
267-
}
268-
arg
269-
} else {
270-
let init = cx.expr_or_init(e);
271-
if init.hir_id != e.hir_id {
272-
init
273-
} else {
274-
break;
275-
}
276-
};
277-
}
278-
279-
(e, gone_trough_unsafe_cell_raw_get)
280-
}

0 commit comments

Comments
 (0)