1 //! Checks validity of naked functions.
3 use rustc_ast::{Attribute, InlineAsmOptions};
4 use rustc_errors::{struct_span_err, Applicability};
6 use rustc_hir::def_id::LocalDefId;
7 use rustc_hir::intravisit::{FnKind, Visitor};
8 use rustc_hir::{ExprKind, HirId, 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;
14 use rustc_target::spec::abi::Abi;
16 fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
17 tcx.hir().visit_item_likes_in_module(
19 &mut CheckNakedFunctions { tcx }.as_deep_visitor(),
23 crate fn provide(providers: &mut Providers) {
24 *providers = Providers { check_mod_naked_functions, ..*providers };
27 struct CheckNakedFunctions<'tcx> {
31 impl<'tcx> Visitor<'tcx> for CheckNakedFunctions<'tcx> {
35 _fd: &'tcx hir::FnDecl<'tcx>,
45 // Closures with a naked attribute are rejected during attribute
46 // check. Don't validate them any further.
49 FnKind::ItemFn(ident, _, ref header, ..) => {
50 ident_span = ident.span;
54 FnKind::Method(ident, ref sig, ..) => {
55 ident_span = ident.span;
56 fn_header = &sig.header;
60 let attrs = self.tcx.hir().attrs(hir_id);
61 let naked = attrs.iter().any(|attr| attr.has_name(sym::naked));
63 let body = self.tcx.hir().body(body_id);
64 check_abi(self.tcx, hir_id, fn_header.abi, ident_span);
65 check_no_patterns(self.tcx, body.params);
66 check_no_parameters_use(self.tcx, body);
67 check_asm(self.tcx, body, span);
68 check_inline(self.tcx, attrs);
73 /// Check that the function isn't inlined.
74 fn check_inline(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
75 for attr in attrs.iter().filter(|attr| attr.has_name(sym::inline)) {
76 tcx.sess.struct_span_err(attr.span, "naked functions cannot be inlined").emit();
80 /// Checks that function uses non-Rust ABI.
81 fn check_abi(tcx: TyCtxt<'_>, hir_id: HirId, abi: Abi, fn_ident_span: Span) {
83 tcx.struct_span_lint_hir(UNDEFINED_NAKED_FUNCTION_ABI, hir_id, fn_ident_span, |lint| {
84 lint.build("Rust ABI is unsupported in naked functions").emit();
89 /// Checks that parameters don't use patterns. Mirrors the checks for function declarations.
90 fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) {
92 match param.pat.kind {
94 | hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, _, None) => {}
99 "patterns not allowed in naked function parameters",
107 /// Checks that function parameters aren't used in the function body.
108 fn check_no_parameters_use<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>) {
109 let mut params = hir::HirIdSet::default();
110 for param in body.params {
111 param.pat.each_binding(|_binding_mode, hir_id, _span, _ident| {
112 params.insert(hir_id);
115 CheckParameters { tcx, params }.visit_body(body);
118 struct CheckParameters<'tcx> {
120 params: hir::HirIdSet,
123 impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> {
124 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
125 if let hir::ExprKind::Path(hir::QPath::Resolved(
127 hir::Path { res: hir::def::Res::Local(var_hir_id), .. },
130 if self.params.contains(var_hir_id) {
135 "referencing function parameters is not allowed in naked functions",
137 .help("follow the calling convention in asm block to use parameters")
142 hir::intravisit::walk_expr(self, expr);
146 /// Checks that function body contains a single inline assembly block.
147 fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>, fn_span: Span) {
148 let mut this = CheckInlineAssembly { tcx, items: Vec::new() };
149 this.visit_body(body);
150 if let [(ItemKind::Asm | ItemKind::Err, _)] = this.items[..] {
153 let mut diag = struct_span_err!(
157 "naked functions must contain a single asm block"
160 let mut must_show_error = false;
161 let mut has_asm = false;
162 let mut has_err = false;
163 for &(kind, span) in &this.items {
165 ItemKind::Asm if has_asm => {
166 must_show_error = true;
167 diag.span_label(span, "multiple asm blocks are unsupported in naked functions");
169 ItemKind::Asm => has_asm = true,
170 ItemKind::NonAsm => {
171 must_show_error = true;
172 diag.span_label(span, "non-asm is unsupported in naked functions");
174 ItemKind::Err => has_err = true,
178 // If the naked function only contains a single asm block and a non-zero number of
179 // errors, then don't show an additional error. This allows for appending/prepending
180 // `compile_error!("...")` statements and reduces error noise.
181 if must_show_error || !has_err {
189 struct CheckInlineAssembly<'tcx> {
191 items: Vec<(ItemKind, Span)>,
194 #[derive(Copy, Clone)]
201 impl<'tcx> CheckInlineAssembly<'tcx> {
202 fn check_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, span: Span) {
205 | ExprKind::ConstBlock(..)
206 | ExprKind::Array(..)
208 | ExprKind::MethodCall(..)
210 | ExprKind::Binary(..)
211 | ExprKind::Unary(..)
216 | ExprKind::Match(..)
218 | ExprKind::Closure(..)
219 | ExprKind::Assign(..)
220 | ExprKind::AssignOp(..)
221 | ExprKind::Field(..)
222 | ExprKind::Index(..)
224 | ExprKind::AddrOf(..)
226 | ExprKind::Break(..)
227 | ExprKind::Continue(..)
229 | ExprKind::Struct(..)
230 | ExprKind::Repeat(..)
231 | ExprKind::Yield(..) => {
232 self.items.push((ItemKind::NonAsm, span));
235 ExprKind::InlineAsm(ref asm) => {
236 self.items.push((ItemKind::Asm, span));
237 self.check_inline_asm(asm, span);
240 ExprKind::DropTemps(..) | ExprKind::Block(..) => {
241 hir::intravisit::walk_expr(self, expr);
245 self.items.push((ItemKind::Err, span));
250 fn check_inline_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) {
251 let unsupported_operands: Vec<Span> = asm
254 .filter_map(|&(ref op, op_sp)| match op {
255 InlineAsmOperand::Const { .. }
256 | InlineAsmOperand::SymFn { .. }
257 | InlineAsmOperand::SymStatic { .. } => None,
258 InlineAsmOperand::In { .. }
259 | InlineAsmOperand::Out { .. }
260 | InlineAsmOperand::InOut { .. }
261 | InlineAsmOperand::SplitInOut { .. } => Some(op_sp),
264 if !unsupported_operands.is_empty() {
267 unsupported_operands,
269 "only `const` and `sym` operands are supported in naked functions",
274 let unsupported_options: Vec<&'static str> = [
275 (InlineAsmOptions::MAY_UNWIND, "`may_unwind`"),
276 (InlineAsmOptions::NOMEM, "`nomem`"),
277 (InlineAsmOptions::NOSTACK, "`nostack`"),
278 (InlineAsmOptions::PRESERVES_FLAGS, "`preserves_flags`"),
279 (InlineAsmOptions::PURE, "`pure`"),
280 (InlineAsmOptions::READONLY, "`readonly`"),
283 .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None })
286 if !unsupported_options.is_empty() {
291 "asm options unsupported in naked functions: {}",
292 unsupported_options.join(", ")
297 if !asm.options.contains(InlineAsmOptions::NORETURN) {
301 .map_or_else(|| asm.template_strs.last().unwrap().2, |op| op.1)
308 "asm in naked functions must use `noreturn` option"
312 "consider specifying that the asm block is responsible \
313 for returning from the function",
314 String::from(", options(noreturn)"),
315 Applicability::MachineApplicable,
322 impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> {
323 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
325 StmtKind::Item(..) => {}
326 StmtKind::Local(..) => {
327 self.items.push((ItemKind::NonAsm, stmt.span));
329 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
330 self.check_expr(expr, stmt.span);
335 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
336 self.check_expr(&expr, expr.span);