1use rustc_ast::{BorrowKind, UnOp};
2use rustc_hir::attrs::AttributeKind;
3use rustc_hir::{Expr, ExprKind, Mutability, find_attr};
4use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, OverloadedDeref};
5use rustc_session::{declare_lint, declare_lint_pass};
6
7use crate::lints::{
8 ImplicitUnsafeAutorefsDiag, ImplicitUnsafeAutorefsMethodNote, ImplicitUnsafeAutorefsOrigin,
9 ImplicitUnsafeAutorefsSuggestion,
10};
11use crate::{LateContext, LateLintPass, LintContext};
12
13#[doc =
r" The `dangerous_implicit_autorefs` lint checks for implicitly taken references"]
#[doc = r" to dereferences of raw pointers."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" unsafe fn fun(ptr: *mut [u8]) -> *mut [u8] {"]
#[doc = r" unsafe { &raw mut (*ptr)[..16] }"]
#[doc =
r" // ^^^^^^ this calls `IndexMut::index_mut(&mut ..., ..16)`,"]
#[doc =
r" // implicitly creating a reference"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" When working with raw pointers it's usually undesirable to create references,"]
#[doc =
r" since they inflict additional safety requirements. Unfortunately, it's possible"]
#[doc =
r" to take a reference to the dereference of a raw pointer implicitly, which inflicts"]
#[doc = r" the usual reference requirements."]
#[doc = r""]
#[doc =
r" If you are sure that you can soundly take a reference, then you can take it explicitly:"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" unsafe fn fun(ptr: *mut [u8]) -> *mut [u8] {"]
#[doc = r" unsafe { &raw mut (&mut *ptr)[..16] }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc =
r" Otherwise try to find an alternative way to achieve your goals using only raw pointers:"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" use std::ptr;"]
#[doc = r""]
#[doc = r" fn fun(ptr: *mut [u8]) -> *mut [u8] {"]
#[doc = r" ptr::slice_from_raw_parts_mut(ptr.cast(), 16)"]
#[doc = r" }"]
#[doc = r" ```"]
pub static DANGEROUS_IMPLICIT_AUTOREFS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "DANGEROUS_IMPLICIT_AUTOREFS",
default_level: ::rustc_lint_defs::Deny,
desc: "implicit reference to a dereference of a raw pointer",
is_externally_loaded: false,
report_in_external_macro: true,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
14 pub DANGEROUS_IMPLICIT_AUTOREFS,
54 Deny,
55 "implicit reference to a dereference of a raw pointer",
56 report_in_external_macro
57}
58
59pub struct ImplicitAutorefs;
#[automatically_derived]
impl ::core::marker::Copy for ImplicitAutorefs { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ImplicitAutorefs { }
#[automatically_derived]
impl ::core::clone::Clone for ImplicitAutorefs {
#[inline]
fn clone(&self) -> ImplicitAutorefs { *self }
}
impl ::rustc_lint_defs::LintPass for ImplicitAutorefs {
fn name(&self) -> &'static str { "ImplicitAutorefs" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([DANGEROUS_IMPLICIT_AUTOREFS]))
}
}
impl ImplicitAutorefs {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([DANGEROUS_IMPLICIT_AUTOREFS]))
}
}declare_lint_pass!(ImplicitAutorefs => [DANGEROUS_IMPLICIT_AUTOREFS]);
60
61impl<'tcx> LateLintPass<'tcx> for ImplicitAutorefs {
62 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
63 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, _, _) => base,
81 ExprKind::MethodCall(_, inner, _, _) => {
82 inner
85 }
86 ExprKind::Field(inner, _) => inner,
87 _ => return,
88 };
89
90 let typeck = cx.typeck_results();
91 let adjustments_table = typeck.adjustments();
92
93 if let Some(adjustments) = adjustments_table.get(inner.hir_id)
94 && let adjustments = peel_derefs_adjustments(&**adjustments)
96 && let [adjustment] = adjustments
98 && let Some((borrow_mutbl, through_overloaded_deref)) = has_implicit_borrow(adjustment)
99 && let ExprKind::Unary(UnOp::Deref, dereferenced) =
100 peel_place_mappers(inner).kind
102 && typeck.expr_ty(dereferenced).is_raw_ptr()
104 && let method_did = match expr.kind {
105 ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
107 _ => None,
108 }
109 && method_did.map(|did| {
{
'done:
{
for i in cx.tcx.get_all_attrs(did) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcNoImplicitAutorefs)
=> {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(cx.tcx.get_all_attrs(did), AttributeKind::RustcNoImplicitAutorefs)).unwrap_or(true)
110 {
111 cx.emit_span_lint(
112 DANGEROUS_IMPLICIT_AUTOREFS,
113 expr.span.source_callsite(),
114 ImplicitUnsafeAutorefsDiag {
115 raw_ptr_span: dereferenced.span,
116 raw_ptr_ty: typeck.expr_ty(dereferenced),
117 origin: if through_overloaded_deref {
118 ImplicitUnsafeAutorefsOrigin::OverloadedDeref
119 } else {
120 ImplicitUnsafeAutorefsOrigin::Autoref {
121 autoref_span: inner.span,
122 autoref_ty: typeck.expr_ty_adjusted(inner),
123 }
124 },
125 method: method_did.map(|did| ImplicitUnsafeAutorefsMethodNote {
126 def_span: cx.tcx.def_span(did),
127 method_name: cx.tcx.item_name(did),
128 }),
129 suggestion: ImplicitUnsafeAutorefsSuggestion {
130 mutbl: borrow_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
141fn peel_place_mappers<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
143 loop {
144 match expr.kind {
145 ExprKind::Index(base, _idx, _) => expr = &base,
146 ExprKind::Field(e, _) => expr = &e,
147 _ => break expr,
148 }
149 }
150}
151
152fn peel_derefs_adjustments<'a>(mut adjs: &'a [Adjustment<'a>]) -> &'a [Adjustment<'a>] {
154 while let [Adjustment { kind: Adjust::Deref(_), .. }, end @ ..] = adjs
155 && !end.is_empty()
156 {
157 adjs = end;
158 }
159 adjs
160}
161
162fn has_implicit_borrow(Adjustment { kind, .. }: &Adjustment<'_>) -> Option<(Mutability, bool)> {
167 match kind {
168 &Adjust::Deref(Some(OverloadedDeref { mutbl, .. })) => Some((mutbl, true)),
169 &Adjust::Borrow(AutoBorrow::Ref(mutbl)) => Some((mutbl.into(), false)),
170 Adjust::NeverToAny
171 | Adjust::Pointer(..)
172 | Adjust::ReborrowPin(..)
173 | Adjust::Deref(None)
174 | Adjust::Borrow(AutoBorrow::RawPtr(..)) => None,
175 }
176}