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(UNDEFINED_NAKED_FUNCTION_ABI, hir_id, span, |lint| {
69 lint.build("Rust ABI is unsupported in naked functions").emit();
74 /// Checks that parameters don't use patterns. Mirrors the checks for function declarations.
75 fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) {
77 match param.pat.kind {
79 | hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, _, None) => {}
84 "patterns not allowed in naked function parameters",
92 /// Checks that function parameters aren't used in the function body.
93 fn check_no_parameters_use<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>) {
94 let mut params = hir::HirIdSet::default();
95 for param in body.params {
96 param.pat.each_binding(|_binding_mode, hir_id, _span, _ident| {
97 params.insert(hir_id);
100 CheckParameters { tcx, params }.visit_body(body);
103 struct CheckParameters<'tcx> {
105 params: hir::HirIdSet,
108 impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> {
109 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
110 if let hir::ExprKind::Path(hir::QPath::Resolved(
112 hir::Path { res: hir::def::Res::Local(var_hir_id), .. },
115 if self.params.contains(var_hir_id) {
120 "referencing function parameters is not allowed in naked functions",
122 .help("follow the calling convention in asm block to use parameters")
127 hir::intravisit::walk_expr(self, expr);
131 /// Checks that function body contains a single inline assembly block.
132 fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &'tcx hir::Body<'tcx>) {
133 let mut this = CheckInlineAssembly { tcx, items: Vec::new() };
134 this.visit_body(body);
135 if let [(ItemKind::Asm | ItemKind::Err, _)] = this.items[..] {
138 let mut diag = struct_span_err!(
140 tcx.def_span(def_id),
142 "naked functions must contain a single asm block"
145 let mut must_show_error = false;
146 let mut has_asm = false;
147 let mut has_err = false;
148 for &(kind, span) in &this.items {
150 ItemKind::Asm if has_asm => {
151 must_show_error = true;
152 diag.span_label(span, "multiple asm blocks are unsupported in naked functions");
154 ItemKind::Asm => has_asm = true,
155 ItemKind::NonAsm => {
156 must_show_error = true;
157 diag.span_label(span, "non-asm is unsupported in naked functions");
159 ItemKind::Err => has_err = true,
163 // If the naked function only contains a single asm block and a non-zero number of
164 // errors, then don't show an additional error. This allows for appending/prepending
165 // `compile_error!("...")` statements and reduces error noise.
166 if must_show_error || !has_err {
174 struct CheckInlineAssembly<'tcx> {
176 items: Vec<(ItemKind, Span)>,
179 #[derive(Copy, Clone)]
186 impl<'tcx> CheckInlineAssembly<'tcx> {
187 fn check_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, span: Span) {
190 | ExprKind::ConstBlock(..)
191 | ExprKind::Array(..)
193 | ExprKind::MethodCall(..)
195 | ExprKind::Binary(..)
196 | ExprKind::Unary(..)
201 | ExprKind::Match(..)
203 | ExprKind::Closure { .. }
204 | ExprKind::Assign(..)
205 | ExprKind::AssignOp(..)
206 | ExprKind::Field(..)
207 | ExprKind::Index(..)
209 | ExprKind::AddrOf(..)
211 | ExprKind::Break(..)
212 | ExprKind::Continue(..)
214 | ExprKind::Struct(..)
215 | ExprKind::Repeat(..)
216 | ExprKind::Yield(..) => {
217 self.items.push((ItemKind::NonAsm, span));
220 ExprKind::InlineAsm(ref asm) => {
221 self.items.push((ItemKind::Asm, span));
222 self.check_inline_asm(asm, span);
225 ExprKind::DropTemps(..) | ExprKind::Block(..) => {
226 hir::intravisit::walk_expr(self, expr);
230 self.items.push((ItemKind::Err, span));
235 fn check_inline_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) {
236 let unsupported_operands: Vec<Span> = asm
239 .filter_map(|&(ref op, op_sp)| match op {
240 InlineAsmOperand::Const { .. }
241 | InlineAsmOperand::SymFn { .. }
242 | InlineAsmOperand::SymStatic { .. } => None,
243 InlineAsmOperand::In { .. }
244 | InlineAsmOperand::Out { .. }
245 | InlineAsmOperand::InOut { .. }
246 | InlineAsmOperand::SplitInOut { .. } => Some(op_sp),
249 if !unsupported_operands.is_empty() {
252 unsupported_operands,
254 "only `const` and `sym` operands are supported in naked functions",
259 let unsupported_options: Vec<&'static str> = [
260 (InlineAsmOptions::MAY_UNWIND, "`may_unwind`"),
261 (InlineAsmOptions::NOMEM, "`nomem`"),
262 (InlineAsmOptions::NOSTACK, "`nostack`"),
263 (InlineAsmOptions::PRESERVES_FLAGS, "`preserves_flags`"),
264 (InlineAsmOptions::PURE, "`pure`"),
265 (InlineAsmOptions::READONLY, "`readonly`"),
268 .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None })
271 if !unsupported_options.is_empty() {
276 "asm options unsupported in naked functions: {}",
277 unsupported_options.join(", ")
282 if !asm.options.contains(InlineAsmOptions::NORETURN) {
286 .map_or_else(|| asm.template_strs.last().unwrap().2, |op| op.1)
293 "asm in naked functions must use `noreturn` option"
297 "consider specifying that the asm block is responsible \
298 for returning from the function",
299 ", options(noreturn)",
300 Applicability::MachineApplicable,
307 impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> {
308 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
310 StmtKind::Item(..) => {}
311 StmtKind::Local(..) => {
312 self.items.push((ItemKind::NonAsm, stmt.span));
314 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
315 self.check_expr(expr, stmt.span);
320 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
321 self.check_expr(&expr, expr.span);