]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/check_unsafety.rs
Rollup merge of #107519 - joboet:raw_os_error_ty, r=Amanieu
[rust.git] / compiler / rustc_mir_transform / src / check_unsafety.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_errors::struct_span_err;
3 use rustc_hir as hir;
4 use rustc_hir::def::DefKind;
5 use rustc_hir::def_id::{DefId, LocalDefId};
6 use rustc_hir::hir_id::HirId;
7 use rustc_hir::intravisit;
8 use rustc_hir::{BlockCheckMode, ExprKind, Node};
9 use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
10 use rustc_middle::mir::*;
11 use rustc_middle::ty::query::Providers;
12 use rustc_middle::ty::{self, TyCtxt};
13 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
14 use rustc_session::lint::Level;
15
16 use std::ops::Bound;
17
18 pub struct UnsafetyChecker<'a, 'tcx> {
19     body: &'a Body<'tcx>,
20     body_did: LocalDefId,
21     violations: Vec<UnsafetyViolation>,
22     source_info: SourceInfo,
23     tcx: TyCtxt<'tcx>,
24     param_env: ty::ParamEnv<'tcx>,
25
26     /// Used `unsafe` blocks in this function. This is used for the "unused_unsafe" lint.
27     used_unsafe_blocks: FxHashSet<HirId>,
28 }
29
30 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
31     fn new(
32         body: &'a Body<'tcx>,
33         body_did: LocalDefId,
34         tcx: TyCtxt<'tcx>,
35         param_env: ty::ParamEnv<'tcx>,
36     ) -> Self {
37         Self {
38             body,
39             body_did,
40             violations: vec![],
41             source_info: SourceInfo::outermost(body.span),
42             tcx,
43             param_env,
44             used_unsafe_blocks: Default::default(),
45         }
46     }
47 }
48
49 impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> {
50     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
51         self.source_info = terminator.source_info;
52         match terminator.kind {
53             TerminatorKind::Goto { .. }
54             | TerminatorKind::SwitchInt { .. }
55             | TerminatorKind::Drop { .. }
56             | TerminatorKind::Yield { .. }
57             | TerminatorKind::Assert { .. }
58             | TerminatorKind::DropAndReplace { .. }
59             | TerminatorKind::GeneratorDrop
60             | TerminatorKind::Resume
61             | TerminatorKind::Abort
62             | TerminatorKind::Return
63             | TerminatorKind::Unreachable
64             | TerminatorKind::FalseEdge { .. }
65             | TerminatorKind::FalseUnwind { .. } => {
66                 // safe (at least as emitted during MIR construction)
67             }
68
69             TerminatorKind::Call { ref func, .. } => {
70                 let func_ty = func.ty(self.body, self.tcx);
71                 let func_id =
72                     if let ty::FnDef(func_id, _) = func_ty.kind() { Some(func_id) } else { None };
73                 let sig = func_ty.fn_sig(self.tcx);
74                 if let hir::Unsafety::Unsafe = sig.unsafety() {
75                     self.require_unsafe(
76                         UnsafetyViolationKind::General,
77                         UnsafetyViolationDetails::CallToUnsafeFunction,
78                     )
79                 }
80
81                 if let Some(func_id) = func_id {
82                     self.check_target_features(*func_id);
83                 }
84             }
85
86             TerminatorKind::InlineAsm { .. } => self.require_unsafe(
87                 UnsafetyViolationKind::General,
88                 UnsafetyViolationDetails::UseOfInlineAssembly,
89             ),
90         }
91         self.super_terminator(terminator, location);
92     }
93
94     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
95         self.source_info = statement.source_info;
96         match statement.kind {
97             StatementKind::Assign(..)
98             | StatementKind::FakeRead(..)
99             | StatementKind::SetDiscriminant { .. }
100             | StatementKind::Deinit(..)
101             | StatementKind::StorageLive(..)
102             | StatementKind::StorageDead(..)
103             | StatementKind::Retag { .. }
104             | StatementKind::AscribeUserType(..)
105             | StatementKind::Coverage(..)
106             | StatementKind::Intrinsic(..)
107             | StatementKind::ConstEvalCounter
108             | StatementKind::Nop => {
109                 // safe (at least as emitted during MIR construction)
110             }
111         }
112         self.super_statement(statement, location);
113     }
114
115     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
116         match rvalue {
117             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
118                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
119                 &AggregateKind::Adt(adt_did, ..) => {
120                     match self.tcx.layout_scalar_valid_range(adt_did) {
121                         (Bound::Unbounded, Bound::Unbounded) => {}
122                         _ => self.require_unsafe(
123                             UnsafetyViolationKind::General,
124                             UnsafetyViolationDetails::InitializingTypeWith,
125                         ),
126                     }
127                 }
128                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
129                     let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
130                         self.tcx.unsafety_check_result(def_id);
131                     self.register_violations(violations, used_unsafe_blocks.iter().copied());
132                 }
133             },
134             _ => {}
135         }
136         self.super_rvalue(rvalue, location);
137     }
138
139     fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
140         if let Operand::Constant(constant) = op {
141             let maybe_uneval = match constant.literal {
142                 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
143                 ConstantKind::Unevaluated(uv, _) => Some(uv),
144             };
145
146             if let Some(uv) = maybe_uneval {
147                 if uv.promoted.is_none() {
148                     let def_id = uv.def.def_id_for_type_of();
149                     if self.tcx.def_kind(def_id) == DefKind::InlineConst {
150                         let local_def_id = def_id.expect_local();
151                         let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
152                             self.tcx.unsafety_check_result(local_def_id);
153                         self.register_violations(violations, used_unsafe_blocks.iter().copied());
154                     }
155                 }
156             }
157         }
158         self.super_operand(op, location);
159     }
160
161     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
162         // On types with `scalar_valid_range`, prevent
163         // * `&mut x.field`
164         // * `x.field = y;`
165         // * `&x.field` if `field`'s type has interior mutability
166         // because either of these would allow modifying the layout constrained field and
167         // insert values that violate the layout constraints.
168         if context.is_mutating_use() || context.is_borrow() {
169             self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
170         }
171
172         // Some checks below need the extra meta info of the local declaration.
173         let decl = &self.body.local_decls[place.local];
174
175         // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
176         // temporary holding the static pointer to avoid duplicate errors
177         // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
178         if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
179             // If the projection root is an artificial local that we introduced when
180             // desugaring `static`, give a more specific error message
181             // (avoid the general "raw pointer" clause below, that would only be confusing).
182             if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
183                 if self.tcx.is_mutable_static(def_id) {
184                     self.require_unsafe(
185                         UnsafetyViolationKind::General,
186                         UnsafetyViolationDetails::UseOfMutableStatic,
187                     );
188                     return;
189                 } else if self.tcx.is_foreign_item(def_id) {
190                     self.require_unsafe(
191                         UnsafetyViolationKind::General,
192                         UnsafetyViolationDetails::UseOfExternStatic,
193                     );
194                     return;
195                 }
196             }
197         }
198
199         // Check for raw pointer `Deref`.
200         for (base, proj) in place.iter_projections() {
201             if proj == ProjectionElem::Deref {
202                 let base_ty = base.ty(self.body, self.tcx).ty;
203                 if base_ty.is_unsafe_ptr() {
204                     self.require_unsafe(
205                         UnsafetyViolationKind::General,
206                         UnsafetyViolationDetails::DerefOfRawPointer,
207                     )
208                 }
209             }
210         }
211
212         // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
213         // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
214         let mut saw_deref = false;
215         for (base, proj) in place.iter_projections().rev() {
216             if proj == ProjectionElem::Deref {
217                 saw_deref = true;
218                 continue;
219             }
220
221             let base_ty = base.ty(self.body, self.tcx).ty;
222             if base_ty.is_union() {
223                 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
224                 // rules are different.
225                 let assign_to_field = !saw_deref
226                     && matches!(
227                         context,
228                         PlaceContext::MutatingUse(
229                             MutatingUseContext::Store
230                                 | MutatingUseContext::Drop
231                                 | MutatingUseContext::AsmOutput
232                         )
233                     );
234                 // If this is just an assignment, determine if the assigned type needs dropping.
235                 if assign_to_field {
236                     // We have to check the actual type of the assignment, as that determines if the
237                     // old value is being dropped.
238                     let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
239                     if assigned_ty.needs_drop(self.tcx, self.param_env) {
240                         // This would be unsafe, but should be outright impossible since we reject such unions.
241                         self.tcx.sess.delay_span_bug(
242                             self.source_info.span,
243                             format!("union fields that need dropping should be impossible: {assigned_ty}")
244                         );
245                     }
246                 } else {
247                     self.require_unsafe(
248                         UnsafetyViolationKind::General,
249                         UnsafetyViolationDetails::AccessToUnionField,
250                     )
251                 }
252             }
253         }
254     }
255 }
256
257 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
258     fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
259         // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
260         assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
261
262         let source_info = self.source_info;
263         let lint_root = self.body.source_scopes[self.source_info.scope]
264             .local_data
265             .as_ref()
266             .assert_crate_local()
267             .lint_root;
268         self.register_violations(
269             [&UnsafetyViolation { source_info, lint_root, kind, details }],
270             [],
271         );
272     }
273
274     fn register_violations<'a>(
275         &mut self,
276         violations: impl IntoIterator<Item = &'a UnsafetyViolation>,
277         new_used_unsafe_blocks: impl IntoIterator<Item = HirId>,
278     ) {
279         let safety = self.body.source_scopes[self.source_info.scope]
280             .local_data
281             .as_ref()
282             .assert_crate_local()
283             .safety;
284         match safety {
285             // `unsafe` blocks are required in safe code
286             Safety::Safe => violations.into_iter().for_each(|&violation| {
287                 match violation.kind {
288                     UnsafetyViolationKind::General => {}
289                     UnsafetyViolationKind::UnsafeFn => {
290                         bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
291                     }
292                 }
293                 if !self.violations.contains(&violation) {
294                     self.violations.push(violation)
295                 }
296             }),
297             // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
298             Safety::FnUnsafe => violations.into_iter().for_each(|&(mut violation)| {
299                 violation.kind = UnsafetyViolationKind::UnsafeFn;
300                 if !self.violations.contains(&violation) {
301                     self.violations.push(violation)
302                 }
303             }),
304             Safety::BuiltinUnsafe => {}
305             Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|_violation| {
306                 self.used_unsafe_blocks.insert(hir_id);
307             }),
308         };
309
310         new_used_unsafe_blocks.into_iter().for_each(|hir_id| {
311             self.used_unsafe_blocks.insert(hir_id);
312         });
313     }
314     fn check_mut_borrowing_layout_constrained_field(
315         &mut self,
316         place: Place<'tcx>,
317         is_mut_use: bool,
318     ) {
319         for (place_base, elem) in place.iter_projections().rev() {
320             match elem {
321                 // Modifications behind a dereference don't affect the value of
322                 // the pointer.
323                 ProjectionElem::Deref => return,
324                 ProjectionElem::Field(..) => {
325                     let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
326                     if let ty::Adt(def, _) = ty.kind() {
327                         if self.tcx.layout_scalar_valid_range(def.did())
328                             != (Bound::Unbounded, Bound::Unbounded)
329                         {
330                             let details = if is_mut_use {
331                                 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
332
333                             // Check `is_freeze` as late as possible to avoid cycle errors
334                             // with opaque types.
335                             } else if !place
336                                 .ty(self.body, self.tcx)
337                                 .ty
338                                 .is_freeze(self.tcx, self.param_env)
339                             {
340                                 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
341                             } else {
342                                 continue;
343                             };
344                             self.require_unsafe(UnsafetyViolationKind::General, details);
345                         }
346                     }
347                 }
348                 _ => {}
349             }
350         }
351     }
352
353     /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
354     /// the called function has target features the calling function hasn't.
355     fn check_target_features(&mut self, func_did: DefId) {
356         // Unsafety isn't required on wasm targets. For more information see
357         // the corresponding check in typeck/src/collect.rs
358         if self.tcx.sess.target.options.is_like_wasm {
359             return;
360         }
361
362         let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
363         // The body might be a constant, so it doesn't have codegen attributes.
364         let self_features = &self.tcx.body_codegen_attrs(self.body_did.to_def_id()).target_features;
365
366         // Is `callee_features` a subset of `calling_features`?
367         if !callee_features.iter().all(|feature| self_features.contains(feature)) {
368             self.require_unsafe(
369                 UnsafetyViolationKind::General,
370                 UnsafetyViolationDetails::CallToFunctionWith,
371             )
372         }
373     }
374 }
375
376 pub(crate) fn provide(providers: &mut Providers) {
377     *providers = Providers {
378         unsafety_check_result: |tcx, def_id| {
379             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
380                 tcx.unsafety_check_result_for_const_arg(def)
381             } else {
382                 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
383             }
384         },
385         unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
386             unsafety_check_result(
387                 tcx,
388                 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
389             )
390         },
391         ..*providers
392     };
393 }
394
395 /// Context information for [`UnusedUnsafeVisitor`] traversal,
396 /// saves (innermost) relevant context
397 #[derive(Copy, Clone, Debug)]
398 enum Context {
399     Safe,
400     /// in an `unsafe fn`
401     UnsafeFn(HirId),
402     /// in a *used* `unsafe` block
403     /// (i.e. a block without unused-unsafe warning)
404     UnsafeBlock(HirId),
405 }
406
407 struct UnusedUnsafeVisitor<'a, 'tcx> {
408     tcx: TyCtxt<'tcx>,
409     used_unsafe_blocks: &'a FxHashSet<HirId>,
410     context: Context,
411     unused_unsafes: &'a mut Vec<(HirId, UnusedUnsafe)>,
412 }
413
414 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
415     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
416         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
417             let used = match self.tcx.lint_level_at_node(UNUSED_UNSAFE, block.hir_id) {
418                 (Level::Allow, _) => true,
419                 _ => self.used_unsafe_blocks.contains(&block.hir_id),
420             };
421             let unused_unsafe = match (self.context, used) {
422                 (_, false) => UnusedUnsafe::Unused,
423                 (Context::Safe, true) | (Context::UnsafeFn(_), true) => {
424                     let previous_context = self.context;
425                     self.context = Context::UnsafeBlock(block.hir_id);
426                     intravisit::walk_block(self, block);
427                     self.context = previous_context;
428                     return;
429                 }
430                 (Context::UnsafeBlock(hir_id), true) => UnusedUnsafe::InUnsafeBlock(hir_id),
431             };
432             self.unused_unsafes.push((block.hir_id, unused_unsafe));
433         }
434         intravisit::walk_block(self, block);
435     }
436
437     fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
438         if matches!(self.tcx.def_kind(c.def_id), DefKind::InlineConst) {
439             self.visit_body(self.tcx.hir().body(c.body))
440         }
441     }
442
443     fn visit_fn(
444         &mut self,
445         fk: intravisit::FnKind<'tcx>,
446         _fd: &'tcx hir::FnDecl<'tcx>,
447         b: hir::BodyId,
448         _s: rustc_span::Span,
449         _id: LocalDefId,
450     ) {
451         if matches!(fk, intravisit::FnKind::Closure) {
452             self.visit_body(self.tcx.hir().body(b))
453         }
454     }
455 }
456
457 fn check_unused_unsafe(
458     tcx: TyCtxt<'_>,
459     def_id: LocalDefId,
460     used_unsafe_blocks: &FxHashSet<HirId>,
461 ) -> Vec<(HirId, UnusedUnsafe)> {
462     let body_id = tcx.hir().maybe_body_owned_by(def_id);
463
464     let Some(body_id) = body_id else {
465         debug!("check_unused_unsafe({:?}) - no body found", def_id);
466         return vec![];
467     };
468
469     let body = tcx.hir().body(body_id);
470     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
471     let context = match tcx.hir().fn_sig_by_hir_id(hir_id) {
472         Some(sig) if sig.header.unsafety == hir::Unsafety::Unsafe => Context::UnsafeFn(hir_id),
473         _ => Context::Safe,
474     };
475
476     debug!(
477         "check_unused_unsafe({:?}, context={:?}, body={:?}, used_unsafe_blocks={:?})",
478         def_id, body, context, used_unsafe_blocks
479     );
480
481     let mut unused_unsafes = vec![];
482
483     let mut visitor = UnusedUnsafeVisitor {
484         tcx,
485         used_unsafe_blocks,
486         context,
487         unused_unsafes: &mut unused_unsafes,
488     };
489     intravisit::Visitor::visit_body(&mut visitor, body);
490
491     unused_unsafes
492 }
493
494 fn unsafety_check_result(
495     tcx: TyCtxt<'_>,
496     def: ty::WithOptConstParam<LocalDefId>,
497 ) -> &UnsafetyCheckResult {
498     debug!("unsafety_violations({:?})", def);
499
500     // N.B., this borrow is valid because all the consumers of
501     // `mir_built` force this.
502     let body = &tcx.mir_built(def).borrow();
503
504     if body.is_custom_mir() {
505         return tcx.arena.alloc(UnsafetyCheckResult {
506             violations: Vec::new(),
507             used_unsafe_blocks: FxHashSet::default(),
508             unused_unsafes: Some(Vec::new()),
509         });
510     }
511
512     let param_env = tcx.param_env(def.did);
513
514     let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
515     checker.visit_body(&body);
516
517     let unused_unsafes = (!tcx.is_typeck_child(def.did.to_def_id()))
518         .then(|| check_unused_unsafe(tcx, def.did, &checker.used_unsafe_blocks));
519
520     tcx.arena.alloc(UnsafetyCheckResult {
521         violations: checker.violations,
522         used_unsafe_blocks: checker.used_unsafe_blocks,
523         unused_unsafes,
524     })
525 }
526
527 fn report_unused_unsafe(tcx: TyCtxt<'_>, kind: UnusedUnsafe, id: HirId) {
528     let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
529     let msg = "unnecessary `unsafe` block";
530     tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg, |lint| {
531         lint.span_label(span, msg);
532         match kind {
533             UnusedUnsafe::Unused => {}
534             UnusedUnsafe::InUnsafeBlock(id) => {
535                 lint.span_label(
536                     tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
537                     "because it's nested under this `unsafe` block",
538                 );
539             }
540         }
541
542         lint
543     });
544 }
545
546 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
547     debug!("check_unsafety({:?})", def_id);
548
549     // closures and inline consts are handled by their parent fn.
550     if tcx.is_typeck_child(def_id.to_def_id()) {
551         return;
552     }
553
554     let UnsafetyCheckResult { violations, unused_unsafes, .. } = tcx.unsafety_check_result(def_id);
555
556     for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
557         let (description, note) = details.description_and_note();
558
559         match kind {
560             UnsafetyViolationKind::General => {
561                 // once
562                 let unsafe_fn_msg = if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) {
563                     " function or"
564                 } else {
565                     ""
566                 };
567
568                 let mut err = struct_span_err!(
569                     tcx.sess,
570                     source_info.span,
571                     E0133,
572                     "{} is unsafe and requires unsafe{} block",
573                     description,
574                     unsafe_fn_msg,
575                 );
576                 err.span_label(source_info.span, description).note(note);
577                 let note_non_inherited = tcx.hir().parent_iter(lint_root).find(|(id, node)| {
578                     if let Node::Expr(block) = node
579                         && let ExprKind::Block(block, _) = block.kind
580                         && let BlockCheckMode::UnsafeBlock(_) = block.rules
581                     {
582                         true
583                     }
584                     else if let Some(sig) = tcx.hir().fn_sig_by_hir_id(*id)
585                         && sig.header.is_unsafe()
586                     {
587                         true
588                     } else {
589                         false
590                     }
591                 });
592                 if let Some((id, _)) = note_non_inherited {
593                     let span = tcx.hir().span(id);
594                     err.span_label(
595                         tcx.sess.source_map().guess_head_span(span),
596                         "items do not inherit unsafety from separate enclosing items",
597                     );
598                 }
599
600                 err.emit();
601             }
602             UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
603                 UNSAFE_OP_IN_UNSAFE_FN,
604                 lint_root,
605                 source_info.span,
606                 format!("{} is unsafe and requires unsafe block (error E0133)", description,),
607                 |lint| lint.span_label(source_info.span, description).note(note),
608             ),
609         }
610     }
611
612     for &(block_id, kind) in unused_unsafes.as_ref().unwrap() {
613         report_unused_unsafe(tcx, kind, block_id);
614     }
615 }
616
617 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
618     tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow
619 }