|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use clippy_utils::sym; |
| 3 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 4 | +use rustc_hir::{Expr, ExprKind}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_middle::ty::layout::LayoutOf; |
| 7 | +use rustc_middle::ty::{self, Ty, TypeVisitableExt}; |
| 8 | +use rustc_session::declare_lint_pass; |
| 9 | + |
| 10 | +declare_clippy_lint! { |
| 11 | + /// ### What it does |
| 12 | + /// |
| 13 | + /// This lint warns when volatile load/store operations |
| 14 | + /// (`write_volatile`/`read_volatile`) are applied to composite types. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// |
| 18 | + /// Volatile operations are typically used with memory mapped IO devices, |
| 19 | + /// where the precise number and ordering of load and store instructions is |
| 20 | + /// important because they can have side effects. This is well defined for |
| 21 | + /// primitive types like `u32`, but less well defined for structures and |
| 22 | + /// other composite types. In practice it's implementation defined, and the |
| 23 | + /// behavior can be rustc-version dependent. |
| 24 | + /// |
| 25 | + /// As a result, code should only apply `write_volatile`/`read_volatile` to |
| 26 | + /// primitive types to be fully well-defined. |
| 27 | + /// |
| 28 | + /// ### Example |
| 29 | + /// ```no_run |
| 30 | + /// struct MyDevice { |
| 31 | + /// addr: usize, |
| 32 | + /// count: usize |
| 33 | + /// } |
| 34 | + /// |
| 35 | + /// fn start_device(device: *mut MyDevice, addr: usize, count: usize) { |
| 36 | + /// unsafe { |
| 37 | + /// device.write_volatile(MyDevice { addr, count }); |
| 38 | + /// } |
| 39 | + /// } |
| 40 | + /// ``` |
| 41 | + /// Instead, operate on each primtive field individually: |
| 42 | + /// ```no_run |
| 43 | + /// struct MyDevice { |
| 44 | + /// addr: usize, |
| 45 | + /// count: usize |
| 46 | + /// } |
| 47 | + /// |
| 48 | + /// fn start_device(device: *mut MyDevice, addr: usize, count: usize) { |
| 49 | + /// unsafe { |
| 50 | + /// (&raw mut (*device).addr).write_volatile(addr); |
| 51 | + /// (&raw mut (*device).count).write_volatile(count); |
| 52 | + /// } |
| 53 | + /// } |
| 54 | + /// ``` |
| 55 | + #[clippy::version = "1.92.0"] |
| 56 | + pub VOLATILE_COMPOSITES, |
| 57 | + nursery, |
| 58 | + "warn about volatile read/write applied to composite types" |
| 59 | +} |
| 60 | +declare_lint_pass!(VolatileComposites => [VOLATILE_COMPOSITES]); |
| 61 | + |
| 62 | +/// Zero-sized types are intrinsically safe to use volatile on since they won't |
| 63 | +/// actually generate *any* loads or stores. But this is also used to skip zero-sized |
| 64 | +/// fields of `#[repr(transparent)]` structures. |
| 65 | +fn is_zero_sized_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { |
| 66 | + cx.layout_of(ty).is_ok_and(|layout| layout.is_zst()) |
| 67 | +} |
| 68 | + |
| 69 | +/// A thin raw pointer or reference. |
| 70 | +fn is_narrow_ptr<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { |
| 71 | + match ty.kind() { |
| 72 | + ty::RawPtr(inner, _) | ty::Ref(_, inner, _) => inner.has_trivial_sizedness(cx.tcx, ty::SizedTraitKind::Sized), |
| 73 | + _ => false, |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/// Enum with some fixed representation and no data-carrying variants. |
| 78 | +fn is_enum_repr_c<'tcx>(_cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { |
| 79 | + ty.ty_adt_def().is_some_and(|adt_def| { |
| 80 | + adt_def.is_enum() && adt_def.repr().inhibit_struct_field_reordering() && adt_def.is_payloadfree() |
| 81 | + }) |
| 82 | +} |
| 83 | + |
| 84 | +/// `#[repr(transparent)]` structures are also OK if the only non-zero |
| 85 | +/// sized field contains a volatile-safe type. |
| 86 | +fn is_struct_repr_transparent<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { |
| 87 | + if let ty::Adt(adt_def, args) = ty.kind() |
| 88 | + && adt_def.is_struct() |
| 89 | + && adt_def.repr().transparent() |
| 90 | + && let [fieldty] = adt_def |
| 91 | + .all_fields() |
| 92 | + .filter_map(|field| { |
| 93 | + let fty = field.ty(cx.tcx, args); |
| 94 | + if is_zero_sized_ty(cx, fty) { None } else { Some(fty) } |
| 95 | + }) |
| 96 | + .collect::<Vec<_>>() |
| 97 | + .as_slice() |
| 98 | + { |
| 99 | + is_volatile_safe_ty(cx, *fieldty) |
| 100 | + } else { |
| 101 | + false |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +/// SIMD can be useful to get larger single loads/stores, though this is still |
| 106 | +/// pretty machine-dependent. |
| 107 | +fn is_simd_repr<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { |
| 108 | + if let ty::Adt(adt_def, _args) = ty.kind() |
| 109 | + && adt_def.is_struct() |
| 110 | + && adt_def.repr().simd() |
| 111 | + { |
| 112 | + let (_size, simdty) = ty.simd_size_and_type(cx.tcx); |
| 113 | + is_volatile_safe_ty(cx, simdty) |
| 114 | + } else { |
| 115 | + false |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +/// Top-level predicate for whether a type is volatile-safe or not. |
| 120 | +fn is_volatile_safe_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { |
| 121 | + ty.is_primitive() |
| 122 | + || is_narrow_ptr(cx, ty) |
| 123 | + || is_zero_sized_ty(cx, ty) |
| 124 | + || is_enum_repr_c(cx, ty) |
| 125 | + || is_simd_repr(cx, ty) |
| 126 | + || is_struct_repr_transparent(cx, ty) |
| 127 | + // We can't know about a generic type, so just let it pass to avoid noise |
| 128 | + || ty.has_non_region_param() |
| 129 | +} |
| 130 | + |
| 131 | +/// Print diagnostic for volatile read/write on non-volatile-safe types. |
| 132 | +fn report_volatile_safe<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, ty: Ty<'tcx>) { |
| 133 | + if !is_volatile_safe_ty(cx, ty) { |
| 134 | + span_lint( |
| 135 | + cx, |
| 136 | + VOLATILE_COMPOSITES, |
| 137 | + expr.span, |
| 138 | + format!("type `{ty}` is not volatile-compatible"), |
| 139 | + ); |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +impl<'tcx> LateLintPass<'tcx> for VolatileComposites { |
| 144 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { |
| 145 | + // Check our expr is calling a method with pattern matching |
| 146 | + match expr.kind { |
| 147 | + // Look for method calls to `write_volatile`/`read_volatile`, which |
| 148 | + // apply to both raw pointers and std::ptr::NonNull. |
| 149 | + ExprKind::MethodCall(name, self_arg, _, _) |
| 150 | + if matches!(name.ident.name, sym::read_volatile | sym::write_volatile) => |
| 151 | + { |
| 152 | + let self_ty = cx.typeck_results().expr_ty(self_arg); |
| 153 | + match self_ty.kind() { |
| 154 | + // Raw pointers |
| 155 | + ty::RawPtr(innerty, _) => report_volatile_safe(cx, expr, *innerty), |
| 156 | + // std::ptr::NonNull |
| 157 | + ty::Adt(_, args) if is_type_diagnostic_item(cx, self_ty, sym::NonNull) => { |
| 158 | + report_volatile_safe(cx, expr, args.type_at(0)); |
| 159 | + }, |
| 160 | + _ => (), |
| 161 | + } |
| 162 | + }, |
| 163 | + |
| 164 | + // Also plain function calls to std::ptr::{read,write}_volatile |
| 165 | + ExprKind::Call(func, [arg_ptr, ..]) => { |
| 166 | + if let ExprKind::Path(ref qpath) = func.kind |
| 167 | + && let Some(def_id) = cx.qpath_res(qpath, func.hir_id).opt_def_id() |
| 168 | + && matches!( |
| 169 | + cx.tcx.get_diagnostic_name(def_id), |
| 170 | + Some(sym::ptr_read_volatile | sym::ptr_write_volatile) |
| 171 | + ) |
| 172 | + && let ty::RawPtr(ptrty, _) = cx.typeck_results().expr_ty_adjusted(arg_ptr).kind() |
| 173 | + { |
| 174 | + report_volatile_safe(cx, expr, *ptrty); |
| 175 | + } |
| 176 | + }, |
| 177 | + _ => {}, |
| 178 | + } |
| 179 | + } |
| 180 | +} |
0 commit comments