1use rustc_abi::{Align, ExternAbi};
2use rustc_hir::attrs::{
3AttributeKind, EiiImplResolution, InlineAttr, InstrumentFnAttras HirInstrumentFnAttr, Linkage,
4RtsanSetting, UsedBy,
5};
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
8use rustc_hir::{selfas hir, Attribute, find_attr};
9use rustc_macros::Diagnostic;
10use rustc_middle::middle::codegen_fn_attrs::{
11CodegenFnAttrFlags, CodegenFnAttrs, InstrumentFnAttr, PatchableFunctionEntry, SanitizerFnAttrs,
12};
13use rustc_middle::mono::Visibility;
14use rustc_middle::query::Providers;
15use rustc_middle::ty::{selfas ty, TyCtxt};
16use rustc_session::diagnostics::feature_err;
17use rustc_session::lint;
18use rustc_span::{Span, sym};
19use rustc_target::spec::Os;
2021use crate::errors;
22use crate::target_features::{
23check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
24};
2526/// In some cases, attributes are only valid on functions, but it's the `check_attr`
27/// pass that checks that they aren't used anywhere else, rather than this module.
28/// In these cases, we bail from performing further checks that are only meaningful for
29/// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
30/// report a delayed bug, just in case `check_attr` isn't doing its job.
31fn try_fn_sig<'tcx>(
32 tcx: TyCtxt<'tcx>,
33 did: LocalDefId,
34 attr_span: Span,
35) -> Option<ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>> {
36use DefKind::*;
3738let def_kind = tcx.def_kind(did);
39if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
40Some(tcx.fn_sig(did))
41 } else {
42tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
43None44 }
45}
4647/// Spans that are collected when processing built-in attributes,
48/// that are useful for emitting diagnostics later.
49#[derive(#[automatically_derived]
impl ::core::default::Default for InterestingAttributeDiagnosticSpans {
#[inline]
fn default() -> InterestingAttributeDiagnosticSpans {
InterestingAttributeDiagnosticSpans {
link_ordinal: ::core::default::Default::default(),
sanitize: ::core::default::Default::default(),
inline: ::core::default::Default::default(),
no_mangle: ::core::default::Default::default(),
}
}
}Default)]
50struct InterestingAttributeDiagnosticSpans {
51 link_ordinal: Option<Span>,
52 sanitize: Option<Span>,
53 inline: Option<Span>,
54 no_mangle: Option<Span>,
55}
5657/// Process the builtin attrs ([`hir::Attribute`]) on the item.
58/// Many of them directly translate to codegen attrs.
59fn process_builtin_attrs(
60 tcx: TyCtxt<'_>,
61 did: LocalDefId,
62 attrs: &[Attribute],
63 codegen_fn_attrs: &mut CodegenFnAttrs,
64) -> InterestingAttributeDiagnosticSpans {
65let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
66let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
6768let parsed_attrs = attrs69 .iter()
70 .filter_map(|attr| if let hir::Attribute::Parsed(attr) = attr { Some(attr) } else { None });
71for attr in parsed_attrs {
72match attr {
73 AttributeKind::Cold => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
74 AttributeKind::ExportName { name, .. } => codegen_fn_attrs.symbol_name = Some(*name),
75 AttributeKind::Inline(inline, span) => {
76 codegen_fn_attrs.inline = *inline;
77 interesting_spans.inline = Some(*span);
78 }
79 AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
80 AttributeKind::RustcAlign { align, .. } => codegen_fn_attrs.alignment = Some(*align),
81 AttributeKind::LinkName { name, .. } => {
82// FIXME Remove check for foreign functions once #[link_name] on non-foreign
83 // functions is a hard error
84if tcx.is_foreign_item(did) {
85 codegen_fn_attrs.symbol_name = Some(*name);
86 }
87 }
88 AttributeKind::LinkOrdinal { ordinal, span } => {
89 codegen_fn_attrs.link_ordinal = Some(*ordinal);
90 interesting_spans.link_ordinal = Some(*span);
91 }
92 AttributeKind::LinkSection { name } => codegen_fn_attrs.link_section = Some(*name),
93 AttributeKind::NoMangle(attr_span) => {
94 interesting_spans.no_mangle = Some(*attr_span);
95if tcx.opt_item_name(did.to_def_id()).is_some() {
96 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
97 } else {
98 tcx.dcx()
99 .span_delayed_bug(*attr_span, "no_mangle should be on a named function");
100 }
101 }
102 AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
103 AttributeKind::TargetFeature { features, attr_span, was_forced } => {
104let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
105 tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
106continue;
107 };
108let safe_target_features =
109#[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
hir::HeaderSafety::SafeTargetFeatures => true,
_ => false,
}matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
110 codegen_fn_attrs.safe_target_features = safe_target_features;
111if safe_target_features && !was_forced {
112if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
113// The `#[target_feature]` attribute is allowed on
114 // WebAssembly targets on all functions. Prior to stabilizing
115 // the `target_feature_11` feature, `#[target_feature]` was
116 // only permitted on unsafe functions because on most targets
117 // execution of instructions that are not supported is
118 // considered undefined behavior. For WebAssembly which is a
119 // 100% safe target at execution time it's not possible to
120 // execute undefined instructions, and even if a future
121 // feature was added in some form for this it would be a
122 // deterministic trap. There is no undefined behavior when
123 // executing WebAssembly so `#[target_feature]` is allowed
124 // on safe functions (but again, only for WebAssembly)
125 //
126 // Note that this is also allowed if `actually_rustdoc` so
127 // if a target is documenting some wasm-specific code then
128 // it's not spuriously denied.
129 //
130 // Now that `#[target_feature]` is permitted on safe functions,
131 // this exception must still exist for allowing the attribute on
132 // `main`, `start`, and other functions that are not usually
133 // allowed.
134} else {
135 check_target_feature_trait_unsafe(tcx, did, *attr_span);
136 }
137 }
138 from_target_feature_attr(
139 tcx,
140 did,
141 features,
142*was_forced,
143 rust_target_features,
144&mut codegen_fn_attrs.target_features,
145 );
146 }
147 AttributeKind::TrackCaller(attr_span) => {
148let is_closure = tcx.is_closure_like(did.to_def_id());
149150if !is_closure
151 && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
152 && fn_sig.skip_binder().abi() != ExternAbi::Rust
153 {
154// This error is already reported in `rustc_ast_passes/src/ast_validation.rs`.
155tcx.dcx().delayed_bug("`#[track_caller]` requires the Rust ABI");
156 }
157if is_closure
158 && !tcx.features().closure_track_caller()
159 && !attr_span.allows_unstable(sym::closure_track_caller)
160 {
161 feature_err(
162&tcx.sess,
163 sym::closure_track_caller,
164*attr_span,
165"`#[track_caller]` on closures is currently unstable",
166 )
167 .emit();
168 }
169 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
170 }
171 AttributeKind::Used { used_by } => match used_by {
172 UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
173 UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
174 UsedBy::Default => {
175let used_form = if tcx.sess.target.os == Os::Illumos {
176// illumos' `ld` doesn't support a section header that would represent
177 // `#[used(linker)]`, see
178 // https://github.com/rust-lang/rust/issues/146169. For that target,
179 // downgrade as if `#[used(compiler)]` was requested and hope for the
180 // best.
181CodegenFnAttrFlags::USED_COMPILER
182 } else {
183 CodegenFnAttrFlags::USED_LINKER
184 };
185 codegen_fn_attrs.flags |= used_form;
186 }
187 },
188 AttributeKind::FfiConst => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,
189 AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
190 AttributeKind::RustcStdInternalSymbol => {
191 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
192 }
193 AttributeKind::Linkage(linkage, span) => {
194let linkage = Some(*linkage);
195196if tcx.is_foreign_item(did) {
197 codegen_fn_attrs.import_linkage = linkage;
198199if tcx.is_mutable_static(did.into()) {
200let mut diag = tcx.dcx().struct_span_err(
201*span,
202"extern mutable statics are not allowed with `#[linkage]`",
203 );
204 diag.note(
205"marking the extern static mutable would allow changing which \
206 symbol the static references rather than make the target of the \
207 symbol mutable",
208 );
209 diag.emit();
210 }
211 } else {
212 codegen_fn_attrs.linkage = linkage;
213 }
214 }
215 AttributeKind::Sanitize { span, .. } => {
216 interesting_spans.sanitize = Some(*span);
217 }
218 AttributeKind::RustcObjcClass { classname } => {
219 codegen_fn_attrs.objc_class = Some(*classname);
220 }
221 AttributeKind::RustcObjcSelector { methname } => {
222 codegen_fn_attrs.objc_selector = Some(*methname);
223 }
224 AttributeKind::RustcEiiForeignItem => {
225 codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
226 }
227 AttributeKind::EiiImpls(impls) => {
228for i in impls {
229let foreign_item = match i.resolution {
230 EiiImplResolution::Macro(def_id) => {
231let Some(extern_item) = {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(EiiDeclaration(target)) => {
break 'done Some(target.foreign_item);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item
232 )else {
233 tcx.dcx().span_delayed_bug(
234 i.span,
235"resolved to something that's not an EII",
236 );
237continue;
238 };
239 extern_item
240 }
241 EiiImplResolution::Known(decl) => decl.foreign_item,
242 EiiImplResolution::Error(_eg) => continue,
243 };
244245// this is to prevent a bug where a single crate defines both the default and explicit implementation
246 // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
247 // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
248 // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
249 // the default implementation is used while an explicit implementation is given.
250if
251// if this is a default impl
252i.is_default
253// iterate over all implementations *in the current crate*
254 // (this is ok since we generate codegen fn attrs in the local crate)
255 // if any of them is *not default* then don't emit the alias.
256&& tcx.externally_implementable_items(LOCAL_CRATE).get(&foreign_item).expect("at least one").1.iter().any(|(_, imp)| !imp.is_default)
257 {
258continue;
259 }
260261 codegen_fn_attrs.foreign_item_symbol_aliases.push((
262 foreign_item,
263if i.is_default { Linkage::WeakAny } else { Linkage::External },
264 Visibility::Default,
265 ));
266 codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
267268// If the declaration is `#[track_caller]`, derive it onto the implementation
269 // too. The shim that forwards to this impl (see `add_function_aliases`) takes
270 // its ABI from the impl's `fn_abi`, so every impl must agree on whether the
271 // caller-location argument is present, otherwise it would be silently dropped.
272if tcx
273 .codegen_fn_attrs(foreign_item)
274 .flags
275 .contains(CodegenFnAttrFlags::TRACK_CALLER)
276 {
277 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
278 }
279 }
280 }
281 AttributeKind::ThreadLocal => {
282 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL
283 }
284 AttributeKind::InstructionSet(instruction_set) => {
285 codegen_fn_attrs.instruction_set = Some(*instruction_set)
286 }
287 AttributeKind::RustcAllocator => {
288 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR
289 }
290 AttributeKind::RustcDeallocator => {
291 codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR
292 }
293 AttributeKind::RustcReallocator => {
294 codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR
295 }
296 AttributeKind::RustcAllocatorZeroed => {
297 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
298 }
299 AttributeKind::RustcNounwind => {
300 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND
301 }
302 AttributeKind::RustcOffloadKernel => {
303 codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
304 }
305 AttributeKind::PatchableFunctionEntry { prefix, entry, section } => {
306 codegen_fn_attrs.patchable_function_entry =
307Some(PatchableFunctionEntry::from_prefix_entry_and_section(
308*prefix, *entry, *section,
309 ));
310 }
311 AttributeKind::InstrumentFn(instrument_fn) => {
312 codegen_fn_attrs.instrument_fn = match instrument_fn {
313 HirInstrumentFnAttr::On => InstrumentFnAttr::On,
314 HirInstrumentFnAttr::Off => InstrumentFnAttr::Off,
315 };
316 }
317_ => {}
318 }
319 }
320321interesting_spans322}
323324/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
325/// Please comment why when adding a new one!
326fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
327// Apply the minimum function alignment here. This ensures that a function's alignment is
328 // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
329 // it happens to be codegen'd (or const-eval'd) in.
330codegen_fn_attrs.alignment =
331 Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
332333// Passed in sanitizer settings are always the default.
334if !(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()) {
::core::panicking::panic("assertion failed: codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()")
};assert!(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default());
335// Replace with #[sanitize] value
336codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
337// On trait methods, inherit the `#[align]` of the trait's method prototype.
338codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
339340// naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
341 // but not for the code generation backend because at that point the naked function will just be
342 // a declaration, with a definition provided in global assembly.
343if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
344codegen_fn_attrs.inline = InlineAttr::Never;
345 }
346347// #73631: closures inherit `#[target_feature]` annotations
348 //
349 // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
350 //
351 // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
352 // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
353 // the function may be inlined into a caller with fewer target features. Also see
354 // <https://github.com/rust-lang/rust/issues/116573>.
355 //
356 // Using `#[inline(always)]` implies that this closure will most likely be inlined into
357 // its parent function, which effectively inherits the features anyway. Boxing this closure
358 // would result in this closure being compiled without the inherited target features, but this
359 // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
360if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
361let owner_id = tcx.parent(did.to_def_id());
362if tcx.def_kind(owner_id).has_codegen_attrs() {
363codegen_fn_attrs364 .target_features
365 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
366 }
367 }
368369// When `no_builtins` is applied at the crate level, we should add the
370 // `no-builtins` attribute to each function to ensure it takes effect in LTO.
371let no_builtins = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
372if no_builtins {
373codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
374 }
375376// inherit track-caller properly
377if tcx.should_inherit_track_caller(did) {
378codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
379 }
380381// Foreign items by default use no mangling for their symbol name.
382if tcx.is_foreign_item(did) {
383codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
384385// There's a few exceptions to this rule though:
386if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
387// * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
388 // both for exports and imports through foreign items. This is handled further,
389 // during symbol mangling logic.
390} else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
391 {
392// * externally implementable items keep their mangled symbol name.
393 // multiple EIIs can have the same name, so not mangling them would be a bug.
394 // Implementing an EII does the appropriate name resolution to make sure the implementations
395 // get the same symbol name as the *mangled* foreign item they refer to so that's all good.
396} else if codegen_fn_attrs.symbol_name.is_some() {
397// * This can be overridden with the `#[link_name]` attribute
398} else {
399// NOTE: there's one more exception that we cannot apply here. On wasm,
400 // some items cannot be `no_mangle`.
401 // However, we don't have enough information here to determine that.
402 // As such, no_mangle foreign items on wasm that have the same defid as some
403 // import will *still* be mangled despite this.
404 //
405 // if none of the exceptions apply; apply no_mangle
406codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
407 }
408 }
409}
410411#[derive(const _: () =
{
impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
SanitizeOnInline where G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
SanitizeOnInline { inline_span: __binding_0 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("non-default `sanitize` will have no effect after inlining")));
;
diag.span_note(__binding_0,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("inlining requested here")));
diag
}
}
}
}
};Diagnostic)]
412#[diag("non-default `sanitize` will have no effect after inlining")]
413struct SanitizeOnInline {
414#[note("inlining requested here")]
415inline_span: Span,
416}
417418#[derive(const _: () =
{
impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for AsyncBlocking
where G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
AsyncBlocking => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the async executor can run blocking code, without realtime sanitizer catching it")));
;
diag
}
}
}
}
};Diagnostic)]
419#[diag("the async executor can run blocking code, without realtime sanitizer catching it")]
420struct AsyncBlocking;
421422fn check_result(
423 tcx: TyCtxt<'_>,
424 did: LocalDefId,
425 interesting_spans: InterestingAttributeDiagnosticSpans,
426 codegen_fn_attrs: &CodegenFnAttrs,
427) {
428// If a function uses `#[target_feature]` it can't be inlined into general
429 // purpose functions as they wouldn't have the right target features
430 // enabled. For that reason we also forbid `#[inline(always)]` as it can't be
431 // respected.
432 //
433 // `#[rustc_force_inline]` doesn't need to be prohibited here, only
434 // `#[inline(always)]`, as forced inlining is implemented entirely within
435 // rustc (and so the MIR inliner can do any necessary checks for compatible target
436 // features).
437 //
438 // This sidesteps the LLVM blockers in enabling `target_features` +
439 // `inline(always)` to be used together (see rust-lang/rust#116573 and
440 // llvm/llvm-project#70563).
441if !codegen_fn_attrs.target_features.is_empty()
442 && #[allow(non_exhaustive_omitted_patterns)] match codegen_fn_attrs.inline {
InlineAttr::Always => true,
_ => false,
}matches!(codegen_fn_attrs.inline, InlineAttr::Always)443 && let Some(span) = interesting_spans.inline
444 {
445let mut diag = tcx446 .dcx()
447 .struct_span_err(span, "cannot use `#[inline(always)]` with `#[target_feature]`");
448diag.note(
449"See this issue for full discussion: \
450 https://github.com/rust-lang/rust/issues/145574",
451 );
452diag.emit();
453 }
454455// warn that inline has no effect when no_sanitize is present
456if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
457 && codegen_fn_attrs.inline.always()
458 && let (Some(sanitize_span), Some(inline_span)) =
459 (interesting_spans.sanitize, interesting_spans.inline)
460 {
461let hir_id = tcx.local_def_id_to_hir_id(did);
462tcx.emit_node_span_lint(
463 lint::builtin::INLINE_NO_SANITIZE,
464hir_id,
465sanitize_span,
466SanitizeOnInline { inline_span },
467 )
468 }
469470// warn for nonblocking async functions, blocks and closures.
471 // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
472if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking473 && let Some(sanitize_span) = interesting_spans.sanitize
474// async fn
475&& (tcx.asyncness(did).is_async()
476// async block
477|| tcx.is_coroutine(did.into())
478// async closure
479|| (tcx.is_closure_like(did.into())
480 && tcx.hir_node_by_def_id(did).expect_closure().kind
481 != rustc_hir::ClosureKind::Closure))
482 {
483let hir_id = tcx.local_def_id_to_hir_id(did);
484tcx.emit_node_span_lint(
485 lint::builtin::RTSAN_NONBLOCKING_ASYNC,
486hir_id,
487sanitize_span,
488AsyncBlocking,
489 );
490 }
491492// error when specifying link_name together with link_ordinal
493if let Some(_) = codegen_fn_attrs.symbol_name
494 && let Some(_) = codegen_fn_attrs.link_ordinal
495 {
496let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
497if let Some(span) = interesting_spans.link_ordinal {
498tcx.dcx().span_err(span, msg);
499 } else {
500tcx.dcx().err(msg);
501 }
502 }
503504if let Some(features) = check_tied_features(
505tcx.sess,
506&codegen_fn_attrs507 .target_features
508 .iter()
509 .map(|features| (features.name.as_str(), true))
510 .collect(),
511 ) {
512let span = {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(TargetFeature {
attr_span: span, .. }) => {
break 'done Some(*span);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span)513 .unwrap_or_else(|| tcx.def_span(did));
514515tcx.dcx()
516 .create_err(errors::TargetFeatureDisableOrEnable {
517features,
518 span: Some(span),
519 missing_features: Some(errors::MissingFeatures),
520 })
521 .emit();
522 }
523}
524525fn handle_lang_items(
526 tcx: TyCtxt<'_>,
527 did: LocalDefId,
528 interesting_spans: &InterestingAttributeDiagnosticSpans,
529 attrs: &[Attribute],
530 codegen_fn_attrs: &mut CodegenFnAttrs,
531) {
532let lang_item = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Lang(lang)) => {
break 'done Some(lang);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Lang(lang) => lang);
533534// Weak lang items have the same semantics as "std internal" symbols in the
535 // sense that they're preserved through all our LTO passes and only
536 // strippable by the linker.
537 //
538 // Additionally weak lang items have predetermined symbol names.
539if let Some(lang_item) = lang_item540 && let Some(link_name) = lang_item.link_name()
541 {
542codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
543codegen_fn_attrs.symbol_name = Some(link_name);
544 }
545546// error when using no_mangle on a lang item item
547if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
548 && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
549 {
550let mut err = tcx551 .dcx()
552 .struct_span_err(
553interesting_spans.no_mangle.unwrap_or_default(),
554"`#[no_mangle]` cannot be used on internal language items",
555 )
556 .with_note("Rustc requires this item to have a specific mangled name.")
557 .with_span_label(tcx.def_span(did), "should be the internal language item");
558if let Some(lang_item) = lang_item559 && let Some(link_name) = lang_item.link_name()
560 {
561err = err562 .with_note("If you are trying to prevent mangling to ease debugging, many")
563 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("debuggers support a command such as `rbreak {0}` to",
link_name))
})format!("debuggers support a command such as `rbreak {link_name}` to"))
564 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("match `.*{0}.*` instead of `break {0}` on a specific name",
link_name))
})format!(
565"match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
566))
567 }
568err.emit();
569 }
570}
571572/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
573///
574/// This happens in 4 stages:
575/// - apply built-in attributes that directly translate to codegen attributes.
576/// - handle lang items. These have special codegen attrs applied to them.
577/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
578/// overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
579/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
580fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
581if truecfg!(debug_assertions) {
582let def_kind = tcx.def_kind(did);
583if !def_kind.has_codegen_attrs() {
{
::core::panicking::panic_fmt(format_args!("unexpected `def_kind` in `codegen_fn_attrs`: {0:?}",
def_kind));
}
};assert!(
584 def_kind.has_codegen_attrs(),
585"unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
586 );
587 }
588589let mut codegen_fn_attrs = CodegenFnAttrs::new();
590let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
591592let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
593handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
594apply_overrides(tcx, did, &mut codegen_fn_attrs);
595check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
596597codegen_fn_attrs598}
599600fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
601// Backtrack to the crate root.
602let mut settings = match tcx.opt_local_parent(did) {
603// Check the parent (recursively).
604Some(parent) => tcx.sanitizer_settings_for(parent),
605// We reached the crate root without seeing an attribute, so
606 // there is no sanitizers to exclude.
607None => SanitizerFnAttrs::default(),
608 };
609610// Check for a sanitize annotation directly on this def.
611if let Some((on_set, off_set, rtsan)) =
612{
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Sanitize {
on_set, off_set, rtsan, .. }) => {
break 'done Some((on_set, off_set, rtsan));
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan))613 {
614// the on set is the set of sanitizers explicitly enabled.
615 // we mask those out since we want the set of disabled sanitizers here
616settings.disabled &= !*on_set;
617// the off set is the set of sanitizers explicitly disabled.
618 // we or those in here.
619settings.disabled |= *off_set;
620// the on set and off set are distjoint since there's a third option: unset.
621 // a node may not set the sanitizer setting in which case it inherits from parents.
622 // the code above in this function does this backtracking
623624 // if rtsan was specified here override the parent
625if let Some(rtsan) = rtsan {
626settings.rtsan_setting = *rtsan;
627 }
628 }
629settings630}
631632/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
633/// applied to the method prototype.
634fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
635tcx.trait_item_of(def_id).is_some_and(|id| {
636tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
637 })
638}
639640/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
641/// attribute on the method prototype (if any).
642fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
643tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
644}
645646pub(crate) fn provide(providers: &mut Providers) {
647*providers = Providers {
648codegen_fn_attrs,
649should_inherit_track_caller,
650inherited_align,
651sanitizer_settings_for,
652 ..*providers653 };
654}