]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/naked_functions.rs
Auto merge of #100557 - dawnofmidnight:tarball-commit-info, r=Mark-Simulacrum
[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(
69             UNDEFINED_NAKED_FUNCTION_ABI,
70             hir_id,
71             span,
72             "Rust ABI is unsupported in naked functions",
73             |lint| lint,
74         );
75     }
76 }
77
78 /// Checks that parameters don't use patterns. Mirrors the checks for function declarations.
79 fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) {
80     for param in params {
81         match param.pat.kind {
82             hir::PatKind::Wild
83             | hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, _, None) => {}
84             _ => {
85                 tcx.sess
86                     .struct_span_err(
87                         param.pat.span,
88                         "patterns not allowed in naked function parameters",
89                     )
90                     .emit();
91             }
92         }
93     }
94 }
95
96 /// Checks that function parameters aren't used in the function body.
97 fn check_no_parameters_use<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>) {
98     let mut params = hir::HirIdSet::default();
99     for param in body.params {
100         param.pat.each_binding(|_binding_mode, hir_id, _span, _ident| {
101             params.insert(hir_id);
102         });
103     }
104     CheckParameters { tcx, params }.visit_body(body);
105 }
106
107 struct CheckParameters<'tcx> {
108     tcx: TyCtxt<'tcx>,
109     params: hir::HirIdSet,
110 }
111
112 impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> {
113     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
114         if let hir::ExprKind::Path(hir::QPath::Resolved(
115             _,
116             hir::Path { res: hir::def::Res::Local(var_hir_id), .. },
117         )) = expr.kind
118         {
119             if self.params.contains(var_hir_id) {
120                 self.tcx
121                     .sess
122                     .struct_span_err(
123                         expr.span,
124                         "referencing function parameters is not allowed in naked functions",
125                     )
126                     .help("follow the calling convention in asm block to use parameters")
127                     .emit();
128                 return;
129             }
130         }
131         hir::intravisit::walk_expr(self, expr);
132     }
133 }
134
135 /// Checks that function body contains a single inline assembly block.
136 fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &'tcx hir::Body<'tcx>) {
137     let mut this = CheckInlineAssembly { tcx, items: Vec::new() };
138     this.visit_body(body);
139     if let [(ItemKind::Asm | ItemKind::Err, _)] = this.items[..] {
140         // Ok.
141     } else {
142         let mut diag = struct_span_err!(
143             tcx.sess,
144             tcx.def_span(def_id),
145             E0787,
146             "naked functions must contain a single asm block"
147         );
148
149         let mut must_show_error = false;
150         let mut has_asm = false;
151         let mut has_err = false;
152         for &(kind, span) in &this.items {
153             match kind {
154                 ItemKind::Asm if has_asm => {
155                     must_show_error = true;
156                     diag.span_label(span, "multiple asm blocks are unsupported in naked functions");
157                 }
158                 ItemKind::Asm => has_asm = true,
159                 ItemKind::NonAsm => {
160                     must_show_error = true;
161                     diag.span_label(span, "non-asm is unsupported in naked functions");
162                 }
163                 ItemKind::Err => has_err = true,
164             }
165         }
166
167         // If the naked function only contains a single asm block and a non-zero number of
168         // errors, then don't show an additional error. This allows for appending/prepending
169         // `compile_error!("...")` statements and reduces error noise.
170         if must_show_error || !has_err {
171             diag.emit();
172         } else {
173             diag.cancel();
174         }
175     }
176 }
177
178 struct CheckInlineAssembly<'tcx> {
179     tcx: TyCtxt<'tcx>,
180     items: Vec<(ItemKind, Span)>,
181 }
182
183 #[derive(Copy, Clone)]
184 enum ItemKind {
185     Asm,
186     NonAsm,
187     Err,
188 }
189
190 impl<'tcx> CheckInlineAssembly<'tcx> {
191     fn check_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, span: Span) {
192         match expr.kind {
193             ExprKind::Box(..)
194             | ExprKind::ConstBlock(..)
195             | ExprKind::Array(..)
196             | ExprKind::Call(..)
197             | ExprKind::MethodCall(..)
198             | ExprKind::Tup(..)
199             | ExprKind::Binary(..)
200             | ExprKind::Unary(..)
201             | ExprKind::Lit(..)
202             | ExprKind::Cast(..)
203             | ExprKind::Type(..)
204             | ExprKind::Loop(..)
205             | ExprKind::Match(..)
206             | ExprKind::If(..)
207             | ExprKind::Closure { .. }
208             | ExprKind::Assign(..)
209             | ExprKind::AssignOp(..)
210             | ExprKind::Field(..)
211             | ExprKind::Index(..)
212             | ExprKind::Path(..)
213             | ExprKind::AddrOf(..)
214             | ExprKind::Let(..)
215             | ExprKind::Break(..)
216             | ExprKind::Continue(..)
217             | ExprKind::Ret(..)
218             | ExprKind::Struct(..)
219             | ExprKind::Repeat(..)
220             | ExprKind::Yield(..) => {
221                 self.items.push((ItemKind::NonAsm, span));
222             }
223
224             ExprKind::InlineAsm(ref asm) => {
225                 self.items.push((ItemKind::Asm, span));
226                 self.check_inline_asm(asm, span);
227             }
228
229             ExprKind::DropTemps(..) | ExprKind::Block(..) => {
230                 hir::intravisit::walk_expr(self, expr);
231             }
232
233             ExprKind::Err => {
234                 self.items.push((ItemKind::Err, span));
235             }
236         }
237     }
238
239     fn check_inline_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) {
240         let unsupported_operands: Vec<Span> = asm
241             .operands
242             .iter()
243             .filter_map(|&(ref op, op_sp)| match op {
244                 InlineAsmOperand::Const { .. }
245                 | InlineAsmOperand::SymFn { .. }
246                 | InlineAsmOperand::SymStatic { .. } => None,
247                 InlineAsmOperand::In { .. }
248                 | InlineAsmOperand::Out { .. }
249                 | InlineAsmOperand::InOut { .. }
250                 | InlineAsmOperand::SplitInOut { .. } => Some(op_sp),
251             })
252             .collect();
253         if !unsupported_operands.is_empty() {
254             struct_span_err!(
255                 self.tcx.sess,
256                 unsupported_operands,
257                 E0787,
258                 "only `const` and `sym` operands are supported in naked functions",
259             )
260             .emit();
261         }
262
263         let unsupported_options: Vec<&'static str> = [
264             (InlineAsmOptions::MAY_UNWIND, "`may_unwind`"),
265             (InlineAsmOptions::NOMEM, "`nomem`"),
266             (InlineAsmOptions::NOSTACK, "`nostack`"),
267             (InlineAsmOptions::PRESERVES_FLAGS, "`preserves_flags`"),
268             (InlineAsmOptions::PURE, "`pure`"),
269             (InlineAsmOptions::READONLY, "`readonly`"),
270         ]
271         .iter()
272         .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None })
273         .collect();
274
275         if !unsupported_options.is_empty() {
276             struct_span_err!(
277                 self.tcx.sess,
278                 span,
279                 E0787,
280                 "asm options unsupported in naked functions: {}",
281                 unsupported_options.join(", ")
282             )
283             .emit();
284         }
285
286         if !asm.options.contains(InlineAsmOptions::NORETURN) {
287             let last_span = asm
288                 .operands
289                 .last()
290                 .map_or_else(|| asm.template_strs.last().unwrap().2, |op| op.1)
291                 .shrink_to_hi();
292
293             struct_span_err!(
294                 self.tcx.sess,
295                 span,
296                 E0787,
297                 "asm in naked functions must use `noreturn` option"
298             )
299             .span_suggestion(
300                 last_span,
301                 "consider specifying that the asm block is responsible \
302                 for returning from the function",
303                 ", options(noreturn)",
304                 Applicability::MachineApplicable,
305             )
306             .emit();
307         }
308     }
309 }
310
311 impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> {
312     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
313         match stmt.kind {
314             StmtKind::Item(..) => {}
315             StmtKind::Local(..) => {
316                 self.items.push((ItemKind::NonAsm, stmt.span));
317             }
318             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
319                 self.check_expr(expr, stmt.span);
320             }
321         }
322     }
323
324     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
325         self.check_expr(&expr, expr.span);
326     }
327 }