|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use clippy_utils::res::MaybeDef; |
| 3 | +use clippy_utils::{SpanlessEq, hash_expr}; |
| 4 | +use rustc_data_structures::fx::FxIndexMap; |
| 5 | +use rustc_hir as hir; |
| 6 | +use rustc_hir::intravisit::{Visitor, walk_expr}; |
| 7 | +use rustc_lint::{LateContext, LateLintPass}; |
| 8 | +use rustc_middle::ty; |
| 9 | +use rustc_session::declare_lint_pass; |
| 10 | +use rustc_span::sym; |
| 11 | + |
| 12 | +declare_clippy_lint! { |
| 13 | + /// ### What it does |
| 14 | + /// Checks for unsafe code calling `.as_ref()` multiple times |
| 15 | + /// on the same generic receiver. |
| 16 | + /// |
| 17 | + /// ### Why is this bad? |
| 18 | + /// Usually `AsRef::as_ref()` is pure and multiple calls will return a |
| 19 | + /// reference to the exact same value. However, unsafe code cannot always |
| 20 | + /// soundly rely on this. |
| 21 | + /// |
| 22 | + /// ### Example |
| 23 | + /// ```no_run |
| 24 | + /// # unsafe fn ffi_call(_ptr: *mut u8, _len: usize) {} |
| 25 | + /// fn safe_ffi_call(data: impl AsRef<[u8]>) { |
| 26 | + /// unsafe { |
| 27 | + /// ffi_call(data.as_ref().as_ptr(), data.as_ref().len()); |
| 28 | + /// } |
| 29 | + /// } |
| 30 | + /// ``` |
| 31 | + /// Use instead: |
| 32 | + /// ```no_run |
| 33 | + /// # unsafe fn ffi_call(_ptr: *mut u8, _len: usize) {} |
| 34 | + /// fn safe_ffi_call(data: impl AsRef<[u8]>) { |
| 35 | + /// let data = data.as_ref(); |
| 36 | + /// unsafe { |
| 37 | + /// ffi_call(data.as_ptr(), data.len()); |
| 38 | + /// } |
| 39 | + /// } |
| 40 | + /// ``` |
| 41 | + /// |
| 42 | + /// ### Known problems |
| 43 | + /// False negatives: Such code can also be unsound when the receiver |
| 44 | + /// is a concrete type from a foreign crate. |
| 45 | + /// |
| 46 | + /// False positives: Not all generic implementations are provided by |
| 47 | + /// foreign code. Not all unsafe code actually relies on the purity of |
| 48 | + /// `as_ref()`. |
| 49 | + #[clippy::version = "1.98.0"] |
| 50 | + pub TRUSTED_ASREF, |
| 51 | + suspicious, |
| 52 | + "unsafe block calls `.as_ref()` multiple times on the same generic receiver" |
| 53 | +} |
| 54 | + |
| 55 | +declare_lint_pass!(TrustedAsref => [TRUSTED_ASREF]); |
| 56 | + |
| 57 | +impl<'tcx> LateLintPass<'tcx> for TrustedAsref { |
| 58 | + fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'tcx>) { |
| 59 | + if block.rules == hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) |
| 60 | + && !block.span.in_external_macro(cx.tcx.sess.source_map()) |
| 61 | + { |
| 62 | + let mut visitor = ForeignAsRefCallVisitor { |
| 63 | + cx, |
| 64 | + receiver_buckets: FxIndexMap::default(), |
| 65 | + }; |
| 66 | + visitor.visit_block(block); |
| 67 | + |
| 68 | + for bucket in visitor.receiver_buckets.into_values() { |
| 69 | + for calls in &bucket { |
| 70 | + check_calls(cx, calls); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +fn check_calls(cx: &LateContext<'_>, calls: &Calls<'_>) { |
| 78 | + let [first_expr, other_exprs @ ..] = &calls.exprs[..] else { |
| 79 | + return; |
| 80 | + }; |
| 81 | + |
| 82 | + if other_exprs.is_empty() { |
| 83 | + return; |
| 84 | + } |
| 85 | + |
| 86 | + span_lint_and_then( |
| 87 | + cx, |
| 88 | + TRUSTED_ASREF, |
| 89 | + first_expr.span, |
| 90 | + "unsafe block calls `as_ref` multiple times on the same receiver", |
| 91 | + |diag| { |
| 92 | + for expr in other_exprs { |
| 93 | + diag.span_note(expr.span, "called again here"); |
| 94 | + } |
| 95 | + diag.help("consider calling `as_ref()` once and reusing the result to avoid potential unsoundness"); |
| 96 | + }, |
| 97 | + ); |
| 98 | +} |
| 99 | + |
| 100 | +struct Calls<'tcx> { |
| 101 | + receiver: &'tcx hir::Expr<'tcx>, |
| 102 | + exprs: Vec<&'tcx hir::Expr<'tcx>>, |
| 103 | +} |
| 104 | + |
| 105 | +struct ForeignAsRefCallVisitor<'a, 'tcx> { |
| 106 | + cx: &'a LateContext<'tcx>, |
| 107 | + receiver_buckets: FxIndexMap<u64, Vec<Calls<'tcx>>>, |
| 108 | +} |
| 109 | + |
| 110 | +impl<'tcx> Visitor<'tcx> for ForeignAsRefCallVisitor<'_, 'tcx> { |
| 111 | + fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { |
| 112 | + if matches!( |
| 113 | + expr.kind, |
| 114 | + hir::ExprKind::Block( |
| 115 | + hir::Block { |
| 116 | + rules: hir::BlockCheckMode::UnsafeBlock(_), |
| 117 | + .. |
| 118 | + }, |
| 119 | + _ |
| 120 | + ) |
| 121 | + ) { |
| 122 | + return; // Do not descend into nested unsafe block |
| 123 | + } |
| 124 | + |
| 125 | + if let hir::ExprKind::MethodCall(_, receiver, _, _) = expr.kind |
| 126 | + && let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) |
| 127 | + && def_id.opt_parent(self.cx).is_diag_item(self.cx, sym::AsRef) |
| 128 | + && let ty::Param(_) = self.cx.typeck_results().expr_ty(receiver).peel_refs().kind() |
| 129 | + { |
| 130 | + let receiver_bucket = self.receiver_buckets.entry(hash_expr(self.cx, receiver)).or_default(); |
| 131 | + |
| 132 | + let calls = match receiver_bucket |
| 133 | + .iter_mut() |
| 134 | + .find(|calls| SpanlessEq::new(self.cx).eq_expr(receiver.span.ctxt(), calls.receiver, receiver)) |
| 135 | + { |
| 136 | + Some(calls) => calls, |
| 137 | + None => receiver_bucket.push_mut(Calls { |
| 138 | + receiver, |
| 139 | + exprs: Vec::new(), |
| 140 | + }), |
| 141 | + }; |
| 142 | + |
| 143 | + calls.exprs.push(expr); |
| 144 | + } |
| 145 | + |
| 146 | + walk_expr(self, expr); |
| 147 | + } |
| 148 | +} |
0 commit comments