Skip to content

Commit f36c11b

Browse files
committed
Implement lint against dangerous implicit autorefs
1 parent 4070857 commit f36c11b

File tree

8 files changed

+446
-1
lines changed

8 files changed

+446
-1
lines changed

Diff for: compiler/rustc_lint/messages.ftl

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

Diff for: compiler/rustc_lint/src/autorefs.rs

+175
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
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_unsafe_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)) => {
171+
Some((mutbl.into(), ImplicitBorrowKind::Borrow))
172+
}
173+
_ => None,
174+
}
175+
}

Diff for: compiler/rustc_lint/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444

4545
mod async_closures;
4646
mod async_fn_in_trait;
47+
mod autorefs;
4748
pub mod builtin;
4849
mod context;
4950
mod deref_into_dyn_supertrait;
@@ -90,6 +91,7 @@ mod unused;
9091

9192
use async_closures::AsyncClosureUsage;
9293
use async_fn_in_trait::AsyncFnInTrait;
94+
use autorefs::*;
9395
use builtin::*;
9496
use deref_into_dyn_supertrait::*;
9597
use drop_forget_useless::*;
@@ -207,6 +209,7 @@ late_lint_methods!(
207209
PathStatements: PathStatements,
208210
LetUnderscore: LetUnderscore,
209211
InvalidReferenceCasting: InvalidReferenceCasting,
212+
ImplicitAutorefs: ImplicitAutorefs,
210213
// Depends on referenced function signatures in expressions
211214
UnusedResults: UnusedResults,
212215
UnitBindings: UnitBindings,

Diff for: compiler/rustc_lint/src/lints.rs

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

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

Diff for: library/alloc/src/vec/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2549,7 +2549,7 @@ impl<T, A: Allocator> Vec<T, A> {
25492549
#[cfg(not(no_global_oom_handling))]
25502550
#[inline]
25512551
unsafe fn append_elements(&mut self, other: *const [T]) {
2552-
let count = unsafe { (*other).len() };
2552+
let count = other.len();
25532553
self.reserve(count);
25542554
let len = self.len();
25552555
unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };

Diff for: tests/ui/lint/implicit_autorefs.fixed

+66
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() {}

Diff for: tests/ui/lint/implicit_autorefs.rs

+66
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)