Skip to content

Commit 5c1f2ae

Browse files
committed
Implement lint against dangerous implicit autorefs
1 parent 5e8544e commit 5c1f2ae

File tree

8 files changed

+469
-1
lines changed

8 files changed

+469
-1
lines changed

compiler/rustc_lint/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,10 @@ lint_impl_trait_overcaptures = `{$self_ty}` will capture more lifetimes than pos
360360
lint_impl_trait_redundant_captures = all possible in-scope parameters are already captured, so `use<...>` syntax is redundant
361361
.suggestion = remove the `use<...>` syntax
362362
363+
lint_implicit_unsafe_autorefs = implicit auto-ref creates a reference to a dereference of a raw pointer
364+
.note = creating a reference requires the pointer to be valid and imposes aliasing requirements
365+
.suggestion = try using a raw pointer method instead; or if this reference is intentional, make it explicit
366+
363367
lint_improper_ctypes = `extern` {$desc} uses type `{$ty}`, which is not FFI-safe
364368
.label = not FFI-safe
365369
.note = the type is defined here

compiler/rustc_lint/src/autorefs.rs

+166
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
use rustc_ast::{BorrowKind, UnOp};
2+
use rustc_hir::{Expr, ExprKind, Mutability};
3+
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, OverloadedDeref};
4+
use rustc_session::{declare_lint, declare_lint_pass};
5+
use rustc_span::sym;
6+
7+
use crate::lints::{ImplicitUnsafeAutorefsDiag, ImplicitUnsafeAutorefsSuggestion};
8+
use crate::{LateContext, LateLintPass, LintContext};
9+
10+
declare_lint! {
11+
/// The `dangerous_implicit_autorefs` lint checks for implicitly taken references
12+
/// to dereferences of raw pointers.
13+
///
14+
/// ### Example
15+
///
16+
/// ```rust
17+
/// use std::ptr::addr_of_mut;
18+
///
19+
/// unsafe fn fun(ptr: *mut [u8]) -> *mut [u8] {
20+
/// addr_of_mut!((*ptr)[..16])
21+
/// // ^^^^^^ this calls `IndexMut::index_mut(&mut ..., ..16)`,
22+
/// // implicitly creating a reference
23+
/// }
24+
/// ```
25+
///
26+
/// {{produces}}
27+
///
28+
/// ### Explanation
29+
///
30+
/// When working with raw pointers it's usually undesirable to create references,
31+
/// since they inflict a lot of safety requirement. Unfortunately, it's possible
32+
/// to take a reference to a dereference of a raw pointer implicitly, which inflicts
33+
/// the usual reference requirements potentially without realizing that.
34+
///
35+
/// If you are sure, you can soundly take a reference, then you can take it explicitly:
36+
/// ```rust
37+
/// # use std::ptr::addr_of_mut;
38+
/// unsafe fn fun(ptr: *mut [u8]) -> *mut [u8] {
39+
/// addr_of_mut!((&mut *ptr)[..16])
40+
/// }
41+
/// ```
42+
///
43+
/// Otherwise try to find an alternative way to achive your goals that work only with
44+
/// raw pointers:
45+
/// ```rust
46+
/// #![feature(slice_ptr_get)]
47+
///
48+
/// unsafe fn fun(ptr: *mut [u8]) -> *mut [u8] {
49+
/// ptr.get_unchecked_mut(..16)
50+
/// }
51+
/// ```
52+
pub DANGEROUS_IMPLICIT_AUTOREFS,
53+
Warn,
54+
"implicit reference to a dereference of a raw pointer",
55+
report_in_external_macro
56+
}
57+
58+
declare_lint_pass!(ImplicitAutorefs => [DANGEROUS_IMPLICIT_AUTOREFS]);
59+
60+
impl<'tcx> LateLintPass<'tcx> for ImplicitAutorefs {
61+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
62+
// This logic has mostly been taken from
63+
// https://github.com/rust-lang/rust/pull/103735#issuecomment-1370420305
64+
65+
// 5. Either of the following:
66+
// a. A deref followed by any non-deref place projection (that intermediate
67+
// deref will typically be auto-inserted)
68+
// b. A method call annotated with `#[rustc_no_implicit_refs]`.
69+
// c. A deref followed by a `addr_of!` or `addr_of_mut!`.
70+
let mut is_coming_from_deref = false;
71+
let inner = match expr.kind {
72+
ExprKind::AddrOf(BorrowKind::Raw, _, inner) => match inner.kind {
73+
ExprKind::Unary(UnOp::Deref, inner) => {
74+
is_coming_from_deref = true;
75+
inner
76+
}
77+
_ => return,
78+
},
79+
ExprKind::Index(base, _, _) => base,
80+
ExprKind::MethodCall(_, inner, _, _)
81+
if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
82+
&& cx.tcx.has_attr(def_id, sym::rustc_no_implicit_autorefs) =>
83+
{
84+
inner
85+
}
86+
ExprKind::Field(inner, _) => {
87+
let typeck = cx.typeck_results();
88+
let adjustments_table = typeck.adjustments();
89+
if let Some(adjustments) = adjustments_table.get(inner.hir_id)
90+
&& let [adjustment] = &**adjustments
91+
&& let &Adjust::Deref(Some(OverloadedDeref { .. })) = &adjustment.kind
92+
{
93+
inner
94+
} else {
95+
return;
96+
}
97+
}
98+
_ => return,
99+
};
100+
101+
let typeck = cx.typeck_results();
102+
let adjustments_table = typeck.adjustments();
103+
104+
if let Some(adjustments) = adjustments_table.get(inner.hir_id)
105+
// 4. Any number of automatically inserted deref/derefmut calls
106+
&& let adjustments = peel_derefs_adjustments(&**adjustments)
107+
// 3. An automatically inserted reference.
108+
&& let [adjustment] = adjustments
109+
&& let Some(borrow_mutbl) = has_implicit_borrow(adjustment)
110+
&& let ExprKind::Unary(UnOp::Deref, dereferenced) =
111+
// 2. Any number of place projections
112+
peel_place_mappers(inner).kind
113+
// 1. Deref of a raw pointer
114+
&& typeck.expr_ty(dereferenced).is_raw_ptr()
115+
{
116+
cx.emit_span_lint(
117+
DANGEROUS_IMPLICIT_AUTOREFS,
118+
expr.span.source_callsite(),
119+
ImplicitUnsafeAutorefsDiag {
120+
suggestion: ImplicitUnsafeAutorefsSuggestion {
121+
mutbl: borrow_mutbl.ref_prefix_str(),
122+
deref: if is_coming_from_deref { "*" } else { "" },
123+
start_span: inner.span.shrink_to_lo(),
124+
end_span: inner.span.shrink_to_hi(),
125+
},
126+
},
127+
)
128+
}
129+
}
130+
}
131+
132+
/// Peels expressions from `expr` that can map a place.
133+
fn peel_place_mappers<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
134+
loop {
135+
match expr.kind {
136+
ExprKind::Index(base, _idx, _) => {
137+
expr = &base;
138+
}
139+
ExprKind::Field(e, _) => expr = &e,
140+
_ => break expr,
141+
}
142+
}
143+
}
144+
145+
/// Peel derefs adjustments
146+
fn peel_derefs_adjustments<'a>(mut adjs: &'a [Adjustment<'a>]) -> &'a [Adjustment<'a>] {
147+
while let [Adjustment { kind: Adjust::Deref(None), .. }, end @ ..] = adjs {
148+
adjs = end;
149+
}
150+
adjs
151+
}
152+
153+
/// Test if some adjustment has some implicit borrow
154+
///
155+
/// Returns `Some(mutability)` if the argument adjustment has implicit borrow in it.
156+
fn has_implicit_borrow(Adjustment { kind, .. }: &Adjustment<'_>) -> Option<Mutability> {
157+
match kind {
158+
&Adjust::Deref(Some(OverloadedDeref { mutbl, .. })) => Some(mutbl),
159+
&Adjust::Borrow(AutoBorrow::Ref(mutbl)) => Some(mutbl.into()),
160+
Adjust::NeverToAny
161+
| Adjust::Pointer(..)
162+
| Adjust::ReborrowPin(..)
163+
| Adjust::Deref(None)
164+
| Adjust::Borrow(AutoBorrow::RawPtr(..)) => None,
165+
}
166+
}

compiler/rustc_lint/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636

3737
mod async_closures;
3838
mod async_fn_in_trait;
39+
mod autorefs;
3940
pub mod builtin;
4041
mod context;
4142
mod dangling;
@@ -82,6 +83,7 @@ mod unused;
8283

8384
use async_closures::AsyncClosureUsage;
8485
use async_fn_in_trait::AsyncFnInTrait;
86+
use autorefs::*;
8587
use builtin::*;
8688
use dangling::*;
8789
use default_could_be_derived::DefaultCouldBeDerived;
@@ -200,6 +202,7 @@ late_lint_methods!(
200202
PathStatements: PathStatements,
201203
LetUnderscore: LetUnderscore,
202204
InvalidReferenceCasting: InvalidReferenceCasting,
205+
ImplicitAutorefs: ImplicitAutorefs,
203206
// Depends on referenced function signatures in expressions
204207
UnusedResults: UnusedResults,
205208
UnitBindings: UnitBindings,

compiler/rustc_lint/src/lints.rs

+20
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,26 @@ pub(crate) enum ShadowedIntoIterDiagSub {
5555
},
5656
}
5757

58+
// autorefs.rs
59+
#[derive(LintDiagnostic)]
60+
#[diag(lint_implicit_unsafe_autorefs)]
61+
#[note]
62+
pub(crate) struct ImplicitUnsafeAutorefsDiag {
63+
#[subdiagnostic]
64+
pub suggestion: ImplicitUnsafeAutorefsSuggestion,
65+
}
66+
67+
#[derive(Subdiagnostic)]
68+
#[multipart_suggestion(lint_suggestion, applicability = "maybe-incorrect")]
69+
pub(crate) struct ImplicitUnsafeAutorefsSuggestion {
70+
pub mutbl: &'static str,
71+
pub deref: &'static str,
72+
#[suggestion_part(code = "({mutbl}{deref}")]
73+
pub start_span: Span,
74+
#[suggestion_part(code = ")")]
75+
pub end_span: Span,
76+
}
77+
5878
// builtin.rs
5979
#[derive(LintDiagnostic)]
6080
#[diag(lint_builtin_while_true)]

library/alloc/src/vec/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2575,7 +2575,7 @@ impl<T, A: Allocator> Vec<T, A> {
25752575
#[inline]
25762576
#[track_caller]
25772577
unsafe fn append_elements(&mut self, other: *const [T]) {
2578-
let count = unsafe { (*other).len() };
2578+
let count = other.len();
25792579
self.reserve(count);
25802580
let len = self.len();
25812581
unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };

tests/ui/lint/implicit_autorefs.fixed

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
//@ check-pass
2+
//@ run-rustfix
3+
4+
#![allow(dead_code)] // for the rustfix-ed code
5+
6+
use std::mem::ManuallyDrop;
7+
use std::ptr::addr_of_mut;
8+
use std::ptr::addr_of;
9+
use std::ops::Deref;
10+
11+
unsafe fn test_const(ptr: *const [u8]) -> *const [u8] {
12+
addr_of!((&(*ptr))[..16])
13+
//~^ WARN implicit auto-ref
14+
}
15+
16+
struct Test {
17+
field: [u8],
18+
}
19+
20+
unsafe fn test_field(ptr: *const Test) -> *const [u8] {
21+
let l = (&(*ptr).field).len();
22+
//~^ WARN implicit auto-ref
23+
24+
addr_of!((&(*ptr).field)[..l - 1])
25+
//~^ WARN implicit auto-ref
26+
}
27+
28+
unsafe fn test_builtin_index(a: *mut [String]) {
29+
_ = (&(*a)[0]).len();
30+
//~^ WARN implicit auto-ref
31+
32+
_ = (&(&(*a))[..1][0]).len();
33+
//~^ WARN implicit auto-ref
34+
//~^^ WARN implicit auto-ref
35+
}
36+
37+
unsafe fn test_overloaded_deref_const(ptr: *const ManuallyDrop<Test>) {
38+
_ = addr_of!((&(*ptr)).field);
39+
//~^ WARN implicit auto-ref
40+
}
41+
42+
unsafe fn test_overloaded_deref_mut(ptr: *mut ManuallyDrop<Test>) {
43+
_ = addr_of_mut!((&mut (*ptr)).field);
44+
//~^ WARN implicit auto-ref
45+
}
46+
47+
unsafe fn test_manually_overloaded_deref() {
48+
struct W<T>(T);
49+
50+
impl<T> Deref for W<T> {
51+
type Target = T;
52+
fn deref(&self) -> &T { &self.0 }
53+
}
54+
55+
let w: W<i32> = W(5);
56+
let w = addr_of!(w);
57+
let _p: *const i32 = addr_of!(*(&**w));
58+
//~^ WARN implicit auto-ref
59+
}
60+
61+
struct Test2 {
62+
// derefs to [u8]
63+
field: &'static [u8]
64+
}
65+
66+
fn test_more_manual_deref(ptr: *const Test2) -> usize {
67+
unsafe { (&(*ptr).field).len() }
68+
//~^ WARN implicit auto-ref
69+
}
70+
71+
unsafe fn test_no_attr(ptr: *mut ManuallyDrop<u8>) {
72+
ptr.write(ManuallyDrop::new(1)); // should not warn, as `ManuallyDrop::write` is not
73+
// annotated with `#[rustc_no_implicit_auto_ref]`
74+
}
75+
76+
fn main() {}

tests/ui/lint/implicit_autorefs.rs

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
//@ check-pass
2+
//@ run-rustfix
3+
4+
#![allow(dead_code)] // for the rustfix-ed code
5+
6+
use std::mem::ManuallyDrop;
7+
use std::ptr::addr_of_mut;
8+
use std::ptr::addr_of;
9+
use std::ops::Deref;
10+
11+
unsafe fn test_const(ptr: *const [u8]) -> *const [u8] {
12+
addr_of!((*ptr)[..16])
13+
//~^ WARN implicit auto-ref
14+
}
15+
16+
struct Test {
17+
field: [u8],
18+
}
19+
20+
unsafe fn test_field(ptr: *const Test) -> *const [u8] {
21+
let l = (*ptr).field.len();
22+
//~^ WARN implicit auto-ref
23+
24+
addr_of!((*ptr).field[..l - 1])
25+
//~^ WARN implicit auto-ref
26+
}
27+
28+
unsafe fn test_builtin_index(a: *mut [String]) {
29+
_ = (*a)[0].len();
30+
//~^ WARN implicit auto-ref
31+
32+
_ = (*a)[..1][0].len();
33+
//~^ WARN implicit auto-ref
34+
//~^^ WARN implicit auto-ref
35+
}
36+
37+
unsafe fn test_overloaded_deref_const(ptr: *const ManuallyDrop<Test>) {
38+
_ = addr_of!((*ptr).field);
39+
//~^ WARN implicit auto-ref
40+
}
41+
42+
unsafe fn test_overloaded_deref_mut(ptr: *mut ManuallyDrop<Test>) {
43+
_ = addr_of_mut!((*ptr).field);
44+
//~^ WARN implicit auto-ref
45+
}
46+
47+
unsafe fn test_manually_overloaded_deref() {
48+
struct W<T>(T);
49+
50+
impl<T> Deref for W<T> {
51+
type Target = T;
52+
fn deref(&self) -> &T { &self.0 }
53+
}
54+
55+
let w: W<i32> = W(5);
56+
let w = addr_of!(w);
57+
let _p: *const i32 = addr_of!(**w);
58+
//~^ WARN implicit auto-ref
59+
}
60+
61+
struct Test2 {
62+
// derefs to [u8]
63+
field: &'static [u8]
64+
}
65+
66+
fn test_more_manual_deref(ptr: *const Test2) -> usize {
67+
unsafe { (*ptr).field.len() }
68+
//~^ WARN implicit auto-ref
69+
}
70+
71+
unsafe fn test_no_attr(ptr: *mut ManuallyDrop<u8>) {
72+
ptr.write(ManuallyDrop::new(1)); // should not warn, as `ManuallyDrop::write` is not
73+
// annotated with `#[rustc_no_implicit_auto_ref]`
74+
}
75+
76+
fn main() {}

0 commit comments

Comments
 (0)