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