|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use clippy_utils::path_def_id; |
| 3 | +use clippy_utils::ty::is_c_void; |
| 4 | +use rustc_hir::{Expr, ExprKind, QPath}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_middle::ty::RawPtr; |
| 7 | +use rustc_middle::ty::TypeAndMut; |
| 8 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 9 | + |
| 10 | +declare_clippy_lint! { |
| 11 | + /// ### What it does |
| 12 | + /// Checks if we're passing a `c_void` raw pointer to `Box::from_raw(_)` |
| 13 | + /// |
| 14 | + /// ### Why is this bad? |
| 15 | + /// However, it is easy to run into the pitfall of calling from_raw with the c_void pointer. |
| 16 | + /// Note that the definition of, say, Box::from_raw is: |
| 17 | + /// |
| 18 | + /// `pub unsafe fn from_raw(raw: *mut T) -> Box<T>` |
| 19 | + /// |
| 20 | + /// meaning that if you pass a *mut c_void you will get a Box<c_void>. |
| 21 | + /// Per the safety requirements in the documentation, for this to be safe, |
| 22 | + /// c_void would need to have the same memory layout as the original type, which is often not the case. |
| 23 | + /// |
| 24 | + /// ### Example |
| 25 | + /// ```rust |
| 26 | + /// # use std::ffi::c_void; |
| 27 | + /// let ptr = Box::into_raw(Box::new(42usize)) as *mut c_void; |
| 28 | + /// let _ = unsafe { Box::from_raw(ptr) }; |
| 29 | + /// ``` |
| 30 | + /// Use instead: |
| 31 | + /// ```rust |
| 32 | + /// # use std::ffi::c_void; |
| 33 | + /// # let ptr = Box::into_raw(Box::new(42usize)) as *mut c_void; |
| 34 | + /// let _ = unsafe { Box::from_raw(ptr as *mut usize) }; |
| 35 | + /// ``` |
| 36 | + /// |
| 37 | + #[clippy::version = "1.66.0"] |
| 38 | + pub FROM_RAW_WITH_VOID_PTR, |
| 39 | + suspicious, |
| 40 | + "creating a `Box` from a raw void pointer" |
| 41 | +} |
| 42 | +declare_lint_pass!(FromRawWithVoidPtr => [FROM_RAW_WITH_VOID_PTR]); |
| 43 | + |
| 44 | +impl LateLintPass<'_> for FromRawWithVoidPtr { |
| 45 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 46 | + if let ExprKind::Call(box_from_raw, [arg]) = expr.kind |
| 47 | + && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_from_raw.kind |
| 48 | + && seg.ident.name == sym!(from_raw) |
| 49 | + // FIXME: This lint is also applicable to other types, like `Rc`, `Arc` and `Weak`. |
| 50 | + && path_def_id(cx, ty).map_or(false, |id| Some(id) == cx.tcx.lang_items().owned_box()) |
| 51 | + && let arg_kind = cx.typeck_results().expr_ty(arg).kind() |
| 52 | + && let RawPtr(TypeAndMut { ty, .. }) = arg_kind |
| 53 | + && is_c_void(cx, *ty) { |
| 54 | + span_lint_and_help(cx, FROM_RAW_WITH_VOID_PTR, expr.span, "creating a `Box` from a raw void pointer", Some(arg.span), "cast this to a pointer of the actual type"); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments