|
| 1 | +use clippy_utils::diagnostics::span_lint_and_note; |
| 2 | +use clippy_utils::{is_uninit_ty_valid, match_def_path, path_to_local_id, paths, peel_hir_expr_while, SpanlessEq}; |
| 3 | +use rustc_hir::def::Res; |
| 4 | +use rustc_hir::{Block, Expr, ExprKind, HirId, PatKind, Stmt, StmtKind}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_middle::ty; |
| 7 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 8 | +use rustc_span::Span; |
| 9 | + |
| 10 | +declare_clippy_lint! { |
| 11 | + /// ### What it does |
| 12 | + /// Checks for the creation of uninitialized `Vec<T>` by calling `set_len()` |
| 13 | + /// immediately after `with_capacity()` or `reserve()`. |
| 14 | + /// |
| 15 | + /// ### Why is this bad? |
| 16 | + /// It creates `Vec<T>` that contains uninitialized data, which leads to an |
| 17 | + /// undefined behavior with most safe operations. |
| 18 | + /// Notably, using uninitialized `Vec<u8>` with generic `Read` is unsound. |
| 19 | + /// |
| 20 | + /// ### Example |
| 21 | + /// ```rust,ignore |
| 22 | + /// let mut vec: Vec<u8> = Vec::with_capacity(1000); |
| 23 | + /// unsafe { vec.set_len(1000); } |
| 24 | + /// reader.read(&mut vec); // undefined behavior! |
| 25 | + /// ``` |
| 26 | + /// Use an initialized buffer: |
| 27 | + /// ```rust,ignore |
| 28 | + /// let mut vec: Vec<u8> = vec![0; 1000]; |
| 29 | + /// reader.read(&mut vec); |
| 30 | + /// ``` |
| 31 | + /// Or, wrap the content in `MaybeUninit`: |
| 32 | + /// ```rust,ignore |
| 33 | + /// let mut vec: Vec<MaybeUninit<T>> = Vec::with_capacity(1000); |
| 34 | + /// unsafe { vec.set_len(1000); } |
| 35 | + /// ``` |
| 36 | + pub UNINIT_VEC, |
| 37 | + correctness, |
| 38 | + "Vec with uninitialized data" |
| 39 | +} |
| 40 | + |
| 41 | +declare_lint_pass!(UninitVec => [UNINIT_VEC]); |
| 42 | + |
| 43 | +impl<'tcx> LateLintPass<'tcx> for UninitVec { |
| 44 | + fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'_>) { |
| 45 | + for w in block.stmts.windows(2) { |
| 46 | + if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = w[1].kind { |
| 47 | + handle_pair(cx, &w[0], expr); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + if let (Some(stmt), Some(expr)) = (block.stmts.last(), block.expr) { |
| 52 | + handle_pair(cx, stmt, expr); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +fn handle_pair(cx: &LateContext<'tcx>, first: &'tcx Stmt<'tcx>, second: &'tcx Expr<'tcx>) { |
| 58 | + if_chain! { |
| 59 | + if let Some(vec) = extract_with_capacity_or_reserve_target(cx, first); |
| 60 | + if let Some((set_len_self, call_span)) = extract_set_len_self(cx, second); |
| 61 | + if vec.eq_expr(cx, set_len_self); |
| 62 | + if let ty::Ref(_, vec_ty, _) = cx.typeck_results().expr_ty_adjusted(set_len_self).kind(); |
| 63 | + if let ty::Adt(_, substs) = vec_ty.kind(); |
| 64 | + // Check T of Vec<T> |
| 65 | + if !is_uninit_ty_valid(cx, substs.type_at(0)); |
| 66 | + then { |
| 67 | + span_lint_and_note( |
| 68 | + cx, |
| 69 | + UNINIT_VEC, |
| 70 | + call_span, |
| 71 | + "calling `set_len()` immediately after reserving a buffer creates uninitialized values", |
| 72 | + Some(first.span), |
| 73 | + "the buffer is reserved here" |
| 74 | + ); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +#[derive(Clone, Copy, Debug)] |
| 80 | +enum LocalOrExpr<'tcx> { |
| 81 | + Local(HirId), |
| 82 | + Expr(&'tcx Expr<'tcx>), |
| 83 | +} |
| 84 | + |
| 85 | +impl<'tcx> LocalOrExpr<'tcx> { |
| 86 | + fn eq_expr(self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { |
| 87 | + match self { |
| 88 | + LocalOrExpr::Local(hir_id) => path_to_local_id(expr, hir_id), |
| 89 | + LocalOrExpr::Expr(self_expr) => SpanlessEq::new(cx).eq_expr(self_expr, expr), |
| 90 | + } |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +/// Returns the target vec of Vec::with_capacity() or Vec::reserve() |
| 95 | +fn extract_with_capacity_or_reserve_target(cx: &LateContext<'_>, stmt: &'tcx Stmt<'_>) -> Option<LocalOrExpr<'tcx>> { |
| 96 | + match stmt.kind { |
| 97 | + StmtKind::Local(local) => { |
| 98 | + // let mut x = Vec::with_capacity() |
| 99 | + if_chain! { |
| 100 | + if let Some(init_expr) = local.init; |
| 101 | + if let PatKind::Binding(_, hir_id, _, None) = local.pat.kind; |
| 102 | + if is_with_capacity(cx, init_expr); |
| 103 | + then { |
| 104 | + Some(LocalOrExpr::Local(hir_id)) |
| 105 | + } else { |
| 106 | + None |
| 107 | + } |
| 108 | + } |
| 109 | + }, |
| 110 | + StmtKind::Expr(expr) | StmtKind::Semi(expr) => { |
| 111 | + match expr.kind { |
| 112 | + ExprKind::Assign(lhs, rhs, _span) if is_with_capacity(cx, rhs) => { |
| 113 | + // self.vec = Vec::with_capacity() |
| 114 | + Some(LocalOrExpr::Expr(lhs)) |
| 115 | + }, |
| 116 | + ExprKind::MethodCall(_, _, [vec_expr, _], _) => { |
| 117 | + // self.vec.reserve() |
| 118 | + if_chain! { |
| 119 | + if let Some(id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); |
| 120 | + if match_def_path(cx, id, &paths::VEC_RESERVE); |
| 121 | + then { |
| 122 | + Some(LocalOrExpr::Expr(vec_expr)) |
| 123 | + } else { |
| 124 | + None |
| 125 | + } |
| 126 | + } |
| 127 | + }, |
| 128 | + _ => None, |
| 129 | + } |
| 130 | + }, |
| 131 | + _ => None, |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +fn is_with_capacity(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> bool { |
| 136 | + if_chain! { |
| 137 | + if let ExprKind::Call(path_expr, _) = &expr.kind; |
| 138 | + if let ExprKind::Path(qpath) = &path_expr.kind; |
| 139 | + if let Res::Def(_, def_id) = cx.qpath_res(qpath, path_expr.hir_id); |
| 140 | + then { |
| 141 | + match_def_path(cx, def_id, &paths::VEC_WITH_CAPACITY) |
| 142 | + } else { |
| 143 | + false |
| 144 | + } |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +/// Returns self if the expression is Vec::set_len() |
| 149 | +fn extract_set_len_self(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> Option<(&'tcx Expr<'tcx>, Span)> { |
| 150 | + // peel unsafe blocks in `unsafe { vec.set_len() }` |
| 151 | + let expr = peel_hir_expr_while(expr, |e| { |
| 152 | + if let ExprKind::Block(block, _) = e.kind { |
| 153 | + match (block.stmts.get(0).map(|stmt| &stmt.kind), block.expr) { |
| 154 | + (None, Some(expr)) => Some(expr), |
| 155 | + (Some(StmtKind::Expr(expr) | StmtKind::Semi(expr)), None) => Some(expr), |
| 156 | + _ => None, |
| 157 | + } |
| 158 | + } else { |
| 159 | + None |
| 160 | + } |
| 161 | + }); |
| 162 | + match expr.kind { |
| 163 | + ExprKind::MethodCall(_, _, [vec_expr, _], _) => { |
| 164 | + cx.typeck_results().type_dependent_def_id(expr.hir_id).and_then(|id| { |
| 165 | + if match_def_path(cx, id, &paths::VEC_SET_LEN) { |
| 166 | + Some((vec_expr, expr.span)) |
| 167 | + } else { |
| 168 | + None |
| 169 | + } |
| 170 | + }) |
| 171 | + }, |
| 172 | + _ => None, |
| 173 | + } |
| 174 | +} |
0 commit comments