|
| 1 | +use clippy_utils::{consts::is_promotable, diagnostics::span_lint_and_note, is_from_proc_macro}; |
| 2 | +use rustc_hir::{BorrowKind, Expr, ExprKind, ItemKind, OwnerNode}; |
| 3 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 4 | +use rustc_middle::lint::in_external_macro; |
| 5 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 6 | + |
| 7 | +declare_clippy_lint! { |
| 8 | + /// ### What it does |
| 9 | + /// Checks for raw pointers pointing to temporary values that will **not** be promoted to a |
| 10 | + /// constant through |
| 11 | + /// [constant promotion](https://doc.rust-lang.org/stable/reference/destructors.html#constant-promotion). |
| 12 | + /// |
| 13 | + /// ### Why is this bad? |
| 14 | + /// Usage of such a pointer can result in Undefined Behavior, as the pointer will stop pointing |
| 15 | + /// to valid stack memory once the temporary is dropped. |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```rust,ignore |
| 19 | + /// fn x() -> *const i32 { |
| 20 | + /// let x = 0; |
| 21 | + /// &x as *const i32 |
| 22 | + /// } |
| 23 | + /// |
| 24 | + /// let x = x(); |
| 25 | + /// unsafe { *x }; // ⚠️ |
| 26 | + /// ``` |
| 27 | + #[clippy::version = "1.72.0"] |
| 28 | + pub PTR_TO_TEMPORARY, |
| 29 | + correctness, |
| 30 | + "disallows returning a raw pointer to a temporary value" |
| 31 | +} |
| 32 | +declare_lint_pass!(PtrToTemporary => [PTR_TO_TEMPORARY]); |
| 33 | + |
| 34 | +impl<'tcx> LateLintPass<'tcx> for PtrToTemporary { |
| 35 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { |
| 36 | + if in_external_macro(cx.sess(), expr.span) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + // Get the final return statement if this is a return statement, or don't lint |
| 41 | + let expr = if let ExprKind::Ret(Some(expr)) = expr.kind { |
| 42 | + expr |
| 43 | + } else if let OwnerNode::Item(parent) = cx.tcx.hir().owner(cx.tcx.hir().get_parent_item(expr.hir_id)) |
| 44 | + && let ItemKind::Fn(_, _, body) = parent.kind |
| 45 | + && let block = cx.tcx.hir().body(body).value |
| 46 | + && let ExprKind::Block(block, _) = block.kind |
| 47 | + && let Some(final_block_expr) = block.expr |
| 48 | + && final_block_expr.hir_id == expr.hir_id |
| 49 | + { |
| 50 | + expr |
| 51 | + } else { |
| 52 | + return; |
| 53 | + }; |
| 54 | + |
| 55 | + if let ExprKind::Cast(cast_expr, _) = expr.kind |
| 56 | + && let ExprKind::AddrOf(BorrowKind::Ref, _, e) = cast_expr.kind |
| 57 | + && !is_promotable(cx, e) |
| 58 | + && !is_from_proc_macro(cx, expr) |
| 59 | + { |
| 60 | + span_lint_and_note( |
| 61 | + cx, |
| 62 | + PTR_TO_TEMPORARY, |
| 63 | + expr.span, |
| 64 | + "returning a raw pointer to a temporary value that cannot be promoted to a constant", |
| 65 | + None, |
| 66 | + "usage of this pointer by callers will cause Undefined Behavior", |
| 67 | + ); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments