Skip to content

Commit f76efa8

Browse files
committed
Implement lint against dangerous implicit autorefs
1 parent 5ed5edc commit f76efa8

File tree

8 files changed

+444
-1
lines changed

8 files changed

+444
-1
lines changed

compiler/rustc_lint/messages.ftl

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

compiler/rustc_lint/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
mod async_closures;
3939
mod async_fn_in_trait;
40+
mod autorefs;
4041
pub mod builtin;
4142
mod context;
4243
mod dangling;
@@ -83,6 +84,7 @@ mod unused;
8384

8485
use async_closures::AsyncClosureUsage;
8586
use async_fn_in_trait::AsyncFnInTrait;
87+
use autorefs::*;
8688
use builtin::*;
8789
use dangling::*;
8890
use default_could_be_derived::DefaultCouldBeDerived;
@@ -201,6 +203,7 @@ late_lint_methods!(
201203
PathStatements: PathStatements,
202204
LetUnderscore: LetUnderscore,
203205
InvalidReferenceCasting: InvalidReferenceCasting,
206+
ImplicitAutorefs: ImplicitAutorefs,
204207
// Depends on referenced function signatures in expressions
205208
UnusedResults: UnusedResults,
206209
UnitBindings: UnitBindings,

compiler/rustc_lint/src/lints.rs

Lines changed: 20 additions & 0 deletions
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

Lines changed: 1 addition & 1 deletion
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) };
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
unsafe fn test_no_attr(ptr: *mut ManuallyDrop<u8>) {
62+
ptr.write(ManuallyDrop::new(1)); // should not warn, as `ManuallyDrop::write` is not
63+
// annotated with `#[rustc_no_implicit_auto_ref]`
64+
}
65+
66+
fn main() {}

tests/ui/lint/implicit_autorefs.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
unsafe fn test_no_attr(ptr: *mut ManuallyDrop<u8>) {
62+
ptr.write(ManuallyDrop::new(1)); // should not warn, as `ManuallyDrop::write` is not
63+
// annotated with `#[rustc_no_implicit_auto_ref]`
64+
}
65+
66+
fn main() {}

0 commit comments

Comments
 (0)