]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/naked_functions.rs
Rollup merge of #102127 - TaKO8Ki:use-appropriate-variable-names, r=lcnr
[rust.git] / compiler / rustc_passes / src / naked_functions.rs
1 //! Checks validity of naked functions.
2
3 use rustc_ast::InlineAsmOptions;
4 use rustc_errors::{struct_span_err, Applicability};
5 use rustc_hir as hir;
6 use rustc_hir::def::DefKind;
7 use rustc_hir::def_id::LocalDefId;
8 use rustc_hir::intravisit::Visitor;
9 use rustc_hir::{ExprKind, InlineAsmOperand, StmtKind};
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_session::lint::builtin::UNDEFINED_NAKED_FUNCTION_ABI;
13 use rustc_span::symbol::sym;
14 use rustc_span::Span;
15 use rustc_target::spec::abi::Abi;
16
17 pub(crate) fn provide(providers: &mut Providers) {
18     *providers = Providers { check_mod_naked_functions, ..*providers };
19 }
20
21 fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
22     let items = tcx.hir_module_items(module_def_id);
23     for def_id in items.definitions() {
24         if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
25             continue;
26         }
27
28         let naked = tcx.has_attr(def_id.to_def_id(), sym::naked);
29         if !naked {
30             continue;
31         }
32
33         let (fn_header, body_id) = match tcx.hir().get_by_def_id(def_id) {
34             hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })
35             | hir::Node::TraitItem(hir::TraitItem {
36                 kind: hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)),
37                 ..
38             })
39             | hir::Node::ImplItem(hir::ImplItem {
40                 kind: hir::ImplItemKind::Fn(sig, body_id),
41                 ..
42             }) => (sig.header, *body_id),
43             _ => continue,
44         };
45
46         let body = tcx.hir().body(body_id);
47         check_abi(tcx, def_id, fn_header.abi);
48         check_no_patterns(tcx, body.params);
49         check_no_parameters_use(tcx, body);
50         check_asm(tcx, def_id, body);
51         check_inline(tcx, def_id);
52     }
53 }
54
55 /// Check that the function isn't inlined.
56 fn check_inline(tcx: TyCtxt<'_>, def_id: LocalDefId) {
57     let attrs = tcx.get_attrs(def_id.to_def_id(), sym::inline);
58     for attr in attrs {
59         tcx.sess.struct_span_err(attr.span, "naked functions cannot be inlined").emit();
60     }
61 }
62
63 /// Checks that function uses non-Rust ABI.
64 fn check_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, abi: Abi) {
65     if abi == Abi::Rust {
66         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
67         let span = tcx.def_span(def_id);
68         tcx.struct_span_lint_hir(UNDEFINED_NAKED_FUNCTION_ABI, hir_id, span, |lint| {
69             lint.build("Rust ABI is unsupported in naked functions").emit();
70         });
71     }
72 }
73
74 /// Checks that parameters don't use patterns. Mirrors the checks for function declarations.
75 fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) {
76     for param in params {
77         match param.pat.kind {
78             hir::PatKind::Wild
79             | hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, _, None) => {}
80             _ => {
81                 tcx.sess
82                     .struct_span_err(
83                         param.pat.span,
84                         "patterns not allowed in naked function parameters",
85                     )
86                     .emit();
87             }
88         }
89     }
90 }
91
92 /// Checks that function parameters aren't used in the function body.
93 fn check_no_parameters_use<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>) {
94     let mut params = hir::HirIdSet::default();
95     for param in body.params {
96         param.pat.each_binding(|_binding_mode, hir_id, _span, _ident| {
97             params.insert(hir_id);
98         });
99     }
100     CheckParameters { tcx, params }.visit_body(body);
101 }
102
103 struct CheckParameters<'tcx> {
104     tcx: TyCtxt<'tcx>,
105     params: hir::HirIdSet,
106 }
107
108 impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> {
109     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
110         if let hir::ExprKind::Path(hir::QPath::Resolved(
111             _,
112             hir::Path { res: hir::def::Res::Local(var_hir_id), .. },
113         )) = expr.kind
114         {
115             if self.params.contains(var_hir_id) {
116                 self.tcx
117                     .sess
118                     .struct_span_err(
119                         expr.span,
120                         "referencing function parameters is not allowed in naked functions",
121                     )
122                     .help("follow the calling convention in asm block to use parameters")
123                     .emit();
124                 return;
125             }
126         }
127         hir::intravisit::walk_expr(self, expr);
128     }
129 }
130
131 /// Checks that function body contains a single inline assembly block.
132 fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &'tcx hir::Body<'tcx>) {
133     let mut this = CheckInlineAssembly { tcx, items: Vec::new() };
134     this.visit_body(body);
135     if let [(ItemKind::Asm | ItemKind::Err, _)] = this.items[..] {
136         // Ok.
137     } else {
138         let mut diag = struct_span_err!(
139             tcx.sess,
140             tcx.def_span(def_id),
141             E0787,
142             "naked functions must contain a single asm block"
143         );
144
145         let mut must_show_error = false;
146         let mut has_asm = false;
147         let mut has_err = false;
148         for &(kind, span) in &this.items {
149             match kind {
150                 ItemKind::Asm if has_asm => {
151                     must_show_error = true;
152                     diag.span_label(span, "multiple asm blocks are unsupported in naked functions");
153                 }
154                 ItemKind::Asm => has_asm = true,
155                 ItemKind::NonAsm => {
156                     must_show_error = true;
157                     diag.span_label(span, "non-asm is unsupported in naked functions");
158                 }
159                 ItemKind::Err => has_err = true,
160             }
161         }
162
163         // If the naked function only contains a single asm block and a non-zero number of
164         // errors, then don't show an additional error. This allows for appending/prepending
165         // `compile_error!("...")` statements and reduces error noise.
166         if must_show_error || !has_err {
167             diag.emit();
168         } else {
169             diag.cancel();
170         }
171     }
172 }
173
174 struct CheckInlineAssembly<'tcx> {
175     tcx: TyCtxt<'tcx>,
176     items: Vec<(ItemKind, Span)>,
177 }
178
179 #[derive(Copy, Clone)]
180 enum ItemKind {
181     Asm,
182     NonAsm,
183     Err,
184 }
185
186 impl<'tcx> CheckInlineAssembly<'tcx> {
187     fn check_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, span: Span) {
188         match expr.kind {
189             ExprKind::Box(..)
190             | ExprKind::ConstBlock(..)
191             | ExprKind::Array(..)
192             | ExprKind::Call(..)
193             | ExprKind::MethodCall(..)
194             | ExprKind::Tup(..)
195             | ExprKind::Binary(..)
196             | ExprKind::Unary(..)
197             | ExprKind::Lit(..)
198             | ExprKind::Cast(..)
199             | ExprKind::Type(..)
200             | ExprKind::Loop(..)
201             | ExprKind::Match(..)
202             | ExprKind::If(..)
203             | ExprKind::Closure { .. }
204             | ExprKind::Assign(..)
205             | ExprKind::AssignOp(..)
206             | ExprKind::Field(..)
207             | ExprKind::Index(..)
208             | ExprKind::Path(..)
209             | ExprKind::AddrOf(..)
210             | ExprKind::Let(..)
211             | ExprKind::Break(..)
212             | ExprKind::Continue(..)
213             | ExprKind::Ret(..)
214             | ExprKind::Struct(..)
215             | ExprKind::Repeat(..)
216             | ExprKind::Yield(..) => {
217                 self.items.push((ItemKind::NonAsm, span));
218             }
219
220             ExprKind::InlineAsm(ref asm) => {
221                 self.items.push((ItemKind::Asm, span));
222                 self.check_inline_asm(asm, span);
223             }
224
225             ExprKind::DropTemps(..) | ExprKind::Block(..) => {
226                 hir::intravisit::walk_expr(self, expr);
227             }
228
229             ExprKind::Err => {
230                 self.items.push((ItemKind::Err, span));
231             }
232         }
233     }
234
235     fn check_inline_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) {
236         let unsupported_operands: Vec<Span> = asm
237             .operands
238             .iter()
239             .filter_map(|&(ref op, op_sp)| match op {
240                 InlineAsmOperand::Const { .. }
241                 | InlineAsmOperand::SymFn { .. }
242                 | InlineAsmOperand::SymStatic { .. } => None,
243                 InlineAsmOperand::In { .. }
244                 | InlineAsmOperand::Out { .. }
245                 | InlineAsmOperand::InOut { .. }
246                 | InlineAsmOperand::SplitInOut { .. } => Some(op_sp),
247             })
248             .collect();
249         if !unsupported_operands.is_empty() {
250             struct_span_err!(
251                 self.tcx.sess,
252                 unsupported_operands,
253                 E0787,
254                 "only `const` and `sym` operands are supported in naked functions",
255             )
256             .emit();
257         }
258
259         let unsupported_options: Vec<&'static str> = [
260             (InlineAsmOptions::MAY_UNWIND, "`may_unwind`"),
261             (InlineAsmOptions::NOMEM, "`nomem`"),
262             (InlineAsmOptions::NOSTACK, "`nostack`"),
263             (InlineAsmOptions::PRESERVES_FLAGS, "`preserves_flags`"),
264             (InlineAsmOptions::PURE, "`pure`"),
265             (InlineAsmOptions::READONLY, "`readonly`"),
266         ]
267         .iter()
268         .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None })
269         .collect();
270
271         if !unsupported_options.is_empty() {
272             struct_span_err!(
273                 self.tcx.sess,
274                 span,
275                 E0787,
276                 "asm options unsupported in naked functions: {}",
277                 unsupported_options.join(", ")
278             )
279             .emit();
280         }
281
282         if !asm.options.contains(InlineAsmOptions::NORETURN) {
283             let last_span = asm
284                 .operands
285                 .last()
286                 .map_or_else(|| asm.template_strs.last().unwrap().2, |op| op.1)
287                 .shrink_to_hi();
288
289             struct_span_err!(
290                 self.tcx.sess,
291                 span,
292                 E0787,
293                 "asm in naked functions must use `noreturn` option"
294             )
295             .span_suggestion(
296                 last_span,
297                 "consider specifying that the asm block is responsible \
298                 for returning from the function",
299                 ", options(noreturn)",
300                 Applicability::MachineApplicable,
301             )
302             .emit();
303         }
304     }
305 }
306
307 impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> {
308     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
309         match stmt.kind {
310             StmtKind::Item(..) => {}
311             StmtKind::Local(..) => {
312                 self.items.push((ItemKind::NonAsm, stmt.span));
313             }
314             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
315                 self.check_expr(expr, stmt.span);
316             }
317         }
318     }
319
320     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
321         self.check_expr(&expr, expr.span);
322     }
323 }