]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_passes/src/naked_functions.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_passes / src / naked_functions.rs
CommitLineData
fc512014
XL
1//! Checks validity of naked functions.
2
94222f64 3use rustc_ast::{Attribute, InlineAsmOptions};
fc512014
XL
4use rustc_hir as hir;
5use rustc_hir::def_id::LocalDefId;
6use rustc_hir::intravisit::{ErasedMap, FnKind, NestedVisitorMap, Visitor};
7use rustc_hir::{ExprKind, HirId, InlineAsmOperand, StmtKind};
8use rustc_middle::ty::query::Providers;
9use rustc_middle::ty::TyCtxt;
94222f64 10use rustc_session::lint::builtin::UNDEFINED_NAKED_FUNCTION_ABI;
fc512014
XL
11use rustc_session::lint::builtin::UNSUPPORTED_NAKED_FUNCTIONS;
12use rustc_span::symbol::sym;
13use rustc_span::Span;
14use rustc_target::spec::abi::Abi;
15
16fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
17 tcx.hir().visit_item_likes_in_module(
18 module_def_id,
19 &mut CheckNakedFunctions { tcx }.as_deep_visitor(),
20 );
21}
22
23crate fn provide(providers: &mut Providers) {
24 *providers = Providers { check_mod_naked_functions, ..*providers };
25}
26
27struct CheckNakedFunctions<'tcx> {
28 tcx: TyCtxt<'tcx>,
29}
30
31impl<'tcx> Visitor<'tcx> for CheckNakedFunctions<'tcx> {
32 type Map = ErasedMap<'tcx>;
33
34 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
35 NestedVisitorMap::None
36 }
37
38 fn visit_fn(
39 &mut self,
40 fk: FnKind<'v>,
41 _fd: &'tcx hir::FnDecl<'tcx>,
42 body_id: hir::BodyId,
43 span: Span,
44 hir_id: HirId,
45 ) {
46 let ident_span;
47 let fn_header;
48
49 match fk {
6a06907d 50 FnKind::Closure => {
fc512014
XL
51 // Closures with a naked attribute are rejected during attribute
52 // check. Don't validate them any further.
53 return;
54 }
55 FnKind::ItemFn(ident, _, ref header, ..) => {
56 ident_span = ident.span;
57 fn_header = header;
58 }
59
60 FnKind::Method(ident, ref sig, ..) => {
61 ident_span = ident.span;
62 fn_header = &sig.header;
63 }
64 }
65
6a06907d
XL
66 let attrs = self.tcx.hir().attrs(hir_id);
67 let naked = attrs.iter().any(|attr| attr.has_name(sym::naked));
fc512014
XL
68 if naked {
69 let body = self.tcx.hir().body(body_id);
70 check_abi(self.tcx, hir_id, fn_header.abi, ident_span);
71 check_no_patterns(self.tcx, body.params);
72 check_no_parameters_use(self.tcx, body);
73 check_asm(self.tcx, hir_id, body, span);
94222f64 74 check_inline(self.tcx, hir_id, attrs);
fc512014
XL
75 }
76 }
77}
78
94222f64
XL
79/// Check that the function isn't inlined.
80fn check_inline(tcx: TyCtxt<'_>, hir_id: HirId, attrs: &[Attribute]) {
81 for attr in attrs.iter().filter(|attr| attr.has_name(sym::inline)) {
82 tcx.struct_span_lint_hir(UNSUPPORTED_NAKED_FUNCTIONS, hir_id, attr.span, |lint| {
83 lint.build("naked functions cannot be inlined").emit();
84 });
85 }
86}
87
fc512014
XL
88/// Checks that function uses non-Rust ABI.
89fn check_abi(tcx: TyCtxt<'_>, hir_id: HirId, abi: Abi, fn_ident_span: Span) {
90 if abi == Abi::Rust {
94222f64 91 tcx.struct_span_lint_hir(UNDEFINED_NAKED_FUNCTION_ABI, hir_id, fn_ident_span, |lint| {
fc512014
XL
92 lint.build("Rust ABI is unsupported in naked functions").emit();
93 });
94 }
95}
96
97/// Checks that parameters don't use patterns. Mirrors the checks for function declarations.
98fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) {
99 for param in params {
100 match param.pat.kind {
101 hir::PatKind::Wild
102 | hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, _, None) => {}
103 _ => {
104 tcx.sess
105 .struct_span_err(
106 param.pat.span,
107 "patterns not allowed in naked function parameters",
108 )
109 .emit();
110 }
111 }
112 }
113}
114
115/// Checks that function parameters aren't used in the function body.
116fn check_no_parameters_use<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>) {
117 let mut params = hir::HirIdSet::default();
118 for param in body.params {
119 param.pat.each_binding(|_binding_mode, hir_id, _span, _ident| {
120 params.insert(hir_id);
121 });
122 }
123 CheckParameters { tcx, params }.visit_body(body);
124}
125
126struct CheckParameters<'tcx> {
127 tcx: TyCtxt<'tcx>,
128 params: hir::HirIdSet,
129}
130
131impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> {
132 type Map = ErasedMap<'tcx>;
133
134 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
135 NestedVisitorMap::None
136 }
137
138 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
139 if let hir::ExprKind::Path(hir::QPath::Resolved(
140 _,
141 hir::Path { res: hir::def::Res::Local(var_hir_id), .. },
142 )) = expr.kind
143 {
144 if self.params.contains(var_hir_id) {
145 self.tcx
146 .sess
147 .struct_span_err(
148 expr.span,
149 "referencing function parameters is not allowed in naked functions",
150 )
151 .help("follow the calling convention in asm block to use parameters")
152 .emit();
153 return;
154 }
155 }
156 hir::intravisit::walk_expr(self, expr);
157 }
158}
159
160/// Checks that function body contains a single inline assembly block.
161fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, hir_id: HirId, body: &'tcx hir::Body<'tcx>, fn_span: Span) {
162 let mut this = CheckInlineAssembly { tcx, items: Vec::new() };
163 this.visit_body(body);
5869c6ff 164 if let [(ItemKind::Asm, _)] = this.items[..] {
fc512014
XL
165 // Ok.
166 } else {
167 tcx.struct_span_lint_hir(UNSUPPORTED_NAKED_FUNCTIONS, hir_id, fn_span, |lint| {
168 let mut diag = lint.build("naked functions must contain a single asm block");
169 let mut has_asm = false;
170 for &(kind, span) in &this.items {
171 match kind {
172 ItemKind::Asm if has_asm => {
173 diag.span_label(
174 span,
175 "multiple asm blocks are unsupported in naked functions",
176 );
177 }
178 ItemKind::Asm => has_asm = true,
179 ItemKind::NonAsm => {
180 diag.span_label(span, "non-asm is unsupported in naked functions");
181 }
182 }
183 }
184 diag.emit();
185 });
186 }
187}
188
189struct CheckInlineAssembly<'tcx> {
190 tcx: TyCtxt<'tcx>,
191 items: Vec<(ItemKind, Span)>,
192}
193
194#[derive(Copy, Clone)]
195enum ItemKind {
196 Asm,
197 NonAsm,
198}
199
200impl<'tcx> CheckInlineAssembly<'tcx> {
201 fn check_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, span: Span) {
202 match expr.kind {
203 ExprKind::Box(..)
204 | ExprKind::ConstBlock(..)
205 | ExprKind::Array(..)
206 | ExprKind::Call(..)
207 | ExprKind::MethodCall(..)
208 | ExprKind::Tup(..)
209 | ExprKind::Binary(..)
210 | ExprKind::Unary(..)
211 | ExprKind::Lit(..)
212 | ExprKind::Cast(..)
213 | ExprKind::Type(..)
214 | ExprKind::Loop(..)
215 | ExprKind::Match(..)
5869c6ff 216 | ExprKind::If(..)
fc512014
XL
217 | ExprKind::Closure(..)
218 | ExprKind::Assign(..)
219 | ExprKind::AssignOp(..)
220 | ExprKind::Field(..)
221 | ExprKind::Index(..)
222 | ExprKind::Path(..)
223 | ExprKind::AddrOf(..)
94222f64 224 | ExprKind::Let(..)
fc512014
XL
225 | ExprKind::Break(..)
226 | ExprKind::Continue(..)
227 | ExprKind::Ret(..)
228 | ExprKind::Struct(..)
229 | ExprKind::Repeat(..)
230 | ExprKind::Yield(..) => {
231 self.items.push((ItemKind::NonAsm, span));
232 }
233
234 ExprKind::InlineAsm(ref asm) => {
235 self.items.push((ItemKind::Asm, span));
236 self.check_inline_asm(expr.hir_id, asm, span);
237 }
238
239 ExprKind::LlvmInlineAsm(..) => {
240 self.items.push((ItemKind::Asm, span));
241 self.tcx.struct_span_lint_hir(
242 UNSUPPORTED_NAKED_FUNCTIONS,
243 expr.hir_id,
244 span,
245 |lint| {
246 lint.build(
247 "the LLVM-style inline assembly is unsupported in naked functions",
248 )
249 .help("use the new asm! syntax specified in RFC 2873")
250 .emit();
251 },
252 );
253 }
254
255 ExprKind::DropTemps(..) | ExprKind::Block(..) | ExprKind::Err => {
256 hir::intravisit::walk_expr(self, expr);
257 }
258 }
259 }
260
261 fn check_inline_asm(&self, hir_id: HirId, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) {
262 let unsupported_operands: Vec<Span> = asm
263 .operands
264 .iter()
265 .filter_map(|&(ref op, op_sp)| match op {
266 InlineAsmOperand::Const { .. } | InlineAsmOperand::Sym { .. } => None,
267 InlineAsmOperand::In { .. }
268 | InlineAsmOperand::Out { .. }
269 | InlineAsmOperand::InOut { .. }
270 | InlineAsmOperand::SplitInOut { .. } => Some(op_sp),
271 })
272 .collect();
273 if !unsupported_operands.is_empty() {
274 self.tcx.struct_span_lint_hir(
275 UNSUPPORTED_NAKED_FUNCTIONS,
276 hir_id,
277 unsupported_operands,
278 |lint| {
279 lint.build("only `const` and `sym` operands are supported in naked functions")
280 .emit();
281 },
282 );
283 }
284
285 let unsupported_options: Vec<&'static str> = [
286 (InlineAsmOptions::NOMEM, "`nomem`"),
287 (InlineAsmOptions::NOSTACK, "`nostack`"),
288 (InlineAsmOptions::PRESERVES_FLAGS, "`preserves_flags`"),
289 (InlineAsmOptions::PURE, "`pure`"),
290 (InlineAsmOptions::READONLY, "`readonly`"),
291 ]
292 .iter()
293 .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None })
294 .collect();
295
296 if !unsupported_options.is_empty() {
297 self.tcx.struct_span_lint_hir(UNSUPPORTED_NAKED_FUNCTIONS, hir_id, span, |lint| {
298 lint.build(&format!(
299 "asm options unsupported in naked functions: {}",
300 unsupported_options.join(", ")
301 ))
302 .emit();
303 });
304 }
305
306 if !asm.options.contains(InlineAsmOptions::NORETURN) {
307 self.tcx.struct_span_lint_hir(UNSUPPORTED_NAKED_FUNCTIONS, hir_id, span, |lint| {
308 lint.build("asm in naked functions must use `noreturn` option").emit();
309 });
310 }
311 }
312}
313
314impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> {
315 type Map = ErasedMap<'tcx>;
316
317 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
318 NestedVisitorMap::None
319 }
320
321 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
322 match stmt.kind {
323 StmtKind::Item(..) => {}
324 StmtKind::Local(..) => {
325 self.items.push((ItemKind::NonAsm, stmt.span));
326 }
327 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
328 self.check_expr(expr, stmt.span);
329 }
330 }
331 }
332
333 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
334 self.check_expr(&expr, expr.span);
335 }
336}