1 //! Checks validity of naked functions.
3 use rustc_ast::InlineAsmOptions;
4 use rustc_errors::{struct_span_err, Applicability};
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;
15 use rustc_target::spec::abi::Abi;
17 pub(crate) fn provide(providers: &mut Providers) {
18 *providers = Providers { check_mod_naked_functions, ..*providers };
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) {
28 let naked = tcx.has_attr(def_id.to_def_id(), sym::naked);
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)),
39 | hir::Node::ImplItem(hir::ImplItem {
40 kind: hir::ImplItemKind::Fn(sig, body_id),
42 }) => (sig.header, *body_id),
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);
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);
59 tcx.sess.struct_span_err(attr.span, "naked functions cannot be inlined").emit();
63 /// Checks that function uses non-Rust ABI.
64 fn check_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, abi: Abi) {
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,
72 "Rust ABI is unsupported in naked functions",
78 /// Checks that parameters don't use patterns. Mirrors the checks for function declarations.
79 fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) {
81 match param.pat.kind {
83 | hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, _, None) => {}
88 "patterns not allowed in naked function parameters",
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);
104 CheckParameters { tcx, params }.visit_body(body);
107 struct CheckParameters<'tcx> {
109 params: hir::HirIdSet,
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(
116 hir::Path { res: hir::def::Res::Local(var_hir_id), .. },
119 if self.params.contains(var_hir_id) {
124 "referencing function parameters is not allowed in naked functions",
126 .help("follow the calling convention in asm block to use parameters")
131 hir::intravisit::walk_expr(self, expr);
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[..] {
142 let mut diag = struct_span_err!(
144 tcx.def_span(def_id),
146 "naked functions must contain a single asm block"
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 {
154 ItemKind::Asm if has_asm => {
155 must_show_error = true;
156 diag.span_label(span, "multiple asm blocks are unsupported in naked functions");
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");
163 ItemKind::Err => has_err = true,
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 {
178 struct CheckInlineAssembly<'tcx> {
180 items: Vec<(ItemKind, Span)>,
183 #[derive(Copy, Clone)]
190 impl<'tcx> CheckInlineAssembly<'tcx> {
191 fn check_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, span: Span) {
194 | ExprKind::ConstBlock(..)
195 | ExprKind::Array(..)
197 | ExprKind::MethodCall(..)
199 | ExprKind::Binary(..)
200 | ExprKind::Unary(..)
205 | ExprKind::Match(..)
207 | ExprKind::Closure { .. }
208 | ExprKind::Assign(..)
209 | ExprKind::AssignOp(..)
210 | ExprKind::Field(..)
211 | ExprKind::Index(..)
213 | ExprKind::AddrOf(..)
215 | ExprKind::Break(..)
216 | ExprKind::Continue(..)
218 | ExprKind::Struct(..)
219 | ExprKind::Repeat(..)
220 | ExprKind::Yield(..) => {
221 self.items.push((ItemKind::NonAsm, span));
224 ExprKind::InlineAsm(ref asm) => {
225 self.items.push((ItemKind::Asm, span));
226 self.check_inline_asm(asm, span);
229 ExprKind::DropTemps(..) | ExprKind::Block(..) => {
230 hir::intravisit::walk_expr(self, expr);
234 self.items.push((ItemKind::Err, span));
239 fn check_inline_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) {
240 let unsupported_operands: Vec<Span> = asm
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),
253 if !unsupported_operands.is_empty() {
256 unsupported_operands,
258 "only `const` and `sym` operands are supported in naked functions",
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`"),
272 .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None })
275 if !unsupported_options.is_empty() {
280 "asm options unsupported in naked functions: {}",
281 unsupported_options.join(", ")
286 if !asm.options.contains(InlineAsmOptions::NORETURN) {
290 .map_or_else(|| asm.template_strs.last().unwrap().2, |op| op.1)
297 "asm in naked functions must use `noreturn` option"
301 "consider specifying that the asm block is responsible \
302 for returning from the function",
303 ", options(noreturn)",
304 Applicability::MachineApplicable,
311 impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> {
312 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
314 StmtKind::Item(..) => {}
315 StmtKind::Local(..) => {
316 self.items.push((ItemKind::NonAsm, stmt.span));
318 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
319 self.check_expr(expr, stmt.span);
324 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
325 self.check_expr(&expr, expr.span);