]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / non_send_fields_in_send_ty.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet;
3 use clippy_utils::ty::{implements_trait, is_copy};
4 use clippy_utils::{is_lint_allowed, match_def_path, paths};
5 use rustc_ast::ImplPolarity;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::{FieldDef, Item, ItemKind, Node};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty::{self, subst::GenericArgKind, Ty};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::sym;
13
14 declare_clippy_lint! {
15 /// ### What it does
16 /// This lint warns about a `Send` implementation for a type that
17 /// contains fields that are not safe to be sent across threads.
18 /// It tries to detect fields that can cause a soundness issue
19 /// when sent to another thread (e.g., `Rc`) while allowing `!Send` fields
20 /// that are expected to exist in a `Send` type, such as raw pointers.
21 ///
22 /// ### Why is this bad?
23 /// Sending the struct to another thread effectively sends all of its fields,
24 /// and the fields that do not implement `Send` can lead to soundness bugs
25 /// such as data races when accessed in a thread
26 /// that is different from the thread that created it.
27 ///
28 /// See:
29 /// * [*The Rustonomicon* about *Send and Sync*](https://doc.rust-lang.org/nomicon/send-and-sync.html)
30 /// * [The documentation of `Send`](https://doc.rust-lang.org/std/marker/trait.Send.html)
31 ///
32 /// ### Known Problems
33 /// This lint relies on heuristics to distinguish types that are actually
34 /// unsafe to be sent across threads and `!Send` types that are expected to
35 /// exist in `Send` type. Its rule can filter out basic cases such as
36 /// `Vec<*const T>`, but it's not perfect. Feel free to create an issue if
37 /// you have a suggestion on how this heuristic can be improved.
38 ///
39 /// ### Example
40 /// ```rust,ignore
41 /// struct ExampleStruct<T> {
42 /// rc_is_not_send: Rc<String>,
43 /// unbounded_generic_field: T,
44 /// }
45 ///
46 /// // This impl is unsound because it allows sending `!Send` types through `ExampleStruct`
47 /// unsafe impl<T> Send for ExampleStruct<T> {}
48 /// ```
49 /// Use thread-safe types like [`std::sync::Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html)
50 /// or specify correct bounds on generic type parameters (`T: Send`).
51 #[clippy::version = "1.57.0"]
52 pub NON_SEND_FIELDS_IN_SEND_TY,
53 nursery,
54 "there is a field that is not safe to be sent to another thread in a `Send` struct"
55 }
56
57 #[derive(Copy, Clone)]
58 pub struct NonSendFieldInSendTy {
59 enable_raw_pointer_heuristic: bool,
60 }
61
62 impl NonSendFieldInSendTy {
63 pub fn new(enable_raw_pointer_heuristic: bool) -> Self {
64 Self {
65 enable_raw_pointer_heuristic,
66 }
67 }
68 }
69
70 impl_lint_pass!(NonSendFieldInSendTy => [NON_SEND_FIELDS_IN_SEND_TY]);
71
72 impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy {
73 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
74 let ty_allowed_in_send = if self.enable_raw_pointer_heuristic {
75 ty_allowed_with_raw_pointer_heuristic
76 } else {
77 ty_allowed_without_raw_pointer_heuristic
78 };
79
80 // Checks if we are in `Send` impl item.
81 // We start from `Send` impl instead of `check_field_def()` because
82 // single `AdtDef` may have multiple `Send` impls due to generic
83 // parameters, and the lint is much easier to implement in this way.
84 if_chain! {
85 if !in_external_macro(cx.tcx.sess, item.span);
86 if let Some(send_trait) = cx.tcx.get_diagnostic_item(sym::Send);
87 if let ItemKind::Impl(hir_impl) = &item.kind;
88 if let Some(trait_ref) = &hir_impl.of_trait;
89 if let Some(trait_id) = trait_ref.trait_def_id();
90 if send_trait == trait_id;
91 if hir_impl.polarity == ImplPolarity::Positive;
92 if let Some(ty_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id);
93 if let self_ty = ty_trait_ref.subst_identity().self_ty();
94 if let ty::Adt(adt_def, impl_trait_substs) = self_ty.kind();
95 then {
96 let mut non_send_fields = Vec::new();
97
98 let hir_map = cx.tcx.hir();
99 for variant in adt_def.variants() {
100 for field in &variant.fields {
101 if_chain! {
102 if let Some(field_hir_id) = field
103 .did
104 .as_local()
105 .map(|local_def_id| hir_map.local_def_id_to_hir_id(local_def_id));
106 if !is_lint_allowed(cx, NON_SEND_FIELDS_IN_SEND_TY, field_hir_id);
107 if let field_ty = field.ty(cx.tcx, impl_trait_substs);
108 if !ty_allowed_in_send(cx, field_ty, send_trait);
109 if let Node::Field(field_def) = hir_map.get(field_hir_id);
110 then {
111 non_send_fields.push(NonSendField {
112 def: field_def,
113 ty: field_ty,
114 generic_params: collect_generic_params(field_ty),
115 })
116 }
117 }
118 }
119 }
120
121 if !non_send_fields.is_empty() {
122 span_lint_and_then(
123 cx,
124 NON_SEND_FIELDS_IN_SEND_TY,
125 item.span,
126 &format!(
127 "some fields in `{}` are not safe to be sent to another thread",
128 snippet(cx, hir_impl.self_ty.span, "Unknown")
129 ),
130 |diag| {
131 for field in non_send_fields {
132 diag.span_note(
133 field.def.span,
134 format!("it is not safe to send field `{}` to another thread", field.def.ident.name),
135 );
136
137 match field.generic_params.len() {
138 0 => diag.help("use a thread-safe type that implements `Send`"),
139 1 if is_ty_param(field.ty) => diag.help(format!("add `{}: Send` bound in `Send` impl", field.ty)),
140 _ => diag.help(format!(
141 "add bounds on type parameter{} `{}` that satisfy `{}: Send`",
142 if field.generic_params.len() > 1 { "s" } else { "" },
143 field.generic_params_string(),
144 snippet(cx, field.def.ty.span, "Unknown"),
145 )),
146 };
147 }
148 },
149 );
150 }
151 }
152 }
153 }
154 }
155
156 struct NonSendField<'tcx> {
157 def: &'tcx FieldDef<'tcx>,
158 ty: Ty<'tcx>,
159 generic_params: Vec<Ty<'tcx>>,
160 }
161
162 impl<'tcx> NonSendField<'tcx> {
163 fn generic_params_string(&self) -> String {
164 self.generic_params
165 .iter()
166 .map(ToString::to_string)
167 .collect::<Vec<_>>()
168 .join(", ")
169 }
170 }
171
172 /// Given a type, collect all of its generic parameters.
173 /// Example: `MyStruct<P, Box<Q, R>>` => `vec![P, Q, R]`
174 fn collect_generic_params(ty: Ty<'_>) -> Vec<Ty<'_>> {
175 ty.walk()
176 .filter_map(|inner| match inner.unpack() {
177 GenericArgKind::Type(inner_ty) => Some(inner_ty),
178 _ => None,
179 })
180 .filter(|&inner_ty| is_ty_param(inner_ty))
181 .collect()
182 }
183
184 /// Be more strict when the heuristic is disabled
185 fn ty_allowed_without_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, send_trait: DefId) -> bool {
186 if implements_trait(cx, ty, send_trait, &[]) {
187 return true;
188 }
189
190 if is_copy(cx, ty) && !contains_pointer_like(cx, ty) {
191 return true;
192 }
193
194 false
195 }
196
197 /// Heuristic to allow cases like `Vec<*const u8>`
198 fn ty_allowed_with_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, send_trait: DefId) -> bool {
199 if implements_trait(cx, ty, send_trait, &[]) || is_copy(cx, ty) {
200 return true;
201 }
202
203 // The type is known to be `!Send` and `!Copy`
204 match ty.kind() {
205 ty::Tuple(fields) => fields
206 .iter()
207 .all(|ty| ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait)),
208 ty::Array(ty, _) | ty::Slice(ty) => ty_allowed_with_raw_pointer_heuristic(cx, *ty, send_trait),
209 ty::Adt(_, substs) => {
210 if contains_pointer_like(cx, ty) {
211 // descends only if ADT contains any raw pointers
212 substs.iter().all(|generic_arg| match generic_arg.unpack() {
213 GenericArgKind::Type(ty) => ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait),
214 // Lifetimes and const generics are not solid part of ADT and ignored
215 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => true,
216 })
217 } else {
218 false
219 }
220 },
221 // Raw pointers are `!Send` but allowed by the heuristic
222 ty::RawPtr(_) => true,
223 _ => false,
224 }
225 }
226
227 /// Checks if the type contains any pointer-like types in substs (including nested ones)
228 fn contains_pointer_like<'tcx>(cx: &LateContext<'tcx>, target_ty: Ty<'tcx>) -> bool {
229 for ty_node in target_ty.walk() {
230 if let GenericArgKind::Type(inner_ty) = ty_node.unpack() {
231 match inner_ty.kind() {
232 ty::RawPtr(_) => {
233 return true;
234 },
235 ty::Adt(adt_def, _) => {
236 if match_def_path(cx, adt_def.did(), &paths::PTR_NON_NULL) {
237 return true;
238 }
239 },
240 _ => (),
241 }
242 }
243 }
244
245 false
246 }
247
248 /// Returns `true` if the type is a type parameter such as `T`.
249 fn is_ty_param(target_ty: Ty<'_>) -> bool {
250 matches!(target_ty.kind(), ty::Param(_))
251 }