Skip to content

Commit becbe21

Browse files
committed
Implement lint against dangerous implicit autorefs
1 parent bf6bb78 commit becbe21

File tree

8 files changed

+449
-1
lines changed

8 files changed

+449
-1
lines changed

compiler/rustc_lint/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,10 @@ lint_identifier_uncommon_codepoints = identifier contains {$codepoints_len ->
269269
270270
lint_ignored_unless_crate_specified = {$level}({$name}) is ignored unless specified at crate level
271271
272+
lint_implicit_unsafe_autorefs = implicit auto-ref creates a reference to a dereference of a raw pointer
273+
.note = creating a reference requires the pointer to be valid and imposes aliasing requirements
274+
.suggestion = try using a raw pointer method instead; or if this reference is intentional, make it explicit
275+
272276
lint_improper_ctypes = `extern` {$desc} uses type `{$ty}`, which is not FFI-safe
273277
.label = not FFI-safe
274278
.note = the type is defined here

compiler/rustc_lint/src/autorefs.rs

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

compiler/rustc_lint/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ extern crate tracing;
4949

5050
mod array_into_iter;
5151
mod async_fn_in_trait;
52+
mod autorefs;
5253
pub mod builtin;
5354
mod context;
5455
mod deref_into_dyn_supertrait;
@@ -93,6 +94,7 @@ use rustc_middle::ty::TyCtxt;
9394

9495
use array_into_iter::ArrayIntoIter;
9596
use async_fn_in_trait::AsyncFnInTrait;
97+
use autorefs::*;
9698
use builtin::*;
9799
use deref_into_dyn_supertrait::*;
98100
use drop_forget_useless::*;
@@ -195,6 +197,7 @@ late_lint_methods!(
195197
PathStatements: PathStatements,
196198
LetUnderscore: LetUnderscore,
197199
InvalidReferenceCasting: InvalidReferenceCasting,
200+
ImplicitAutorefs: ImplicitAutorefs,
198201
// Depends on referenced function signatures in expressions
199202
UnusedResults: UnusedResults,
200203
UnitBindings: UnitBindings,

compiler/rustc_lint/src/lints.rs

+20
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,26 @@ pub enum ArrayIntoIterDiagSub {
5050
},
5151
}
5252

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

library/alloc/src/vec/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2112,7 +2112,7 @@ impl<T, A: Allocator> Vec<T, A> {
21122112
#[cfg(not(no_global_oom_handling))]
21132113
#[inline]
21142114
unsafe fn append_elements(&mut self, other: *const [T]) {
2115-
let count = unsafe { (*other).len() };
2115+
let count = other.len();
21162116
self.reserve(count);
21172117
let len = self.len();
21182118
unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };

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

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)