Skip to content

Treat safe target_feature functions as unsafe by default #134317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion compiler/rustc_ast_lowering/src/delegation.rs
Original file line number Diff line number Diff line change
@@ -189,7 +189,15 @@ impl<'hir> LoweringContext<'_, 'hir> {
) -> hir::FnSig<'hir> {
let header = if let Some(local_sig_id) = sig_id.as_local() {
match self.resolver.delegation_fn_sigs.get(&local_sig_id) {
Some(sig) => self.lower_fn_header(sig.header, hir::Safety::Safe),
Some(sig) => self.lower_fn_header(
sig.header,
if sig.target_feature && !matches!(sig.header.safety, Safety::Unsafe(_)) {
hir::Safety::Unsafe { target_feature: true }
} else {
hir::Safety::Safe
},
&[],
),
None => self.generate_header_error(),
}
} else {
36 changes: 28 additions & 8 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
@@ -231,7 +231,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
});
let sig = hir::FnSig {
decl,
header: this.lower_fn_header(*header, hir::Safety::Safe),
header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
span: this.lower_span(*fn_sig_span),
};
hir::ItemKind::Fn(sig, generics, body_id)
@@ -609,7 +609,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let owner_id = hir_id.expect_owner();
self.lower_attrs(hir_id, &i.attrs);
let attrs = self.lower_attrs(hir_id, &i.attrs);
let item = hir::ForeignItem {
owner_id,
ident: self.lower_ident(i.ident),
@@ -633,7 +633,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
});

// Unmarked safety in unsafe block defaults to unsafe.
let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe);
let header = self.lower_fn_header(
sig.header,
hir::Safety::Unsafe { target_feature: false },
attrs,
);

hir::ForeignItemKind::Fn(
hir::FnSig { header, decl, span: self.lower_span(sig.span) },
@@ -644,7 +648,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
ForeignItemKind::Static(box StaticItem { ty, mutability, expr: _, safety }) => {
let ty = self
.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
let safety =
self.lower_safety(*safety, hir::Safety::Unsafe { target_feature: false });

hir::ForeignItemKind::Static(ty, *mutability, safety)
}
@@ -748,7 +753,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
self.lower_attrs(hir_id, &i.attrs);
let attrs = self.lower_attrs(hir_id, &i.attrs);
let trait_item_def_id = hir_id.expect_owner();

let (generics, kind, has_default) = match &i.kind {
@@ -775,6 +780,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
i.id,
FnDeclKind::Trait,
sig.header.coroutine_kind,
attrs,
);
(generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
}
@@ -793,6 +799,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
i.id,
FnDeclKind::Trait,
sig.header.coroutine_kind,
attrs,
);
(generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
}
@@ -878,7 +885,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let has_value = true;
let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
self.lower_attrs(hir_id, &i.attrs);
let attrs = self.lower_attrs(hir_id, &i.attrs);

