|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use rustc_ast::BinOpKind; |
| 3 | +use rustc_hir::{Expr, ExprKind}; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_middle::ty::{self}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// Checks for the usage of division (/) and remainder (%) operations |
| 11 | + /// when performed on any integer types using the default Div and Rem trait implementations. |
| 12 | + /// |
| 13 | + /// ### Why is this bad? |
| 14 | + /// In cryptographic contexts, division can result in timing sidechannel vulnerabilities, |
| 15 | + /// and needs to be replaced with constant-time code instead (e.g. Barrett reduction). |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```no_run |
| 19 | + /// let my_div = 10 / 2; |
| 20 | + /// ``` |
| 21 | + /// Use instead: |
| 22 | + /// ```no_run |
| 23 | + /// let my_div = 10 >> 1; |
| 24 | + /// ``` |
| 25 | + #[clippy::version = "1.78.0"] |
| 26 | + pub INTEGER_DIVISION_REMAINDER_USED, |
| 27 | + restriction, |
| 28 | + "use of disallowed default division and remainder operations" |
| 29 | +} |
| 30 | + |
| 31 | +declare_lint_pass!(IntegerDivisionRemainderUsed => [INTEGER_DIVISION_REMAINDER_USED]); |
| 32 | + |
| 33 | +impl LateLintPass<'_> for IntegerDivisionRemainderUsed { |
| 34 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 35 | + if let ExprKind::Binary(op, lhs, rhs) = &expr.kind |
| 36 | + && let BinOpKind::Div | BinOpKind::Rem = op.node |
| 37 | + && let lhs_ty = cx.typeck_results().expr_ty(lhs) |
| 38 | + && let rhs_ty = cx.typeck_results().expr_ty(rhs) |
| 39 | + && let ty::Int(_) | ty::Uint(_) = lhs_ty.peel_refs().kind() |
| 40 | + && let ty::Int(_) | ty::Uint(_) = rhs_ty.peel_refs().kind() |
| 41 | + { |
| 42 | + span_lint( |
| 43 | + cx, |
| 44 | + INTEGER_DIVISION_REMAINDER_USED, |
| 45 | + expr.span.source_callsite(), |
| 46 | + &format!("use of {} has been disallowed in this context", op.node.as_str()), |
| 47 | + ); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments