Skip to main content

rustc_lint/
autorefs.rs

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