let (generics, kind) = match &i.kind {
AssocItemKind::Const(box ConstItem { generics, ty, expr, .. }) => self.lower_generics(
@@ -908,6 +915,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
i.id,
if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
sig.header.coroutine_kind,
attrs,
);

(generics, hir::ImplItemKind::Fn(sig, body_id))
@@ -1322,8 +1330,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
id: NodeId,
kind: FnDeclKind,
coroutine_kind: Option<CoroutineKind>,
attrs: &[Attribute],
) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
let header = self.lower_fn_header(sig.header, hir::Safety::Safe);
let header = self.lower_fn_header(sig.header, hir::Safety::Safe, attrs);
let itctx = ImplTraitContext::Universal;
let (generics, decl) = self.lower_generics(generics, id, itctx, |this| {
this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind)
@@ -1335,12 +1344,23 @@ impl<'hir> LoweringContext<'_, 'hir> {
&mut self,
h: FnHeader,
default_safety: hir::Safety,
attrs: &[Attribute],
) -> hir::FnHeader {
let asyncness = if let Some(CoroutineKind::Async { span, .. }) = h.coroutine_kind {
hir::IsAsync::Async(span)
} else {
hir::IsAsync::NotAsync
};

let default_safety = if attrs.iter().any(|attr| attr.has_name(sym::target_feature))
&& !matches!(h.safety, Safety::Unsafe(_))
&& default_safety.is_safe()
{
hir::Safety::Unsafe { target_feature: true }
} else {
default_safety
};

hir::FnHeader {
safety: self.lower_safety(h.safety, default_safety),
asyncness,
@@ -1394,7 +1414,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

pub(super) fn lower_safety(&mut self, s: Safety, default: hir::Safety) -> hir::Safety {
match s {
Safety::Unsafe(_) => hir::Safety::Unsafe,
Safety::Unsafe(_) => hir::Safety::Unsafe { target_feature: false },
Safety::Default => default,
Safety::Safe(_) => hir::Safety::Safe,
}
6 changes: 3 additions & 3 deletions compiler/rustc_codegen_gcc/src/intrinsic/mod.rs
Original file line number Diff line number Diff line change
@@ -1222,7 +1222,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
iter::once(i8p),
tcx.types.unit,
false,
rustc_hir::Safety::Unsafe,
rustc_hir::Safety::Unsafe { target_feature: false },
Abi::Rust,
)),
);
@@ -1233,7 +1233,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
[i8p, i8p].iter().cloned(),
tcx.types.unit,
false,
rustc_hir::Safety::Unsafe,
rustc_hir::Safety::Unsafe { target_feature: false },
Abi::Rust,
)),
);
@@ -1242,7 +1242,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
[try_fn_ty, i8p, catch_fn_ty],
tcx.types.i32,
false,
rustc_hir::Safety::Unsafe,
rustc_hir::Safety::Unsafe { target_feature: false },
Abi::Rust,
));
let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
6 changes: 3 additions & 3 deletions compiler/rustc_codegen_llvm/src/intrinsic.rs
Original file line number Diff line number Diff line change
@@ -1091,7 +1091,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[i8p],
tcx.types.unit,
false,
hir::Safety::Unsafe,
hir::Safety::Unsafe { target_feature: false },
ExternAbi::Rust,
)),
);
@@ -1102,7 +1102,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[i8p, i8p],
tcx.types.unit,
false,
hir::Safety::Unsafe,
hir::Safety::Unsafe { target_feature: false },
ExternAbi::Rust,
)),
);
@@ -1111,7 +1111,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[try_fn_ty, i8p, catch_fn_ty],
tcx.types.i32,
false,
hir::Safety::Unsafe,
hir::Safety::Unsafe { target_feature: false },
ExternAbi::Rust,
));
let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
6 changes: 4 additions & 2 deletions compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@ use rustc_errors::{DiagMessage, SubdiagMessage, struct_span_code_err};
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS;
use rustc_hir::{HirId, LangItem, lang_items};
use rustc_hir::{self as hir, HirId, LangItem, lang_items};
use rustc_middle::middle::codegen_fn_attrs::{
CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry,
};
@@ -251,7 +251,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
sym::target_feature => {
if !tcx.is_closure_like(did.to_def_id())
&& let Some(fn_sig) = fn_sig()
&& fn_sig.skip_binder().safety().is_safe()
&& matches!(fn_sig.skip_binder().safety(), hir::Safety::Unsafe {
target_feature: true
})
{
if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
// The `#[target_feature]` attribute is allowed on
16 changes: 12 additions & 4 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
@@ -3390,14 +3390,21 @@ impl<'hir> Item<'hir> {
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(Encodable, Decodable, HashStable_Generic)]
pub enum Safety {
Unsafe,
Unsafe {
/// Whether this is a safe target_feature function.
/// We treat those as unsafe almost everywhere, but in unsafeck,
/// which allows calling them from other target_feature functions
/// without an `unsafe` block.
target_feature: bool,
},
Safe,
}

impl Safety {
pub fn prefix_str(self) -> &'static str {
match self {
Self::Unsafe => "unsafe ",
Self::Unsafe { target_feature: false } => "unsafe ",
Self::Unsafe { target_feature: true } => "#[target_feature] ",
Self::Safe => "",
}
}
@@ -3410,7 +3417,7 @@ impl Safety {
#[inline]
pub fn is_safe(self) -> bool {
match self {
Self::Unsafe => false,
Self::Unsafe { .. } => false,
Self::Safe => true,
}
}
@@ -3419,7 +3426,8 @@ impl Safety {
impl fmt::Display for Safety {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match *self {
Self::Unsafe => "unsafe",
Self::Unsafe { target_feature: false } => "unsafe",
Self::Unsafe { target_feature: true } => "#[target_feature] safe",
Self::Safe => "safe",
})
}
6 changes: 3 additions & 3 deletions compiler/rustc_hir_analysis/src/check/intrinsic.rs
Original file line number Diff line number Diff line change
@@ -76,7 +76,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
tcx.fn_sig(intrinsic_id).skip_binder().safety()
} else {
// Old-style intrinsics are never safe
Safety::Unsafe
Safety::Unsafe { target_feature: false }
};
let is_in_list = match tcx.item_name(intrinsic_id.into()) {
// When adding a new intrinsic to this list,
@@ -137,7 +137,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
| sym::fdiv_algebraic
| sym::frem_algebraic
| sym::const_eval_select => hir::Safety::Safe,
_ => hir::Safety::Unsafe,
_ => hir::Safety::Unsafe { target_feature: false },
};

if has_safe_attr != is_in_list {
@@ -216,7 +216,7 @@ pub fn check_intrinsic_type(
return;
}
};
(n_tps, 0, 0, inputs, output, hir::Safety::Unsafe)
(n_tps, 0, 0, inputs, output, hir::Safety::Unsafe { target_feature: false })
} else {
let safety = intrinsic_operation_unsafety(tcx, intrinsic_id);
let (n_tps, n_cts, inputs, output) = match intrinsic_name {
12 changes: 6 additions & 6 deletions compiler/rustc_hir_analysis/src/coherence/unsafety.rs
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ pub(super) fn check_item(
let trait_def_safety = if is_copy {
// If `Self` has unsafe fields, `Copy` is unsafe to implement.
if trait_header.trait_ref.skip_binder().self_ty().has_unsafe_fields() {
rustc_hir::Safety::Unsafe
rustc_hir::Safety::Unsafe { target_feature: false }
} else {
rustc_hir::Safety::Safe
}
@@ -33,7 +33,7 @@ pub(super) fn check_item(
};

match (trait_def_safety, unsafe_attr, trait_header.safety, trait_header.polarity) {
(Safety::Safe, None, Safety::Unsafe, Positive | Reservation) => {
(Safety::Safe, None, Safety::Unsafe { .. }, Positive | Reservation) => {
let span = tcx.def_span(def_id);
return Err(struct_span_code_err!(
tcx.dcx(),
@@ -51,7 +51,7 @@ pub(super) fn check_item(
.emit());
}

(Safety::Unsafe, _, Safety::Safe, Positive | Reservation) => {
(Safety::Unsafe { .. }, _, Safety::Safe, Positive | Reservation) => {
let span = tcx.def_span(def_id);
return Err(struct_span_code_err!(
tcx.dcx(),
@@ -109,14 +109,14 @@ pub(super) fn check_item(
.emit());
}

(_, _, Safety::Unsafe, Negative) => {
(_, _, Safety::Unsafe { .. }, Negative) => {
// Reported in AST validation
assert!(tcx.dcx().has_errors().is_some(), "unsafe negative impl");
Ok(())
}
(_, _, Safety::Safe, Negative)
| (Safety::Unsafe, _, Safety::Unsafe, Positive | Reservation)
| (Safety::Safe, Some(_), Safety::Unsafe, Positive | Reservation)
| (Safety::Unsafe { .. }, _, Safety::Unsafe { .. }, Positive | Reservation)
| (Safety::Safe, Some(_), Safety::Unsafe { .. }, Positive | Reservation)
| (Safety::Safe, None, Safety::Safe, _) => Ok(()),
}
}
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/collect.rs
Original file line number Diff line number Diff line change
@@ -1371,7 +1371,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFn
// constructors for structs with `layout_scalar_valid_range` are unsafe to call
let safety = match tcx.layout_scalar_valid_range(adt_def_id) {
(Bound::Unbounded, Bound::Unbounded) => hir::Safety::Safe,
_ => hir::Safety::Unsafe,
_ => hir::Safety::Unsafe { target_feature: false },
};
ty::Binder::dummy(tcx.mk_fn_sig(inputs, ty, false, safety, ExternAbi::Rust))
}
4 changes: 2 additions & 2 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
@@ -2293,8 +2293,8 @@ impl<'a> State<'a> {

fn print_safety(&mut self, s: hir::Safety) {
match s {
hir::Safety::Safe => {}
hir::Safety::Unsafe => self.word_nbsp("unsafe"),
hir::Safety::Unsafe { target_feature: true } | hir::Safety::Safe => {}
hir::Safety::Unsafe { target_feature: false } => self.word_nbsp("unsafe"),
}
}

11 changes: 8 additions & 3 deletions compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
@@ -863,7 +863,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
let outer_universe = self.infcx.universe();

let result = if let ty::FnPtr(_, hdr_b) = b.kind()
&& fn_ty_a.safety().is_safe()
&& matches!(
fn_ty_a.safety(),
hir::Safety::Safe | hir::Safety::Unsafe { target_feature: true }
)
&& hdr_b.safety.is_unsafe()
{
let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
@@ -924,10 +927,12 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
return Err(TypeError::IntrinsicCast);
}

// Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
// Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396),
// report a better error than a safety mismatch.
// FIXME(target_feature): do this inside `coerce_from_safe_fn`

if b_hdr.safety.is_safe()
&& !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
&& matches!(a_sig.safety(), hir::Safety::Unsafe { target_feature: true })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in #134090 (comment), we might want to make this actually safe if the function this happens in has the required features.
We probably shouldn't change it now, but we might want to modify the comment/FIXME accordingly

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the features are also set via target information that can't differ between crates linked together?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if doing so is supposed to be ok...

Anyway, I guess the point of the comment is that if you can call a function, then you also ought to be able to take a safe fn pointer to it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But safe pointers can be passed around to code where it's not safe to use them.

With the change I made (plus encoding the actually used target features) we can in theory start creating safe target feature pointers by keeping the target feature information on the function pointer type.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

target_feature_11 enables this:

#[target_feature(enable = "avx2")]
fn bar() -> fn() {
    || avx2()
}

which is not particularly different from allowing coercion of avx2 to a fn pointer. If you have concerns about this, the stabilization PR is probably the better place to discuss it (the stabilization report mentions why it's OK to do this)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh right, yea that makes sense. You already had to call an unsafe function to get here, and it's not a footgun, because it's global informatiom, not local

{
return Err(TypeError::TargetFeatureCast(def_id));
}
Loading