diff --git a/compiler/rustc_attr_ir/src/attribute_docs.rs b/compiler/rustc_attr_ir/src/attribute_docs.rs index cb42c7a7bd742..5b1c1c9687d5d 100644 --- a/compiler/rustc_attr_ir/src/attribute_docs.rs +++ b/compiler/rustc_attr_ir/src/attribute_docs.rs @@ -167,6 +167,21 @@ const _: () = (); /// [`object_lifetime_default`]: ../rustc_middle/ty/struct.TyCtxt.html#method.object_lifetime_default const _: () = (); +#[cfg_attr(not(bootstrap), doc(attribute = "rustc_dump_ptrauth_discriminator"))] +/// Dumps the function pointer type discriminator of the annotated function. +/// +/// The discriminator is computed from an encoding of the function's signature (function type). The +/// `ptrauth_encoding` argument prints this encoding, while the `ptrauth_hash` argument prints the +/// resulting discriminator hash. +/// +/// See [`AttributeKind::RustcDumpPtrauthDiscriminator`] for the internal representation of this +/// attribute. +/// +/// # Example +/// +#[doc = include_example!("rustc_dump_ptrauth_discriminator")] +const _: () = (); + #[doc(attribute = "rustc_dump_symbol_name")] /// Dumps the symbol name of the annotated item, also demangling it if necessary. /// diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 26db9819bb7ca..ee20945ced906 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -626,6 +626,12 @@ pub enum RustcDumpLayoutKind { Size, } +#[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)] +pub enum RustcDumpPtrauthDiscriminatorKind { + Encoding, + Hash, +} + #[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute, PartialEq, Eq)] pub enum RustcMirKind { PrettyLiveLocals, @@ -1158,6 +1164,11 @@ pub enum AttributeKind { /// Represents `#[profiler_runtime]` ProfilerRuntime, + /// Represents `#[rustc_ptrauth_c_discriminator(N)]` + PtrauthCDiscriminator { + discriminator: u16, + }, + /// Represents [`#[recursion_limit]`](https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute) RecursionLimit { limit: Limit, @@ -1329,6 +1340,9 @@ pub enum AttributeKind { /// Represents the [`rustc_dump_object_lifetime_defaults`](./attribute.rustc_dump_object_lifetime_defaults.html) attribute. RustcDumpObjectLifetimeDefaults, + /// Represents the [`rustc_dump_ptrauth_discriminator`](./attribute.rustc_dump_ptrauth_discriminator.html) attribute. + RustcDumpPtrauthDiscriminator(ThinVec), + /// Represents the [`rustc_dump_symbol_name`](./attribute.rustc_dump_symbol_name.html) attribute. RustcDumpSymbolName(Span), diff --git a/compiler/rustc_attr_ir/src/encode_cross_crate.rs b/compiler/rustc_attr_ir/src/encode_cross_crate.rs index ca9b79ccc8a51..21d746630cdb8 100644 --- a/compiler/rustc_attr_ir/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_ir/src/encode_cross_crate.rs @@ -100,6 +100,8 @@ impl AttributeKind { ProcMacroAttribute => No, ProcMacroDerive { .. } => No, ProfilerRuntime => No, + // Fields of a type are read by the crate that codegens a static of that type. + PtrauthCDiscriminator { .. } => Yes, RecursionLimit { .. } => No, ReexportTestHarnessMain(..) => No, RegisterTool { .. } => No, @@ -144,6 +146,7 @@ impl AttributeKind { RustcDumpItemBounds => No, RustcDumpLayout(..) => No, RustcDumpObjectLifetimeDefaults => No, + RustcDumpPtrauthDiscriminator(..) => No, RustcDumpSymbolName(..) => Yes, RustcDumpUserArgs => No, RustcDumpVariances => No, @@ -319,6 +322,7 @@ impl AttributeKind { ProcMacroAttribute => false, ProcMacroDerive { .. } => false, ProfilerRuntime => false, + PtrauthCDiscriminator { .. } => false, RecursionLimit { .. } => false, ReexportTestHarnessMain(..) => false, RegisterTool { .. } => false, @@ -363,6 +367,7 @@ impl AttributeKind { RustcDumpItemBounds => false, RustcDumpLayout(..) => false, RustcDumpObjectLifetimeDefaults => false, + RustcDumpPtrauthDiscriminator(..) => false, RustcDumpSymbolName(..) => false, RustcDumpUserArgs => false, RustcDumpVariances => false, diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 25eb0b9887c53..86f1054a540a1 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -66,6 +66,7 @@ pub(crate) mod path; pub(crate) mod pin_v2; pub(crate) mod proc_macro_attrs; pub(crate) mod prototype; +pub(crate) mod ptrauth_c_discriminator; pub(crate) mod repr; pub(crate) mod rustc_allocator; pub(crate) mod rustc_dump; diff --git a/compiler/rustc_attr_parsing/src/attributes/ptrauth_c_discriminator.rs b/compiler/rustc_attr_parsing/src/attributes/ptrauth_c_discriminator.rs new file mode 100644 index 0000000000000..8504d52dd2f5e --- /dev/null +++ b/compiler/rustc_attr_parsing/src/attributes/ptrauth_c_discriminator.rs @@ -0,0 +1,33 @@ +use rustc_ast::LitKind; +use rustc_feature::AttributeStability; + +use super::prelude::*; + +/// Parses `#[rustc_ptrauth_c_discriminator(N)]` on a static, or on a field of a type held in a static: +/// code addresses are signed with discriminator `N`. +pub(crate) struct PtrauthCDiscriminatorParser; +impl SingleAttributeParser for PtrauthCDiscriminatorParser { + const PATH: &[Symbol] = &[sym::rustc_ptrauth_c_discriminator]; + const ALLOWED_TARGETS: AllowedTargets<'_> = + AllowedTargets::AllowList(&[Allow(Target::Static), Allow(Target::Field)]); + const TEMPLATE: AttributeTemplate = template!(List: &["discriminator"]); + const STABILITY: AttributeStability = unstable!(ptrauth_c_discriminator); + + fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { + let single = cx.expect_single_element_list(args, cx.attr_span)?; + let Some(lit) = single.as_lit() else { + cx.adcx().expected_integer_literal(single.span()); + return None; + }; + let LitKind::Int(value, _) = lit.kind else { + cx.adcx().expected_integer_literal(single.span()); + return None; + }; + let Ok(discriminator) = u16::try_from(value.get()) else { + cx.adcx().expected_integer_literal_in_range(single.span(), 0, u16::MAX as isize); + return None; + }; + + Some(AttributeKind::PtrauthCDiscriminator { discriminator }) + } +} diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs index 9a2a9681f78ea..729890e84cb47 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs @@ -1,5 +1,7 @@ use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target}; -use rustc_attr_ir::{AttributeKind, RustcDumpLayoutKind, RustcShowSpansKind}; +use rustc_attr_ir::{ + AttributeKind, RustcDumpLayoutKind, RustcDumpPtrauthDiscriminatorKind, RustcShowSpansKind, +}; use rustc_feature::AttributeStability; use rustc_span::{Span, Symbol, sym}; @@ -178,6 +180,56 @@ impl CombineAttributeParser for RustcDumpLayoutParser { } } +pub(crate) struct RustcDumpPtrauthDiscriminatorParser; + +impl CombineAttributeParser for RustcDumpPtrauthDiscriminatorParser { + const PATH: &[Symbol] = &[sym::rustc_dump_ptrauth_discriminator]; + + type Item = RustcDumpPtrauthDiscriminatorKind; + + const CONVERT: ConvertFn = + |items, _| AttributeKind::RustcDumpPtrauthDiscriminator(items); + + const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Fn)]); + + const TEMPLATE: AttributeTemplate = template!(List: &["encoding", "hash"]); + const STABILITY: AttributeStability = unstable!(rustc_attrs); + + fn extend( + cx: &mut AcceptContext<'_, '_>, + args: &ArgParser, + ) -> impl IntoIterator { + let Some(items) = cx.expect_list(args, cx.attr_span) else { + return vec![]; + }; + + let mut result = Vec::new(); + for item in items.mixed() { + let Some(arg) = item.meta_item_no_args() else { + cx.adcx().expected_not_literal(item.span()); + continue; + }; + let Some(ident) = arg.ident() else { + cx.adcx().expected_identifier(arg.span()); + return vec![]; + }; + let kind = match ident.name { + sym::ptrauth_encoding => RustcDumpPtrauthDiscriminatorKind::Encoding, + sym::ptrauth_hash => RustcDumpPtrauthDiscriminatorKind::Hash, + _ => { + cx.adcx().expected_specific_argument( + ident.span, + &[sym::ptrauth_encoding, sym::ptrauth_hash], + ); + continue; + } + }; + result.push(kind); + } + result + } +} + pub(crate) struct RustcDumpObjectLifetimeDefaultsParser; impl NoArgsAttributeParser for RustcDumpObjectLifetimeDefaultsParser { diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 59c583d4eb435..4581cf61bcf94 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -56,6 +56,7 @@ use crate::attributes::path::PathParser as PathAttributeParser; use crate::attributes::pin_v2::*; use crate::attributes::proc_macro_attrs::*; use crate::attributes::prototype::*; +use crate::attributes::ptrauth_c_discriminator::*; use crate::attributes::repr::*; use crate::attributes::rustc_allocator::*; use crate::attributes::rustc_dump::*; @@ -197,6 +198,7 @@ attribute_parsers!( Combine, Combine, Combine, + Combine, Combine, Combine, Combine, @@ -230,6 +232,7 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index 531ff0da6922b..3613836b29266 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -1918,6 +1918,21 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn fptosi_sat(&mut self, val: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.fptoint_sat(true, val, dest_ty) } + + fn ptrauth_resign( + &mut self, + _value: Self::Value, + _old_key: u32, + _old_discriminator: u64, + _new_key: u32, + _new_discriminator: u64, + ) -> Self::Value { + bug!("Resigning of pointers not implemented"); + } + + fn ptrauth_strip(&mut self, _value: Self::Value, _key: u32) -> Self::Value { + bug!("Stripping of pointer signatures not implemented"); + } } impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { diff --git a/compiler/rustc_codegen_gcc/src/int.rs b/compiler/rustc_codegen_gcc/src/int.rs index bef1af78c6a7a..3b0189432fa03 100644 --- a/compiler/rustc_codegen_gcc/src/int.rs +++ b/compiler/rustc_codegen_gcc/src/int.rs @@ -425,6 +425,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { fixed_count: 3, conv: CanonAbi::C, can_unwind: false, + ptrauth_discriminator: None, }; fn_abi.adjust_for_foreign_abi(self.cx, ExternAbi::C { unwind: false }); diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 2f57ecdaa6f19..edcf015ef9b7f 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -7,7 +7,7 @@ pub(crate) mod autodiff; pub(crate) mod gpu_offload; use libc::{c_char, c_uint}; -use rustc_abi::{self as abi, Align, CanonAbi, Float, Size, WrappingRange}; +use rustc_abi::{self as abi, Align, Float, Size, WrappingRange}; use rustc_attr_ir::UnrollAttr; use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope}; @@ -1532,6 +1532,34 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx); attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]); } + + fn ptrauth_resign( + &mut self, + value: Value<'ll>, + old_key: u32, + old_discriminator: u64, + new_key: u32, + new_discriminator: u64, + ) -> Value<'ll> { + let ptr_as_int = self.ptrtoint(value, self.type_i64()); + let resigned_int = self.call_intrinsic( + "llvm.ptrauth.resign", + &[], + &[ + ptr_as_int, + self.const_i32(old_key as i32), + self.const_i64(old_discriminator as i64), + self.const_i32(new_key as i32), + self.const_i64(new_discriminator as i64), + ], + ); + + self.inttoptr(resigned_int, self.val_ty(value)) + } + + fn ptrauth_strip(&mut self, value: Value<'ll>, key: u32) -> Value<'ll> { + self.call_intrinsic("llvm.ptrauth.strip", &[], &[value, self.const_i32(key as i32)]) + } } impl<'ll> Builder<'_, 'll, '_> { @@ -2156,11 +2184,9 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { ) -> Option> { let schema = self.sess().pointer_authentication_functions()?; - // Pointer authentication support is currently limited to extern "C" calls; filter out other - // ABIs. - if fn_abi?.conv != CanonAbi::C { - return None; - } + // `ptrauth_discriminator` is only Some for ABIs that support pointer authentication (None + // by default) - see `is_ptrauth_signed_abi`. + let discriminator = fn_abi?.ptrauth_discriminator?; // Filter out LLVM intrinsics. if llvm::get_value_name(llfn).starts_with(b"llvm.") { return None; @@ -2175,10 +2201,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { // discussion in the rust-lang issue: Some(llvm::OperandBundleBox::new( "ptrauth", - &[ - self.const_u32(schema.key as u32), - self.const_u64(schema.constant_discriminator as u64), - ], + &[self.const_u32(schema.key as u32), self.const_u64(discriminator)], )) } diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index c6f2ea0f82ab3..114a25ad218d7 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -4,7 +4,7 @@ use std::borrow::Borrow; use libc::c_uint; use rustc_abi::Primitive::Pointer; -use rustc_abi::{self as abi, ExternAbi, HasDataLayout as _}; +use rustc_abi::{self as abi, HasDataLayout as _}; use rustc_ast::Mutability; use rustc_codegen_ssa::traits::*; use rustc_crate_store::DllImport; @@ -13,6 +13,7 @@ use rustc_hashes::Hash128; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_middle::mir::interpret::{GlobalAlloc, PointerArithmetic, Scalar}; +use rustc_middle::ptrauth::{is_ptrauth_signed_abi, ptrauth_signing_discriminator_for}; use rustc_middle::ty::{Instance, TyCtxt}; use rustc_session::{PointerAuthAddressDiscriminator, PointerAuthSchema}; use rustc_span::bug; @@ -26,7 +27,7 @@ use crate::llvm::{ }; pub(crate) fn maybe_sign_fn_ptr<'ll, 'tcx>( - cx: &CodegenCx<'ll, '_>, + cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, llfn: llvm::Value<'ll>, schema: &PointerAuthSchema, @@ -40,9 +41,8 @@ pub(crate) fn maybe_sign_fn_ptr<'ll, 'tcx>( if !matches!(cx.tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) { return llfn; } - // Only C ABI - let abi = cx.tcx.fn_sig(def_id).skip_binder().abi(); - if !matches!(abi, ExternAbi::C { .. } | ExternAbi::System { .. }) { + // Only supported ABIs + if !is_ptrauth_signed_abi(cx.tcx.fn_sig(def_id).skip_binder().abi()) { return llfn; } // Ignore LLVM intrinsics @@ -53,6 +53,16 @@ pub(crate) fn maybe_sign_fn_ptr<'ll, 'tcx>( return llfn; } + // Under function pointer type discrimination, a function pointer is signed with the + // discriminator of the function it points to, whatever type it is later stored as or + // reinterpreted as. Reinterpretation is a plain bit copy, and a call authenticates with the + // discriminator of the type it is made through, so only calls through a signature that is not + // ABI-compatible with the callee fail, and those calls are UB already. Schemas without type + // discrimination (e.g. init/fini) keep their constant discriminator. + let Some(discriminator) = ptrauth_signing_discriminator_for(cx.tcx, schema, instance) else { + return llfn; + }; + let addr_diversity = match schema.is_address_discriminated { PointerAuthAddressDiscriminator::HardwareAddress(true) => Some(llfn), PointerAuthAddressDiscriminator::HardwareAddress(false) => None, @@ -62,7 +72,7 @@ pub(crate) fn maybe_sign_fn_ptr<'ll, 'tcx>( Some(unsafe { llvm::LLVMConstIntToPtr(llval, llty) }) } }; - const_ptr_auth(llfn, schema.key as u32, schema.constant_discriminator as u64, addr_diversity) + const_ptr_auth(llfn, schema.key as u32, discriminator as u64, addr_diversity) } /* @@ -228,7 +238,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { } }; - let init = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No); + let init = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No, &[]); let alloc = alloc.inner(); let value = match alloc.mutability { diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index e9a1aae4d2140..f26be554c46aa 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -1,6 +1,6 @@ use std::ops::Range; -use rustc_abi::{Align, ExternAbi, HasDataLayout, Primitive, Scalar, Size, WrappingRange}; +use rustc_abi::{Align, HasDataLayout, Primitive, Scalar, Size, WrappingRange}; use rustc_attr_ir::Linkage; use rustc_attr_ir::lang_items::LangItem; use rustc_codegen_ssa::common; @@ -13,14 +13,19 @@ use rustc_middle::mir::interpret::{ read_target_uint, }; use rustc_middle::mono::MonoItem; +use rustc_middle::ptrauth::{PtrauthCDiscriminatorError, ptrauth_c_discriminator_slots}; use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf}; use rustc_middle::ty::{self, Instance}; +use rustc_session::{PointerAuthDiscrimination, PointerAuthSchema}; use rustc_span::{Symbol, bug, span_bug}; use rustc_target::spec::Arch; use tracing::{debug, instrument, trace}; use crate::common::CodegenCx; -use crate::diagnostics::SymbolAlreadyDefined; +use crate::diagnostics::{ + PtrauthCDiscriminatorConflict, PtrauthCDiscriminatorFieldNotSlot, + PtrauthCDiscriminatorStaticNotSlot, SymbolAlreadyDefined, +}; use crate::llvm::{self, Type, Value, const_ptr_auth}; use crate::{base, debuginfo}; @@ -35,11 +40,15 @@ pub(crate) enum IsInitOrFini { Yes, No, } +/// `ptrauth_c_slots` are the offsets of the slots marked `#[rustc_ptrauth_c_discriminator]`, sorted, with +/// their discriminators (see `ptrauth_c_discriminator_slots`). A code address in one of them is +/// signed with that discriminator instead of its function's. pub(crate) fn const_alloc_to_llvm<'ll>( cx: &CodegenCx<'ll, '_>, alloc: &Allocation, is_static: IsStatic, is_init_fini: IsInitOrFini, + ptrauth_c_slots: &[(Size, u16)], ) -> Value<'ll> { // We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or // integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be @@ -119,10 +128,32 @@ pub(crate) fn const_alloc_to_llvm<'ll>( as u64; let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx); + // Function pointers are signed with the discriminator of the function they point to (see + // `maybe_sign_fn_ptr`), independently of the type of the field holding them, except in + // slots marked `#[rustc_ptrauth_c_discriminator(N)]`, which uses the value of `N`. Init/fini + // entries use their own schema. + let c_slot_schema; let schema = if cx.sess().pointer_authentication() { match is_init_fini { IsInitOrFini::Yes => cx.sess().pointer_authentication_init_fini(), - IsInitOrFini::No => cx.sess().pointer_authentication_functions(), + IsInitOrFini::No => { + let c_slot = ptrauth_c_slots + .binary_search_by_key(&Size::from_bytes(offset), |&(offset, _)| offset) + .ok() + .map(|i| ptrauth_c_slots[i].1); + match (cx.sess().pointer_authentication_functions(), c_slot) { + // A slot in C's encoding is signed with the discriminator C uses for it. + (Some(schema), Some(discriminator)) => { + c_slot_schema = PointerAuthSchema { + discrimination_kind: PointerAuthDiscrimination::Constant, + constant_discriminator: discriminator, + ..schema.clone() + }; + Some(&c_slot_schema) + } + (schema, _) => schema, + } + } } } else { None @@ -173,7 +204,52 @@ fn codegen_static_initializer<'ll, 'tcx>( } }) .unwrap_or(IsInitOrFini::No); - Ok((const_alloc_to_llvm(cx, alloc.inner(), IsStatic::Yes, is_in_init_fini), alloc)) + let ptrauth_c_slots = ptrauth_c_slots(cx, def_id, &is_in_init_fini); + Ok(( + const_alloc_to_llvm(cx, alloc.inner(), IsStatic::Yes, is_in_init_fini, &ptrauth_c_slots), + alloc, + )) +} + +/// The slots of the static `def_id` marked `#[rustc_ptrauth_c_discriminator]` (see +/// `ptrauth_c_discriminator_slots`). +/// +/// Without function pointer type discrimination, C signs every code address with the same +/// discriminator as Rust does (0), so the marks change nothing (but are still checked). +/// Init/fini entries keep the init/fini schema. +fn ptrauth_c_slots<'ll, 'tcx>( + cx: &CodegenCx<'ll, 'tcx>, + def_id: DefId, + is_in_init_fini: &IsInitOrFini, +) -> Vec<(Size, u16)> { + if !cx.sess().pointer_authentication() || matches!(is_in_init_fini, IsInitOrFini::Yes) { + return Vec::new(); + } + let slots = match ptrauth_c_discriminator_slots(cx.tcx, def_id) { + Ok(slots) => slots, + Err(PtrauthCDiscriminatorError::StaticNotSlot { ty }) => { + cx.tcx.dcx().emit_err(PtrauthCDiscriminatorStaticNotSlot { + span: cx.tcx.def_span(def_id), + ty: ty.to_string(), + }); + return Vec::new(); + } + Err(PtrauthCDiscriminatorError::FieldNotSlot { field, ty }) => { + cx.tcx.dcx().emit_err(PtrauthCDiscriminatorFieldNotSlot { + span: cx.tcx.def_span(field), + ty: ty.to_string(), + }); + return Vec::new(); + } + Err(PtrauthCDiscriminatorError::Conflict { offset }) => { + cx.tcx.dcx().emit_err(PtrauthCDiscriminatorConflict { + span: cx.tcx.def_span(def_id), + offset: offset.bytes(), + }); + return Vec::new(); + } + }; + if cx.sess().pointer_authentication_fn_ptr_type_discrimination() { slots } else { Vec::new() } } fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: Value<'ll>, mut align: Align) { @@ -196,7 +272,8 @@ fn check_and_apply_linkage<'ll, 'tcx>( if let Some(linkage) = attrs.import_linkage { debug!("get_static: sym={} linkage={:?}", sym, linkage); - let mut should_sign = false; + // The discriminator to sign the address of an `extern_weak` function with (if needed). + let mut ptrauth_discriminator = None; // Declare a symbol `foo`. If `foo` is an extern_weak symbol, we declare // an extern_weak function, otherwise a global with the desired linkage. let actual_global = if matches!(attrs.import_linkage, Some(Linkage::ExternalWeak)) { @@ -210,12 +287,10 @@ fn check_and_apply_linkage<'ll, 'tcx>( { let fn_sig = sig.with(*header); let fn_abi = cx.fn_abi_of_fn_ptr(fn_sig, ty::List::empty()); - // Decide if the initializer needs to be signed - if cx.sess().pointer_authentication_functions().is_some() - && matches!(fn_sig.abi(), ExternAbi::C { .. } | ExternAbi::System { .. }) - { - should_sign = true; - } + // The initializer is called through its function pointer type, if type + // discrimination is enabled it is signed with the discriminator calls through that + // type authenticate with. + ptrauth_discriminator = fn_abi.ptrauth_discriminator; cx.declare_fn(sym, fn_abi, None) } else { cx.declare_global(sym, cx.type_i8()) @@ -230,7 +305,7 @@ fn check_and_apply_linkage<'ll, 'tcx>( cx.assume_dso_local(actual_global, true); // Sign the function pointer that is used to initialize the global - let initializer = if should_sign { + let initializer = if let Some(discriminator) = ptrauth_discriminator { let schema = cx .tcx .sess @@ -240,7 +315,7 @@ fn check_and_apply_linkage<'ll, 'tcx>( const_ptr_auth( actual_global, schema.key as u32, - schema.constant_discriminator as u64, + discriminator, None, /* address_diversity */ ) } else { @@ -909,7 +984,7 @@ impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> { fn static_addr_of(&self, alloc: ConstAllocation<'_>, kind: Option<&str>) -> Value<'ll> { // FIXME: should we cache `const_alloc_to_llvm` to avoid repeating this for the // same `ConstAllocation`? - let cv = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No); + let cv = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No, &[]); let gv = self.static_addr_of_impl(cv, alloc.inner().align, kind); // static_addr_of_impl returns the bare global variable, which might not be in the default diff --git a/compiler/rustc_codegen_llvm/src/diagnostics.rs b/compiler/rustc_codegen_llvm/src/diagnostics.rs index 7d24dec502dbb..bfa82f3164af8 100644 --- a/compiler/rustc_codegen_llvm/src/diagnostics.rs +++ b/compiler/rustc_codegen_llvm/src/diagnostics.rs @@ -18,6 +18,39 @@ pub(crate) struct SymbolAlreadyDefined<'a> { #[diag("`-Zsanitizer=memtag` requires `-Ctarget-feature=+mte`")] pub(crate) struct SanitizerMemtagRequiresMte; +#[derive(Diagnostic)] +#[diag( + "`#[rustc_ptrauth_c_discriminator]` on a static needs a pointer or a pointer-sized integer, or an array of them, not `{$ty}`" +)] +#[help( + "put `#[rustc_ptrauth_c_discriminator]` on the fields of `{$ty}` that hold code addresses instead" +)] +pub(crate) struct PtrauthCDiscriminatorStaticNotSlot { + #[primary_span] + pub span: Span, + pub ty: String, +} + +#[derive(Diagnostic)] +#[diag( + "`#[rustc_ptrauth_c_discriminator]` needs a field that is a pointer or a pointer-sized integer, or an array of them, not `{$ty}`" +)] +pub(crate) struct PtrauthCDiscriminatorFieldNotSlot { + #[primary_span] + pub span: Span, + pub ty: String, +} + +#[derive(Diagnostic)] +#[diag( + "fields marked `#[rustc_ptrauth_c_discriminator]` with different discriminators overlap at offset {$offset}" +)] +pub(crate) struct PtrauthCDiscriminatorConflict { + #[primary_span] + pub span: Span, + pub offset: u64, +} + pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>); impl Diagnostic<'_> for ParseTargetMachineConfig<'_> { diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index 1bfd977c2fce3..cdc4175006eef 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -1,5 +1,7 @@ -use rustc_abi::{Align, FieldIdx, WrappingRange}; +use rustc_abi::{Align, BackendRepr, FieldIdx, Primitive, WrappingRange}; use rustc_middle::mir::SourceInfo; +use rustc_middle::ptrauth::ptrauth_c_encoding; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt}; use rustc_session::config::OptLevel; use rustc_span::{ErrorGuaranteed, bug, span_bug, sym}; @@ -8,7 +10,7 @@ use rustc_target::spec::Arch; use super::operand::{OperandRef, OperandValue}; use super::place::PlaceValue; use super::{FunctionCx, IntrinsicResult}; -use crate::common::{AtomicRmwBinOp, SynchronizationScope}; +use crate::common::{AtomicRmwBinOp, IntPredicate, SynchronizationScope}; use crate::diagnostics::InvalidMonomorphization; use crate::mir::operand::OperandRefBuilder; use crate::traits::*; @@ -220,6 +222,38 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } OperandValue::Immediate(value) } + sym::ptrauth_c_cast => { + let (src_ty, dst_ty) = (fn_args.type_at(0), fn_args.type_at(1)); + let src_disc = ptrauth_c_encoding(bx.tcx(), src_ty).discriminator(); + let dst_disc = ptrauth_c_encoding(bx.tcx(), dst_ty).discriminator(); + let (Some(src_disc), true) = (src_disc, is_ptr_sized_scalar(bx, args[0].layout)) + else { + return IntrinsicResult::Err(invalid_monomorphization_int_or_ptr_type(src_ty)); + }; + let (Some(dst_disc), true) = (dst_disc, is_ptr_sized_scalar(bx, result_layout)) + else { + return IntrinsicResult::Err(invalid_monomorphization_int_or_ptr_type(dst_ty)); + }; + OperandValue::Immediate(codegen_ptrauth_c_cast( + bx, + args[0], + result_layout, + src_disc, + dst_disc, + )) + } + sym::ptrauth_strip => { + let ty = fn_args.type_at(0); + if !is_ptr_sized_scalar(bx, args[0].layout) { + return IntrinsicResult::Err(invalid_monomorphization_int_or_ptr_type(ty)); + } + let addr = scalar_to_usize(bx, args[0]); + let addr = match bx.sess().pointer_authentication_fn_ptr_key() { + Some(key) => bx.ptrauth_strip(addr, key as u32), + None => addr, + }; + OperandValue::Immediate(addr) + } sym::arith_offset => { let ty = fn_args.type_at(0); let layout = bx.layout_of(ty); @@ -636,6 +670,95 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } +/// Return true if `layout` is a pointer-sized scalar holding a pointer or an integer (a value that +/// can hold a code address). +fn is_ptr_sized_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &Bx, + layout: TyAndLayout<'tcx>, +) -> bool { + match layout.backend_repr { + BackendRepr::Scalar(s) => { + matches!(s.primitive(), Primitive::Pointer(_) | Primitive::Int(..)) + && s.size(bx) == bx.data_layout().pointer_size() + } + _ => false, + } +} + +/// Returns the pointer-sized scalar `op` as a `usize` value. +fn scalar_to_usize<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + op: OperandRef<'tcx, Bx::Value>, +) -> Bx::Value { + let BackendRepr::Scalar(s) = op.layout.backend_repr else { + bug!("expected a scalar, found {:?}", op.layout); + }; + let imm = op.immediate(); + match s.primitive() { + Primitive::Pointer(_) => bx.ptrtoint(imm, bx.type_isize()), + _ => imm, + } +} + +/// Lowers `ptrauth_c_cast`: reinterprets the pointer-sized scalar `src` as `dst_layout` and, under +/// function pointer type discrimination, resigning the code address it holds from `src_disc` to +/// `dst_disc` (if they differ) . +fn codegen_ptrauth_c_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + src: OperandRef<'tcx, Bx::Value>, + dst_layout: TyAndLayout<'tcx>, + src_disc: u16, + dst_disc: u16, +) -> Bx::Value { + let BackendRepr::Scalar(src_scalar) = src.layout.backend_repr else { + bug!("expected a scalar, found {:?}", src.layout); + }; + let BackendRepr::Scalar(dst_scalar) = dst_layout.backend_repr else { + bug!("expected a scalar, found {:?}", dst_layout); + }; + let ptr_ty = bx.type_ptr(); + let imm = src.immediate(); + let mut ptr = match src_scalar.primitive() { + Primitive::Pointer(_) => imm, + _ => bx.inttoptr(imm, ptr_ty), + }; + + if bx.sess().pointer_authentication_fn_ptr_type_discrimination() && src_disc != dst_disc { + let key = bx.sess().pointer_authentication_fn_ptr_key().unwrap() as u32; + ptr = if src_scalar.valid_range(bx.cx()).contains(0) { + let align = bx.tcx().data_layout.pointer_align(); + let size = bx.tcx().data_layout.pointer_size(); + let slot = bx.alloca(size, align); + + let null_bb = bx.append_sibling_block("ptrauth.null"); + let resign_bb = bx.append_sibling_block("ptrauth.resign"); + let end_bb = bx.append_sibling_block("ptrauth.end"); + + let is_null = bx.icmp(IntPredicate::IntEQ, ptr, bx.const_null(ptr_ty)); + bx.cond_br(is_null, null_bb, resign_bb); + + bx.switch_to_block(null_bb); + bx.store(bx.const_null(ptr_ty), slot, align); + bx.br(end_bb); + + bx.switch_to_block(resign_bb); + let resigned = bx.ptrauth_resign(ptr, key, src_disc.into(), key, dst_disc.into()); + bx.store(resigned, slot, align); + bx.br(end_bb); + + bx.switch_to_block(end_bb); + bx.load(ptr_ty, slot, align) + } else { + bx.ptrauth_resign(ptr, key, src_disc.into(), key, dst_disc.into()) + }; + } + + match dst_scalar.primitive() { + Primitive::Pointer(_) => ptr, + _ => bx.ptrtoint(ptr, bx.type_isize()), + } +} + // Returns the width of an int Ty, and if it's signed or not // Returns None if the type is not an integer // FIXME: there’s multiple of this functions, investigate using some of the already existing diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index 7164bf51e7049..7f7949ce14013 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -182,7 +182,17 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { let BackendRepr::Scalar(scalar) = layout.backend_repr else { bug!("from_const: invalid ByVal layout: {:#?}", layout); }; - let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout)); + let llval = match x { + // A pointer to a function is signed as `get_fn_addr` signs it (see + // `maybe_sign_fn_ptr`), which only needs the session schema. + Scalar::Ptr(..) => bx.scalar_to_backend_with_pac( + x, + scalar, + bx.immediate_backend_type(layout), + bx.sess().pointer_authentication_functions(), + ), + _ => bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout)), + }; OperandValue::Immediate(llval) } ConstValue::ZeroSized => return OperandRef::zero_sized(layout), @@ -225,6 +235,15 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { alloc_range(start, size), /*read_provenance*/ matches!(s.primitive(), abi::Primitive::Pointer(_)), ) { + // A pointer to a function is signed as `get_fn_addr` signs it (see + // `maybe_sign_fn_ptr`), which only needs the session schema. + Ok(val) if matches!(s.primitive(), abi::Primitive::Pointer(_)) => bx + .scalar_to_backend_with_pac( + val, + s, + ty, + bx.sess().pointer_authentication_functions(), + ), Ok(val) => bx.scalar_to_backend(val, s, ty), Err(_) => bx.const_poison(ty), } diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 9acfad1fb2a5e..c4b9a58439130 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -685,4 +685,17 @@ pub trait BuilderMethods<'a, 'tcx>: fn zext(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn apply_attrs_to_cleanup_callsite(&mut self, llret: Self::Value); + + fn ptrauth_resign( + &mut self, + value: Self::Value, + old_key: u32, + old_discriminator: u64, + new_key: u32, + new_discriminator: u64, + ) -> Self::Value; + + /// Removes the pointer authentication signature from `value` (a pointer-sized integer signed + /// with `key`) and returns the bare address as an integer of the same type. + fn ptrauth_strip(&mut self, value: Self::Value, key: u32) -> Self::Value; } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 2c7da64def4ce..62e9d8f0435ad 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -213,6 +213,15 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ensure_monomorphic_enough(tp_ty)?; self.write_type_id(tp_ty, dest)?; } + sym::ptrauth_fn_ptr_discriminator => { + let tp_ty = instance.args.type_at(0); + ensure_monomorphic_enough(tp_ty)?; + let discriminator = match rustc_middle::ptrauth::ptrauth_c_encoding(tcx, tp_ty) { + rustc_middle::ptrauth::PtrauthCEncoding::FnPtr(discriminator) => discriminator, + _ => 0, + }; + self.write_scalar(Scalar::from_u64(discriminator.into()), dest)?; + } sym::type_id_eq => { let a_ty = self.read_type_id(&args[0])?; let b_ty = self.read_type_id(&args[1])?; diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index c431e4aa2ba9b..624c278b097f9 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -203,6 +203,7 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::rustc_dump_item_bounds, sym::rustc_dump_layout, sym::rustc_dump_object_lifetime_defaults, + sym::rustc_dump_ptrauth_discriminator, sym::rustc_dump_symbol_name, sym::rustc_dump_user_args, sym::rustc_dump_variances, @@ -250,6 +251,7 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::rustc_preserve_ub_checks, sym::rustc_proc_macro_decls, sym::rustc_promotable, + sym::rustc_ptrauth_c_discriminator, sym::rustc_pub_transparent, sym::rustc_reallocator, sym::rustc_regions, diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index b2823e3ab9c06..34474f2285f8e 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -706,6 +706,9 @@ declare_features! ( (unstable, prfchw_target_feature, "1.78.0", Some(150256)), /// Allows macro attributes on expressions and statements. (unstable, proc_macro_hygiene, "1.30.0", Some(54727)), + /// Allows `#[rustc_ptrauth_c_discriminator(N)]` on fields and statics, to sign the code addresses a + /// static holds with the discriminator C uses for their slot. + (unstable, ptrauth_c_discriminator, "CURRENT_RUSTC_VERSION", Some(148640)), /// Allows the use of raw-dylibs on ELF platforms (incomplete, raw_dylib_elf, "1.87.0", Some(135694)), /// Allows the `Reborrow` and `CoerceShared` traits. diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index f15febe2c1633..112238050e922 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -137,6 +137,8 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::ptr_guaranteed_cmp | sym::ptr_mask | sym::ptr_metadata + | sym::ptrauth_fn_ptr_discriminator + | sym::ptrauth_strip | sym::resumable_breakpoint | sym::return_address | sym::rotate_left @@ -638,6 +640,10 @@ pub(crate) fn check_intrinsic_type( sym::aggregate_raw_ptr => (3, 0, vec![param(1), param(2)], param(0)), sym::ptr_metadata => (2, 0, vec![Ty::new_imm_ptr(tcx, param(0))], param(1)), + sym::ptrauth_c_cast => (2, 0, vec![param(0)], param(1)), + sym::ptrauth_fn_ptr_discriminator => (1, 0, vec![], tcx.types.u64), + sym::ptrauth_strip => (1, 0, vec![param(0)], tcx.types.usize), + sym::ub_checks | sym::overflow_checks => (0, 0, Vec::new(), tcx.types.bool), // contract_check_requires::(C) -> bool, where C: impl Fn() -> bool diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 7b881f99fb8d7..364aead2e5ba0 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -34,7 +34,7 @@ use rustc_middle::ty::{self, RegisteredTools, TyCtxt}; use rustc_middle::util::Providers; use rustc_parse::lexer::StripTokens; use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal}; -use rustc_passes::{abi_test, input_stats, layout_test}; +use rustc_passes::{abi_test, input_stats, layout_test, ptrauth_test}; use rustc_resolve::{Resolver, ResolverOutputs}; use rustc_session::config::{Input, Offload, OutFileName, OutputFilenames, OutputType}; use rustc_session::diagnostics::feature_err; @@ -1222,6 +1222,7 @@ fn run_required_analyses(tcx: TyCtxt<'_>) { }); sess.time("layout_testing", || layout_test::test_layout(tcx)); + sess.time("ptrauth_testing", || ptrauth_test::test_ptrauth_discriminator(tcx)); sess.time("abi_testing", || abi_test::test_abi(tcx)); } diff --git a/compiler/rustc_middle/src/ptrauth/c_discriminator.rs b/compiler/rustc_middle/src/ptrauth/c_discriminator.rs new file mode 100644 index 0000000000000..cf354953ea7dc --- /dev/null +++ b/compiler/rustc_middle/src/ptrauth/c_discriminator.rs @@ -0,0 +1,171 @@ +//! `#[rustc_ptrauth_c_discriminator(N)]`: code addresses that a static holds in C's encoding. +//! +//! Rust signs a function pointer with the discriminator of the function it points to. C instead +//! encodes a code address according to the type of the slot holding it: `0` for `void *` or an +//! integer, or the discriminator of the slot's type. At runtime, `ptrauth_c_cast` can be used to +//! convert between discriminators. A static's initializer cannot call it, so the slots of a static +//! that hold a code address in C's encoding (requiring adjustment) are marked with the +//! discriminator C uses for them: +//! +//! - on a field: the field, in every static whose type contains it; +//! - on a static: the static itself, when it is a single slot or an array of slots. +//! +//! A slot is a pointer, or an integer of pointer size, or an array of them. Unmarked code +//! addresses keep the discriminator of their function. + +use rustc_abi::{BackendRepr, FieldsShape, HasDataLayout, Primitive, Size}; +use rustc_attr_ir::find_attr; +use rustc_hir::def_id::DefId; + +use crate::ty::layout::{LayoutCx, TyAndLayout}; +use crate::ty::{self, Instance, Ty, TyCtxt}; + +/// A misplaced `#[rustc_ptrauth_c_discriminator]`. +#[derive(Debug)] +pub enum PtrauthCDiscriminatorError<'tcx> { + /// On a static whose type is not a slot or an array of slots. + StaticNotSlot { ty: Ty<'tcx> }, + /// On a field whose type is not a slot or an array of slots. + FieldNotSlot { field: DefId, ty: Ty<'tcx> }, + /// Two marked fields of a union overlap with different discriminators. + Conflict { offset: Size }, +} + +/// Returns the offsets (sorted), in the allocation of the static `static_def_id`, of the slots +/// marked `#[rustc_ptrauth_c_discriminator]`, with the discriminator of each. +/// +/// Only the static's own allocation is covered: code addresses behind a reference live in +/// another allocation, which may be shared with other uses. Fields inside enums are not covered, +/// as their offsets depend on the variant. +pub fn ptrauth_c_discriminator_slots<'tcx>( + tcx: TyCtxt<'tcx>, + static_def_id: DefId, +) -> Result, PtrauthCDiscriminatorError<'tcx>> { + let typing_env = ty::TypingEnv::fully_monomorphized(); + let ty = Instance::mono(tcx, static_def_id).ty(tcx, typing_env); + let Ok(layout) = tcx.layout_of(typing_env.as_query_input(ty)) else { + return Ok(Vec::new()); + }; + let cx = LayoutCx::new(tcx, typing_env); + + let mut slots = Vec::new(); + if let Some(discriminator) = marked_discriminator(tcx, static_def_id) { + if !collect_marked(tcx, &cx, layout, Size::ZERO, discriminator, &mut slots) { + return Err(PtrauthCDiscriminatorError::StaticNotSlot { ty }); + } + return Ok(slots); + } + + collect_fields(tcx, &cx, layout, Size::ZERO, &mut slots)?; + slots.sort_by_key(|&(offset, _)| offset); + slots.dedup(); + if let Some(w) = slots.windows(2).find(|w| w[0].0 == w[1].0) { + return Err(PtrauthCDiscriminatorError::Conflict { offset: w[0].0 }); + } + Ok(slots) +} + +/// The discriminator for a field or a static marked with the attribute. +fn marked_discriminator(tcx: TyCtxt<'_>, def_id: DefId) -> Option { + find_attr!(tcx, def_id, PtrauthCDiscriminator { discriminator } => *discriminator) +} + +/// True if `layout` is a slot: a pointer, or an integer of pointer size. +fn is_slot<'tcx>(tcx: TyCtxt<'tcx>, layout: TyAndLayout<'tcx>) -> bool { + match layout.backend_repr { + BackendRepr::Scalar(scalar) => { + matches!(scalar.primitive(), Primitive::Pointer(_) | Primitive::Int(..)) + && scalar.size(&tcx) == tcx.data_layout().pointer_size() + } + _ => false, + } +} + +/// Records `layout` - a marked slot or array of slots at `base`, with `discriminator`. Returns +/// `false` if non found. +fn collect_marked<'tcx>( + tcx: TyCtxt<'tcx>, + cx: &LayoutCx<'tcx>, + layout: TyAndLayout<'tcx>, + base: Size, + discriminator: u16, + slots: &mut Vec<(Size, u16)>, +) -> bool { + if is_slot(tcx, layout) { + slots.push((base, discriminator)); + return true; + } + if let ty::Array(..) = layout.ty.kind() + && let FieldsShape::Array { stride, count } = layout.fields + { + let mut element = Vec::new(); + if !collect_marked(tcx, cx, layout.field(cx, 0), Size::ZERO, discriminator, &mut element) { + return false; + } + repeat(&element, base, stride, count, slots); + return true; + } + false +} + +/// Records the marked fields reachable from `layout` at `base`, without following references. +fn collect_fields<'tcx>( + tcx: TyCtxt<'tcx>, + cx: &LayoutCx<'tcx>, + layout: TyAndLayout<'tcx>, + base: Size, + slots: &mut Vec<(Size, u16)>, +) -> Result<(), PtrauthCDiscriminatorError<'tcx>> { + match layout.ty.kind() { + ty::Adt(def, _) if def.is_struct() || def.is_union() => { + for (idx, field) in def.non_enum_variant().fields.iter_enumerated() { + let field_layout = layout.field(cx, idx.as_usize()); + let offset = base + layout.fields.offset(idx.as_usize()); + if let Some(discriminator) = marked_discriminator(tcx, field.did) { + if !collect_marked(tcx, cx, field_layout, offset, discriminator, slots) { + return Err(PtrauthCDiscriminatorError::FieldNotSlot { + field: field.did, + ty: field_layout.ty, + }); + } + } else { + collect_fields(tcx, cx, field_layout, offset, slots)?; + } + } + } + ty::Array(..) => { + if let FieldsShape::Array { stride, count } = layout.fields { + let mut element = Vec::new(); + collect_fields(tcx, cx, layout.field(cx, 0), Size::ZERO, &mut element)?; + repeat(&element, base, stride, count, slots); + } + } + ty::Tuple(..) => { + for idx in 0..layout.fields.count() { + let offset = base + layout.fields.offset(idx); + collect_fields(tcx, cx, layout.field(cx, idx), offset, slots)?; + } + } + _ => {} + } + Ok(()) +} + +/// Helper for arrays, records teh slots of one array element `element` and repeats it `count` +/// times. +fn repeat( + element: &[(Size, u16)], + base: Size, + stride: Size, + count: u64, + slots: &mut Vec<(Size, u16)>, +) { + if element.is_empty() { + return; + } + for i in 0..count { + for &(offset, discriminator) in element { + slots.push((base + stride * i + offset, discriminator)); + } + } +} diff --git a/compiler/rustc_middle/src/ptrauth/discriminator.rs b/compiler/rustc_middle/src/ptrauth/discriminator.rs index d44ecafb775ef..6038067ff9627 100644 --- a/compiler/rustc_middle/src/ptrauth/discriminator.rs +++ b/compiler/rustc_middle/src/ptrauth/discriminator.rs @@ -18,25 +18,26 @@ //! The computation is structured into three conceptual stages: //! //! ### 1. Type normalization and lowering -//! Rust types are converted into a language-independent representation -//! (`ClangDiscTy`) that mirrors the type categories used by Clang when computing -//! function pointer discriminators. This includes canonicalization such as -//! treating all pointer-like types uniformly and mapping Rust constructs onto -//! their closest C equivalents. -//! One notable exception is C `_Complex`. Rust has no corresponding native type, -//! so there is no canonical Rust representation to map onto Clang's `_Complex` -//! type category. Rather than infer one (for example, by treating `(f32, f32)` -//! or `(f64, f64)` as complex numbers), this implementation leaves such -//! representation choices to users and does not provide dedicated `_Complex` -//! encoding. +//! +//! Rust types are first canonicalized according to ABI representation +//! (treating ABI-equivalent wrappers and niche representations as their +//! underlying representation, and treating pointer-like types uniformly), +//! then converted into a language-independent representation (`ClangDiscTy`) +//! that mirrors the type categories used by Clang when computing function +//! pointer discriminators. +//! +//! C `_Complex T` corresponds to `core::num::Complex` (the `complex` lang +//! item) for float and integer `T`s. //! //! ### 2. Type encoding +//! //! The lowered representation is serialized into a byte stream using rules //! intended to match Clang's implementation in: //! `encodeTypeForFunctionPointerAuth`. The resulting encoding describes the //! function signature in a target-independent form suitable for hashing. //! //! ### 3. Discriminator hashing +//! //! The encoded byte stream is hashed using LLVM's stable SipHash-2-4 based //! discriminator algorithm. The implementation here is a direct translation //! of LLVM/Clang's logic and must remain bit-for-bit compatible. See: @@ -48,18 +49,22 @@ //! - High-level API //! - `FnPtrDiscriminatorSource` //! - `ptrauth_compute_fn_ptr_type_discriminator_for` -//! - `ptrauth_clone_discriminated_schema_for` +//! - `is_ptrauth_signed_abi` +//! - `ptrauth_signing_discriminator_for` //! //! - Low-level API -//! - `FnPtrTypeDiscriminatorInput` +//! - `FnPtrTypeDiscriminatorInput` - canonical function signature input for +//! discriminator calculation (as a convenience it exposes the function ABI +//! through `abi()`) //! - `compute_fn_ptr_type_discriminator` //! -//! - Signature extraction -//! - `extract_fn_ptr_type` +//! - C encoding of a value's type +//! - `PtrauthCEncoding` +//! - `ptrauth_c_encoding` //! //! - Clang-compatible type model //! - `ClangDiscTy` -//! - `canonicalize_c_type` +//! - `canonicalize_abi_compatible_type` //! - `to_clang_disc_ty` //! //! - Encoding @@ -72,15 +77,17 @@ //! discriminator computation. Divergence from Clang will result in incompatible //! pointer authentication values across language boundaries. //! -//! This implementation intentionally approximates Clang's behavior for extern "C" -//! function types only. It does NOT attempt to model full type system rules. +//! This implementation intentionally approximates Clang's behavior for +//! `extern "C"` and `extern "system"` function types only. It does NOT attempt +//! to model full Rust type system rules. -use rustc_abi::ExternAbi; +use rustc_abi::{ExternAbi, TagEncoding, Variants}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt, Unnormalized}; -use rustc_session::PointerAuthSchema; -use rustc_span::sym; +use rustc_session::{PointerAuthDiscrimination, PointerAuthSchema}; +use rustc_target::spec::Arch; use crate::ptrauth::llvm_siphash::llvm_pointer_auth_stable_siphash; +use crate::ty::layout::LayoutCx; /// Types that can serve as a source for function pointer type discrimination. /// @@ -96,30 +103,21 @@ pub trait FnPtrDiscriminatorSource<'tcx>: Sized { fn discriminator_input(self, tcx: TyCtxt<'tcx>) -> Option>; } -/// Enables discriminator computation directly from Rust function types. -/// -/// Accepts both: -/// - `FnPtr`: actual function pointer types -/// - `FnDef`: function items +/// Enables discriminator computation for function pointer types. /// -/// FnDef is only accepted for convenience; the discriminator is still computed -/// from the instantiated function signature. +/// Only `FnPtr` is accepted: function items (`FnDef`) have no runtime code +/// address, and wrappers such as `Option` are handled by +/// `ptrauth_c_encoding`, which peels them based on their layout. impl<'tcx> FnPtrDiscriminatorSource<'tcx> for Ty<'tcx> { fn discriminator_input(self, tcx: TyCtxt<'tcx>) -> Option> { - let ty = extract_fn_ptr_type(tcx, self)?; - + let ty = tcx.normalize_erasing_regions( + ty::TypingEnv::fully_monomorphized(), + Unnormalized::new(self), + ); match ty.kind() { ty::FnPtr(sig, header) => { - let sig = sig.skip_binder(); - Some(FnPtrTypeDiscriminatorInput::from_sig_tys(sig, header)) + Some(FnPtrTypeDiscriminatorInput::from_sig_tys(sig.skip_binder(), header)) } - - ty::FnDef(def_id, args) => { - let sig = tcx.fn_sig(*def_id).instantiate(tcx, args.skip_binder()).skip_binder(); - - Some(FnPtrTypeDiscriminatorInput::from_sig(sig)) - } - _ => None, } } @@ -131,15 +129,22 @@ impl<'tcx> FnPtrDiscriminatorSource<'tcx> for Ty<'tcx> { /// normalized before constructing the canonical discriminator input. impl<'tcx> FnPtrDiscriminatorSource<'tcx> for Instance<'tcx> { fn discriminator_input(self, tcx: TyCtxt<'tcx>) -> Option> { - let sig = tcx - .instantiate_and_normalize_erasing_regions( - self.args, - ty::TypingEnv::fully_monomorphized(), - tcx.fn_sig(self.def_id()), - ) - .skip_binder(); - - Some(FnPtrTypeDiscriminatorInput::from_sig(sig)) + let typing_env = ty::TypingEnv::fully_monomorphized(); + + match self.ty(tcx, typing_env).kind() { + ty::FnDef(def_id, args) => { + let sig = tcx + .instantiate_and_normalize_erasing_regions( + args.skip_binder(), + typing_env, + tcx.fn_sig(*def_id), + ) + .skip_binder(); + Some(FnPtrTypeDiscriminatorInput::from_sig(sig)) + } + // Closures, coroutines, etc. are never called via an `extern "C"` function pointer. + _ => None, + } } } /// Enables discriminator computation directly from instantiated function @@ -169,37 +174,88 @@ where S: FnPtrDiscriminatorSource<'tcx>, { let input = source.discriminator_input(tcx)?; - Some(compute_fn_ptr_type_discriminator(tcx, &input)) + compute_fn_ptr_type_discriminator(tcx, &input) } -/// Clones a pointer authentication schema and updates its constant -/// discriminator. -/// -/// If `schema` is `Some`, the function computes a function pointer type -/// discriminator from `source` and stores it in the cloned schema's -/// `constant_discriminator` field. -/// -/// If no discriminator can be computed (for example, because `source` does not -/// represent a function pointer type), the schema is returned unchanged. +/// Return true if a function pointer with this ABI is signed under pointer +/// authentication and calls through them authenticated. +pub fn is_ptrauth_signed_abi(abi: ExternAbi) -> bool { + matches!(abi, ExternAbi::C { .. } | ExternAbi::System { .. }) +} + +/// Returns a discriminator for function pointer in `source` that is used for +/// signing and authentication under given `schema`. None if the function ABI +/// does not support function pointer authentication. /// -/// This is intended as a convenience helper for code generation sites that need -/// to attach function pointer type discrimination to a generic schema before -/// calling `get_fn_addr`. -pub fn ptrauth_clone_discriminated_schema_for<'tcx, S>( +/// With function pointer type discrimination this is the discriminator +/// calculated for the `source` (for a function instance, the function's own +/// signature, whatever type the pointer is later stored as), otherwise +/// `schema`'s constant discriminator. +pub fn ptrauth_signing_discriminator_for<'tcx, S>( tcx: TyCtxt<'tcx>, - mut schema: Option, + schema: &PointerAuthSchema, source: S, -) -> Option +) -> Option where S: FnPtrDiscriminatorSource<'tcx>, { - if let Some(ref mut s) = schema { - if let Some(disc) = ptrauth_compute_fn_ptr_type_discriminator_for(tcx, source) { - s.constant_discriminator = disc; + let input = source.discriminator_input(tcx)?; + if !is_ptrauth_signed_abi(input.abi()) { + return None; + } + match schema.discrimination_kind { + PointerAuthDiscrimination::Type => compute_fn_ptr_type_discriminator(tcx, &input), + _ => Some(schema.constant_discriminator), + } +} + +/// How a value of a given type holds a code address under C's pointer authentication encoding. +/// +/// Rust signs a function pointer with the discriminator of the function it points to, whatever +/// type it is stored as. C encodes a code address according to the type of the slot holding it. +/// Explicit resigns, `ptrauth_c_cast` intrinsic, can be used to convert between the encodings of +/// two types, the way a C type-cast does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PtrauthCEncoding { + /// An `extern "C"`/`"system"` function pointer, also behind `Option` or a `repr(transparent)` + /// wrapper: signed with the discriminator of the function pointer type. + FnPtr(u16), + /// A raw pointer, reference or integer: Clang signs a code address held in one with + /// zero-discrimination. + Opaque, + /// A function pointer with an ABI that pointer authentication does not sign (e.g. `"Rust"`). + UnsignedFnPtr, + /// Any other type. + Unsupported, +} + +impl PtrauthCEncoding { + /// The discriminator of this encoding, or `None` if it cannot hold a signed code address. + pub fn discriminator(self) -> Option { + match self { + PtrauthCEncoding::FnPtr(discriminator) => Some(discriminator), + PtrauthCEncoding::Opaque => Some(0), + PtrauthCEncoding::UnsignedFnPtr | PtrauthCEncoding::Unsupported => None, } } +} - schema +/// Returns how a value of type `ty` holds a code address under C's pointer authentication +/// encoding. See `PtrauthCEncoding`. +/// +/// Works on a canonicalized type, to honor the ABI rules. For example: `Option` and +/// `repr(transparent)` wrappers are peeled off, because their layout is that of the underlying +/// function pointer. +pub fn ptrauth_c_encoding<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> PtrauthCEncoding { + let ty = canonicalize_abi_compatible_type(tcx, ty); + match ty.kind() { + ty::FnPtr(..) => ty + .discriminator_input(tcx) + .and_then(|input| compute_fn_ptr_type_discriminator(tcx, &input)) + .map_or(PtrauthCEncoding::UnsignedFnPtr, PtrauthCEncoding::FnPtr), + ty::RawPtr(..) | ty::Ref(..) | ty::Int(_) | ty::Uint(_) => PtrauthCEncoding::Opaque, + _ => PtrauthCEncoding::Unsupported, + } } /// Canonical representation of a function signature used for pointer @@ -213,7 +269,11 @@ pub struct FnPtrTypeDiscriminatorInput<'tcx> { } impl<'tcx> FnPtrTypeDiscriminatorInput<'tcx> { - fn from_sig(sig: ty::FnSig<'tcx>) -> Self { + pub fn abi(&self) -> ExternAbi { + self.abi + } + + pub fn from_sig(sig: ty::FnSig<'tcx>) -> Self { FnPtrTypeDiscriminatorInput { inputs: sig.inputs(), output: sig.output(), @@ -232,39 +292,15 @@ impl<'tcx> FnPtrTypeDiscriminatorInput<'tcx> { } } -/// Unwraps optional function pointers and normalizes the type. -/// -/// Only `Option` is supported for nullability modeling, matching C ABI -/// null pointer conventions. -fn extract_fn_ptr_type<'tcx>(tcx: TyCtxt<'tcx>, mut ty: Ty<'tcx>) -> Option> { - ty = tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), Unnormalized::new(ty)); - - loop { - match ty.kind() { - ty::Adt(def, args) if tcx.lang_items().option_type() == Some(def.did()) => { - ty = args.type_at(0); - continue; - } - - ty::FnPtr(..) | ty::FnDef(..) => { - return Some(ty); - } - - _ => return None, - } - } -} - -/// Computes the Clang-compatible function pointer type discriminator. -/// -/// This is the low-level discriminator computation routine operating on an -/// already constructed `FnPtrTypeDiscriminatorInput`. -fn compute_fn_ptr_type_discriminator<'tcx>( +/// Encodes the signature described by `input` the way Clang's +/// `encodeTypeForFunctionPointerAuth` does, as the input to the discriminator +/// hash. Returns `None` for unsupported ABIs (see `is_ptrauth_signed_abi`). +fn encode_fn_ptr_type_discriminator<'tcx>( tcx: TyCtxt<'tcx>, input: &FnPtrTypeDiscriminatorInput<'tcx>, -) -> u16 { - if !matches!(input.abi, ExternAbi::C { .. } | ExternAbi::System { .. }) { - return 0; +) -> Option { + if !is_ptrauth_signed_abi(input.abi) { + return None; } let mut enc = PtrauthEncoder::new(); @@ -282,7 +318,31 @@ fn compute_fn_ptr_type_discriminator<'tcx>( enc.push(b'E'); - enc.finish() + Some(enc) +} + +/// Computes the Clang-compatible function pointer type discriminator. +/// +/// This is the low-level discriminator calculation function operating on +/// `FnPtrTypeDiscriminatorInput`. Returns `None` for unsupported ABIs (see +/// `is_ptrauth_signed_abi`). +pub fn compute_fn_ptr_type_discriminator<'tcx>( + tcx: TyCtxt<'tcx>, + input: &FnPtrTypeDiscriminatorInput<'tcx>, +) -> Option { + encode_fn_ptr_type_discriminator(tcx, input).map(|enc| enc.finish()) +} + +/// Returns the raw Clang-compatible type encoding used as input to the +/// discriminator hash. +/// +/// This is primarily used for debugging and comparing Rust's encoding against +/// Clang's `encodeTypeForFunctionPointerAuth`. +pub fn debug_encode_fn_ptr_type<'tcx>( + tcx: TyCtxt<'tcx>, + input: &FnPtrTypeDiscriminatorInput<'tcx>, +) -> String { + encode_fn_ptr_type_discriminator(tcx, input).map(|enc| enc.debug_string()).unwrap_or_default() } // Clang disc type. @@ -298,15 +358,17 @@ enum ClangDiscTy<'tcx> { // - raw pointers (`*const T`, `*mut T`) // - Rust references (`&T`, `&mut T`) // - function pointers + // - `Box` (canonicalized to a raw pointer) + // - `NonNull` (canonicalized through its transparent representation) + // - DST pointer-like types (`dyn Trait`, slices, `str`) // All collapse to a single Clang-compatible 'P' node. Pointer, Array { elem: Ty<'tcx> }, - // FIXME(jchlands) Decide if to support Complex types in future. Clang has - // dedicated node for this `Type::Complex`, Rust does not. So we could match - // against a Tuple(FP_TYPE, FP_TYPE). - // Complex(Ty<'tcx>), + // C `_Complex T`: `core::num::Complex` (`#[repr(complex)]`). + Complex { elem: Ty<'tcx> }, + Vector { bytes: u64 }, EnumLikeInt, @@ -315,35 +377,67 @@ enum ClangDiscTy<'tcx> { Void, } -// Canonicalize Option-wrapped pointer types used to model C nullable pointers. -// -// Rust and Clang should compute identical discriminators for equivalent C APIs. -// Clang does not distinguish nullable from non-nullable pointer types when -// computing function pointer authentication discriminators, so -// `Option` and `Option<*mut T>` are encoded identically to their -// underlying pointer types. -// -// Although `Option<*mut T>` is not considered FFI-safe by Rust and triggers the -// `improper_ctypes`/`improper_ctypes_definitions` lints, this is a warning -// rather than a hard error. Canonicalizing it here preserves Clang-compatible -// discriminator computation. -// -// Please see the following tests for sample use cases: -// pauth-fn-ptr-type-discrimination-option-callback.rs, -// pauth-fn-ptr-type-discrimination-option-return.rs and pauth-fn-ptr-type-discrimination-option.rs -fn canonicalize_c_type<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - if let ty::Adt(def, args) = ty.kind() - && tcx.is_diagnostic_item(sym::Option, def.did()) - { - let inner = args.type_at(0); - - match inner.kind() { - ty::FnPtr(..) | ty::RawPtr(..) => return inner, - _ => {} +/// Canonicalizes Rust types that have the same ABI representation as a simpler +/// C-compatible type for discriminator purposes. +/// +/// As a result ABI-compatible types get the same discriminator: +/// - a pattern type becomes its base type; +/// - `Box` becomes `*const T`; +/// - a size-0, alignment-1 type becomes `()`; +/// - a `repr(transparent)` wrapper becomes its non-1-ZST field; +/// - a two-variant enum with a niche becomes its payload. +/// +/// The work is done on layouts, so it also merges some types that Rust does not +/// guarantee to be ABI-compatible, for example: `Option` and `bool`. That +/// only makes discriminators coarser, while still correct. +/// +/// The steps repeat until nothing changes, as one can enable another: +/// `Option>` becomes `Box`, then `*const T`. +fn canonicalize_abi_compatible_type<'tcx>(tcx: TyCtxt<'tcx>, mut ty: Ty<'tcx>) -> Ty<'tcx> { + let typing_env = ty::TypingEnv::fully_monomorphized(); + + loop { + let before = ty; + + if let ty::Pat(base, _) = ty.kind() { + ty = *base; + } + + if ty.is_box_global(tcx) { + ty = Ty::new_imm_ptr( + tcx, + ty.boxed_ty().expect("is_box_global() returned true, so this must be a Box"), + ); + } + + if let Ok(layout) = tcx.layout_of(typing_env.as_query_input(ty)) { + if layout.is_zst() && layout.align.bytes() == 1 { + ty = tcx.types.unit; + } else if matches!(ty.kind(), ty::Adt(..)) { + let cx = LayoutCx::new(tcx, typing_env); + ty = layout.peel_transparent_wrappers_from_non_1zst(&cx).ty; + } + } + + if let ty::Adt(def, args) = ty.kind() + && def.is_enum() + && def.variants().len() == 2 + && let Ok(layout) = tcx.layout_of(typing_env.as_query_input(ty)) + && let Variants::Multiple { + tag_encoding: TagEncoding::Niche { untagged_variant, .. }, + .. + } = layout.variants + { + let variant = def.variant(untagged_variant); + if let [field] = &variant.fields.raw[..] { + ty = tcx.normalize_erasing_regions(typing_env, field.ty(tcx, *args)); + } } - } - ty + if ty == before { + return ty; + } + } } /// Lowers a Rust type into a Clang-compatible discriminator type. @@ -352,24 +446,20 @@ fn canonicalize_c_type<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { /// that intentionally matches Clang's function pointer authentication encoding /// rules where Rust has a direct language-level equivalent. /// -/// In particular C `_Complex`, without a canonical Rust equivalent, is not -/// recognized. This avoids introducing heuristics for user-defined -/// representations that may vary across codebases. -/// /// Important invariants: /// - All pointer-like types (Rust refs, raw pointers, fn pointers) collapse to /// `Pointer`. /// - Struct/union types are encoded using name only, not layout. /// - Enums are treated as integers. /// - SIMD types are encoded only by total byte size (no lane semantics). -/// - No attempt is made to recognize user-defined representations of C -/// `_Complex` types. +/// - Only `core::num::Complex` with the C `_Complex` ABI is encoded as +/// `_Complex`. /// This must remain in sync with Clang's `encodeTypeForFunctionPointerAuth`. fn to_clang_disc_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ClangDiscTy<'tcx> { - let ty = canonicalize_c_type(tcx, ty); + let ty = canonicalize_abi_compatible_type(tcx, ty); match ty.kind() { // C void / Rust () - _ if ty.is_unit() => ClangDiscTy::Void, + _ if ty.is_unit() || ty.is_never() => ClangDiscTy::Void, // scalars ty::Bool => ClangDiscTy::Bool, @@ -378,7 +468,8 @@ fn to_clang_disc_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ClangDiscTy<'tcx> ty::Int(_) | ty::Uint(_) => ClangDiscTy::Int, ty::Float(f) => ClangDiscTy::Float(f), - // everything pointer-like collapses + // Pointer-like types form a discriminator boundary: the pointee type + // does not participate in the encoding. ty::RawPtr(..) | ty::Ref(..) | ty::FnPtr(..) | ty::Dynamic(..) | ty::Slice(_) | ty::Str => { ClangDiscTy::Pointer } @@ -386,8 +477,16 @@ fn to_clang_disc_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ClangDiscTy<'tcx> // arrays ignore size ty::Array(elem, _) => ClangDiscTy::Array { elem: *elem }, - // enums to integer collapse - ty::Adt(def, _) if def.is_enum() => ClangDiscTy::EnumLikeInt, + // enums to integer collapse - mirrors Clang's Type::Enum handling, + // which recurses into the enum's underlying integer type. + // A non-niche, data-carrying enum (e.g. Option<*mut T>) is not an + // "enumerated type" in the C11 sense, such enums fall through to the + // general Adt(_) => AdtName(..) arm below instead. + ty::Adt(def, _) if def.is_enum() && def.is_payloadfree() => ClangDiscTy::EnumLikeInt, + + // C `_Complex T`, recurses into the element type. + ty::Adt(_, args) if is_c_complex(tcx, ty) => ClangDiscTy::Complex { elem: args.type_at(0) }, + // simd vectors ty::Adt(def, args) if def.repr().simd() => { // Clang encodes SIMD vectors by their total size @@ -417,6 +516,17 @@ fn to_clang_disc_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ClangDiscTy<'tcx> } } +/// Returns true if `ty` is `core::num::Complex` with the ABI of C `_Complex +/// T`. +/// +/// Uses the same check as the calling convention code, so a type is encoded as +/// `_Complex` exactly when it is passed as one. +fn is_c_complex<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { + let typing_env = ty::TypingEnv::fully_monomorphized(); + let cx = LayoutCx::new(tcx, typing_env); + tcx.layout_of(typing_env.as_query_input(ty)).is_ok_and(|layout| layout.is_complex_number(&cx)) +} + // Encoder struct PtrauthEncoder { buf: Vec, @@ -438,6 +548,10 @@ impl PtrauthEncoder { fn finish(&self) -> u16 { llvm_pointer_auth_stable_siphash(&self.buf) } + + fn debug_string(&self) -> String { + String::from_utf8_lossy(&self.buf).into_owned() + } } /// Encodes a ClangDiscTy into the discriminator byte stream. @@ -452,13 +566,25 @@ fn encode_ty<'tcx>(enc: &mut PtrauthEncoder, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) { ClangDiscTy::Bool | ClangDiscTy::Char | ClangDiscTy::Int => enc.push(b'i'), ClangDiscTy::Float(f) => match f.bit_width() { - 16 => enc.push_str("Dh"), + 16 => enc.push_str("DF16_"), 32 => enc.push(b'f'), 64 => enc.push(b'd'), - 128 => enc.push(b'g'), + 128 => match tcx.sess.target.arch { + Arch::AArch64 + if !tcx.sess.target.is_like_darwin && !tcx.sess.target.is_like_windows => + { + enc.push(b'e') + } + _ => enc.push(b'g'), + }, _ => enc.push(b'?'), }, + ClangDiscTy::Complex { elem } => { + enc.push(b'C'); + encode_ty(enc, tcx, elem); + } + ClangDiscTy::Void => enc.push(b'v'), // pointer boundary (NO RECURSION) diff --git a/compiler/rustc_middle/src/ptrauth/mod.rs b/compiler/rustc_middle/src/ptrauth/mod.rs index 0eeef5e07f61c..2566530fbabab 100644 --- a/compiler/rustc_middle/src/ptrauth/mod.rs +++ b/compiler/rustc_middle/src/ptrauth/mod.rs @@ -1,7 +1,10 @@ +pub mod c_discriminator; pub mod discriminator; pub mod llvm_siphash; +pub use c_discriminator::{PtrauthCDiscriminatorError, ptrauth_c_discriminator_slots}; pub use discriminator::{ - FnPtrDiscriminatorSource, FnPtrTypeDiscriminatorInput, ptrauth_clone_discriminated_schema_for, - ptrauth_compute_fn_ptr_type_discriminator_for, + FnPtrDiscriminatorSource, FnPtrTypeDiscriminatorInput, PtrauthCEncoding, is_ptrauth_signed_abi, + ptrauth_c_encoding, ptrauth_compute_fn_ptr_type_discriminator_for, + ptrauth_signing_discriminator_for, }; diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 5dd1718d68d49..12cddbb7cb457 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -289,6 +289,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::PinV2(..) => (), AttributeKind::PreludeImport => (), AttributeKind::ProfilerRuntime => (), + AttributeKind::PtrauthCDiscriminator { .. } => (), AttributeKind::RecursionLimit { .. } => (), AttributeKind::ReexportTestHarnessMain(..) => (), AttributeKind::RegisterTool { .. } => (), @@ -333,6 +334,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::RustcDumpItemBounds => (), AttributeKind::RustcDumpLayout(..) => (), AttributeKind::RustcDumpObjectLifetimeDefaults => (), + AttributeKind::RustcDumpPtrauthDiscriminator(..) => (), AttributeKind::RustcDumpSymbolName(..) => (), AttributeKind::RustcDumpUserArgs => (), AttributeKind::RustcDumpVariances => (), diff --git a/compiler/rustc_passes/src/lib.rs b/compiler/rustc_passes/src/lib.rs index d37d1bea932fe..25cba5ab47b1a 100644 --- a/compiler/rustc_passes/src/lib.rs +++ b/compiler/rustc_passes/src/lib.rs @@ -27,6 +27,7 @@ pub mod hir_id_validator; pub mod input_stats; pub mod layout_test; mod lib_features; +pub mod ptrauth_test; mod reachable; pub mod stability; mod upvars; diff --git a/compiler/rustc_passes/src/ptrauth_test.rs b/compiler/rustc_passes/src/ptrauth_test.rs new file mode 100644 index 0000000000000..d7328a72f4c45 --- /dev/null +++ b/compiler/rustc_passes/src/ptrauth_test.rs @@ -0,0 +1,46 @@ +use rustc_attr_ir::{RustcDumpPtrauthDiscriminatorKind, find_attr}; +use rustc_hir::def::DefKind; +use rustc_middle::ptrauth::FnPtrTypeDiscriminatorInput; +use rustc_middle::ptrauth::discriminator::{ + compute_fn_ptr_type_discriminator, debug_encode_fn_ptr_type, +}; +use rustc_middle::ty::TyCtxt; + +pub fn test_ptrauth_discriminator(tcx: TyCtxt<'_>) { + if !tcx.features().rustc_attrs() { + return; + } + for def_id in tcx.hir_crate_items(()).definitions() { + if tcx.def_kind(def_id) != DefKind::Fn { + continue; + } + let Some(kinds) = find_attr!(tcx, def_id, RustcDumpPtrauthDiscriminator(kinds) => kinds) + else { + continue; + }; + + let sig = tcx.fn_sig(def_id).instantiate_identity().skip_binder(); + let input = FnPtrTypeDiscriminatorInput::from_sig(sig); + let span = tcx.def_span(def_id); + + for kind in kinds { + let message = match kind { + RustcDumpPtrauthDiscriminatorKind::Encoding => { + format!( + "ptrauth discriminator encoding: \"{}\"", + debug_encode_fn_ptr_type(tcx, &input) + ) + } + RustcDumpPtrauthDiscriminatorKind::Hash => { + match compute_fn_ptr_type_discriminator(tcx, &input) { + Some(res) => { + format!("ptrauth discriminator hash: {} (0x{:x})", res, res) + } + None => "ptrauth discriminator hash: unavailable".to_string(), + } + } + }; + tcx.dcx().span_err(span, message); + } + } +} diff --git a/compiler/rustc_session/src/diagnostics.rs b/compiler/rustc_session/src/diagnostics.rs index 26239df3028f9..583374e49ab6b 100644 --- a/compiler/rustc_session/src/diagnostics.rs +++ b/compiler/rustc_session/src/diagnostics.rs @@ -394,12 +394,6 @@ pub(crate) struct StackProtectorNotSupportedForTarget<'a> { pub(crate) target_triple: &'a TargetTuple, } -#[derive(Diagnostic)] -#[diag("function pointer type discrimination is not supported")] -pub(crate) struct PointerAuthenticationTypeDiscriminationNotSupportedForTarget<'a> { - pub(crate) target_triple: &'a TargetTuple, -} - #[derive(Diagnostic)] #[diag( "`-Z pointer-authentication` is not supported for target {$target_triple} and will be ignored" diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 6b7e2214f26d9..4e8886cff5a71 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -96,6 +96,7 @@ pub enum PointerAuthARM8_3Key { } /// Forms of extra discrimination. +#[derive(Clone)] pub enum PointerAuthDiscrimination { /// No additional discrimination. None, @@ -108,6 +109,7 @@ pub enum PointerAuthDiscrimination { } /// Types of address discrimination. +#[derive(Clone)] pub enum PointerAuthAddressDiscriminator { /// Enable/disable hardware address discrimination. HardwareAddress(bool), @@ -116,6 +118,7 @@ pub enum PointerAuthAddressDiscriminator { Synthetic(u64), } +#[derive(Clone)] pub struct PointerAuthSchema { pub is_address_discriminated: PointerAuthAddressDiscriminator, pub discrimination_kind: PointerAuthDiscrimination, @@ -206,8 +209,7 @@ impl PointerAuthConfig { const GOT: u32 = 8; const GOTOS: u32 = 9; const TYPEINFO_VT_PTR_DISCR: u32 = 10; - // FIXME(jchlanda) We don't yet support function pointer type discrimination. - // const FPTR_TYPE_DISCR: u32 = 11; + const FPTR_TYPE_DISCR: u32 = 11; let pauth_abi_version: u32 = (u32::from(self.intrinsics) << INTRINSICS) | (u32::from(self.function_pointers.is_some()) << CALLS) @@ -225,7 +227,10 @@ impl PointerAuthConfig { })) << INIT_FINI_ADDR_DISC) | (u32::from(self.elf_got) << GOT) | (u32::from(self.indirect_gotos) << GOTOS) - | (u32::from(self.typeinfo_vt_ptr_discrimination) << TYPEINFO_VT_PTR_DISCR); + | (u32::from(self.typeinfo_vt_ptr_discrimination) << TYPEINFO_VT_PTR_DISCR) + | (u32::from(self.function_pointers.as_ref().is_some_and(|schema| { + matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type) + })) << FPTR_TYPE_DISCR); pauth_abi_version } @@ -1286,6 +1291,18 @@ impl Session { pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> { self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref()) } + + /// True if function pointers are signed with function pointer type discrimination. + pub fn pointer_authentication_fn_ptr_type_discrimination(&self) -> bool { + self.pointer_authentication_functions().is_some_and(|schema| { + matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type) + }) + } + + /// The key function pointers are signed with, if they are signed. + pub fn pointer_authentication_fn_ptr_key(&self) -> Option { + self.pointer_authentication_functions().map(|schema| schema.key) + } } // JUSTIFICATION: part of session construction @@ -1569,19 +1586,6 @@ fn validate_commandline_args_with_session_available(sess: &Session) { sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported); } - if sess - .pointer_auth_config - .as_ref() - .and_then(|cfg| cfg.function_pointers.as_ref()) - .is_some_and(|schema| matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type)) - { - sess.dcx().emit_err( - diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget { - target_triple: &sess.opts.target_triple, - }, - ); - } - if sess.target.cfg_abi != CfgAbi::Pauthtest && !sess.opts.unstable_opts.pointer_authentication.is_empty() { diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 70adbf6d7fee5..7a52fa077652f 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1688,6 +1688,12 @@ symbols! { ptr_write_bytes, ptr_write_unaligned, ptr_write_volatile, + ptrauth_c_cast, + ptrauth_c_discriminator, + ptrauth_encoding, + ptrauth_fn_ptr_discriminator, + ptrauth_hash, + ptrauth_strip, pub_macro_rules, pub_restricted, public, @@ -1840,6 +1846,7 @@ symbols! { rustc_dump_item_bounds, rustc_dump_layout, rustc_dump_object_lifetime_defaults, + rustc_dump_ptrauth_discriminator, rustc_dump_symbol_name, rustc_dump_user_args, rustc_dump_variances, @@ -1895,6 +1902,7 @@ symbols! { rustc_private, rustc_proc_macro_decls, rustc_promotable, + rustc_ptrauth_c_discriminator, rustc_pub_transparent, rustc_reallocator, rustc_regions, diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 79ced518115cf..64b6bb105c1da 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -664,12 +664,18 @@ pub struct FnAbi<'a, Ty> { pub conv: CanonAbi, /// Indicates if an unwind may happen across a call to this function. pub can_unwind: bool, + /// The function pointer discriminator that a call using this `FnAbi` uses to create a call + /// bundle. + /// When type discrimination is on, contains per type discriminator otherwise a schema defined + /// constant discriminator. None, if this ABI doesn't participate in pointer authentication. + pub ptrauth_discriminator: Option, } // Needs to be a custom impl because of the bounds on the `TyAndLayout` debug impl. impl<'a, Ty: fmt::Display> fmt::Debug for FnAbi<'a, Ty> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let FnAbi { args, ret, c_variadic, fixed_count, conv, can_unwind } = self; + let FnAbi { args, ret, c_variadic, fixed_count, conv, can_unwind, ptrauth_discriminator } = + self; f.debug_struct("FnAbi") .field("args", args) .field("ret", ret) @@ -677,6 +683,7 @@ impl<'a, Ty: fmt::Display> fmt::Debug for FnAbi<'a, Ty> { .field("fixed_count", fixed_count) .field("conv", conv) .field("can_unwind", can_unwind) + .field("ptrauth_discriminator", ptrauth_discriminator) .finish() } } @@ -1007,6 +1014,6 @@ mod size_asserts { use super::*; // tidy-alphabetical-start static_assert_size!(ArgAbi<'_, usize>, 56); - static_assert_size!(FnAbi<'_, usize>, 80); + static_assert_size!(FnAbi<'_, usize>, 96); // tidy-alphabetical-end } diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 5c72f6cba3989..04f33051e7902 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -6,6 +6,7 @@ use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; use rustc_hir as hir; use rustc_middle::middle::deduced_param_attrs::DeducedParamAttrs; +use rustc_middle::ptrauth::ptrauth_signing_discriminator_for; use rustc_middle::query::Providers; use rustc_middle::ty::layout::{ FnAbiError, HasTyCtxt, HasTypingEnv, LayoutCx, LayoutOf, TyAndLayout, fn_can_unwind, @@ -613,6 +614,10 @@ fn fn_abi_new_uncached<'tcx>( }), sig.abi(), ), + ptrauth_discriminator: tcx + .sess + .pointer_authentication_functions() + .and_then(|schema| ptrauth_signing_discriminator_for(tcx, schema, sig).map(Into::into)), }; fn_abi_adjust_for_abi(cx, &mut fn_abi, sig.abi()); debug!("fn_abi_new_uncached = {:?}", fn_abi); diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 5c20f4a93fb2e..8e58c9380a421 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -1219,6 +1219,51 @@ pub const unsafe fn slice_get_unchecked< #[rustc_intrinsic] pub fn ptr_mask(ptr: *const T, mask: usize) -> *const T; +/// Converts a code address from the pointer authentication encoding of `Src` to that of `Dst`. +/// +/// Under function pointer type discrimination, Rust signs a function pointer with the discriminator +/// of the function it points to (pointee type), and never resigns it when it is reinterpreted. C +/// (Clang) encodes a code address according to the type of the slot holding it. This intrinsic is +/// the explicit conversion between those encodings, the Rust equivalent of a C type-cast. It is +/// intended to be used where a code address crosses into, or out of a C slot that erased its type +/// (`dlsym`, `void *` user data). +/// +/// `Src` and `Dst` must each be one of: an `extern "C"`/`"system"` function pointer, a thin raw +/// pointer, or a pointer-sized integer. Null is passed through unchanged. Without type +/// discrimination, this is a plain reinterpretation. +/// +/// # Safety +/// +/// `src` must be null, or signed according to the encoding of `Src`. Otherwise authentication +/// fails. +#[rustc_nounwind] +#[rustc_intrinsic] +pub unsafe fn ptrauth_c_cast(src: Src) -> Dst; + +/// The discriminator of the function pointer type `F`, as used for `extern "C"` function pointers +/// under function pointer type discrimination. Matches Clang's +/// `__builtin_ptrauth_type_discriminator`. Returns 0 for types that are not `extern "C"` function +/// pointers. Must be evaluated at compile time, e.g. `const { ptrauth_fn_ptr_discriminator::() +/// }`. +/// +/// Note that, unlike most intrinsics, this is safe to call; it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold any safety invariants. +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_comptime] +pub fn ptrauth_fn_ptr_discriminator() -> u64; + +/// Returns the address of `ptr` with any pointer authentication signature removed, for comparing +/// and printing code addresses. Without pointer authentication, returns the address unchanged. +/// +/// `T` must be a thin raw pointer, a function pointer or a pointer-sized integer. +/// +/// Note that, unlike most intrinsics, this is safe to call; it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold any safety invariants. +#[rustc_nounwind] +#[rustc_intrinsic] +pub fn ptrauth_strip(ptr: T) -> usize; + /// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::()` and an alignment of `align_of::()`. /// diff --git a/src/doc/rustc/src/platform-support/aarch64-unknown-linux-pauthtest.md b/src/doc/rustc/src/platform-support/aarch64-unknown-linux-pauthtest.md index 1118145a2097c..9ca2cb1e3c0d0 100644 --- a/src/doc/rustc/src/platform-support/aarch64-unknown-linux-pauthtest.md +++ b/src/doc/rustc/src/platform-support/aarch64-unknown-linux-pauthtest.md @@ -105,50 +105,34 @@ When using the AccessSoftek scripts to build the sysroot, the result includes a Clang-based toolchain. In this case, no wrapper script is required, `/bin/aarch64-linux-pauthtest-clang` can be used directly. +Whichever compiler is used, define the following environment variables before running +`x.py`: + +```sh +export PAUTHTEST_SYSROOT=/aarch64-linux-pauthtest/usr +export PAUTHTEST_RESOURCE_DIR=/lib/clang/ +``` + ## Building the target Introduction of `aarch64-unknown-linux-pauthtest` target needs to be propagated to various crates/repos, so that they can correctly recognise and handle it. -Specifically: -* `cc-rs`: https://github.com/jchlanda/cc-rs/tree/jakub/cc-v1.2.28-pauthtest -* `libc`: https://github.com/jchlanda/libc/tree/jakub/0.2.183-pauthtest +At the time of writing this document the following require changes: +* `cc-rs`: `bootstrap` pins `cc` 1.2.62, which does not know the target. `cc` 1.4.3, the + version `rustc_llvm` already uses, supports it. * `backtrace`: https://github.com/jchlanda/backtrace-rs/tree/jakub/backtrace-v0.3.76-pauthtest -The patched versions of `cc-rs` and `libc` will have to be registered through -`[patch.crates-io]` section of `Cargo.toml` files both in: -`/src/bootstrap/` and `/library/`. Check out `cc-rs` and -`libc` to `/patches` and update config files. See attached diff for -details: - -
+Update the `cc` pin in `/src/bootstrap/Cargo.toml`, then run +`cargo update --manifest-path src/bootstrap/Cargo.toml -p cc --precise 1.4.3`: ```diff -diff --git a/library/Cargo.toml b/library/Cargo.toml -index e30e6240942..fb5a12f0065 100644 ---- a/library/Cargo.toml -+++ b/library/Cargo.toml -@@ -59,3 +59,4 @@ rustflags = ["-Cpanic=abort"] - rustc-std-workspace-core = { path = 'rustc-std-workspace-core' } - rustc-std-workspace-alloc = { path = 'rustc-std-workspace-alloc' } - rustc-std-workspace-std = { path = 'rustc-std-workspace-std' } -+libc = { path = '/patches/libc' } -diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml -index e1725db60cf..46763cdf9a4 100644 ---- a/src/bootstrap/Cargo.toml -+++ b/src/bootstrap/Cargo.toml -@@ -94,3 +94,6 @@ debug = 0 - [profile.dev.package] - # Only use debuginfo=1 to further reduce compile times. - bootstrap.debug = 1 -+ -+[patch.crates-io] -+cc = { path = '/patches/cc-rs' } +-cc = "=1.2.62" ++cc = "=1.4.3" ``` -
+With `cc` 1.4.3, `bootstrap` finds the sysroot through the environment variables described +above. -In contrast to `cc-rs` and `libc`, which are external crates resolved from -[crates.io](https://crates.io/) and can be overridden using `[patch.crates-io]`, `backtrace` is included in the Rust repository as a git submodule under `/library/backtrace`. At the time of writing, the necessary change has not yet been committed there, which means an in-tree patch is currently @@ -392,9 +376,6 @@ Authentication ELF ABI. Rust does not implement C++ virtual dispatch semantics, authenticated C++ member function pointers, or authenticated virtual table pointers. -Similarly, `function-pointer-type-discrimination` is recognized for ABI -compatibility purposes, but full support is not yet implemented in Rust. - Even when these features do not directly affect generated Rust code, they still contribute to the emitted PAuth ABI metadata through the LLVM module flags: `aarch64-elf-pauthabi-platform`, `aarch64-elf-pauthabi-version`. These flags are @@ -432,6 +413,42 @@ precedence, matching Clang's behavior. For example, the following would leave -Zpointer-authentication=+init-fini,-init-fini ``` +### Function pointer type discrimination + +Under `function-pointer-type-discrimination`, Rust signs an `extern "C"` or +`extern "system"` function pointer with the discriminator of the function it +points to, computed from its signature as Clang computes it for the +corresponding C function type. It never resigns it: transmutes, `as` casts, +union reads and copies keep its bits. A call authenticates with the +discriminator of the type it is made through, so calls through an ABI-compatible +type work, and calls that are UB fail authentication. Function pointers of other +ABIs are neither signed nor authenticated. Init/fini entries keep their own +discriminator. + +C signs a code address with the discriminator of the type of the slot that holds +it, and a cast to another type resigns it for the new type. Rust signs a +function pointer with the discriminator of the function it points to, and never +resigns it. So whether a code address needs resigning when it passes between +Rust and C depends on the type of the slot on the C side: + +* a function pointer of the function's own type: C and Rust use the same + discriminator, so the pointer is passed as is; +* a function pointer of another type, such as a generic callback type (for + example GLib's `GCallback`): C uses the discriminator of that type, so the + pointer must be resigned for it; +* a `void *` or an integer (`dlsym`, user data): C uses discriminator 0, so the + pointer must be resigned for 0. + +At runtime, `core::intrinsics::ptrauth_c_cast::` does the resign, as +the C cast would. A static's initializer is evaluated at compile time, so for +code addresses in a static, +[`#[rustc_ptrauth_c_discriminator(N)]`](../../unstable-book/language-features/ptrauth-c-discriminator.html) +on the static or on one of its fields sets the discriminator instead. +`core::intrinsics::ptrauth_fn_ptr_discriminator::()` gives the discriminator +of a function pointer type, as Clang's `__builtin_ptrauth_type_discriminator` +does, and `core::intrinsics::ptrauth_strip` removes the signature, to compare +code addresses. + ## Cross-compilation toolchains and C code This target supports interoperability with C code. A @@ -462,17 +479,48 @@ The following categories are supported (all present in tree): * pauth-extern-c.rs * pauth-extern-c-direct-indirect-call.rs * pauth-extern-weak-global.rs + * pauth-signed-abi.rs * pauth-init-fini.rs * pauth-attr-special-funcs.rs + * pauth-attr-cli-flags.rs + * pauth-fn-ptr-type-discrimination-complex.rs + * pauth-fn-ptr-type-discrimination-const-aggregate.rs + * pauth-fn-ptr-type-discrimination-const-scalar.rs + * pauth-fn-ptr-type-discrimination-deeply-nested.rs + * pauth-fn-ptr-type-discrimination-encoder.rs + * pauth-fn-ptr-type-discrimination-fn-ptr-return-type.rs + * pauth-fn-ptr-type-discrimination-instance-signing.rs + * pauth-fn-ptr-type-discrimination-intrinsics.rs + * pauth-fn-ptr-type-discrimination-c-discriminator.rs + * pauth-fn-ptr-type-discrimination-no-resign.rs + * pauth-fn-ptr-type-discrimination-option-callback.rs + * pauth-fn-ptr-type-discrimination-option-return.rs + * pauth-fn-ptr-type-discrimination-option.rs + * pauth-fn-ptr-type-discrimination-recursive-statics.rs + * pauth-fn-ptr-type-discrimination-running-test.rs + * pauth-fn-ptr-type-discrimination-rust-array.rs + * pauth-fn-ptr-type-discrimination-simd.rs + * pauth-fn-ptr-type-discrimination-static-allocs.rs + * pauth-fn-ptr-type-discrimination-struct-members.rs + * pauth-fn-ptr-type-discrimination-struct-name.rs + * pauth-fn-ptr-type-discrimination-transparent-wrapper.rs + * pauth-fn-ptr-type-discrimination-vtable.rs + * pauth-drop-terminator (implemented in run-make) * End-to-end execution tests * Rust-driven quicksort (pauth-quicksort-rust-driver) * C-driven quicksort (pauth-quicksort-c-driver) + * C/Rust interop under function pointer type discrimination + (pauth-fn-ptr-type-discrimination-interop-ir) * UI error/warning reporting * crt-static-pauthtest.rs * pauth-static-link-warning * enable_pointer_authentication_validation.rs * invalid_target_pointer_authentication.rs - * type_discrimination_not_supported_pointer_authentication.rs + * discriminator-abi-compat.rs + * discriminator-complex-encoding.rs + * discriminator-float-encoding.rs + * ptrauth-c-discriminator-misplaced.rs + * ptrauth-c-discriminator-range.rs * incompatible_pauth.rs * Unit tests for siphash function: * compiler/rustc_middle/src/ptrauth/llvm_siphash/tests.rs @@ -494,14 +542,43 @@ x.py test --target aarch64-unknown-linux-pauthtest --force-rerun assembly-llvm \ tests/codegen-llvm/pauth/pauth-extern-c.rs \ tests/codegen-llvm/pauth/pauth-extern-c-direct-indirect-call.rs \ tests/codegen-llvm/pauth/pauth-extern-weak-global.rs \ + tests/codegen-llvm/pauth/pauth-signed-abi.rs \ tests/codegen-llvm/pauth/pauth-init-fini.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-complex.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-aggregate.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-scalar.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-deeply-nested.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-encoder.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-fn-ptr-return-type.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-instance-signing.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-intrinsics.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-c-discriminator.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-no-resign.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-callback.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-return.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-recursive-statics.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-running-test.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-rust-array.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-simd.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-static-allocs.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-members.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-name.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-transparent-wrapper.rs \ + tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-vtable.rs \ tests/run-make/pauth-quicksort-rust-driver \ tests/run-make/pauth-quicksort-c-driver \ tests/run-make/pauth-static-link-warning \ + tests/run-make/pauth-drop-terminator \ + tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir \ tests/ui/statics/crt-static-pauthtest.rs \ tests/ui/pointer_authentication/enable_pointer_authentication_validation.rs \ tests/ui/pointer_authentication/invalid_target_pointer_authentication.rs \ - tests/ui/pointer_authentication/type_discrimination_not_supported_pointer_authentication.rs \ + tests/ui/pointer_authentication/discriminator-abi-compat.rs \ + tests/ui/pointer_authentication/discriminator-complex-encoding.rs \ + tests/ui/pointer_authentication/discriminator-float-encoding.rs \ + tests/ui/pointer_authentication/ptrauth-c-discriminator-misplaced.rs \ + tests/ui/pointer_authentication/ptrauth-c-discriminator-range.rs \ tests/ui/target_modifiers/incompatible_pauth.rs ``` diff --git a/src/doc/unstable-book/src/language-features/ptrauth-c-discriminator.md b/src/doc/unstable-book/src/language-features/ptrauth-c-discriminator.md new file mode 100644 index 0000000000000..4d881037084c8 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/ptrauth-c-discriminator.md @@ -0,0 +1,55 @@ +# `ptrauth_c_discriminator` + +The tracking issue for this feature is: [#148640] + +[#148640]: https://github.com/rust-lang/rust/issues/148640 + +------------------------ + +The `ptrauth_c_discriminator` feature allows setting the pointer authentication discriminator of a +code address held in a static, on targets with function pointer type discrimination (see [the +`aarch64-unknown-linux-pauthtest` target][pauthtest]). + +[pauthtest]: ../../rustc/platform-support/aarch64-unknown-linux-pauthtest.html + +Rust signs a function pointer with the discriminator of the function it points to. C signs a code +address with the discriminator of the type of the slot holding it, for example 0 for a `void *`. +For a slot whose type differs from the function's, `#[rustc_ptrauth_c_discriminator(N)]` makes a +static's initializer sign the code address with `N` instead: + +- on a field, it applies to that field in every static whose type contains it; +- on a static, it applies to the static itself, which must be a pointer, a pointer-sized integer, + or an array of them. + +Only a static's initializer is affected. A value written at runtime, or read back as a Rust +function pointer, still needs `core::intrinsics::ptrauth_c_cast`. + +Without function pointer type discrimination, the attribute has no effect. + +## Examples + +```rust +#![feature(ptrauth_c_discriminator)] + +use std::ffi::c_void; + +extern "C" fn callback(x: i32) -> i32 { + x +} + +// A table passed to C, which reads `handler` as a `void *`. +#[repr(C)] +pub struct Entry { + pub id: u32, + #[rustc_ptrauth_c_discriminator(0)] + pub handler: *const c_void, +} + +pub static mut ENTRIES: [Entry; 1] = [Entry { id: 1, handler: callback as *const c_void }]; + +// A static that is itself a `void *`. +#[rustc_ptrauth_c_discriminator(0)] +pub static mut CALLBACK: *const c_void = callback as *const c_void; + +fn main() {} +``` diff --git a/tests/auxiliary/minicore.rs b/tests/auxiliary/minicore.rs index aca69642057ab..2a0fc33513761 100644 --- a/tests/auxiliary/minicore.rs +++ b/tests/auxiliary/minicore.rs @@ -165,6 +165,8 @@ pub mod arch { pub struct PhantomData; impl Copy for PhantomData {} +#[rustc_diagnostic_item = "Option"] +#[lang = "Option"] pub enum Option { None, Some(T), @@ -302,11 +304,18 @@ pub trait Add { fn add(self, _: Rhs) -> Self::Output; } +// Avoid needing to add all of the overflow handling and panic language items impl Add for isize { type Output = isize; fn add(self, other: isize) -> isize { - 7 // avoid needing to add all of the overflow handling and panic language items + 7 + } +} +impl Add for i32 { + type Output = i32; + fn add(self, rhs: i32) -> i32 { + 7 } } @@ -353,18 +362,30 @@ impl_marker_trait!( ); impl Sync for () {} - impl Sync for [T; N] {} +impl Sync for Option {} +impl Sync for &T {} + // Function pointers are treated as `Sync` to match real `core` behavior. // // Minicore provides only the minimal set of impls required by tests. Rather // than exhaustively covering all possible function pointer signatures, -// additional impls should be added as needed. -impl Sync for fn() -> R {} -impl Sync for extern "C" fn() -> R {} -impl Sync for unsafe extern "C" fn() -> R {} -impl Sync for extern "C" fn(A) -> R {} -impl Sync for unsafe extern "C" fn(A) -> R {} +// additional arities should be added as needed. +macro_rules! impl_sync_for_fn_ptrs { + ($(($($T:ident),*)),* $(,)?) => { + $( + impl<$($T,)* R> Sync for fn($($T),*) -> R {} + + impl<$($T,)* R> Sync for extern "C" fn($($T),*) -> R {} + impl<$($T,)* R> Sync for unsafe extern "C" fn($($T),*) -> R {} + + impl<$($T,)* R> Sync for extern "C" fn($($T,)* ...) -> R {} + impl<$($T,)* R> Sync for unsafe extern "C" fn($($T,)* ...) -> R {} + )* + }; +} + +impl_sync_for_fn_ptrs!((), (A), (A, B), (A, B, C), (A, B, C, D),); #[lang = "drop_glue"] fn drop_glue(_: &mut T) {} @@ -401,7 +422,7 @@ pub trait CoerceUnsized {} impl<'a, 'b: 'a, T: PointeeSized + Unsize, U: PointeeSized> CoerceUnsized<&'a U> for &'b T {} #[lang = "drop"] -trait Drop { +pub trait Drop { fn drop(&mut self); } @@ -458,6 +479,15 @@ pub mod ptr { unsafe { volatile_store(dst, src) }; } + + #[inline] + #[rustc_diagnostic_item = "ptr_read_volatile"] + pub unsafe fn read_volatile(src: *const T) -> T { + #[rustc_intrinsic] + pub unsafe fn volatile_load(src: *const T) -> T; + + unsafe { volatile_load(src) } + } } pub mod hint { @@ -518,9 +548,10 @@ pub mod num { #[lang = "c_void"] #[repr(u8)] +#[allow(non_camel_case_types)] pub enum c_void { - __variant1, - __variant2, + Variant1, + Variant2, } #[allow_internal_unstable(internal_syntax)] diff --git a/tests/codegen-llvm/pauth/pauth-attr-cli-flags.rs b/tests/codegen-llvm/pauth/pauth-attr-cli-flags.rs index 513850f1dd4db..64e44910d0af8 100644 --- a/tests/codegen-llvm/pauth/pauth-attr-cli-flags.rs +++ b/tests/codegen-llvm/pauth/pauth-attr-cli-flags.rs @@ -1,5 +1,5 @@ // ignore-tidy-file-linelength -//@ revisions: DEFAULT ALL DISABLE_JUMP DISABLE_AUTH_TRAPS DISABLE_CALLS DISABLE_INDIRCT_GOTOS DISABLE_RETURNS DISABLE_INTRINSICS DISABLE_TYPEINFO DISABLE_VT_PTR_ADDR DISABLE_VT_PTR_TYPE NONE +//@ revisions: DEFAULT ALL DISABLE_JUMP DISABLE_AUTH_TRAPS DISABLE_CALLS DISABLE_INDIRCT_GOTOS DISABLE_RETURNS DISABLE_INTRINSICS DISABLE_TYPEINFO DISABLE_VT_PTR_ADDR DISABLE_VT_PTR_TYPE FN_PTR_TYPE_DISC NONE //@ add-minicore #![crate_type = "lib"] @@ -31,6 +31,8 @@ extern crate minicore; //@[DISABLE_VT_PTR_ADDR] compile-flags: --target=aarch64-unknown-linux-pauthtest -Zpointer-authentication=-vt-ptr-addr-discrimination //@[DISABLE_VT_PTR_TYPE] needs-llvm-components: aarch64 //@[DISABLE_VT_PTR_TYPE] compile-flags: --target=aarch64-unknown-linux-pauthtest -Zpointer-authentication=-vt-ptr-type-discrimination +//@[FN_PTR_TYPE_DISC] needs-llvm-components: aarch64 +//@[FN_PTR_TYPE_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest -Zpointer-authentication=+function-pointer-type-discrimination //@[NONE] needs-llvm-components: aarch64 //@[NONE] compile-flags: --target=aarch64-unknown-linux-pauthtest -Zpointer-authentication=-aarch64-jump-table-hardening,-auth-traps,-calls,-indirect-gotos,-return-addresses,-init-fini,-init-fini-address-discrimination,-intrinsics,-typeinfo-vt-ptr-discrimination,-vt-ptr-addr-discrimination,-vt-ptr-type-discrimination @@ -117,6 +119,10 @@ pub fn main() {} // DISABLE_VT_PTR_TYPE: !{i32 1, !"aarch64-elf-pauthabi-platform", i32 268435458} // DISABLE_VT_PTR_TYPE-NEXT: !{i32 1, !"aarch64-elf-pauthabi-version", i32 1759} +// Function pointer type discrimination sets bit 11 (`FPTR_TYPE_DISCR`) on top of the default. +// FN_PTR_TYPE_DISC: !{i32 1, !"aarch64-elf-pauthabi-platform", i32 268435458} +// FN_PTR_TYPE_DISC-NEXT: !{i32 1, !"aarch64-elf-pauthabi-version", i32 3839} + // NONE-NOT: ptrauth-returns // NONE-NOT: aarch64-jump-table-hardening // NONE-NOT: ptrauth-auth-traps diff --git a/tests/codegen-llvm/pauth/pauth-attr-special-funcs.rs b/tests/codegen-llvm/pauth/pauth-attr-special-funcs.rs index 24ab1abb10e67..abc67c8000bd3 100644 --- a/tests/codegen-llvm/pauth/pauth-attr-special-funcs.rs +++ b/tests/codegen-llvm/pauth/pauth-attr-special-funcs.rs @@ -10,7 +10,10 @@ use std::panic; -// CHECK: define {{.*}} @__rust_try{{.*}} [[ATTR_TRY:#[0-9]+]] +// Make sure that `rust_eh_personality` is not signed. +// CHECK: define internal i32 @{{.*}}lang_start{{.*}}pauth_attr_special_funcs(ptr %{{.*}}) unnamed_addr #[[#]] personality ptr @{{[_A-Za-z0-9]*}}rust_eh_personality +// CHECK: define {{.*}} @__rust_try({{.*}}) unnamed_addr [[ATTR_TRY:#[0-9]+]] personality ptr @{{[_A-Za-z0-9]*}}rust_eh_personality + // CHECK: define {{.*}} @main{{.*}} [[ATTR_MAIN:#[0-9]+]] // CHECK: attributes [[ATTR_TRY]] = { {{.*}}"aarch64-jump-table-hardening" diff --git a/tests/codegen-llvm/pauth/pauth-extern-c-direct-indirect-call.rs b/tests/codegen-llvm/pauth/pauth-extern-c-direct-indirect-call.rs index b47637a687bb0..b2e666915bcfc 100644 --- a/tests/codegen-llvm/pauth/pauth-extern-c-direct-indirect-call.rs +++ b/tests/codegen-llvm/pauth/pauth-extern-c-direct-indirect-call.rs @@ -1,3 +1,7 @@ +// ignore-tidy-file-linelength +// The combining of ptrauth constant callee into bundle was introduced after LLVM 21: +// https://github.com/llvm/llvm-project/pull/94706 +//@ min-llvm-version: 22 //@ add-minicore // ignore-tidy-linelength //@ revisions: O0_PAUTH O3_PAUTH diff --git a/tests/codegen-llvm/pauth/pauth-extern-weak-global.rs b/tests/codegen-llvm/pauth/pauth-extern-weak-global.rs index b7c1f5fd06479..01ecc40b43053 100644 --- a/tests/codegen-llvm/pauth/pauth-extern-weak-global.rs +++ b/tests/codegen-llvm/pauth/pauth-extern-weak-global.rs @@ -1,37 +1,56 @@ -// ignore-tidy-linelength -//@ revisions: O0_PAUTH O3_PAUTH O0_NO_PAUTH O3_NO_PAUTH +// ignore-tidy-file-linelength //@ add-minicore +//@ revisions: DISC NO_DISC NO_PAUTH -//@ [O0_PAUTH] needs-llvm-components: aarch64 -//@ [O0_PAUTH] compile-flags: --target=aarch64-unknown-linux-pauthtest -C opt-level=0 -//@ [O3_PAUTH] needs-llvm-components: aarch64 -//@ [O3_PAUTH] compile-flags: --target=aarch64-unknown-linux-pauthtest -C opt-level=3 -//@ [O0_NO_PAUTH] needs-llvm-components: aarch64 -//@ [O0_NO_PAUTH] compile-flags: --target=aarch64-unknown-linux-gnu -C opt-level=0 -//@ [O3_NO_PAUTH] needs-llvm-components: aarch64 -//@ [O3_NO_PAUTH] compile-flags: --target=aarch64-unknown-linux-gnu -C opt-level=3 +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination +//@ [NO_PAUTH] needs-llvm-components: aarch64 +//@ [NO_PAUTH] compile-flags: --target=aarch64-unknown-linux-gnu --crate-type=lib -#![crate_type = "lib"] +// An `extern_weak` static of type `Option` is lowered to an internal global +// initialised with the address of the weak function, or null if the function is not defined at +// link time. Calls through the static authenticate with the discriminator of its function pointer +// type, so the address is signed with that discriminator; without type discrimination, with 0. +// +// Discriminators: `extern "C" fn(i32)` = 2712, `extern "C" fn() -> i64` = 42271. + +#![feature(no_core, lang_items, linkage)] #![no_std] #![no_core] -#![feature(no_core)] -#![feature(linkage)] extern crate minicore; use minicore::*; -// O0_PAUTH: @{{[0-9A-Za-z_]+}}FUNCTION_PTR_DECL = constant ptr ptrauth (ptr @extern_weak_fn, i32 0) -// O0_PAUTH: declare i64 @extern_weak_fn({{.*}}) -// O3_PAUTH: @{{[0-9A-Za-z_]+}}FUNCTION_PTR_DECL = constant ptr ptrauth (ptr @extern_weak_fn, i32 0) -// O3_PAUTH: declare {{.*}} i64 @extern_weak_fn({{.*}}) -// -// O0_NO_PAUTH-NOT: ptr ptrauth -// O3_NO_PAUTH-NOT: ptr ptrauth extern "C" { - #[link_name = "extern_weak_fn"] #[linkage = "extern_weak"] - fn extern_weak_fn() -> i64; + #[link_name = "weak_cb"] + static WEAK_CB: Option; + + #[linkage = "extern_weak"] + #[link_name = "weak_getter"] + static WEAK_GETTER: Option i64>; } -#[used] -static FUNCTION_PTR_DECL: unsafe extern "C" fn() -> i64 = extern_weak_fn; +// DISC-DAG: @_rust_extern_with_linkage_{{[0-9a-f]+}}_weak_cb = internal {{.*}}global ptr ptrauth (ptr @weak_cb, i32 0, i64 2712) +// DISC-DAG: @_rust_extern_with_linkage_{{[0-9a-f]+}}_weak_getter = internal {{.*}}global ptr ptrauth (ptr @weak_getter, i32 0, i64 42271) +// NO_DISC-DAG: @_rust_extern_with_linkage_{{[0-9a-f]+}}_weak_cb = internal {{.*}}global ptr ptrauth (ptr @weak_cb, i32 0) +// NO_DISC-DAG: @_rust_extern_with_linkage_{{[0-9a-f]+}}_weak_getter = internal {{.*}}global ptr ptrauth (ptr @weak_getter, i32 0) +// NO_PAUTH-DAG: @_rust_extern_with_linkage_{{[0-9a-f]+}}_weak_cb = internal {{.*}}global ptr @weak_cb +// NO_PAUTH-DAG: @_rust_extern_with_linkage_{{[0-9a-f]+}}_weak_getter = internal {{.*}}global ptr @weak_getter + +// CHECK-DAG: declare extern_weak {{.*}}@weak_cb( +// CHECK-DAG: declare extern_weak {{.*}}@weak_getter( + +#[no_mangle] +#[allow(unused_unsafe)] +pub fn weak_cb_addr() -> *const Option { + unsafe { &raw const WEAK_CB } +} + +#[no_mangle] +#[allow(unused_unsafe)] +pub fn weak_getter_addr() -> *const Option i64> { + unsafe { &raw const WEAK_GETTER } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-c-discriminator.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-c-discriminator.rs new file mode 100644 index 0000000000000..aec64d0ff0c4e --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-c-discriminator.rs @@ -0,0 +1,124 @@ +// ignore-tidy-file-linelength +//@ add-minicore +//@ revisions: DISC NO_DISC + +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// `#[rustc_ptrauth_c_discriminator(N)]` marks the slots of a static that hold a code address with an +// explicit encoding (`N`): +// * on a field, that field in every static containing it; +// * on a static, the static itself or every element of an array static. +// +// A code address in a marked slot is signed with `N`; every other one keeps the discriminator of +// its function. Matching is by offset, so null entries, arrays and nested structs need nothing +// special. +// +// Without type discrimination, every code address is signed with 0. +// +// Discriminators: +// * `extern "C" fn(i32)` = 2712, +// * `extern "C" fn()` = 18983. + +#![feature(no_core, lang_items, ptrauth_c_discriminator)] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::Option::{self, None, Some}; +use minicore::mem::transmute; + +pub type GCallback = Option; + +pub extern "C" fn cb_i32(_: i32) {} +pub extern "C" fn cb_void() {} + +// A static that is itself a slot. +#[used] +#[rustc_ptrauth_c_discriminator(0)] +// DISC-DAG: @{{.*}}OPAQUE = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), align 8 +// NO_DISC-DAG: @{{.*}}OPAQUE = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), align 8 +static mut OPAQUE: *const u8 = cb_i32 as *const u8; + +// The same, unmarked: the function's own discriminator. +#[used] +// DISC-DAG: @{{.*}}UNMARKED = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0, i64 2712), align 8 +// NO_DISC-DAG: @{{.*}}UNMARKED = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), align 8 +static mut UNMARKED: *const u8 = cb_i32 as *const u8; + +// A stati carray: every element. +#[used] +#[rustc_ptrauth_c_discriminator(0)] +// DISC-DAG: @{{.*}}TABLE = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +// NO_DISC-DAG: @{{.*}}TABLE = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +static mut TABLE: [*const u8; 2] = [cb_i32 as *const u8, cb_void as *const u8]; + +// A type erased method table: one marked field, in an array of structs. +#[repr(C)] +pub struct NativeMethod { + pub name: *const u8, + #[rustc_ptrauth_c_discriminator(0)] + pub fn_ptr: *const u8, +} + +#[used] +// DISC-DAG: @{{.*}}METHODS = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +// NO_DISC-DAG: @{{.*}}METHODS = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +static mut METHODS: [NativeMethod; 2] = [ + NativeMethod { name: 0 as *const u8, fn_ptr: cb_i32 as *const u8 }, + NativeMethod { name: 0 as *const u8, fn_ptr: cb_void as *const u8 }, +]; + +// Exactly typed, generic callback and `void *` slots in one struct. The typed field needs no +// mark: the function's own discriminator is the one of its type. +#[repr(C)] +pub struct Mixed { + pub typed: Option, + #[rustc_ptrauth_c_discriminator(18983)] + pub callback: GCallback, + #[rustc_ptrauth_c_discriminator(0)] + pub user: *const u8, +} + +#[used] +// DISC-DAG: @{{.*}}MIXED = {{.*}}<{ ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0, i64 2712), ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0, i64 18983), ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0) }> +// NO_DISC-DAG: @{{.*}}MIXED = {{.*}}<{ ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0) }> +static mut MIXED: Mixed = Mixed { + typed: Some(cb_i32), + callback: unsafe { transmute::(cb_i32) }, + user: cb_i32 as *const u8, +}; + +// Null entries do not shift anything: the code address in `user` is still matched by its offset. +#[used] +// DISC-DAG: @{{.*}}SPARSE = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +// NO_DISC-DAG: @{{.*}}SPARSE = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +static mut SPARSE: Mixed = Mixed { typed: None, callback: None, user: cb_void as *const u8 }; + +// A marked field of a nested struct. +#[repr(C)] +pub struct Outer { + pub tag: usize, + pub inner: NativeMethod, +} + +#[used] +// DISC-DAG: @{{.*}}NESTED = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +// NO_DISC-DAG: @{{.*}}NESTED = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_void, i32 0) }> +static mut NESTED: Outer = + Outer { tag: 1, inner: NativeMethod { name: 0 as *const u8, fn_ptr: cb_void as *const u8 } }; + +// A union: the marked member's encoding applies to the slot, whichever member initialised it. +#[repr(C)] +pub union MethodPtr { + pub with_args: Option, + #[rustc_ptrauth_c_discriminator(18983)] + pub erased: GCallback, +} + +#[used] +// DISC-DAG: @{{.*}}UNION = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0, i64 18983), align 8 +// NO_DISC-DAG: @{{.*}}UNION = {{.*}}ptr ptrauth (ptr @{{[0-9A-Za-z_]*}}cb_i32, i32 0), align 8 +static mut UNION: MethodPtr = MethodPtr { with_args: Some(cb_i32) }; diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-complex.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-complex.rs new file mode 100644 index 0000000000000..8de4cd331f577 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-complex.rs @@ -0,0 +1,138 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 +// +// Function pointer type discriminators for `core::num::Complex` must match Clang's encoding of C +// `_Complex T`: 'C' followed by the element type. + +#![feature(no_core, lang_items, f16, f128)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::num::Complex; + +#[repr(transparent)] +pub struct Wrap(Complex); + +// An ordinary repr(C) struct that happens to be named `Complex`: not `_Complex`. +pub mod user { + #[repr(C)] + pub struct Complex { + pub re: f32, + pub im: f32, + } +} + +// C: void (*)(float _Complex) -> "FvCfE" +// CHECK-LABEL: @call_cf +#[no_mangle] +pub fn call_cf(f: extern "C" fn(Complex), x: Complex) { + // DISC: [ "ptrauth"(i32 0, i64 5745) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(x) +} + +// C: void (*)(double _Complex) -> "FvCdE" +// CHECK-LABEL: @call_cd +#[no_mangle] +pub fn call_cd(f: extern "C" fn(Complex), x: Complex) { + // DISC: [ "ptrauth"(i32 0, i64 65236) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(x) +} + +// C: void (*)(int _Complex) -> "FvCiE" +// CHECK-LABEL: @call_ci +// DISC: [ "ptrauth"(i32 0, i64 13305) ] +// NO_DISC: [ "ptrauth"(i32 0, i64 0) ] +#[no_mangle] +pub fn call_ci(f: extern "C" fn(Complex), x: Complex) { + f(x) +} + +// C: long double _Complex (*)(void) -> "FCeE" (long double is binary128 here) +// CHECK-LABEL: @call_ret_ce +#[no_mangle] +pub fn call_ret_ce(f: extern "C" fn() -> Complex) -> Complex { + // DISC: [ "ptrauth"(i32 0, i64 776) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f() +} + +// C: _Float16 _Complex (*)(void) -> "FCDF16_E" +// CHECK-LABEL: @call_ret_ch +#[no_mangle] +pub fn call_ret_ch(f: extern "C" fn() -> Complex) -> Complex { + // DISC: [ "ptrauth"(i32 0, i64 17465) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f() +} + +// C: double _Complex (*)(float _Complex) -> "FCdCfE" +// CHECK-LABEL: @call_cf_to_cd +#[no_mangle] +pub fn call_cf_to_cd( + f: extern "C" fn(Complex) -> Complex, + x: Complex, +) -> Complex { + // DISC: [ "ptrauth"(i32 0, i64 24171) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(x) +} + +// C: void (*)(float _Complex, int _Complex, double _Complex) -> "FvCfCiCdE" +// CHECK-LABEL: @call_mixed +#[no_mangle] +pub fn call_mixed( + f: extern "C" fn(Complex, Complex, Complex), + a: Complex, + b: Complex, + c: Complex, +) { + // DISC: [ "ptrauth"(i32 0, i64 44841) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(a, b, c) +} + +// A repr(transparent) wrapper is canonicalized away: same as `call_cf`. +// CHECK-LABEL: @call_wrap +#[no_mangle] +pub fn call_wrap(f: extern "C" fn(Wrap), x: Wrap) { + // DISC: [ "ptrauth"(i32 0, i64 5745) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(x) +} + +// C: struct Complex { float re, im; }; void (*)(struct Complex) -> "Fv7ComplexE" +// CHECK-LABEL: @call_user +#[no_mangle] +pub fn call_user(f: extern "C" fn(user::Complex), x: user::Complex) { + // DISC: [ "ptrauth"(i32 0, i64 50183) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(x) +} + +// Baseline float, not complex. C: void (*)(float) -> "FvfE" +// CHECK-LABEL: @call_f +#[no_mangle] +pub fn call_f(f: extern "C" fn(f32), x: f32) { + // DISC: [ "ptrauth"(i32 0, i64 21613) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(x) +} + +// Baseline two floats, still not complex. C: void (*)(float, float) -> "FvffE" +// CHECK-LABEL: @call_ff +#[no_mangle] +pub fn call_ff(f: extern "C" fn(f32, f32), a: f32, b: f32) { + // DISC: [ "ptrauth"(i32 0, i64 47857) ] + // NO_DISC: [ "ptrauth"(i32 0, i64 0) ] + f(a, b) +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-aggregate.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-aggregate.rs new file mode 100644 index 0000000000000..0649b6c20d1c5 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-aggregate.rs @@ -0,0 +1,73 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 +// +// Make sure that `OperandRef::from_const_alloc`'s `read_scalar` closure +// (compiler/rustc_codegen_ssa/src/mir/operand.rs), correctly signs function pointers. +// +// PAIR / PAIR_REV exercise the `BackendRepr::ScalarPair` arm with the function pointer in each of +// the two field positions. And the offset used to key the discriminator lookup (0 for field `a`, +// `b_offset` for field `b`). +// TRIO forces `BackendRepr::Memory`. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; + +extern "C" { + fn f(ctx: *mut i32) -> i32; +} + +type FnPtr = unsafe extern "C" fn(*mut i32) -> i32; + +#[used] +// Baseline. +// DISC: @{{.*}}T_PTR = constant ptr ptrauth (ptr @{{.*}}f, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_PTR = constant ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static T_PTR: FnPtr = f; + +// ScalarPair, function pointer at field `a` (local offset 0). +const PAIR: (FnPtr, i32) = (f, 1); + +#[repr(C)] +struct PairRev { + x: i32, + f: FnPtr, +} + +// ScalarPair, function pointer at field `b` +const PAIR_REV: PairRev = PairRev { x: 2, f }; + +// BackendRepr::Memory +// DISC: private unnamed_addr constant <{ ptr, [8 x i8] }> <{ ptr ptrauth (ptr @{{.*}}f, i32 0, i64 12410), [8 x i8] +// NO_DISC: private unnamed_addr constant <{ ptr, [8 x i8] }> <{ ptr ptrauth (ptr @{{.*}}f, i32 0), [8 x i8] +const TRIO: (FnPtr, i32, i32) = (f, 3, 4); + +// CHECK-LABEL: main +pub fn main() { + let mut x = 42i32; + unsafe { + // DISC: call i32 ptrauth (ptr @f, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_PTR(&mut x as *mut i32); + + // DISC: call i32 ptrauth (ptr @f, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = PAIR.0(&mut x as *mut i32); + + // DISC: call i32 ptrauth (ptr @f, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = (PAIR_REV.f)(&mut x as *mut i32); + + // DISC: call i32 %{{.*}}(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 %{{.*}}(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = TRIO.0(&mut x as *mut i32); + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-scalar.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-scalar.rs new file mode 100644 index 0000000000000..2b8e85ae57865 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-const-scalar.rs @@ -0,0 +1,48 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 +// +// Make sure that a function pointer materialized from a `const` item carries the same discriminator +// as the identical signature materialized from a `static`. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; + +extern "C" { + fn f(ctx: *mut i32) -> i32; +} + +type FnPtr = unsafe extern "C" fn(*mut i32) -> i32; + +#[used] +// DISC: @{{.*}}T_STATIC = constant ptr ptrauth (ptr @{{.*}}f, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_STATIC = constant ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static T_STATIC: FnPtr = f; + +// `const`, not `static`: this is the exact case the fix addresses. A bare standalone function +// pointer constant has no separate global of its own - it's inlined as an LLVM constant operand +// directly at each use site, which is why the check below lives at the call site rather than on +// a symbol (unlike T_STATIC above). +const T_CONST: FnPtr = f; + +// CHECK-LABEL: main +pub fn main() { + let mut x = 42i32; + unsafe { + // DISC: call i32 ptrauth (ptr @f, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_STATIC(&mut x as *mut i32); + + // DISC: call i32 ptrauth (ptr @f, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_CONST(&mut x as *mut i32); + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-deeply-nested.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-deeply-nested.rs new file mode 100644 index 0000000000000..7ce3c628c2388 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-deeply-nested.rs @@ -0,0 +1,104 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC + +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Make sure that the compiler can see through chains of nested structs, both when used as globals, +// arguments and returns. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; +use minicore::hint::black_box; + +// Nested fn ptr chain. +type L0 = extern "C" fn(i32) -> i32; +type L1 = extern "C" fn(L0) -> i32; +type L2 = extern "C" fn(L1) -> i32; +type L3 = extern "C" fn(L2) -> i32; +type L4 = extern "C" fn(L3) -> i32; +// Function returning fn ptr. +type DeepRet = extern "C" fn() -> L0; + +#[used] +// DISC: @{{.*}}T_DEEP = constant ptr ptrauth (ptr @{{.*}}f_deep, i32 0, i64 1059), align 8 +// NO_DISC: @{{.*}}T_DEEP = constant ptr ptrauth (ptr @{{.*}}f_deep, i32 0), align 8 +static T_DEEP: unsafe extern "C" fn(L4) -> DeepRet = f_deep; + +// Leaf callback. +// CHECK-LABEL: callback_i32 +pub extern "C" fn callback_i32(x: i32) -> i32 { + x +} + +// Dummy chain impl. +// CHECK-LABEL: dummy_l1 +// CHECK: (ptr [[CB:%.*]]) +pub extern "C" fn dummy_l1(cb: L0) -> i32 { + // DISC: call i32 [[CB]](i32 5) {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // NO_DISC: call i32 [[CB]](i32 5) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + cb(5) +} +// CHECK-LABEL: dummy_l2 +// CHECK: (ptr [[CB:%.*]]) +pub extern "C" fn dummy_l2(cb: L1) -> i32 { + // DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}callback_i32, i32 0, i64 2981)) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}callback_i32, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + cb(callback_i32) +} +// CHECK-LABEL: dummy_l3 +// CHECK: (ptr [[CB:%.*]]) +pub extern "C" fn dummy_l3(cb: L2) -> i32 { + // DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}dummy_l1, i32 0, i64 12410)) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}dummy_l1, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + cb(dummy_l1) +} +// CHECK-LABEL: dummy_l4 +// CHECK: (ptr [[CB:%.*]]) +pub extern "C" fn dummy_l4(cb: L3) -> i32 { + // DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}dummy_l2, i32 0, i64 12410)) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}dummy_l2, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + cb(dummy_l2) +} +// Return fn impl. +// CHECK-LABEL: returned_fn +pub extern "C" fn returned_fn() -> L0 { + // DISC: ret ptr ptrauth (ptr @{{.*}}callback_i32, i32 0, i64 2981) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}callback_i32, i32 0) + return callback_i32; +} +// Entry point to the chain, takes L4 and returns function returning fn ptr. +// CHECK-LABEL: f_deep +// CHECK: (ptr [[CB:%.*]]) +pub extern "C" fn f_deep(cb: L4) -> DeepRet { + // DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}dummy_l3, i32 0, i64 12410)) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 [[CB]](ptr ptrauth (ptr @{{.*}}dummy_l3, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + cb(dummy_l3); + // DISC: ret ptr ptrauth (ptr @{{.*}}returned_fn, i32 0, i64 34128) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}returned_fn, i32 0) + return returned_fn; +} + +// CHECK-LABEL: main +pub fn main() { + unsafe { + // DISC: [[RET_FN:%.*]] = call ptr ptrauth (ptr @{{.*}}f_deep, i32 0, i64 1059)(ptr ptrauth (ptr @{{.*}}dummy_l4, i32 0, i64 12410)) {{.*}} [ "ptrauth"(i32 0, i64 1059) ] + // NO_DISC: [[RET_FN:%.*]] = call ptr ptrauth (ptr @{{.*}}f_deep, i32 0)(ptr ptrauth (ptr @{{.*}}dummy_l4, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let ret_fn: DeepRet = T_DEEP(dummy_l4); + // DISC: [[INNER_FN:%.*]] = call ptr [[RET_FN]]() {{.*}} [ "ptrauth"(i32 0, i64 34128) ] + // NO_DISC: [[INNER_FN:%.*]] = call ptr [[RET_FN]]() {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let inner_fn: L0 = ret_fn(); + // DISC: call i32 [[INNER_FN]](i32 42) {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // NO_DISC: call i32 [[INNER_FN]](i32 42) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let result = inner_fn(42); + + black_box(result); + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-encoder.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-encoder.rs new file mode 100644 index 0000000000000..27f7a5069acc7 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-encoder.rs @@ -0,0 +1,550 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Test generation of function-pointer type discriminators. The discriminator values were obtained +// from Clang by compiling equivalent C code (included). Both compilers must generate identical +// values. +// +// The `encode_ty` function in is responsible +// for converting types to the literal values that are then used as the basis for hashing. Its +// implementation is a faithful translation of Clang's `encodeTypeForFunctionPointerAuth`. + +#![feature(repr_simd)] +#![feature(simd_ffi)] +#![feature(f16, f128)] +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::{c_void, mem}; + +// Builtin types. +extern "C" { + fn f_i32(x: i32) -> i32; + fn f_h(x: f16) -> f16; + fn f_f(x: f32) -> f32; + fn f_d(x: f64) -> f64; + fn f_2d(x: f64, y: f64) -> f64; + fn f_ld(x: f128) -> f128; + fn f_v() -> (); +} +type fn_i32 = unsafe extern "C" fn(i32) -> i32; +type fn_h = unsafe extern "C" fn(f16) -> f16; +type fn_f = unsafe extern "C" fn(f32) -> f32; +type fn_d = unsafe extern "C" fn(f64) -> f64; +type fn_2d = unsafe extern "C" fn(f64, f64) -> f64; +type fn_ld = unsafe extern "C" fn(f128) -> f128; +type fn_v = unsafe extern "C" fn() -> (); +// discriminator: 2981 (0x0BA5), encoding: FiiE +// DISC: @{{.*}}T_I32 = constant ptr ptrauth (ptr @f_i32, i32 0, i64 2981), align 8 +// NO_DISC: @{{.*}}T_I32 = constant ptr ptrauth (ptr @f_i32, i32 0), align 8 +#[used] +static T_I32: fn_i32 = f_i32; +// discriminator: 37553 (0x92B1), encoding: FDF16_DF16_E +// DISC: @{{.*}}T_H = constant ptr ptrauth (ptr @f_h, i32 0, i64 37553), align 8 +// NO_DISC: @{{.*}}T_H = constant ptr ptrauth (ptr @f_h, i32 0), align 8 +#[used] +static T_H: fn_h = f_h; +// discriminator: 28450 (0x6F22), encoding: FffE +// DISC: @{{.*}}T_F = constant ptr ptrauth (ptr @f_f, i32 0, i64 28450), align 8 +// NO_DISC: @{{.*}}T_F = constant ptr ptrauth (ptr @f_f, i32 0), align 8 +#[used] +static T_F: fn_f = f_f; +// discriminator: 43115 (0xA86B), encoding: FddE +// DISC: @{{.*}}T_D = constant ptr ptrauth (ptr @f_d, i32 0, i64 43115), align 8 +// NO_DISC: @{{.*}}T_D = constant ptr ptrauth (ptr @f_d, i32 0), align 8 +#[used] +static T_D: fn_d = f_d; +// discriminator: 38695 (0x9727), encoding: FdddE +// DISC: @{{.*}}T_2D = constant ptr ptrauth (ptr @f_2d, i32 0, i64 38695), align 8 +// NO_DISC: @{{.*}}T_2D = constant ptr ptrauth (ptr @f_2d, i32 0), align 8 +#[used] +static T_2D: fn_2d = f_2d; +// discriminator: 25877 (0x6515), encoding: FeeE +// DISC: @{{.*}}T_LD = constant ptr ptrauth (ptr @f_ld, i32 0, i64 25877), align 8 +// NO_DISC: @{{.*}}T_LD = constant ptr ptrauth (ptr @f_ld, i32 0), align 8 +#[used] +static T_LD: fn_ld = f_ld; +// discriminator: 18983 (0x4A27), encoding: FvE +// DISC: @{{.*}}T_V = constant ptr ptrauth (ptr @f_v, i32 0, i64 18983), align 8 +// NO_DISC: @{{.*}}T_V = constant ptr ptrauth (ptr @f_v, i32 0), align 8 +#[used] +static T_V: fn_v = f_v; + +// Pointer types. +extern "C" { + fn f_ptr(x: *mut i32) -> i32; +} +type fn_ptr = unsafe extern "C" fn(*mut i32) -> i32; +// discriminator: 12410 (0x307A), encoding: FiPE +// DISC: @{{.*}}T_PTR = constant ptr ptrauth (ptr @f_ptr, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_PTR = constant ptr ptrauth (ptr @f_ptr, i32 0), align 8 +#[used] +static T_PTR: fn_ptr = f_ptr; + +// Array types. +extern "C" { + fn f_arr_2(x: *mut i32) -> i32; + fn f_arr_4(x: *mut i32) -> i32; + fn f_arr2(x: *mut i32) -> i32; +} +type fn_arr_2 = unsafe extern "C" fn(*mut i32) -> i32; +type fn_arr_4 = unsafe extern "C" fn(*mut i32) -> i32; +type fn_arr2 = unsafe extern "C" fn(*mut i32) -> i32; +// discriminator: 12410 (0x307A), encoding: FiPE +// DISC: @{{.*}}T_ARR_2 = constant ptr ptrauth (ptr @f_arr_2, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_ARR_2 = constant ptr ptrauth (ptr @f_arr_2, i32 0), align 8 +#[used] +static T_ARR_2: fn_arr_2 = f_arr_2; +// discriminator: 12410 (0x307A), encoding: FiPE +// DISC: @{{.*}}T_ARR_4 = constant ptr ptrauth (ptr @f_arr_4, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_ARR_4 = constant ptr ptrauth (ptr @f_arr_4, i32 0), align 8 +#[used] +static T_ARR_4: fn_arr_4 = f_arr_4; +// discriminator: 12410 (0x307A), encoding: FiPE +// DISC: @{{.*}}T_ARR2 = constant ptr ptrauth (ptr @f_arr2, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_ARR2 = constant ptr ptrauth (ptr @f_arr2, i32 0), align 8 +#[used] +static T_ARR2: fn_arr2 = f_arr2; + +// Function types. +extern "C" { + fn f_nested(g: extern "C" fn(i32) -> i32, x: i32) -> i32; +} +type fn_i32_i32 = extern "C" fn(i32) -> i32; +type fn_nested = unsafe extern "C" fn(fn_i32_i32, i32) -> i32; +// discriminator: 20679 (0x50C7), encoding: FiPiE +// DISC: @{{.*}}T_NESTED = constant ptr ptrauth (ptr @f_nested, i32 0, i64 20679), align 8 +// NO_DISC: @{{.*}}T_NESTED = constant ptr ptrauth (ptr @f_nested, i32 0), align 8 +#[used] +static T_NESTED: fn_nested = f_nested; + +// Variadic function. +extern "C" { + fn f_var(x: i32, ...) -> i32; +} +type fn_var = unsafe extern "C" fn(i32, ...) -> i32; +// discriminator: 7476 (0x1D34), encoding: FiizE +// DISC: @{{.*}}T_VAR = constant ptr ptrauth (ptr @f_var, i32 0, i64 7476), align 8 +// NO_DISC: @{{.*}}T_VAR = constant ptr ptrauth (ptr @f_var, i32 0), align 8 +#[used] +static T_VAR: fn_var = f_var; + +// Enum coercion to int. +#[repr(i32)] +enum MyEnum { + A = 1, + B = 2, +} +extern "C" { + fn f_enum(x: MyEnum) -> MyEnum; +} +type fn_enum = unsafe extern "C" fn(MyEnum) -> MyEnum; +// discriminator: 2981 (0x0BA5), encoding: FiiE +// DISC: @{{.*}}T_ENUM = constant ptr ptrauth (ptr @f_enum, i32 0, i64 2981), align 8 +// NO_DISC: @{{.*}}T_ENUM = constant ptr ptrauth (ptr @f_enum, i32 0), align 8 +#[used] +static T_ENUM: fn_enum = f_enum; + +// Struct types. +#[repr(C)] +struct MyStruct { + x: i32, +} +extern "C" { + fn f_struct(x: MyStruct) -> MyStruct; +} +type fn_struct = unsafe extern "C" fn(MyStruct) -> MyStruct; +// discriminator: 17754 (0x455A), encoding: F8MyStruct8MyStructE +// DISC: @{{.*}}T_STRUCT = constant ptr ptrauth (ptr @f_struct, i32 0, i64 17754), align 8 +// NO_DISC: @{{.*}}T_STRUCT = constant ptr ptrauth (ptr @f_struct, i32 0), align 8 +#[used] +static T_STRUCT: fn_struct = f_struct; + +// Function pointer as arguments. +extern "C" { + fn f_fp(h: extern "C" fn(i32) -> i32) -> i32; +} +type fn_i32_i32_fp_as_arg = extern "C" fn(i32) -> i32; +type fn_fp = unsafe extern "C" fn(fn_i32_i32_fp_as_arg) -> i32; +// discriminator: 12410 (0x307A), encoding: FiPE +// DISC: @{{.*}}T_FP = constant ptr ptrauth (ptr @f_fp, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_FP = constant ptr ptrauth (ptr @f_fp, i32 0), align 8 +#[used] +static T_FP: fn_fp = f_fp; + +// SIMD vector type. +#[repr(simd)] +struct Int4([i32; 4]); +extern "C" { + fn f_vec(x: Int4) -> Int4; +} +type FnVec = unsafe extern "C" fn(Int4) -> Int4; +// discriminator: 34246 (0x85C6), encoding: FDv16Dv16E +// DISC: @{{.*}}T_VEC = constant ptr ptrauth (ptr @f_vec, i32 0, i64 34246), align 8 +// NO_DISC: @{{.*}}T_VEC = constant ptr ptrauth (ptr @f_vec, i32 0), align 8 +#[used] +static T_VEC: FnVec = f_vec; + +// Mixed. +type fn_i32_f = unsafe extern "C" fn(f32) -> i32; +extern "C" { + fn f_mixed(g: fn_i32_f, arr: *mut *mut f32, d: f64) -> i32; +} +type fn_mixed = unsafe extern "C" fn(fn_i32_f, *mut *mut f32, f64) -> i32; +// discriminator: 36791 (0x8FB7), encoding: FiPPdE +// DISC: @{{.*}}T_MIXED = constant ptr ptrauth (ptr @f_mixed, i32 0, i64 36791), align 8 +// NO_DISC: @{{.*}}T_MIXED = constant ptr ptrauth (ptr @f_mixed, i32 0), align 8 +#[used] +static T_MIXED: fn_mixed = f_mixed; + +// Quicksort. +type FnCmp = unsafe extern "C" fn(*const c_void, *const c_void) -> i32; +type FnQsort = unsafe extern "C" fn(*mut c_void, usize, usize, FnCmp); +extern "C" { + fn quickSort(base: *mut c_void, n: usize, size: usize, cmp: FnCmp); + + fn cmpI32Ascending(lhs: *const c_void, rhs: *const c_void) -> i32; +} +#[used] +static T_QSORT: FnQsort = quickSort; +// discriminator: 39926 (0x9BF6) of: FvPiiPE +// DISC: @{{.*}}T_QSORT = constant ptr ptrauth (ptr @quickSort, i32 0, i64 39926), align 8 +// NO_DISC: @{{.*}}T_QSORT = constant ptr ptrauth (ptr @quickSort, i32 0), align 8 +#[used] +// discriminator: 58622 (0xE4FE) of: FiPPE +// DISC: @{{.*}}T_CMP_I32_ASCENDING = constant ptr ptrauth (ptr @cmpI32Ascending, i32 0, i64 58622), align 8 +// NO_DISC: @{{.*}}T_CMP_I32_ASCENDING = constant ptr ptrauth (ptr @cmpI32Ascending, i32 0), align 8 +static T_CMP_I32_ASCENDING: FnCmp = cmpI32Ascending; + +// Callbacks. +extern "C" fn callback_i32(x: i32) -> i32 { + x + 1 +} +unsafe extern "C" fn callback_f32_to_i32(x: f32) -> i32 { + x as i32 +} +type FnCallbackI32 = unsafe extern "C" fn(i32) -> i32; +type FnCallbackF32ToI32 = unsafe extern "C" fn(f32) -> i32; +#[used] +// discriminator: 2981 (0x0BA5) of: FiiE +// DISC: @{{.*}}T_CALLBACK_I32 = constant ptr ptrauth (ptr @{{.*}}callback_i32, i32 0, i64 2981), align 8 +// NO_DISC: @{{.*}}T_CALLBACK_I32 = constant ptr ptrauth (ptr @{{.*}}callback_i32, i32 0), align 8 +static T_CALLBACK_I32: FnCallbackI32 = callback_i32; +#[used] +// discriminator: 48468 (0xBD54) of: FifE +// DISC: @{{.*}}T_CALLBACK_F32_TO_I32 = constant ptr ptrauth (ptr @{{.*}}callback_f32_to_i32, i32 0, i64 48468), align 8 +// NO_DISC: @{{.*}}T_CALLBACK_F32_TO_I32 = constant ptr ptrauth (ptr @{{.*}}callback_f32_to_i32, i32 0), align 8 +static T_CALLBACK_F32_TO_I32: FnCallbackF32ToI32 = callback_f32_to_i32; + +// Test the calling of the functions. +pub fn main() { + unsafe { + // Builtin types. + + // DISC: %{{.*}} = call i32 ptrauth (ptr @f_i32, i32 0, i64 2981)(i32 123) {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // NO_DISC: %{{.*}} = call i32 ptrauth (ptr @f_i32, i32 0)(i32 123) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_I32(123); + // DISC: %{{.*}} = call half ptrauth (ptr @f_h, i32 0, i64 37553)(half {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 37553) ] + // NO_DISC: %{{.*}} = call half ptrauth (ptr @f_h, i32 0)(half {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_H(1.25); + // DISC: %{{.*}} = call float ptrauth (ptr @f_f, i32 0, i64 28450)(float {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 28450) ] + // NO_DISC: %{{.*}} = call float ptrauth (ptr @f_f, i32 0)(float {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_F(1.25); + // DISC: %{{.*}} = call double ptrauth (ptr @f_d, i32 0, i64 43115)(double {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 43115) ] + // NO_DISC: %{{.*}} = call double ptrauth (ptr @f_d, i32 0)(double {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_D(2.5); + // DISC: %{{.*}} = call double ptrauth (ptr @f_2d, i32 0, i64 38695)(double {{.*}}, double {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 38695) ] + // NO_DISC: %{{.*}} = call double ptrauth (ptr @f_2d, i32 0)(double {{.*}}, double {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_2D(1.0, 2.0); + // DISC: %{{.*}} = call fp128 ptrauth (ptr @f_ld, i32 0, i64 25877)(fp128 {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 25877) ] + // NO_DISC: %{{.*}} = call fp128 ptrauth (ptr @f_ld, i32 0)(fp128 {{.*}}) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_LD(1.0f128); + // DISC: call void ptrauth (ptr @f_v, i32 0, i64 18983)() {{.*}} [ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void ptrauth (ptr @f_v, i32 0)() {{.*}} [ "ptrauth"(i32 0, i64 0) ] + T_V(); + + // Pointer type. + let mut x = 42i32; + // DISC: %{{.*}} = call i32 ptrauth (ptr @f_ptr, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: %{{.*}} = call i32 ptrauth (ptr @f_ptr, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_PTR(&mut x); + + // Array types. + let mut arr2 = [1i32, 2]; + let mut arr4 = [1i32, 2, 3, 4]; + let mut arrn = [1i32, 2, 3]; + + // DISC-DAG: call i32 ptrauth (ptr @f_arr_2, i32 0, i64 12410)(ptr %arr2) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC-DAG: call i32 ptrauth (ptr @f_arr_2, i32 0)(ptr %arr2) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_ARR_2((&mut arr2) as *mut [i32; 2] as *mut i32); + // DISC-DAG: call i32 ptrauth (ptr @f_arr_4, i32 0, i64 12410)(ptr %arr4) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC-DAG: call i32 ptrauth (ptr @f_arr_4, i32 0)(ptr %arr4) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_ARR_4((&mut arr4) as *mut [i32; 4] as *mut i32); + // DISC-DAG: call i32 ptrauth (ptr @f_arr2, i32 0, i64 12410)(ptr %arrn) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC-DAG: call i32 ptrauth (ptr @f_arr2, i32 0)(ptr %arrn) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_ARR2((&mut arrn) as *mut [i32; 3] as *mut i32); + + // Function argument. + // DISC: call i32 ptrauth (ptr @f_nested, i32 0, i64 20679)(ptr ptrauth (ptr @{{.*}}callback_i32, i32 0, i64 2981), i32 123) {{.*}} [ "ptrauth"(i32 0, i64 20679) ] + // NO_DISC: call i32 ptrauth (ptr @f_nested, i32 0)(ptr ptrauth (ptr @{{.*}}callback_i32, i32 0), i32 123) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_NESTED(callback_i32, 123); + + // Variadic. + // DISC: call i32 (i32, ...) ptrauth (ptr @f_var, i32 0, i64 7476){{.*}} [ "ptrauth"(i32 0, i64 7476) ] + // NO_DISC: call i32 (i32, ...) ptrauth (ptr @f_var, i32 0){{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_VAR(3, 10i32, 20i32, 30i32); + + // Enum. + // DISC: call i32 ptrauth (ptr @f_enum, i32 0, i64 2981)(i32 1) {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // NO_DISC: call i32 ptrauth (ptr @f_enum, i32 0)(i32 1) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_ENUM(MyEnum::A); + + // Struct. + // DISC: call i64 ptrauth (ptr @f_struct, i32 0, i64 17754){{.*}} [ "ptrauth"(i32 0, i64 17754) ] + // NO_DISC: ){{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_STRUCT(MyStruct { x: 123 }); + + // Function pointer argument. + // DISC: call i32 ptrauth (ptr @f_fp, i32 0, i64 12410)(ptr ptrauth (ptr @{{.*}}callback_i32, i32 0, i64 2981)) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_fp, i32 0)(ptr ptrauth (ptr @{{.*}}callback_i32, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_FP(callback_i32); + + // SIMD vector. + // DISC: call <4 x i32> ptrauth (ptr @f_vec, i32 0, i64 34246)(<4 x i32>{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <4 x i32> ptrauth (ptr @f_vec, i32 0)(<4 x i32>{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_VEC(Int4([1, 2, 3, 4])); + + // Mixed case. + let mut value = 1.0f32; + let mut ptr = &mut value as *mut f32; + // DISC: call i32 ptrauth (ptr @f_mixed, i32 0, i64 36791)(ptr ptrauth (ptr @{{.*}}callback_f32_to_i32, i32 0, i64 48468), {{.*}} [ "ptrauth"(i32 0, i64 36791) ] + // NO_DISC: call i32 ptrauth (ptr @f_mixed, i32 0)(ptr ptrauth (ptr @{{.*}}callback_f32_to_i32, i32 0), {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_MIXED(callback_f32_to_i32, &mut ptr, 2.0); + + // Comparator. + let lhs = 1i32; + let rhs = 2i32; + // DISC: call i32 ptrauth (ptr @cmpI32Ascending, i32 0, i64 58622)(ptr %lhs, ptr %rhs) {{.*}} [ "ptrauth"(i32 0, i64 58622) ] + // NO_DISC: call i32 ptrauth (ptr @cmpI32Ascending, i32 0)(ptr %lhs, ptr %rhs) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_CMP_I32_ASCENDING( + // (&lhs as *const i32).cast(), + // (&rhs as *const i32).cast(), + (&lhs as *const i32) as *const c_void, + (&rhs as *const i32) as *const c_void, + ); + + // Quicksort. + let mut values = [42i32, 7, 19, 3, 11]; + // DISC: call void ptrauth (ptr @quickSort, i32 0, i64 39926)(ptr %values, i64 5, i64 4, ptr ptrauth (ptr @cmpI32Ascending, i32 0, i64 58622)) {{.*}} [ "ptrauth"(i32 0, i64 39926) ] + // NO_DISC: call void ptrauth (ptr @quickSort, i32 0)(ptr %values, i64 5, i64 4, ptr ptrauth (ptr @cmpI32Ascending, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + T_QSORT( + (&mut values as *mut [i32; 5]) as *mut i32 as *mut c_void, + //values.as_mut_ptr().cast(), + 5, + 4, + T_CMP_I32_ASCENDING, + ); + } +} + +// Equivalent C code: +// +// #include +// #include +// +// // Builtin types. +// int32_t f_i32(int32_t x); +// float f_f(float x); +// double f_d(double x); +// double f_2d(double x, double y); +// long double f_ld(long double x); +// void f_v(void); +// +// typedef int32_t (*fn_i32)(int32_t); +// typedef float (*fn_f)(float); +// typedef double (*fn_d)(double); +// typedef double (*fn_2d)(double, double); +// typedef void (*fn_v)(void); +// +// __attribute__((used)) static fn_i32 T_I32 = f_i32; +// __attribute__((used)) static fn_f T_F = f_f; +// __attribute__((used)) static fn_d T_D = f_d; +// __attribute__((used)) static fn_2d T_2D = f_2d; +// __attribute__((used)) static fn_v T_V = f_v; +// +// // Pointer types. +// int32_t f_ptr(int32_t *x); +// +// typedef int32_t (*fn_ptr)(int32_t *); +// +// __attribute__((used)) static fn_ptr T_PTR = f_ptr; +// +// // Array types. +// int32_t f_arr_2(int32_t x[2]); +// int32_t f_arr_4(int32_t x[4]); +// +// typedef int32_t (*fn_arr_2)(int32_t[2]); +// typedef int32_t (*fn_arr_4)(int32_t[4]); +// +// __attribute__((used)) static fn_arr_2 T_ARR_2 = f_arr_2; +// __attribute__((used)) static fn_arr_4 T_ARR_4 = f_arr_4; +// // incomplete array +// int32_t f_arr2(int32_t x[]); +// +// typedef int32_t (*fn_arr2)(int32_t[]); +// +// __attribute__((used)) static fn_arr2 T_ARR2 = f_arr2; +// +// // Function types. +// int32_t f_nested(int32_t (*g)(int32_t), int32_t x); +// +// typedef int32_t (*fn_i32_i32)(int32_t); +// typedef int32_t (*fn_nested)(fn_i32_i32, int32_t); +// +// __attribute__((used)) static fn_nested T_NESTED = f_nested; +// +// // Variadic function. +// int32_t f_var(int32_t x, ...); +// +// typedef int32_t (*fn_var)(int32_t, ...); +// +// __attribute__((used)) static fn_var T_VAR = f_var; +// +// // Enum to integer coercion. +// typedef enum { A = 1, B = 2 } MyEnum; +// +// MyEnum f_enum(MyEnum x); +// +// typedef MyEnum (*fn_enum)(MyEnum); +// +// __attribute__((used)) static fn_enum T_ENUM = f_enum; +// +// // Struct. +// typedef struct { +// int x; +// } MyStruct; +// +// MyStruct f_struct(MyStruct x); +// +// typedef MyStruct (*fn_struct)(MyStruct); +// +// __attribute__((used)) static fn_struct T_STRUCT = f_struct; +// +// // Pointer to function pointer. +// int32_t f_fp(int32_t (*h)(int32_t)); +// +// typedef int32_t (*fn_i32_i32)(int32_t); +// typedef int32_t (*fn_fp)(fn_i32_i32); +// +// __attribute__((used)) static fn_fp T_FP = f_fp; +// +// // SIMD vector. +// typedef int32_t int4 __attribute__((vector_size(16))); +// +// int4 f_vec(int4 x); +// +// typedef int4 (*fn_vec)(int4); +// +// __attribute__((used)) static fn_vec T_VEC = f_vec; +// +// // Mix. +// int32_t f_mixed(int32_t (*g)(float), float *arr[4], double d); +// +// typedef int32_t (*fn_mixed)(int32_t (*)(float), float *[4], double); +// +// __attribute__((used)) static fn_mixed T_MIXED = f_mixed; +// +// // Qsort +// void quickSort(void *Base, size_t N, size_t Size, +// int (*Cmp)(const void *, const void *)); +// +// int cmpI32Ascending(const void *LHS, const void *RHS); +// typedef void (*fn_qsort)(void *, size_t, size_t, +// int (*)(const void *, const void *)); +// typedef int (*fn_cmp)(const void *, const void *); +// +// __attribute__((used)) static fn_qsort T_QSORT = quickSort; +// __attribute__((used)) static fn_cmp T_CMP_I32_ASCENDING = cmpI32Ascending; +// +// // Callbacks +// static int32_t callback_i32(int32_t x) { return x + 1; } +// static int32_t callback_f32_to_i32(float x) { return (int32_t)x; } +// typedef int32_t (*fn_callback_i32)(int32_t); +// typedef int32_t (*fn_callback_f32_to_i32)(float); +// __attribute__((used)) static fn_callback_i32 T_CALLBACK_I32 = callback_i32; +// __attribute__((used)) static fn_callback_f32_to_i32 T_CALLBACK_F32_TO_I32 = +// callback_f32_to_i32; +// +// int main(void) { +// /* Builtin types. */ +// (void)T_I32(123); +// (void)T_F(1.25f); +// (void)T_D(2.5); +// (void)T_2D(1.0, 2.0); +// T_V(); +// +// /* Pointer type. */ +// int32_t x = 42; +// (void)T_PTR(&x); +// +// /* Array types. */ +// int32_t arr2[2] = {1, 2}; +// int32_t arr4[4] = {1, 2, 3, 4}; +// int32_t arrn[3] = {1, 2, 3}; +// +// (void)T_ARR_2(arr2); +// (void)T_ARR_4(arr4); +// (void)T_ARR2(arrn); +// +// /* Function argument. */ +// (void)T_NESTED(callback_i32, 123); +// +// /* Variadic. */ +// (void)T_VAR(3, 10, 20, 30); +// +// /* Enum. */ +// (void)T_ENUM(A); +// +// /* Struct. */ +// (void)T_STRUCT((MyStruct){.x = 123}); +// +// /* Function pointer argument. */ +// (void)T_FP(callback_i32); +// +// /* SIMD vector. */ +// int4 v = {1, 2, 3, 4}; +// (void)T_VEC(v); +// +// /* Mixed case. */ +// float value0 = 1.0f; +// float value1 = 2.0f; +// float value2 = 3.0f; +// float value3 = 4.0f; +// +// float *arrp[4] = {&value0, &value1, &value2, &value3}; +// +// (void)T_MIXED(callback_f32_to_i32, arrp, 1.0); +// +// /* Comparator. */ +// int32_t lhs = 1; +// int32_t rhs = 2; +// +// (void)T_CMP_I32_ASCENDING(&lhs, &rhs); +// +// /* Quicksort. */ +// int32_t values[] = {42, 7, 19, 3, 11}; +// +// T_QSORT(values, sizeof(values) / sizeof(values[0]), sizeof(values[0]), +// T_CMP_I32_ASCENDING); +// +// return 0; +// } diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-fn-ptr-return-type.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-fn-ptr-return-type.rs new file mode 100644 index 0000000000000..296aedd31b3b7 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-fn-ptr-return-type.rs @@ -0,0 +1,43 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Test generation of function-pointer type discriminators for functions returning a function +// pointer themselves. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; + +extern "C" { + fn f_ret_fp(x: i32) -> extern "C" fn(i32) -> i32; +} + +type FnCallback = extern "C" fn(i32) -> i32; +type FnRetFp = unsafe extern "C" fn(i32) -> FnCallback; + +#[used] +// discriminator: 32957 (0x80BD), encoding: FPiE +// DISC: @{{.*}}T_RET_FP = constant ptr ptrauth (ptr @f_ret_fp, i32 0, i64 32957), align 8 +// NO_DISC: @{{.*}}T_RET_FP = constant ptr ptrauth (ptr @f_ret_fp, i32 0), align 8 +static T_RET_FP: FnRetFp = f_ret_fp; + +pub fn main() { + unsafe { + // discriminator: 32957 (0x80BD), encoding: FPiE + // DISC: [[CB:%.*]] = call ptr ptrauth (ptr @f_ret_fp, i32 0, i64 32957)(i32 123) {{.*}} [ "ptrauth"(i32 0, i64 32957) ] + // NO_DISC: [[CB:%.*]] = call ptr ptrauth (ptr @f_ret_fp, i32 0)(i32 123) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let cb = T_RET_FP(123); + // discriminator: 2981 (0x0BA5), encoding: FiiE + // DISC: call i32 [[CB]](i32 456) {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // NO_DISC: call i32 [[CB]](i32 456) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = cb(456); + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-instance-signing.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-instance-signing.rs new file mode 100644 index 0000000000000..cbc2dff293535 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-instance-signing.rs @@ -0,0 +1,87 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC + +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// A function pointer is signed with the discriminator of the function instance it points to: for +// a generic function, the instantiated signature; for methods, the method's own signature. This +// holds whether the pointer is created at runtime or in a constant. +// +// Discriminators: `fn(i32)` = 2712, `fn(*const u8)` = 10942, `fn(i32) -> i32` = 2981. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::Sync; + +extern "C" fn generic(_: T) {} + +pub struct S; + +impl S { + extern "C" fn method(x: i32) -> i32 { + x + } +} + +pub trait Tr { + extern "C" fn assoc(x: i32) -> i32; +} + +impl Tr for S { + extern "C" fn assoc(x: i32) -> i32 { + x + } +} + +pub struct Table { + a: extern "C" fn(i32), + b: extern "C" fn(*const u8), + c: extern "C" fn(i32) -> i32, +} + +impl Sync for Table {} + +// DISC-DAG: @{{.*}}TABLE = constant <{ ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0, i64 2712), ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0, i64 10942), ptr ptrauth (ptr @{{.*}}assoc{{.*}}, i32 0, i64 2981) }> +// NO_DISC-DAG: @{{.*}}TABLE = constant <{ ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0), ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0), ptr ptrauth (ptr @{{.*}}assoc{{.*}}, i32 0) }> +#[used] +pub static TABLE: Table = Table { a: generic::, b: generic::<*const u8>, c: ::assoc }; + +// CHECK-LABEL: @reify_generic_i32( +#[no_mangle] +pub fn reify_generic_i32() -> extern "C" fn(i32) { + // DISC: ret ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0, i64 2712) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0) + generic:: +} + +// CHECK-LABEL: @reify_generic_ptr( +#[no_mangle] +pub fn reify_generic_ptr() -> extern "C" fn(*const u8) { + // DISC: ret ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0, i64 10942) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}generic{{.*}}, i32 0) + generic::<*const u8> +} + +// CHECK-LABEL: @reify_inherent_method( +#[no_mangle] +pub fn reify_inherent_method() -> extern "C" fn(i32) -> i32 { + // DISC: ret ptr ptrauth (ptr @{{.*}}method{{.*}}, i32 0, i64 2981) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}method{{.*}}, i32 0) + S::method +} + +// CHECK-LABEL: @reify_trait_method( +#[no_mangle] +pub fn reify_trait_method() -> extern "C" fn(i32) -> i32 { + // DISC: ret ptr ptrauth (ptr @{{.*}}assoc{{.*}}, i32 0, i64 2981) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}assoc{{.*}}, i32 0) + ::assoc +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-intrinsics.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-intrinsics.rs new file mode 100644 index 0000000000000..5c136a4d256b5 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-intrinsics.rs @@ -0,0 +1,192 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC + +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// The explicit pointer authentication intrinsics: +// * `ptrauth_c_cast` resigns a code address between the C encodings of two types: a function +// pointer type uses its type discriminator, a raw pointer or an integer uses 0. Without type +// discrimination every encoding is 0, so nothing is resigned. +// * `ptrauth_fn_ptr_discriminator` is the type discriminator of a function pointer type. +// * `ptrauth_strip` removes the signature of a code address. +// +// Discriminators: +// * `extern "C" fn()` = 18983 +// * `extern "C" fn(i32)` = 2712. + +#![feature(no_core, lang_items, intrinsics, rustc_attrs)] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::Option; + +#[rustc_intrinsic] +unsafe fn ptrauth_c_cast(src: Src) -> Dst; + +#[rustc_intrinsic] +#[rustc_comptime] +fn ptrauth_fn_ptr_discriminator() -> u64; + +#[rustc_intrinsic] +fn ptrauth_strip(ptr: T) -> usize; + +type F0 = extern "C" fn(); +type F1 = extern "C" fn(i32); + +// A `void *` from C (e.g. `dlsym`) carries discriminator 0. It may be null, so the resign is +// guarded by a null check. +// CHECK-LABEL: @from_void_ptr( +#[no_mangle] +pub unsafe fn from_void_ptr(p: *const ()) -> Option { + // DISC: icmp eq ptr %p, null + // DISC: br i1 %{{.*}}, label %ptrauth.null, label %ptrauth.resign + // DISC: ptrauth.resign: + // DISC: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 0, i32 0, i64 2712) + // DISC: ptrauth.end: + // NO_DISC-NOT: @llvm.ptrauth.resign + // NO_DISC-NOT: ptrauth.null + // CHECK: ret ptr + unsafe { ptrauth_c_cast::<*const (), Option>(p) } +} + +// A non-null function pointer handed to C as a `void *`: no null check. +// CHECK-LABEL: @to_void_ptr( +#[no_mangle] +pub unsafe fn to_void_ptr(f: F1) -> *const () { + // DISC-NOT: ptrauth.null + // DISC: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 2712, i32 0, i64 0) + // NO_DISC-NOT: @llvm.ptrauth.resign + // CHECK: ret ptr + unsafe { ptrauth_c_cast::(f) } +} + +// A generic callback slot (GLib's `GCallback`, Vulkan's `PFN_vkVoidFunction`): resign between +// the discriminators of the real and the generic function pointer type. +// CHECK-LABEL: @to_generic_callback( +#[no_mangle] +pub unsafe fn to_generic_callback(f: F1) -> F0 { + // DISC-NOT: ptrauth.null + // DISC: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 2712, i32 0, i64 18983) + // NO_DISC-NOT: @llvm.ptrauth.resign + // CHECK: ret ptr + unsafe { ptrauth_c_cast::(f) } +} + +// CHECK-LABEL: @from_generic_callback( +#[no_mangle] +pub unsafe fn from_generic_callback(g: Option) -> Option { + // DISC: br i1 %{{.*}}, label %ptrauth.null, label %ptrauth.resign + // DISC: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 18983, i32 0, i64 2712) + // NO_DISC-NOT: @llvm.ptrauth.resign + // CHECK: ret ptr + unsafe { ptrauth_c_cast::, Option>(g) } +} + +// An integer from C (`uintptr_t`) carries discriminator 0. +// CHECK-LABEL: @from_integer( +#[no_mangle] +pub unsafe fn from_integer(addr: usize) -> Option { + // DISC: inttoptr i64 %addr to ptr + // DISC: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 0, i32 0, i64 18983) + // NO_DISC-NOT: @llvm.ptrauth.resign + // CHECK: ret ptr + unsafe { ptrauth_c_cast::>(addr) } +} + +// The same encoding on both sides: nothing to resign. +// CHECK-LABEL: @same_encoding( +#[no_mangle] +pub unsafe fn same_encoding(p: *const ()) -> usize { + // CHECK-NOT: @llvm.ptrauth.resign + // CHECK: ptrtoint ptr %p to i64 + // CHECK-NOT: @llvm.ptrauth.resign + // CHECK: ret i64 + unsafe { ptrauth_c_cast::<*const (), usize>(p) } +} + +// CHECK-LABEL: @same_fn_type( +#[no_mangle] +pub unsafe fn same_fn_type(f: F1) -> Option { + // CHECK-NOT: @llvm.ptrauth.resign + // CHECK: ret ptr %f + unsafe { ptrauth_c_cast::>(f) } +} + +// The resigned pointer is called through its type: the call authenticates with that type. +// CHECK-LABEL: @call_from_void_ptr( +#[no_mangle] +pub unsafe fn call_from_void_ptr(p: *const ()) { + // DISC: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 0, i32 0, i64 2712) + // DISC: call void %{{.*}}(i32 7) {{.*}}[ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void %{{.*}}(i32 7) {{.*}}[ "ptrauth"(i32 0, i64 0) ] + let f = unsafe { ptrauth_c_cast::<*const (), F1>(p) }; + f(7); +} + +// CHECK-LABEL: @strip( +#[no_mangle] +pub fn strip(f: F1) -> usize { + // CHECK: [[ADDR:%.*]] = ptrtoint ptr %f to i64 + // CHECK: [[STRIPPED:%.*]] = call i64 @llvm.ptrauth.strip(i64 [[ADDR]], i32 0) + // CHECK: ret i64 [[STRIPPED]] + ptrauth_strip(f) +} + +// The discriminator does not depend on whether type discrimination is enabled, like Clang's +// `__builtin_ptrauth_type_discriminator`. +// CHECK-LABEL: @discriminator_f1( +#[no_mangle] +pub fn discriminator_f1() -> u64 { + // CHECK: ret i64 2712 + const { ptrauth_fn_ptr_discriminator::() } +} + +// CHECK-LABEL: @discriminator_option_f0( +#[no_mangle] +pub fn discriminator_option_f0() -> u64 { + // CHECK: ret i64 18983 + const { ptrauth_fn_ptr_discriminator::>() } +} + +// Not an `extern "C"` function pointer: 0. +// CHECK-LABEL: @discriminator_rust_abi( +#[no_mangle] +pub fn discriminator_rust_abi() -> u64 { + // CHECK: ret i64 0 + const { ptrauth_fn_ptr_discriminator::() } +} + +// CHECK-LABEL: @discriminator_nested_option( +#[no_mangle] +pub fn discriminator_nested_option() -> u64 { + // CHECK: ret i64 0 + const { ptrauth_fn_ptr_discriminator::>>() } +} + +extern "C" fn item() {} + +const fn discriminator_of_val(_: &F) -> u64 { + const { ptrauth_fn_ptr_discriminator::() } +} + +// A function item type is zero-sized, so it does not hold a code address either; it needs to be +// coerced to a function pointer first. +// CHECK-LABEL: @discriminator_fn_item( +#[no_mangle] +pub fn discriminator_fn_item() -> u64 { + // CHECK: ret i64 0 + const { discriminator_of_val(&item) } +} + +// CHECK-LABEL: @discriminator_fn_item_coerced( +#[no_mangle] +pub fn discriminator_fn_item_coerced() -> u64 { + // CHECK: ret i64 18983 + const { discriminator_of_val::(&(item as F0)) } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-no-resign.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-no-resign.rs new file mode 100644 index 0000000000000..3b4aa28ee3d1f --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-no-resign.rs @@ -0,0 +1,164 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC + +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// A function pointer is signed with the discriminator of the function it points to, and +// reinterpreting it never resigns it. Transmute, `as` casts, union reads, reads through a cast +// pointer and memcpy are all plain bit copies. A round trip through another function pointer type, +// a raw pointer or an integer therefore needs nothing: the final call authenticates with the +// discriminator of `extern "C" fn()`, which is the one `f` was signed with. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::Option::{self, Some}; +use minicore::copy_nonoverlapping; +use minicore::mem::{size_of, transmute}; + +type F0 = extern "C" fn(); +type F1 = extern "C" fn(i32); + +extern "C" fn f() {} +extern "C" fn g(_: i32) {} +extern "C" fn h() {} + +union Pun { + f0: F0, + f1: F1, +} + +// CHECK-LABEL: @via_transmute( +#[no_mangle] +pub fn via_transmute() { + // CHECK-NOT: llvm.ptrauth.resign + let p: F0 = f; + let q: F1 = unsafe { transmute(p) }; + let r: F0 = unsafe { transmute(q) }; + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + r(); +} + +// Calling through the erased type authenticates with that type's discriminator. The pointer is +// still signed for `fn()`, so this traps at runtime, as calling `f` as `fn(i32)` is UB. +// CHECK-LABEL: @via_transmute_call_erased( +#[no_mangle] +pub fn via_transmute_call_erased() { + // CHECK-NOT: llvm.ptrauth.resign + let p: F0 = f; + let q: F1 = unsafe { transmute(p) }; + // DISC: call void {{.*}}(i32 1) {{.*}}[ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void {{.*}}(i32 1) {{.*}}[ "ptrauth"(i32 0, i64 0) ] + q(1); +} + +// CHECK-LABEL: @via_union( +#[no_mangle] +pub fn via_union() { + // CHECK-NOT: llvm.ptrauth.resign + let u = Pun { f0: f }; + let q: F1 = unsafe { u.f1 }; + let u2 = Pun { f1: q }; + let r: F0 = unsafe { u2.f0 }; + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + r(); +} + +// CHECK-LABEL: @via_pointer_read( +#[no_mangle] +pub fn via_pointer_read() { + // CHECK-NOT: llvm.ptrauth.resign + let p: F0 = f; + let q: F1 = unsafe { *(&p as *const F0 as *const F1) }; + let r: F0 = unsafe { *(&q as *const F1 as *const F0) }; + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + r(); +} + +// CHECK-LABEL: @via_memcpy( +#[no_mangle] +pub fn via_memcpy() { + // CHECK-NOT: llvm.ptrauth.resign + let p: F0 = f; + let mut q: F1 = g; + let mut r: F0 = h; + unsafe { + copy_nonoverlapping( + &p as *const F0 as *const u8, + &mut q as *mut F1 as *mut u8, + const { size_of::() }, + ); + copy_nonoverlapping( + &q as *const F1 as *const u8, + &mut r as *mut F0 as *mut u8, + const { size_of::() }, + ); + } + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + r(); +} + +// CHECK-LABEL: @via_as_cast( +#[no_mangle] +pub fn via_as_cast() { + // CHECK-NOT: llvm.ptrauth.resign + let p: F0 = f; + let raw = p as *const (); + let r: F0 = unsafe { transmute(raw) }; + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + r(); +} + +// CHECK-LABEL: @via_raw_pointer( +#[no_mangle] +pub fn via_raw_pointer() { + // CHECK-NOT: llvm.ptrauth.resign + let p: F0 = f; + let raw: *const () = unsafe { transmute(p) }; + let r: F0 = unsafe { transmute(raw) }; + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + r(); +} + +// CHECK-LABEL: @via_integer( +#[no_mangle] +pub fn via_integer() { + // CHECK-NOT: llvm.ptrauth.resign + let p: F0 = f; + let addr: usize = unsafe { transmute(p) }; + let r: F0 = unsafe { transmute(addr) }; + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + r(); +} + +// CHECK-LABEL: @via_option( +#[no_mangle] +pub fn via_option() { + // CHECK-NOT: llvm.ptrauth.resign + // CHECK-NOT: ptrauth.null + let p: Option = Some(f); + let q: Option = unsafe { transmute(p) }; + let r: Option = unsafe { transmute(q) }; + // DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void {{.*}}() {{.*}}[ "ptrauth"(i32 0, i64 0) ] + if let Some(r) = r { + r(); + } +} + +// The intrinsic is not even declared. +// CHECK-NOT: @llvm.ptrauth.resign diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-callback.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-callback.rs new file mode 100644 index 0000000000000..2d1ae421bd998 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-callback.rs @@ -0,0 +1,103 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Nullable pointer arguments emulated with `Option`. A two-variant enum is encoded as its payload +// only when it has the payload's layout: +// * `Option` and `Option<&T>` use the payload's null niche, so they are ABI-compatible with +// the bare pointer and encode as `P`. +// * `Option<*mut T>` needs a tag, because null is a valid raw pointer, so it must not encode as +// `P`. +// +// Discriminators: +// 18786: "Fi6OptionE" +// 12410: "FiPE" +// 2981: "FiiE" + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::Option::{None, Some}; +use minicore::{Option, c_void}; + +extern "C" { + fn f_opt(cb: Option i32>) -> i32; + fn f_raw(cb: unsafe extern "C" fn(i32) -> i32) -> i32; + + fn r_opt(ctx: Option<&i32>) -> i32; + + fn g_opt(ctx: Option<*mut c_void>) -> i32; + fn g_raw(ctx: *mut c_void) -> i32; + + fn callback_i32(x: i32) -> i32; +} + +type FnOpt = unsafe extern "C" fn(Option i32>) -> i32; +type FnRaw = unsafe extern "C" fn(unsafe extern "C" fn(i32) -> i32) -> i32; +type RefOpt = unsafe extern "C" fn(Option<&i32>) -> i32; +type DataOpt = unsafe extern "C" fn(Option<*mut c_void>) -> i32; +type DataRaw = unsafe extern "C" fn(*mut c_void) -> i32; + +// The statics may be emitted in any order. +// DISC-DAG: @{{.*}}T_OPT = constant ptr ptrauth (ptr @{{.*}}f_opt, i32 0, i64 12410), align 8 +// DISC-DAG: @{{.*}}T_RAW = constant ptr ptrauth (ptr @{{.*}}f_raw, i32 0, i64 12410), align 8 +// DISC-DAG: @{{.*}}G_OPT = constant ptr ptrauth (ptr @{{.*}}g_opt, i32 0, i64 18786), align 8 +// DISC-DAG: @{{.*}}G_RAW = constant ptr ptrauth (ptr @{{.*}}g_raw, i32 0, i64 12410), align 8 +// NO_DISC-DAG: @{{.*}}T_OPT = constant ptr ptrauth (ptr @{{.*}}f_opt, i32 0), align 8 +// NO_DISC-DAG: @{{.*}}T_RAW = constant ptr ptrauth (ptr @{{.*}}f_raw, i32 0), align 8 +// NO_DISC-DAG: @{{.*}}G_OPT = constant ptr ptrauth (ptr @{{.*}}g_opt, i32 0), align 8 +// NO_DISC-DAG: @{{.*}}G_RAW = constant ptr ptrauth (ptr @{{.*}}g_raw, i32 0), align 8 +#[used] +static T_OPT: FnOpt = f_opt; +#[used] +static T_RAW: FnRaw = f_raw; +#[used] +static G_OPT: DataOpt = g_opt; +#[used] +static G_RAW: DataRaw = g_raw; + +// `Option<&i32>` makes this a higher-ranked function pointer type, which does not implement +// `Sync` in minicore, so it is a `const` rather than a `static`. +const R_OPT: RefOpt = r_opt; + +// CHECK-LABEL: main +pub fn main() { + let mut x = 42i32; + + unsafe { + // Function pointers. + // DISC: call i32 ptrauth (ptr @f_opt, i32 0, i64 12410)(ptr ptrauth (ptr @callback_i32, i32 0, i64 2981)) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_opt, i32 0)(ptr ptrauth (ptr @callback_i32, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_OPT(Some(callback_i32)); + // DISC: call i32 ptrauth (ptr @f_opt, i32 0, i64 12410)(ptr null) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_opt, i32 0)(ptr null) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_OPT(None); + // DISC: call i32 ptrauth (ptr @f_raw, i32 0, i64 12410)(ptr ptrauth (ptr @callback_i32, i32 0, i64 2981)) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_raw, i32 0)(ptr ptrauth (ptr @callback_i32, i32 0)) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_RAW(callback_i32); + + // References. + // DISC: call i32 ptrauth (ptr @r_opt, i32 0, i64 12410)(ptr align 4 %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @r_opt, i32 0)(ptr align 4 %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = R_OPT(Some(&x)); + + // Raw pointers. + // DISC: call i32 ptrauth (ptr @g_opt, i32 0, i64 18786){{.*}} [ "ptrauth"(i32 0, i64 18786) ] + // NO_DISC: call i32 ptrauth (ptr @g_opt, i32 0){{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = G_OPT(Some((&mut x as *mut i32) as *mut c_void)); + // DISC: call i32 ptrauth (ptr @g_opt, i32 0, i64 18786){{.*}} [ "ptrauth"(i32 0, i64 18786) ] + // NO_DISC: call i32 ptrauth (ptr @g_opt, i32 0){{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = G_OPT(None); + // DISC: call i32 ptrauth (ptr @g_raw, i32 0, i64 12410){{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @g_raw, i32 0){{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = G_RAW((&mut x as *mut i32) as *mut c_void); + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-return.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-return.rs new file mode 100644 index 0000000000000..7c8ea5f5c3c78 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option-return.rs @@ -0,0 +1,42 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Test generation of function-pointer type discriminators for optional returns. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::Option; +use minicore::Option::{None, Some}; + +extern "C" { + fn f_ret_option() -> Option i32>; +} + +type FnRetOption = unsafe extern "C" fn() -> Option i32>; + +#[used] +// DISC: @{{.*}}T_RET_OPTION = constant ptr ptrauth (ptr @{{.*}}f_ret_option, i32 0, i64 34128), align 8 +// NO_DISC: @{{.*}}T_RET_OPTION = constant ptr ptrauth (ptr @{{.*}}f_ret_option, i32 0), align 8 +static T_RET_OPTION: FnRetOption = f_ret_option; + +pub fn main() { + unsafe { + // DISC: call ptr ptrauth (ptr @f_ret_option, i32 0, i64 34128)() {{.*}} [ "ptrauth"(i32 0, i64 34128) ] + // NO_DISC: call ptr ptrauth (ptr @f_ret_option, i32 0)() {{.*}} [ "ptrauth"(i32 0, i64 0) ] + if let Some(cb) = T_RET_OPTION() { + // DISC: call i32 %cb(i32 123) {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // NO_DISC: call i32 %cb(i32 123) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = cb(123); + } + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option.rs new file mode 100644 index 0000000000000..a23a3b7083c54 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-option.rs @@ -0,0 +1,36 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. + +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Test generation of function-pointer type discriminators for optional variables. The statics +// may be emitted in any order. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::Option; +use minicore::Option::{None, Some}; + +extern "C" fn f(_: i32) {} + +// Rust function pointers are no-nullable, so this can not be expressed: +// void (*test_constant_null)(int) = 0; +// Use Option instead. +type TestConstantNullTy = unsafe extern "C" fn(i32); + +#[used] +// DISC-DAG: @{{.*}}TEST_CONSTANT_NON_NULL = constant ptr ptrauth (ptr @{{.*}}f, i32 0, i64 2712), align 8 +// NO_DISC-DAG: @{{.*}}TEST_CONSTANT_NON_NULL = constant ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static TEST_CONSTANT_NON_NULL: Option = Some(f); +#[used] +// CHECK-DAG: @{{.*}}TEST_CONSTANT_NULL = constant {{.*}} zeroinitializer, align 8 +static TEST_CONSTANT_NULL: Option = None; diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-recursive-statics.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-recursive-statics.rs new file mode 100644 index 0000000000000..88982c75c15de --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-recursive-statics.rs @@ -0,0 +1,165 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. + +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Tests function-pointer type discriminator generation for pointer authentication across nested +// static allocations, wrapper references, and padded structs. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; +use minicore::Sync; +use minicore::hint::black_box; + +extern "C" fn foo(_: f32) {} +extern "C" fn bar(_: i32) {} + +impl Sync for InnerA {} +impl Sync for InnerB {} +impl Sync for Outer {} + +// DISC-DAG: @[[INNER_A:[^ ]*T_INNER_A]] = constant ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 21613) +// DISC-DAG: @[[INNER_B:[^ ]*T_INNER_B]] = constant ptr ptrauth (ptr @{{.*}}bar, i32 0, i64 2712) +// NO_DISC-DAG: @[[INNER_A:[^ ]*T_INNER_A]] = constant ptr ptrauth (ptr @{{.*}}foo, i32 0) +// NO_DISC-DAG: @[[INNER_B:[^ ]*T_INNER_B]] = constant ptr ptrauth (ptr @{{.*}}bar, i32 0) +// CHECK-DAG: @[[T_OUTER:[^ ]*T_OUTER]] = constant ptr @[[ALLOC:alloc_[0-9a-f]+]] +// CHECK-DAG: @[[ALLOC]] = private unnamed_addr constant <{ ptr, ptr }> <{ ptr @[[INNER_A]], ptr @[[INNER_B]] }> + +// DISC-DAG: @[[HAS_FN_PTR:[^ ]*T_HAS_FN_PTR]] = constant ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 21613) +// NO_DISC-DAG: @[[HAS_FN_PTR:[^ ]*T_HAS_FN_PTR]] = constant ptr ptrauth (ptr @{{.*}}foo, i32 0) +// CHECK-DAG: @[[WRAPPER_1:[^ ]*T_WRAPPER_1]] = constant <{ [8 x i8], ptr }> <{ [8 x i8] {{.*}}, ptr @[[HAS_FN_PTR]] }> +// CHECK-DAG: @[[WRAPPER_2_ALLOC:alloc_[0-9a-f]+]] = private unnamed_addr constant <{ [4 x i8], [4 x i8], ptr }> <{ [4 x i8] {{.*}}, [4 x i8] {{.*}}, ptr @[[WRAPPER_1]] }> +// CHECK-DAG: @[[WRAPPER_2:[^ ]*T_WRAPPER_2]] = constant ptr @[[WRAPPER_2_ALLOC]] + +// DISC-DAG: @[[PADDED_INNER:[^ ]*T_PADDED_INNER]] = constant <{ [2 x i8], [6 x i8], ptr, [1 x i8], [7 x i8], ptr }> <{ [2 x i8] {{.*}}, [6 x i8] {{.*}}, ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 21613), [1 x i8] {{.*}}, [7 x i8] {{.*}}, ptr ptrauth (ptr @{{.*}}bar, i32 0, i64 2712) }> +// NO_DISC-DAG: @[[PADDED_INNER:[^ ]*T_PADDED_INNER]] = constant <{ [2 x i8], [6 x i8], ptr, [1 x i8], [7 x i8], ptr }> <{ [2 x i8] {{.*}}, [6 x i8] {{.*}}, ptr ptrauth (ptr @{{.*}}foo, i32 0), [1 x i8] {{.*}}, [7 x i8] {{.*}}, ptr ptrauth (ptr @{{.*}}bar, i32 0) }> +// CHECK-DAG: @[[PADDED_OUTER:[^ ]*T_PADDED_OUTER]] = constant ptr @[[PADDED_ALLOC:alloc_[0-9a-f]+]] +// CHECK-DAG: @[[PADDED_ALLOC]] = private unnamed_addr constant <{ [1 x i8], [7 x i8], ptr, [4 x i8], [4 x i8] }> <{ [1 x i8] {{.*}}, [7 x i8] {{.*}}, ptr @[[PADDED_INNER]], [4 x i8] {{.*}}, [4 x i8] {{.*}} }> + +#[repr(C)] +struct InnerA { + f: extern "C" fn(f32), +} + +#[repr(C)] +struct InnerB { + g: extern "C" fn(i32), +} + +#[repr(C)] +struct Outer { + a: &'static InnerA, + b: &'static InnerB, +} + +#[used] +static T_INNER_A: InnerA = InnerA { f: foo }; + +#[used] +static T_INNER_B: InnerB = InnerB { g: bar }; + +#[used] +static T_OUTER: &Outer = &Outer { a: &T_INNER_A, b: &T_INNER_B }; + +// CHECK-LABEL: test_1_two_inners +pub fn test_1_two_inners() { + // DISC: call void {{.*}}(float {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 21613) ] + // NO_DISC: call void {{.*}}(float {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + black_box((T_INNER_A.f))(0.12f32); + + // DISC: call void {{.*}}(i32 {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void {{.*}}(i32 {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + black_box((T_INNER_B.g))(22); + + // DISC: call void {{.*}}(float {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 21613) ] + // NO_DISC: call void {{.*}}(float {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + black_box((T_OUTER.a.f))(0.32f32); + + // DISC: call void {{.*}}(i32 {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void {{.*}}(i32 {{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + black_box((T_OUTER.b.g))(42); +} + +impl Sync for HasFnPtr {} +impl Sync for Wrapper1 {} +impl Sync for Wrapper2 {} + +#[repr(C)] +struct HasFnPtr { + f: extern "C" fn(_: f32), +} + +#[repr(C)] +struct Wrapper1 { + pad: u64, + p: &'static HasFnPtr, +} + +#[repr(C)] +struct Wrapper2 { + pad: u32, + w: &'static Wrapper1, +} + +#[used] +static T_HAS_FN_PTR: HasFnPtr = HasFnPtr { f: foo }; + +#[used] +static T_WRAPPER_1: Wrapper1 = Wrapper1 { pad: 42, p: &T_HAS_FN_PTR }; + +#[used] +static T_WRAPPER_2: &'static Wrapper2 = &Wrapper2 { pad: 7, w: &T_WRAPPER_1 }; + +pub fn test_2_nested_wrappers() { + // DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 21613) + // NO_DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 0) + black_box((T_HAS_FN_PTR.f))(0.22f32); + // DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 21613) + // NO_DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 0) + black_box((T_WRAPPER_1.p.f))(0.32f32); + // DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 21613) + // NO_DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 0) + black_box((T_WRAPPER_2.w.p.f))(0.42f32); +} + +impl Sync for PaddedInner {} +impl Sync for PaddedOuter {} + +#[repr(C)] +struct PaddedInner { + pad: u16, + f: extern "C" fn(f32), + pad_2: u8, + f_2: extern "C" fn(i32), +} + +#[repr(C)] +struct PaddedOuter { + pad_3: u8, + inner: &'static PaddedInner, + pad_4: u32, +} + +#[used] +static T_PADDED_INNER: PaddedInner = PaddedInner { pad: 0, f: foo, pad_2: 1, f_2: bar }; + +#[used] +static T_PADDED_OUTER: &PaddedOuter = &PaddedOuter { pad_3: 2, pad_4: 3, inner: &T_PADDED_INNER }; + +// CHECK-LABEL: test_3_padded_structs +pub fn test_3_padded_structs() { + // DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 21613) + // NO_DISC: call void {{.*}}(float {{.*}}){{.*}}"ptrauth"(i32 0, i64 0) + black_box((T_PADDED_OUTER.inner.f))(0.32f32); + // DISC: call void {{.*}}(i32 {{.*}}){{.*}}"ptrauth"(i32 0, i64 2712) + // NO_DISC: call void {{.*}}(i32 {{.*}}){{.*}}"ptrauth"(i32 0, i64 0) + black_box((T_PADDED_OUTER.inner.f_2))(42); +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-running-test.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-running-test.rs new file mode 100644 index 0000000000000..17488d61a5885 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-running-test.rs @@ -0,0 +1,291 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. + +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// This is a Rust reimplementation of Clang's main type-discrimination test: +// https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGen/ptrauth-function-type-discriminator.c +// Variable and function names match the original C test. + +#![feature(no_core, lang_items, ptrauth_c_discriminator)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::Option::{None, Some}; +use minicore::hint::black_box; +use minicore::mem::transmute; +use minicore::{Option, c_void, ptr}; + +extern "C" fn f() {} +extern "C" fn f2(_: i32) {} + +// 1 +// Rust function pointers are no-nullable, so this can not be expressed directly. +// ```c +// void (*test_constant_null)(int) = 0; +// ``` +// Use Option instead. +type TestConstantNullTy = unsafe extern "C" fn(i32); + +#[used] +// CHECK-DAG: @{{.*}}TEST_CONSTANT_NULL = constant {{.*}} zeroinitializer, +static TEST_CONSTANT_NULL: Option = None; +#[used] +// DISC-DAG: @{{.*}}TEST_CONSTANT_NON_NULL = constant ptr ptrauth (ptr @{{.*}}f2, i32 0, i64 2712), align 8 +// NO_DISC-DAG: @{{.*}}TEST_CONSTANT_NON_NULL = constant ptr ptrauth (ptr @{{.*}}f2, i32 0), align 8 +static TEST_CONSTANT_NON_NULL: Option = Some(f2); + +// 2 +// Clang expects to generate the discriminator based on the "casted to" type +// ```c +// void f(void); +// void (*test_constant_cast)(int) = (void (*)(int))f; +// ``` +// Rust does not allow incompatible function pointer casts. `transmute` seems to be the closes to +// the cast. Unlike Clang, Rust signs a function pointer with the discriminator of the function it +// points to (`f`: `void(void)`, 18983), not the type it is stored as, and transmute does not +// resign. Calling `f` through `fn(i32)` is UB in Rust and fails authentication. +#[used] +// DISC-DAG: @{{.*}}TEST_CONSTANT_CAST = constant ptr ptrauth (ptr @{{.*}}f, i32 0, i64 18983), align 8 +// NO_DISC-DAG: @{{.*}}TEST_CONSTANT_CAST = constant ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static TEST_CONSTANT_CAST: unsafe extern "C" fn(i32) = unsafe { transmute(f as extern "C" fn()) }; + +// 3 +// Clang can handle incomplete enum declaration, collapsing it to int: +// ```c +// enum Enum0; +// void enum_func(enum Enum0); +// void (*enum_func_ptr)(enum Enum0) = enum_func; +// ``` +// Mimic it with type Enum0 assigned to i32 and `__opaque`. +type Enum0 = i32; +#[repr(C)] +enum Enum1 { + __opaque, +} +extern "C" { + fn enum_func(arg: Enum0); +} +unsafe extern "C" fn enum_func_1(_x: Enum1) {} +#[used] +// DISC-DAG: @{{.*}}TEST_ENUM_FUNC_PTR = constant ptr ptrauth (ptr @{{.*}}enum_func, i32 0, i64 2712), align 8 +// NO_DISC-DAG: @{{.*}}TEST_ENUM_FUNC_PTR = constant ptr ptrauth (ptr @{{.*}}enum_func, i32 0), align 8 +static TEST_ENUM_FUNC_PTR: unsafe extern "C" fn(Enum0) = enum_func; +#[used] +// DISC-DAG: @{{.*}}TEST_ENUM_FUNC_PTR_1 = constant ptr ptrauth (ptr @{{.*}}enum_func_1, i32 0, i64 2712), align 8 +// NO_DISC-DAG: @{{.*}}TEST_ENUM_FUNC_PTR_1 = constant ptr ptrauth (ptr @{{.*}}enum_func_1, i32 0), align 8 +static TEST_ENUM_FUNC_PTR_1: unsafe extern "C" fn(Enum1) = enum_func_1; + +// 4 +// Rust can't fn -> *mut c_void casts. Use a chain of transmute. +// ```c +// void *test_opaque = +// #ifdef __cplusplus +// (void *) +// #endif +// (void (*)(int))(double (*)(double))f; +// ``` +// Clang signs a function address held in a `void *` with discriminator 0. Rust signs it with the +// discriminator of `f` (18983): reinterpreting a function pointer never resigns it. Exporting it to C +// as a `void *` requires an explicit resign, or, in a static, `#[rustc_ptrauth_c_discriminator(0)]` (below). +#[used] +// DISC-DAG: @{{.*}}TEST_OPAQUE = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0, i64 18983), align 8 +// NO_DISC-DAG: @{{.*}}TEST_OPAQUE = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static mut TEST_OPAQUE: *const c_void = unsafe { + let p: extern "C" fn(f64) -> f64 = transmute:: f64>(f); + transmute:: f64, *const c_void>(p) +}; +#[used] +// Also test a case that uses: as *const c_void. +// DISC-DAG: @{{.*}}TEST_OPAQUE_1 = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0, i64 18983), align 8 +// NO_DISC-DAG: @{{.*}}TEST_OPAQUE_1 = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static mut TEST_OPAQUE_1: *const c_void = f as *const () as *const c_void; + +// The same two statics, marked as holding the code address in C's encoding for a `void *`: signed +// with discriminator 0, as Clang does. +#[used] +#[rustc_ptrauth_c_discriminator(0)] +// DISC-DAG: @{{.*}}TEST_OPAQUE_C = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +// NO_DISC-DAG: @{{.*}}TEST_OPAQUE_C = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static mut TEST_OPAQUE_C: *const c_void = unsafe { + let p: extern "C" fn(f64) -> f64 = transmute:: f64>(f); + transmute:: f64, *const c_void>(p) +}; +#[used] +#[rustc_ptrauth_c_discriminator(0)] +// DISC-DAG: @{{.*}}TEST_OPAQUE_1_C = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +// NO_DISC-DAG: @{{.*}}TEST_OPAQUE_1_C = {{.*}} ptr ptrauth (ptr @{{.*}}f, i32 0), align 8 +static mut TEST_OPAQUE_1_C: *const c_void = f as *const () as *const c_void; + +// 5 +// ```c +// unsigned long test_intptr_t = (unsigned long)f; +// ``` +// This is explicitly forbidden in Rust. Hypothetically we could get it through: +// #[used] +// static TEST_INTPTR_T: usize = f as usize; +// #[used] +// static TEST_INTPTR_T_1: usize = unsafe { +// transmute::(f) +// }; +// But the compiler would not allow that issuing an error: +// error: pointers cannot be cast to integers during const eval +// And diagnostic: +// * for TEST_INTPTR_T: +// | static TEST_INTPTR_T: usize = f as usize; +// | ^^^^^^^^^^ +// | +// = note: at compile-time, pointers do not have an integer value +// = note: avoiding this restriction via `transmute`, `union`, or raw pointers leads to compile-time undefined behavior +// * for TEST_INTPTR_T_1: +// | static TEST_INTPTR_T_1: usize = unsafe { +// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `TEST_INTPTR_T_1` failed here +// | +// = help: this code performed an operation that depends on the underlying bytes representing a pointer +// = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported +// +// The same limitation applies to: +// 6 +// ```c +// void (*test_through_long)(int) = (void (*)(int))(long)f; +// ``` +// 7 +// ```c +// long test_to_long = (long)(double (*)())f; +// ``` + +extern "C" fn external_function() {} + +// 8 and 9 +// In Rust function automatically decays to function pointer. Furthermore, `&` used on function is +// not meant to produce a pointer to the function, instead it generates a reference to the function +// item. Use an intermediate `REF` variable to perform a round trip through reference. +// ```c +// void (*fptr1)(void) = external_function; +// void (*fptr2)(void) = &external_function; +// ``` +#[used] +// DISC-DAG: @{{.*}}FPTR1 = constant ptr ptrauth (ptr @{{.*}}external_function, i32 0, i64 18983), align 8 +// NO_DISC-DAG: @{{.*}}FPTR1 = constant ptr ptrauth (ptr @{{.*}}external_function, i32 0), align 8 +static FPTR1: extern "C" fn() = external_function; +// 9 +#[used] +static REF: &extern "C" fn() = &(external_function as extern "C" fn()); +#[used] +// DISC-DAG: @{{.*}}FPTR2 = constant ptr ptrauth (ptr @{{.*}}external_function, i32 0, i64 18983), align 8 +// NO_DISC-DAG: @{{.*}}FPTR2 = constant ptr ptrauth (ptr @{{.*}}external_function, i32 0), align 8 +static FPTR2: extern "C" fn() = *REF; + +// Rust doesn't support `__builtin_ptrauth_blend_discriminator` or `__builtin_ptrauth_sign_constant` +// builtins. +// 10 +// ```c +// void (*fptr3)(void) = __builtin_ptrauth_sign_constant(&external_function, 2, 26); +// ``` +// 11 +// ```c +// void (*fptr4)(void) = __builtin_ptrauth_sign_constant(&external_function, 2, __builtin_ptrauth_blend_discriminator(&fptr4, 26)); +// ``` + +// 12 +// Test calling through a global function pointer. +// ```c +// void (*fnptr)(void); +// void test_call() { +// fnptr(); +// } +// ``` +#[used] +// DISC-DAG: @{{.*}}FNPTR = {{.*}}ptr ptrauth (ptr @{{.*}}external_function, i32 0, i64 18983), align 8 +// NO_DISC-DAG: @{{.*}}FNPTR = {{.*}}ptr ptrauth (ptr @{{.*}}external_function, i32 0), align 8 +static mut FNPTR: extern "C" fn() = external_function; +// CHECK-LABEL {{.*}}test_call +pub unsafe fn test_call() { + // CHECK: [[FNPTR_PTR:%.*]] = load ptr, ptr @{{.*}}FNPTR, align 8 + // DISC: call void [[FNPTR_PTR]]() {{.*}} "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void [[FNPTR_PTR]]() {{.*}} "ptrauth"(i32 0, i64 0) ] + FNPTR(); +} + +// 13 +// ```c +// void (*test_function_pointer())(void) { +// return external_function; +// } +// ``` +// CHECK-LABEL: @{{.*}}test_function_pointer +pub extern "C" fn test_function_pointer() -> extern "C" fn() { + // DISC: ret ptr ptrauth (ptr @{{.*}}external_function, i32 0, i64 18983) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}external_function, i32 0) + external_function +} + +// 14 +// C tests that the discriminator is stable when a struct type transitions from incomplete to +// complete. Rust has no notion of type completion, so this case has no direct equivalent. +// ```c +// struct InitiallyIncomplete; +// extern struct InitiallyIncomplete returns_initially_incomplete(void); +// +// void use_while_incomplete() { +// struct InitiallyIncomplete (*fnptr)(void) = &returns_initially_incomplete; +// } +// +// struct InitiallyIncomplete { int x; }; +// void use_while_complete() { +// struct InitiallyIncomplete (*fnptr)(void) = &returns_initially_incomplete; +// } +// ``` + +// 15 +// K&R function definition can be expressed in Rust and in any case a function definition without a +// prototype is deprecated in all versions of C and is not supported in C23 +// ```c +// void knr(param) +// int param; +// {} +// +// void test_knr() { +// void (*p)() = knr; +// p(0); +// } +// ``` + +// 16 +// Rust does not allow for redeclaration of functions +// ```c +// void test_redeclaration() { +// void redecl(); +// void (*ptr)() = redecl; +// void redecl(int); +// void (*ptr2)(int) = redecl; +// ptr(); +// ptr2(0); +// } +// ``` + +// 17 +// This is redeclaration of functions using Kernighan and Ritchie notation, not supported. +// ```c +// void knr2(param) +// int param; +// {} +// +// void test_redecl_knr() { +// void (*p)() = knr2; +// p(); +// +// void knr2(int); +// +// void (*p2)(int) = knr2; +// p2(0); +// +// } +// ``` diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-rust-array.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-rust-array.rs new file mode 100644 index 0000000000000..1b7b0af989c0e --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-rust-array.rs @@ -0,0 +1,65 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. + +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Make sure that signing/auth happens for every element of an array. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::mem; + +type Fn = extern "C" fn(i32) -> i32; + +#[repr(C)] +pub struct S { + pub f: Fn, + pub x: i32, +} + +extern "C" fn foo(x: i32) -> i32 { + x + 1 +} + +#[used] +// DISC: @{{.*}}TEST_ARR = {{.*}} ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 2981), {{.*}} ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 2981), {{.*}} ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 2981) +// NO_DISC: @{{.*}}TEST_ARR = {{.*}} ptr ptrauth (ptr @{{.*}}foo, i32 0), {{.*}} ptr ptrauth (ptr @{{.*}}foo, i32 0), {{.*}} ptr ptrauth (ptr @{{.*}}foo, i32 0) +static TEST_ARR: [S; 3] = [S { f: foo, x: 1 }, S { f: foo, x: 2 }, S { f: foo, x: 3 }]; + +#[inline(never)] +// CHECK-LABEL: use_array +pub fn use_array(arr: &[S; 3]) -> i32 { + let [a, b, c] = arr; + // DISC: call i32 {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // DISC: call i32 {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // DISC: call i32 {{.*}} [ "ptrauth"(i32 0, i64 2981) ] + // NO_DISC: call i32 {{.*}} [ "ptrauth"(i32 0, i64 0) ] + // NO_DISC: call i32 {{.*}} [ "ptrauth"(i32 0, i64 0) ] + // NO_DISC: call i32 {{.*}} [ "ptrauth"(i32 0, i64 0) ] + (a.f)(a.x) + (b.f)(b.x) + (c.f)(c.x) +} + +#[no_mangle] +// CHECK-LABEL: test +pub fn test() -> i32 { + // DISC: store ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 2981) + // NO_DISC: store ptr ptrauth (ptr @{{.*}}foo, i32 0) + // CHECK: store i32 1 + // DISC: store ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 2981) + // NO_DISC: store ptr ptrauth (ptr @{{.*}}foo, i32 0) + // CHECK: store i32 2 + // DISC: store ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 2981) + // NO_DISC: store ptr ptrauth (ptr @{{.*}}foo, i32 0) + // CHECK: store i32 3 + let TEST_LOCAL_ARR: [S; 3] = [S { f: foo, x: 1 }, S { f: foo, x: 2 }, S { f: foo, x: 3 }]; + use_array(&TEST_ARR) + use_array(&TEST_LOCAL_ARR) +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-simd.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-simd.rs new file mode 100644 index 0000000000000..569ea3d6bfecc --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-simd.rs @@ -0,0 +1,140 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. + +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// For encoding purposes, Clang is only interested in the total size of the vector, so all the +// combinations below should generate the same encoding: FDv16Dv16E, discriminator: 34246 (0x85C6). + +#![feature(no_core, lang_items, repr_simd, simd_ffi)] +#![no_std] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; + +#[repr(simd)] +struct I8x16([i8; 16]); +#[repr(simd)] +struct I16x8([i16; 8]); +#[repr(simd)] +struct I32x4([i32; 4]); +#[repr(simd)] +struct I64x2([i64; 2]); +#[repr(simd)] +struct U8x16([u8; 16]); +#[repr(simd)] +struct U16x8([u16; 8]); +#[repr(simd)] +struct U32x4([u32; 4]); +#[repr(simd)] +struct U64x2([u64; 2]); +#[repr(simd)] +struct F32x4([f32; 4]); +#[repr(simd)] +struct F64x2([f64; 2]); + +extern "C" { + fn f_i8x16(x: I8x16) -> I8x16; + fn f_i16x8(x: I16x8) -> I16x8; + fn f_i32x4(x: I32x4) -> I32x4; + fn f_i64x2(x: I64x2) -> I64x2; + fn f_u8x16(x: U8x16) -> U8x16; + fn f_u16x8(x: U16x8) -> U16x8; + fn f_u32x4(x: U32x4) -> U32x4; + fn f_u64x2(x: U64x2) -> U64x2; + fn f_f32x4(x: F32x4) -> F32x4; + fn f_f64x2(x: F64x2) -> F64x2; +} + +type FnI8x16 = unsafe extern "C" fn(I8x16) -> I8x16; +type FnI16x8 = unsafe extern "C" fn(I16x8) -> I16x8; +type FnI32x4 = unsafe extern "C" fn(I32x4) -> I32x4; +type FnI64x2 = unsafe extern "C" fn(I64x2) -> I64x2; +type FnU8x16 = unsafe extern "C" fn(U8x16) -> U8x16; +type FnU16x8 = unsafe extern "C" fn(U16x8) -> U16x8; +type FnU32x4 = unsafe extern "C" fn(U32x4) -> U32x4; +type FnU64x2 = unsafe extern "C" fn(U64x2) -> U64x2; +type FnF32x4 = unsafe extern "C" fn(F32x4) -> F32x4; +type FnF64x2 = unsafe extern "C" fn(F64x2) -> F64x2; + +#[used] +// DISC: {{.*}}T_I8x16 = constant ptr ptrauth (ptr @f_i8x16, i32 0, i64 34246) +// NO_DISC: {{.*}}T_I8x16 = constant ptr ptrauth (ptr @f_i8x16, i32 0) +static T_I8x16: FnI8x16 = f_i8x16; +#[used] +// DISC: {{.*}}T_I16x8 = constant ptr ptrauth (ptr @f_i16x8, i32 0, i64 34246) +// NO_DISC: {{.*}}T_I16x8 = constant ptr ptrauth (ptr @f_i16x8, i32 0) +static T_I16x8: FnI16x8 = f_i16x8; +#[used] +// DISC: {{.*}}T_I32x4 = constant ptr ptrauth (ptr @f_i32x4, i32 0, i64 34246) +// NO_DISC: {{.*}}T_I32x4 = constant ptr ptrauth (ptr @f_i32x4, i32 0) +static T_I32x4: FnI32x4 = f_i32x4; +#[used] +// DISC: {{.*}}T_I64x2 = constant ptr ptrauth (ptr @f_i64x2, i32 0, i64 34246) +// NO_DISC: {{.*}}T_I64x2 = constant ptr ptrauth (ptr @f_i64x2, i32 0) +static T_I64x2: FnI64x2 = f_i64x2; +#[used] +// DISC: {{.*}}T_U8x16 = constant ptr ptrauth (ptr @f_u8x16, i32 0, i64 34246) +// NO_DISC: {{.*}}T_U8x16 = constant ptr ptrauth (ptr @f_u8x16, i32 0) +static T_U8x16: FnU8x16 = f_u8x16; +#[used] +// DISC: {{.*}}T_U16x8 = constant ptr ptrauth (ptr @f_u16x8, i32 0, i64 34246) +// NO_DISC: {{.*}}T_U16x8 = constant ptr ptrauth (ptr @f_u16x8, i32 0) +static T_U16x8: FnU16x8 = f_u16x8; +#[used] +// DISC: {{.*}}T_U32x4 = constant ptr ptrauth (ptr @f_u32x4, i32 0, i64 34246) +// NO_DISC: {{.*}}T_U32x4 = constant ptr ptrauth (ptr @f_u32x4, i32 0) +static T_U32x4: FnU32x4 = f_u32x4; +#[used] +// DISC: {{.*}}T_U64x2 = constant ptr ptrauth (ptr @f_u64x2, i32 0, i64 34246) +// NO_DISC: {{.*}}T_U64x2 = constant ptr ptrauth (ptr @f_u64x2, i32 0) +static T_U64x2: FnU64x2 = f_u64x2; +#[used] +// DISC: {{.*}}T_F32x4 = constant ptr ptrauth (ptr @f_f32x4, i32 0, i64 34246) +// NO_DISC: {{.*}}T_F32x4 = constant ptr ptrauth (ptr @f_f32x4, i32 0) +static T_F32x4: FnF32x4 = f_f32x4; +#[used] +// DISC: {{.*}}T_F64x2 = constant ptr ptrauth (ptr @f_f64x2, i32 0, i64 34246) +// NO_DISC: {{.*}}T_F64x2 = constant ptr ptrauth (ptr @f_f64x2, i32 0) +static T_F64x2: FnF64x2 = f_f64x2; + +pub fn main() { + unsafe { + // DISC: call <16 x i8> ptrauth (ptr @f_i8x16, i32 0, i64 34246)(<16 x i8> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <16 x i8> ptrauth (ptr @f_i8x16, i32 0)(<16 x i8> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_I8x16(I8x16([0; 16])); + // DISC: call <8 x i16> ptrauth (ptr @f_i16x8, i32 0, i64 34246)(<8 x i16> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <8 x i16> ptrauth (ptr @f_i16x8, i32 0)(<8 x i16> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_I16x8(I16x8([0; 8])); + // DISC: call <4 x i32> ptrauth (ptr @f_i32x4, i32 0, i64 34246)(<4 x i32> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <4 x i32> ptrauth (ptr @f_i32x4, i32 0)(<4 x i32> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_I32x4(I32x4([0; 4])); + // DISC: call <2 x i64> ptrauth (ptr @f_i64x2, i32 0, i64 34246)(<2 x i64> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <2 x i64> ptrauth (ptr @f_i64x2, i32 0)(<2 x i64> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_I64x2(I64x2([0; 2])); + // DISC: call <16 x i8> ptrauth (ptr @f_u8x16, i32 0, i64 34246)(<16 x i8> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <16 x i8> ptrauth (ptr @f_u8x16, i32 0)(<16 x i8> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_U8x16(U8x16([0; 16])); + // DISC: call <8 x i16> ptrauth (ptr @f_u16x8, i32 0, i64 34246)(<8 x i16> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <8 x i16> ptrauth (ptr @f_u16x8, i32 0)(<8 x i16> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_U16x8(U16x8([0; 8])); + // DISC: call <4 x i32> ptrauth (ptr @f_u32x4, i32 0, i64 34246)(<4 x i32> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <4 x i32> ptrauth (ptr @f_u32x4, i32 0)(<4 x i32> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_U32x4(U32x4([0; 4])); + // DISC: call <2 x i64> ptrauth (ptr @f_u64x2, i32 0, i64 34246)(<2 x i64> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <2 x i64> ptrauth (ptr @f_u64x2, i32 0)(<2 x i64> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_U64x2(U64x2([0; 2])); + // DISC: call <4 x float> ptrauth (ptr @f_f32x4, i32 0, i64 34246)(<4 x float> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <4 x float> ptrauth (ptr @f_f32x4, i32 0)(<4 x float> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_F32x4(F32x4([0.0; 4])); + // DISC: call <2 x double> ptrauth (ptr @f_f64x2, i32 0, i64 34246)(<2 x double> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 34246) ] + // NO_DISC: call <2 x double> ptrauth (ptr @f_f64x2, i32 0)(<2 x double> %{{.*}}) #{{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_F64x2(F64x2([0.0; 2])); + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-static-allocs.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-static-allocs.rs new file mode 100644 index 0000000000000..c357cef62a2b4 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-static-allocs.rs @@ -0,0 +1,128 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Test pointer authentication generation in compile-time constants. Covers standalone function +// pointer constants, promoted temporaries, immutable and mutable statics, arrays of function +// pointers, and mixed structs containing function pointers with different signatures and +// discriminators. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; +use minicore::Sync; + +// DISC-DAG: @[[SCALAR_ALLOC:alloc_[0-9a-f]+]] = private unnamed_addr constant ptr ptrauth (ptr {{.*}}foo{{.*}}, i32 0, i64 18983) +// NO_DISC-DAG: @[[SCALAR_ALLOC:alloc_[0-9a-f]+]] = private unnamed_addr constant ptr ptrauth (ptr {{.*}}foo{{.*}}, i32 0) + +// DISC-DAG: @[[MIXED_ALLOC:alloc_[0-9a-f]+]] = private unnamed_addr constant <{ ptr, ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 18983), ptr ptrauth (ptr @{{.*}}foo_i32, i32 0, i64 2712), ptr ptrauth (ptr @{{.*}}foo_i64, i32 0, i64 2712), ptr ptrauth (ptr @{{.*}}foo_ret, i32 0, i64 42271) }> +// NO_DISC-DAG: @[[MIXED_ALLOC:alloc_[0-9a-f]+]] = private unnamed_addr constant <{ ptr, ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0), ptr ptrauth (ptr @{{.*}}foo_i32, i32 0), ptr ptrauth (ptr @{{.*}}foo_i64, i32 0), ptr ptrauth (ptr @{{.*}}foo_ret, i32 0) }> + +// DISC-DAG: @[[STATIC_MIXED:.*STATIC_MIXED]] = constant <{ ptr, ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 18983), ptr ptrauth (ptr @{{.*}}foo_i32, i32 0, i64 2712), ptr ptrauth (ptr @{{.*}}foo_i64, i32 0, i64 2712), ptr ptrauth (ptr @{{.*}}foo_ret, i32 0, i64 42271) }> +// NO_DISC-DAG: @[[STATIC_MIXED:.*STATIC_MIXED]] = constant <{ ptr, ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0), ptr ptrauth (ptr @{{.*}}foo_i32, i32 0), ptr ptrauth (ptr @{{.*}}foo_i64, i32 0), ptr ptrauth (ptr @{{.*}}foo_ret, i32 0) }> + +// DISC-DAG: @[[STATIC_TABLE:.*STATIC_TABLE]] = constant <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 18983), ptr ptrauth (ptr @{{.*}}bar, i32 0, i64 18983) }> +// NO_DISC-DAG: @[[STATIC_TABLE:.*STATIC_TABLE]] = constant <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0), ptr ptrauth (ptr @{{.*}}bar, i32 0) }> + +// DISC-DAG: @[[MUT_TABLE:.*MUT_TABLE]] = global <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0, i64 18983), ptr ptrauth (ptr @{{.*}}bar, i32 0, i64 18983) }> +// NO_DISC-DAG: @[[MUT_TABLE:.*MUT_TABLE]] = global <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}foo, i32 0), ptr ptrauth (ptr @{{.*}}bar, i32 0) }> + +extern "C" fn foo() {} +extern "C" fn foo_i32(_: i32) {} +extern "C" fn foo_i64(_: i64) {} +extern "C" fn foo_ret() -> i32 { + 0 +} +extern "C" fn bar() {} + +const F: extern "C" fn() = foo; + +// CHECK-LABEL: test_scalar +pub fn test_scalar() { + // DISC: call void ptrauth (ptr @{{.*}}foo{{.*}}, i32 0, i64 18983)() + // NO_DISC: call void ptrauth (ptr @{{.*}}foo{{.*}}, i32 0)() + let p: &'static extern "C" fn() = &F; + p(); +} + +#[repr(C)] +struct Mixed { + a: extern "C" fn(), + b: extern "C" fn(i32), + c: extern "C" fn(i64), + d: extern "C" fn() -> i32, +} + +impl Sync for Mixed {} + +// CHECK-LABEL: test_promoted_mixed +pub fn test_promoted_mixed() { + // CHECK: %{{.*}} = load ptr, ptr @[[MIXED_ALLOC]] + // DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 0) ] + // CHECK: %{{.*}} = load ptr, ptr getelementptr inbounds (i8, ptr @[[MIXED_ALLOC]], i64 8), + // DISC: call void %{{.*}}(i32 1) #[[#]] [ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void %{{.*}}(i32 1) #[[#]] [ "ptrauth"(i32 0, i64 0) ] + // CHECK: %{{.*}} = load ptr, ptr getelementptr inbounds (i8, ptr @[[MIXED_ALLOC]], i64 16), + // DISC: call void %{{.*}}(i64 1) #[[#]] [ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void %{{.*}}(i64 1) #[[#]] [ "ptrauth"(i32 0, i64 0) ] + // CHECK: %{{.*}} = load ptr, ptr getelementptr inbounds (i8, ptr @[[MIXED_ALLOC]], i64 24), + // DISC: call i32 %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 42271) ] + // NO_DISC: call i32 %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 0) ] + let x: &'static Mixed = &Mixed { a: foo, b: foo_i32, c: foo_i64, d: foo_ret }; + + (x.a)(); + (x.b)(1); + (x.c)(1); + let _ = (x.d)(); +} + +#[used] +static STATIC_MIXED: Mixed = Mixed { a: foo, b: foo_i32, c: foo_i64, d: foo_ret }; + +// CHECK-LABEL: test_static_mixed +pub fn test_static_mixed() { + // CHECK: %{{.*}} = load ptr, ptr @[[STATIC_MIXED]] + // DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 0) ] + // CHECK: %{{.*}} = load ptr, ptr getelementptr inbounds (i8, ptr @[[STATIC_MIXED]], i64 8), + // DISC: call void %{{.*}}(i32 1) #[[#]] [ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void %{{.*}}(i32 1) #[[#]] [ "ptrauth"(i32 0, i64 0) ] + (STATIC_MIXED.a)(); + (STATIC_MIXED.b)(1); +} + +#[used] +static STATIC_TABLE: [extern "C" fn(); 2] = [foo, bar]; + +// CHECK-LABEL: test_static_array +pub fn test_static_array() { + let p = &raw const STATIC_TABLE as *const extern "C" fn(); + + // CHECK: call ptr {{.*}}read_volatile{{.*}}(ptr @[[STATIC_TABLE]]) + // DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 0) ] + unsafe { + (minicore::ptr::read_volatile(p))(); + } +} + +#[used] +static mut MUT_TABLE: [extern "C" fn(); 2] = [foo, bar]; + +// CHECK-LABEL: test_mut_static +pub unsafe fn test_mut_static() { + let p = &raw const MUT_TABLE as *const extern "C" fn(); + + // CHECK: call ptr {{.*}}read_volatile{{.*}}(ptr @[[MUT_TABLE]]) + // DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 18983) ] + // NO_DISC: call void %{{.*}}() #[[#]] [ "ptrauth"(i32 0, i64 0) ] + (minicore::ptr::read_volatile(p))(); +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-members.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-members.rs new file mode 100644 index 0000000000000..35aa7b985edf5 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-members.rs @@ -0,0 +1,200 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. + +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Check the signing of internal members of structs that are themselves function pointers. +// Transmuting never resigns: the bits are copied unchanged, so a call through the new type +// authenticates with the new type's discriminator (and traps at runtime if the signatures are not +// ABI-compatible, which is UB in Rust). + +#![feature(no_core, lang_items)] +#![crate_type = "lib"] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::{Sync, mem, ptr}; + +// Function definitions, used as members in structs. +extern "C" fn f() {} +extern "C" fn g(i32: i32) {} +extern "C" fn h(i64: i64, j: i64) {} +extern "C" fn i(i64: i64, b: i64, c: f32) {} + +// Structs... +#[repr(transparent)] +struct A(extern "C" fn()); + +#[repr(transparent)] +struct B(extern "C" fn(i32)); + +#[repr(transparent)] +struct C(extern "C" fn(i64, i64)); + +#[repr(transparent)] +struct NotFn(u64); + +#[repr(transparent)] +struct AlsoNotFn(u64); + +// and their wrappers (L - level). +#[repr(transparent)] +struct L1A(A); + +#[repr(transparent)] +struct L1B(B); + +#[repr(transparent)] +struct L2A(L1A); + +#[repr(transparent)] +struct L2B(L1B); + +#[repr(transparent)] +struct L3A(L2A); + +#[repr(transparent)] +struct L3B(L2B); + +#[repr(transparent)] +struct L4A(L3A); + +#[repr(transparent)] +struct L4B(L3B); + +#[repr(transparent)] +struct L5A(L4A); + +#[repr(transparent)] +struct L5B(L4B); + +#[repr(C)] +struct MixedPair { + f0: extern "C" fn(), + f1: extern "C" fn(i32), +} + +#[repr(transparent)] +struct L1NotFn(NotFn); + +#[repr(transparent)] +struct L1AlsoNotFn(AlsoNotFn); + +// Make sure that static initialization traverses struct members and uses correct discriminators. +// DISC-DAG: @{{.*}}T_TREE_SRC = constant <{ ptr, ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}f, i32 0, i64 18983), ptr ptrauth (ptr @{{.*}}g, i32 0, i64 2712), ptr ptrauth (ptr @{{.*}}h, i32 0, i64 55265), ptr ptrauth (ptr @{{.*}}i, i32 0, i64 44485) }> +// NO_DISC-DAG: @{{.*}}T_TREE_SRC = constant <{ ptr, ptr, ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}f, i32 0), ptr ptrauth (ptr @{{.*}}g, i32 0), ptr ptrauth (ptr @{{.*}}h, i32 0), ptr ptrauth (ptr @{{.*}}i, i32 0) }> +// DISC-DAG: @{{.*}}T_WRAPPED_FN_PTR = internal constant ptr ptrauth (ptr @{{.*}}g, i32 0, i64 2712) +// NO_DISC-DAG: @{{.*}}T_WRAPPED_FN_PTR = internal constant ptr ptrauth (ptr @{{.*}}g, i32 0) + +// DISC-DAG: @{{.*}}T_TUPLE = constant <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}f, i32 0, i64 18983), ptr ptrauth (ptr @{{.*}}g, i32 0, i64 2712) }> +// NO_DISC-DAG: @{{.*}}T_TUPLE = constant <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}f, i32 0), ptr ptrauth (ptr @{{.*}}g, i32 0) }> + +// DISC-DAG: @{{.*}}T_TUPLE_2 = constant <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}m, i32 0, i64 21613), ptr ptrauth (ptr @{{.*}}n, i32 0, i64 7718) }> +// NO_DISC-DAG: @{{.*}}T_TUPLE_2 = constant <{ ptr, ptr }> <{ ptr ptrauth (ptr @{{.*}}m, i32 0), ptr ptrauth (ptr @{{.*}}n, i32 0) }> + +// Negative control. +#[inline(never)] +// CHECK-DAG: test_4_non_fnptr_cast +pub fn test_4_non_fnptr_cast() { + // CHECK-NOT: llvm.ptrauth.resign + // CHECK-NOT: ptrauth + let x = L1NotFn(NotFn(123)); + let y: L1AlsoNotFn = unsafe { mem::transmute(x) }; + + unsafe { + ptr::read_volatile(&y); + } +} + +// Aggregate reinterpretation (the whole Struct, not just a Member) with mixed members. +#[inline(never)] +// CHECK-DAG: test_6_mixed_layout_cast +pub fn test_6_mixed_layout_cast() { + let x = (A(f), NotFn(999)); + // DISC: store ptr ptrauth (ptr @{{.*}}f, i32 0, i64 18983), ptr + // NO_DISC: [[Y:%.*]] = alloca [16 x i8] + // NO_DISC: store ptr ptrauth (ptr @{{.*}}f, i32 0), ptr [[Y]] + let y: (B, AlsoNotFn) = unsafe { mem::transmute(x) }; + + unsafe { + ptr::read_volatile(&y); + // DISC-NOT: call i64 @llvm.ptrauth.resign + // DISC: call void %{{.*}}(i32 42) {{.*}} [ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: [[Y_LOAD:%.*]] = load ptr, ptr [[Y]] + // NO_DISC: call void [[Y_LOAD]](i32 42) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + (y.0.0)(42); + } +} + +#[repr(transparent)] +struct Wrapper(extern "C" fn(i32)); + +impl Sync for Wrapper {} + +static T_WRAPPED_FN_PTR: Wrapper = Wrapper(g); + +#[repr(C)] +struct RootSrc { + f0: extern "C" fn(), + f1: extern "C" fn(i32), + f2: extern "C" fn(i64, i64), + f3: extern "C" fn(i64, i64, f32), +} + +impl Sync for RootSrc {} + +#[used] +static T_TREE_SRC: RootSrc = RootSrc { f0: f, f1: g, f2: h, f3: i }; + +type T0 = extern "C" fn(); +type T1 = extern "C" fn(i32); + +type T2 = extern "C" fn(f32); +type T3 = extern "C" fn(f64); + +#[repr(C)] +struct TupleSrc { + pair: (T0, T1), +} + +#[repr(C)] +struct TupleDst { + pair: (T2, T3), +} + +impl Sync for TupleSrc {} +impl Sync for TupleDst {} + +extern "C" fn m(f32: f32) {} +extern "C" fn n(f64: f64) {} +#[used] +static T_TUPLE: TupleSrc = TupleSrc { pair: (f, g) }; +#[used] +static T_TUPLE_2: TupleDst = TupleDst { pair: (m, n) }; + +#[inline(never)] +// Tuple test +// CHECK-DAG: test_9_tuple +pub fn test_9_tuple() { + let src = TupleSrc { pair: (f, g) }; + let _ = unsafe { ptr::read_volatile(&src) }; + // DISC: store ptr ptrauth (ptr @{{.*}}f, i32 0, i64 18983) + // DISC: store ptr ptrauth (ptr @{{.*}}g, i32 0, i64 2712) + // NO_DISC: store ptr ptrauth (ptr @{{.*}}f, i32 0) + // NO_DISC: store ptr ptrauth (ptr @{{.*}}g, i32 0) + // CHECK-NOT: call i64 @llvm.ptrauth.resign + let dst: TupleDst = unsafe { mem::transmute(src) }; + + // DISC: call void %{{.*}}(float {{.*}}) #[[#]] [ "ptrauth"(i32 0, i64 21613) ] + // DISC: call void %{{.*}}(double {{.*}}) #[[#]] [ "ptrauth"(i32 0, i64 7718) ] + // NO_DISC: call void %{{.*}}(float {{.*}}) #[[#]] [ "ptrauth"(i32 0, i64 0) ] + // NO_DISC: call void %{{.*}}(double {{.*}}) #[[#]] [ "ptrauth"(i32 0, i64 0) ] + (dst.pair.0)(0.42f32); + (dst.pair.1)(0.4242f64); +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-name.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-name.rs new file mode 100644 index 0000000000000..25dc48e932d23 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-struct-name.rs @@ -0,0 +1,97 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. + +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Make sure that rust only uses the final part of struct's name (`Foo` or `Bar`), so that the +// discriminators are `F3FooE` and `F3BarE`, not using def path for the base of encoding. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; +use minicore::hint::black_box; + +#[repr(C)] +pub struct Foo { + x: i32, +} + +#[repr(C)] +pub struct Bar { + x: i32, +} + +extern "C" fn takes_foo(_: Foo) {} +extern "C" fn takes_bar(_: Bar) {} + +#[used] +// DISC-DAG: @{{.*}}FOO_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes_foo, i32 0, i64 58649) +// Without type discriminators all the functions are the same, so compiler is able to use both +// takes_foo/take_bar. +// NO_DISC-DAG: @{{.*}}FOO_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes_{{foo|bar}}, i32 0) +static FOO_FNPTR: extern "C" fn(Foo) = takes_foo; + +#[used] +// DISC-DAG: @{{.*}}BAR_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes_bar, i32 0, i64 41614) +// NO_DISC-DAG: @{{.*}}BAR_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes_{{foo|bar}}, i32 0) +static BAR_FNPTR: extern "C" fn(Bar) = takes_bar; + +// While not possible to express in C, we could force it through C++ path with something along the +// lines of: +// ```c++ +// namespace a { +// struct SameName { +// int x; +// }; +// +// void takes(SameName) {} +// } +// +// namespace b { +// struct SameName { +// int x; +// }; +// +// void takes(SameName) {} +// } +// +// void (*a_fnptr)(a::SameName) = a::takes; +// void (*b_fnptr)(b::SameName) = b::takes; +// ``` +// Make sure that Rust uses `Fv8SameNameE` for both `A_FNPTR` and `B_FNPTR`, not +// `Fv11a::SameNameE`, or `Fv11b::SameNameE`. + +mod a { + #[repr(C)] + pub struct SameName { + pub x: i32, + } + + pub extern "C" fn takes(_: SameName) {} +} + +mod b { + #[repr(C)] + pub struct SameName { + pub x: i32, + } + + pub extern "C" fn takes(_: SameName) {} +} + +#[used] +// DISC-DAG: @{{.*}}A_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes, i32 0, i64 57535) +// NO_DISC-DAG: @{{.*}}A_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes{{.*}}, i32 0) +static A_FNPTR: extern "C" fn(a::SameName) = a::takes; + +#[used] +// DISC-DAG: @{{.*}}B_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes, i32 0, i64 57535) +// NO_DISC-DAG: @{{.*}}B_FNPTR = constant ptr ptrauth (ptr @{{.*}}takes{{.*}}, i32 0) +static B_FNPTR: extern "C" fn(b::SameName) = b::takes; diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-transparent-wrapper.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-transparent-wrapper.rs new file mode 100644 index 0000000000000..0238f314ac2d9 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-transparent-wrapper.rs @@ -0,0 +1,107 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 +// +// Regression test for `#[repr(transparent)]`. +// +// `#[repr(transparent)]` is Rust's explicit ABI guarantee that a wrapper struct has the exact size, +// alignment, and calling convention of its one (non-1-ZST) field. +// +// Discriminators: +// 12410: "FiPE" +// 62802: "Fi14NotTransparentE" + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] +#![crate_type = "lib"] +extern crate minicore; +use minicore::Option; +use minicore::Option::Some; + +#[repr(transparent)] +pub struct Handle(*mut i32); + +// A same-shaped wrapper WITHOUT `#[repr(transparent)]` this must NOT collapse to the pointer bucket +pub struct NotTransparent(*mut i32); + +pub struct Marker; + +// A 1-ZST filler field placed before the significant field, to actually exercise `non_1zst_field`'s +// real search rather than something that would coincidentally also pass for a plain single-field +// wrapper. +#[repr(transparent)] +pub struct HandleWithMarker(Marker, *mut i32); + +// Composition with Option<&T>. +#[repr(transparent)] +pub struct OptRefWrapper<'a>(Option<&'a i32>); + +extern "C" { + fn f_ptr(x: *mut i32) -> i32; + fn f_handle(x: Handle) -> i32; + fn f_not_transparent(x: NotTransparent) -> i32; + fn f_handle_with_marker(x: HandleWithMarker) -> i32; + fn f_opt_ref_wrapped(x: OptRefWrapper) -> i32; +} + +type FnPtr = unsafe extern "C" fn(*mut i32) -> i32; +type FnHandle = unsafe extern "C" fn(Handle) -> i32; +type FnNotTransparent = unsafe extern "C" fn(NotTransparent) -> i32; +type FnHandleWithMarker = unsafe extern "C" fn(HandleWithMarker) -> i32; +type FnOptRefWrapped = unsafe extern "C" fn(OptRefWrapper) -> i32; + +#[used] +// Baseline: bare pointer argument. +// DISC: @{{.*}}T_PTR = constant ptr ptrauth (ptr @{{.*}}f_ptr, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_PTR = constant ptr ptrauth (ptr @{{.*}}f_ptr, i32 0), align 8 +static T_PTR: FnPtr = f_ptr; + +#[used] +// DISC: @{{.*}}T_HANDLE = constant ptr ptrauth (ptr @{{.*}}f_handle, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_HANDLE = constant ptr ptrauth (ptr @{{.*}}f_handle, i32 0), align 8 +static T_HANDLE: FnHandle = f_handle; + +#[used] +// DISC-NOT: @{{.*}}T_NOT_TRANSPARENT = constant ptr ptrauth (ptr @{{.*}}f_not_transparent, i32 0, i64 12410), align 8 +// DISC: @{{.*}}T_NOT_TRANSPARENT = constant ptr ptrauth (ptr @{{.*}}f_not_transparent, i32 0, i64 62802), align 8 +// NO_DISC: @{{.*}}T_NOT_TRANSPARENT = constant ptr ptrauth (ptr @{{.*}}f_not_transparent, i32 0), align 8 +static T_NOT_TRANSPARENT: FnNotTransparent = f_not_transparent; + +#[used] +// DISC: @{{.*}}T_HANDLE_WITH_MARKER = constant ptr ptrauth (ptr @{{.*}}f_handle_with_marker, i32 0, i64 12410), align 8 +// NO_DISC: @{{.*}}T_HANDLE_WITH_MARKER = constant ptr ptrauth (ptr @{{.*}}f_handle_with_marker, i32 0), align 8 +static T_HANDLE_WITH_MARKER: FnHandleWithMarker = f_handle_with_marker; + +const T_OPT_REF_WRAPPED: FnOptRefWrapped = f_opt_ref_wrapped; + +// CHECK-LABEL: main +pub fn main() { + let mut x = 42i32; + unsafe { + // DISC: call i32 ptrauth (ptr @f_ptr, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_ptr, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_PTR(&mut x as *mut i32); + + // DISC: call i32 ptrauth (ptr @f_handle, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_handle, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_HANDLE(Handle(&mut x as *mut i32)); + + // DISC: call i32 ptrauth (ptr @f_not_transparent, i32 0, i64 62802)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 62802) ] + // NO_DISC: call i32 ptrauth (ptr @f_not_transparent, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_NOT_TRANSPARENT(NotTransparent(&mut x as *mut i32)); + + // DISC: call i32 ptrauth (ptr @f_handle_with_marker, i32 0, i64 12410)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_handle_with_marker, i32 0)(ptr %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_HANDLE_WITH_MARKER(HandleWithMarker(Marker, &mut x as *mut i32)); + + // DISC: call i32 ptrauth (ptr @f_opt_ref_wrapped, i32 0, i64 12410)(ptr align 4 %x) {{.*}} [ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 ptrauth (ptr @f_opt_ref_wrapped, i32 0)(ptr align 4 %x) {{.*}} [ "ptrauth"(i32 0, i64 0) ] + let _ = T_OPT_REF_WRAPPED(OptRefWrapper(Some(&x))); + } +} diff --git a/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-vtable.rs b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-vtable.rs new file mode 100644 index 0000000000000..2997c8e633922 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-fn-ptr-type-discrimination-vtable.rs @@ -0,0 +1,65 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC + +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// A trait method may be `extern "C"`. The vtable entry of an `extern "C"` method is signed with the +// discriminator of the impl method, and a virtual call authenticates with the discriminator of the +// trait method. The two signatures only differ in the type of `self`, which is a pointer in both, +// so the discriminators are equal. +// Rust ABI methods stay unsigned. +// +// Discriminators: `extern "C" fn(&S) -> i32` = 12410. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::*; + +pub trait T { + fn rust_method(&self) -> i32; + extern "C" fn c_method(&self) -> i32; +} + +pub struct S; + +impl T for S { + fn rust_method(&self) -> i32 { + 1 + } + extern "C" fn c_method(&self) -> i32 { + 2 + } +} + +// DISC: @vtable.{{[0-9]+}} = {{.*}}ptr @{{.*}}rust_method{{.*}}, ptr ptrauth (ptr @{{.*}}c_method{{.*}}, i32 0, i64 12410) +// NO_DISC: @vtable.{{[0-9]+}} = {{.*}}ptr @{{.*}}rust_method{{.*}}, ptr ptrauth (ptr @{{.*}}c_method{{.*}}, i32 0) + +// CHECK-LABEL: @make( +#[no_mangle] +pub fn make() -> &'static dyn T { + &S +} + +// CHECK-LABEL: @call_c_method( +#[no_mangle] +pub fn call_c_method(x: &dyn T) -> i32 { + // DISC: call i32 %{{.*}}(ptr {{.*}}) {{.*}}[ "ptrauth"(i32 0, i64 12410) ] + // NO_DISC: call i32 %{{.*}}(ptr {{.*}}) {{.*}}[ "ptrauth"(i32 0, i64 0) ] + x.c_method() +} + +// CHECK-LABEL: @call_rust_method( +#[no_mangle] +pub fn call_rust_method(x: &dyn T) -> i32 { + // CHECK-NOT: "ptrauth" + // CHECK: ret i32 + x.rust_method() +} diff --git a/tests/codegen-llvm/pauth/pauth-init-fini.rs b/tests/codegen-llvm/pauth/pauth-init-fini.rs index 5550100ae7f92..1fd0105965bbf 100644 --- a/tests/codegen-llvm/pauth/pauth-init-fini.rs +++ b/tests/codegen-llvm/pauth/pauth-init-fini.rs @@ -1,6 +1,6 @@ // ignore-tidy-file-linelength //@ add-minicore -//@ revisions: O0_PAUTH O3_PAUTH O0_PAUTH-ADDR-DISC O3_PAUTH-ADDR-DISC O0_PAUTH-NO-INIT-FINI O3_PAUTH-NO-INIT-FINI +//@ revisions: O0_PAUTH O3_PAUTH O0_PAUTH-ADDR-DISC O3_PAUTH-ADDR-DISC O0_PAUTH-NO-INIT-FINI O3_PAUTH-NO-INIT-FINI O0_PAUTH-FN-TY-DISC O3_PAUTH-FN-TY-DISC //@ [O0_PAUTH] needs-llvm-components: aarch64 //@ [O0_PAUTH] compile-flags: --target=aarch64-unknown-linux-pauthtest -C opt-level=0 @@ -14,9 +14,14 @@ //@ [O3_PAUTH-ADDR-DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest -C opt-level=3 -Zpointer-authentication=+init-fini-address-discrimination //@ [O3_PAUTH-NO-INIT-FINI] needs-llvm-components: aarch64 //@ [O3_PAUTH-NO-INIT-FINI] compile-flags: --target=aarch64-unknown-linux-pauthtest -C opt-level=0 -Zpointer-authentication=-init-fini +//@ [O0_PAUTH-FN-TY-DISC] needs-llvm-components: aarch64 +//@ [O0_PAUTH-FN-TY-DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest -C opt-level=0 -Zpointer-authentication=+function-pointer-type-discrimination +//@ [O3_PAUTH-FN-TY-DISC] needs-llvm-components: aarch64 +//@ [O3_PAUTH-FN-TY-DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest -C opt-level=3 -Zpointer-authentication=+function-pointer-type-discrimination // Make sure that init/fini metadata uses correct discriminator: 0xd9d4/55764 - ptrauth_string_discriminator("init_fini"). -// And that address discriminator can be enabled. +// And that address discriminator can be enabled. Function pointer type discrimination does not apply +// to init/fini entries: they keep the init/fini discriminator. #![feature(no_core, lang_items)] #![no_std] @@ -28,6 +33,8 @@ use minicore::*; // O0_PAUTH: @{{[0-9A-Za-z_]+}}GLOBAL_INIT = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}init_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".init_array.90" // O3_PAUTH: @{{[0-9A-Za-z_]+}}GLOBAL_INIT = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}init_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".init_array.90" +// O0_PAUTH-FN-TY-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_INIT = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}init_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".init_array.90" +// O3_PAUTH-FN-TY-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_INIT = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}init_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".init_array.90" // O0_PAUTH-ADDR-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_INIT = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}init_fn, i32 0, i64 55764, ptr @_RNvCsf7kshQi9mOB_15pauth_init_fini7init_fn), section ".init_array.90" // O3_PAUTH-ADDR-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_INIT = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}init_fn, i32 0, i64 55764, ptr @_RNvCsf7kshQi9mOB_15pauth_init_fini7init_fn), section ".init_array.90" // O0_PAUTH-NO-INIT-FINI-NOT: @{{[0-9A-Za-z_]+}}GLOBAL_INIT = constant ptr ptrauth @@ -38,6 +45,8 @@ static GLOBAL_INIT: extern "C" fn() = init_fn; // O0_PAUTH: @{{[0-9A-Za-z_]+}}GLOBAL_FINI = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}fini_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".fini_array.90" // O3_PAUTH: @{{[0-9A-Za-z_]+}}GLOBAL_FINI = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}fini_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".fini_array.90" +// O0_PAUTH-FN-TY-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_FINI = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}fini_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".fini_array.90" +// O3_PAUTH-FN-TY-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_FINI = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}fini_fn, i32 0, i64 55764, ptr inttoptr (i64 1 to ptr)), section ".fini_array.90" // O0_PAUTH-ADDR-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_FINI = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}fini_fn, i32 0, i64 55764, ptr @_RNvCsf7kshQi9mOB_15pauth_init_fini7fini_fn), section ".fini_array.90" // O3_PAUTH-ADDR-DISC: @{{[0-9A-Za-z_]+}}GLOBAL_FINI = constant ptr ptrauth (ptr @{{[0-9A-Za-z_]+}}fini_fn, i32 0, i64 55764, ptr @_RNvCsf7kshQi9mOB_15pauth_init_fini7fini_fn), section ".fini_array.90" // O0_PAUTH-NO-INIT-FINI-NOT: @{{[0-9A-Za-z_]+}}GLOBAL_FINI = constant ptr ptrauth diff --git a/tests/codegen-llvm/pauth/pauth-signed-abi.rs b/tests/codegen-llvm/pauth/pauth-signed-abi.rs new file mode 100644 index 0000000000000..2e32a6692d1e6 --- /dev/null +++ b/tests/codegen-llvm/pauth/pauth-signed-abi.rs @@ -0,0 +1,61 @@ +// ignore-tidy-file-linelength +//@ add-minicore +// Run it at O0, so that the compiler doesn't optimise the calls away. +//@ revisions: DISC NO_DISC + +//@ [DISC] needs-llvm-components: aarch64 +//@ [DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination -C opt-level=0 +//@ [NO_DISC] needs-llvm-components: aarch64 +//@ [NO_DISC] compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=-function-pointer-type-discrimination -C opt-level=0 + +// Function pointers are signed, and calls through them authenticated, for the same set of ABIs: +// `extern "C"` and `extern "system"` (see `is_ptrauth_signed_abi`). +// +// Discriminators: `extern "C" fn(i32)` = 2712. + +// FIXME: jchlanda - decide if `efiapi` should also participate in pointer authentication. + +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::*; + +extern "C" fn c_fn(_: i32) {} + +extern "efiapi" fn efi_fn(_: i32) {} + +// CHECK-LABEL: @reify_c( +#[no_mangle] +pub fn reify_c() -> extern "C" fn(i32) { + // DISC: ret ptr ptrauth (ptr @{{.*}}c_fn{{.*}}, i32 0, i64 2712) + // NO_DISC: ret ptr ptrauth (ptr @{{.*}}c_fn{{.*}}, i32 0) + c_fn +} + +// CHECK-LABEL: @reify_efiapi( +#[no_mangle] +pub fn reify_efiapi() -> extern "efiapi" fn(i32) { + // CHECK-NOT: ptrauth + // CHECK: ret ptr @{{.*}}efi_fn + efi_fn +} + +// CHECK-LABEL: @call_c( +#[no_mangle] +pub fn call_c(f: extern "C" fn(i32)) { + // DISC: call void %{{.*}}(i32 1) {{.*}}[ "ptrauth"(i32 0, i64 2712) ] + // NO_DISC: call void %{{.*}}(i32 1) {{.*}}[ "ptrauth"(i32 0, i64 0) ] + f(1) +} + +// CHECK-LABEL: @call_efiapi( +#[no_mangle] +pub fn call_efiapi(f: extern "efiapi" fn(i32)) { + // CHECK-NOT: "ptrauth" + // CHECK: call void %{{.*}}(i32 1) + // CHECK-NOT: "ptrauth" + // CHECK: ret void + f(1) +} diff --git a/tests/run-make/pauth-drop-terminator/before_instcombine.check b/tests/run-make/pauth-drop-terminator/before_instcombine.check new file mode 100644 index 0000000000000..50b46ecf4ae2e --- /dev/null +++ b/tests/run-make/pauth-drop-terminator/before_instcombine.check @@ -0,0 +1,4 @@ +// CHECK-LABEL: ; *** IR Dump Before InstCombinePass + +// CHECK-LABEL: define void @{{.*}}Drop4drop +// CHECK: call void ptrauth (ptr @c_cleanup, i32 0)(i32 noundef %{{.*}}) #[[#]] [ "ptrauth"(i32 0, i64 0) ] diff --git a/tests/run-make/pauth-drop-terminator/before_instcombine_ty_disc.check b/tests/run-make/pauth-drop-terminator/before_instcombine_ty_disc.check new file mode 100644 index 0000000000000..57f2d8d91e28f --- /dev/null +++ b/tests/run-make/pauth-drop-terminator/before_instcombine_ty_disc.check @@ -0,0 +1,4 @@ +// CHECK-LABEL: ; *** IR Dump Before InstCombinePass + +// CHECK-LABEL: define void @{{.*}}Drop4drop +// CHECK: call void ptrauth (ptr @c_cleanup, i32 0, i64 2712)(i32 noundef %{{.*}}) #[[#]] [ "ptrauth"(i32 0, i64 2712) ] diff --git a/tests/run-make/pauth-drop-terminator/full_ir.check b/tests/run-make/pauth-drop-terminator/full_ir.check new file mode 100644 index 0000000000000..ad4c80c0675c4 --- /dev/null +++ b/tests/run-make/pauth-drop-terminator/full_ir.check @@ -0,0 +1,3 @@ +// CHECK-LABEL: define void @{{.*}}Drop4drop +// CHECK-NOT: call void ptrauth (ptr @c_cleanup +// CHECK: tail call void @c_cleanup diff --git a/tests/run-make/pauth-drop-terminator/main.rs b/tests/run-make/pauth-drop-terminator/main.rs new file mode 100644 index 0000000000000..45646cfd6da60 --- /dev/null +++ b/tests/run-make/pauth-drop-terminator/main.rs @@ -0,0 +1,22 @@ +extern "C" { + fn c_cleanup(x: i32); +} + +struct Bomb(i32); + +impl Drop for Bomb { + fn drop(&mut self) { + unsafe { + c_cleanup(self.0); + } + } +} + +pub fn may_unwind(x: i32) { + let b = Bomb(x); + + match b.0 { + 0 => return, + _ => {} + } +} diff --git a/tests/run-make/pauth-drop-terminator/rmake.rs b/tests/run-make/pauth-drop-terminator/rmake.rs new file mode 100644 index 0000000000000..bb69570ae2adf --- /dev/null +++ b/tests/run-make/pauth-drop-terminator/rmake.rs @@ -0,0 +1,61 @@ +// Make sure that for `aarch64-unknown-linux-pauthtest` compiler correctly signs drop terminators. +// Please note that the generated pattern: +// ```llvm +// tail call void ptrauth (ptr @c_cleanup, i32 0)(ptr @c_cleanup, i32 0, i64 2712) #2 [ "ptrauth"(i32 0, i64 2712) ] +// ``` +// is optimised out by LLVM's instcombine, hence dump the IR before that pass and inspect it. + +//@ only-pauthtest +// ignore-tidy-file-linelength + +use run_make_support::path_helpers::source_root; +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + let sibling = source_root().join("tests/run-make/pauth-drop-terminator"); + + let output = rustc() + .input("main.rs") + .target("aarch64-unknown-linux-pauthtest") + .opt_level("3") + .arg("--crate-type=lib") + .arg("--emit=llvm-ir") + .arg("-C") + .arg("llvm-args=-print-before=instcombine") + .run(); + + let stderr = output.stderr_utf8(); + + // -print-before outputs to stderr, so copy it over to a file, that can later be used by + // filecheck. + rfs::write("before_instcombine.ll", stderr); + + llvm_filecheck() + .patterns(sibling.join("before_instcombine.check")) + .stdin_buf(rfs::read("before_instcombine.ll")) + .run(); + + llvm_filecheck().patterns(sibling.join("full_ir.check")).stdin_buf(rfs::read("main.ll")).run(); + + // Compile again now using function pointer type discrimination. + let output = rustc() + .input("main.rs") + .target("aarch64-unknown-linux-pauthtest") + .opt_level("3") + .arg("--crate-type=lib") + .arg("--emit=llvm-ir") + .arg("-Zpointer-authentication=+function-pointer-type-discrimination") + .arg("-Cunsafe-allow-abi-mismatch=pointer-authentication") + .arg("-C") + .arg("llvm-args=-print-before=instcombine") + .run(); + + let stderr = output.stderr_utf8(); + + rfs::write("before_instcombine_ty_disc.ll", stderr); + + llvm_filecheck() + .patterns(sibling.join("before_instcombine_ty_disc.check")) + .stdin_buf(rfs::read("before_instcombine_ty_disc.ll")) + .run(); +} diff --git a/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/c.check b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/c.check new file mode 100644 index 0000000000000..bb47f9fcb2971 --- /dev/null +++ b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/c.check @@ -0,0 +1,22 @@ +// C side, as Clang lowers it under function pointer type discrimination: a code address is signed +// according to the C type of the slot holding it, and C casts resign. + +CHECK-LABEL: define {{.*}}@apply( +CHECK: "ptrauth"(i32 0, i64 [[BINOP]]) + +CHECK-LABEL: define {{.*}}@get_sub( +CHECK: ptrauth (ptr @c_sub, i32 0, i64 [[BINOP]]) + +CHECK-LABEL: define {{.*}}@lookup( +CHECK: {{ptrauth \(ptr @c_mul, i32 0\)|@llvm.ptrauth.resign\(.*@c_mul.*, i32 0, i64 0\)}} + +CHECK-LABEL: define {{.*}}@invoke_callback( +CHECK: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 [[GENERIC]], i32 0, i64 [[BINOP]]) +CHECK: "ptrauth"(i32 0, i64 [[BINOP]]) + +CHECK-LABEL: define {{.*}}@get_proc( +CHECK: {{ptrauth \(ptr @c_sub, i32 0, i64 |@llvm.ptrauth.resign\(.*@c_sub.*, i32 0, i64 }}[[GENERIC]]) + +CHECK-LABEL: define {{.*}}@call_opaque( +CHECK: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 0, i32 0, i64 [[BINOP]]) +CHECK: "ptrauth"(i32 0, i64 [[BINOP]]) diff --git a/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/interop.c b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/interop.c new file mode 100644 index 0000000000000..c2229eb6f043d --- /dev/null +++ b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/interop.c @@ -0,0 +1,40 @@ +// C side of the interop test. Built with Clang's function pointer type discrimination: a code +// address is signed according to the C type of the slot holding it, and C casts resign. + +#include +#include + +typedef int (*binop_t)(int, int); +typedef void (*generic_cb_t)(void); + +static int c_sub(int a, int b) { return a - b; } +static int c_mul(int a, int b) { return a * b; } + +// Correctly typed callback: C calls a Rust function through its real type. +int apply(binop_t op, int a, int b) { return op(a, b); } + +// Correctly typed function pointer returned to Rust. +binop_t get_sub(void) { return c_sub; } + +// `dlsym`-like lookup: the code address is handed out as a `void *` (discriminator 0). +void *lookup(const char *name) { + if (strcmp(name, "mul") == 0) + return (void *)c_mul; + return NULL; +} + +// Generic callback slot (GLib's `GCallback` style): the callback is stored with the generic type +// and cast back to its real type before the call. +static generic_cb_t g_slot; +void register_callback(generic_cb_t cb) { g_slot = cb; } +int invoke_callback(int a, int b) { return ((binop_t)g_slot)(a, b); } + +// Generic callback handed out by C. +generic_cb_t get_proc(const char *name) { + if (strcmp(name, "sub") == 0) + return (generic_cb_t)c_sub; + return NULL; +} + +// A code address passed in as `void *` user data, cast back before the call. +int call_opaque(void *fn, int a, int b) { return ((binop_t)fn)(a, b); } diff --git a/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/interop.rs b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/interop.rs new file mode 100644 index 0000000000000..bab471187faf0 --- /dev/null +++ b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/interop.rs @@ -0,0 +1,73 @@ +// Rust side of the IR-level interop test, mirroring the C functions in `interop.c`. + +#![feature(core_intrinsics)] +#![allow(internal_features)] + +use std::ffi::{c_char, c_int, c_void}; +use std::intrinsics::ptrauth_c_cast; +use std::mem::transmute; + +type BinOp = unsafe extern "C" fn(c_int, c_int) -> c_int; +type GenericCb = unsafe extern "C" fn(); + +unsafe extern "C" { + fn apply(op: BinOp, a: c_int, b: c_int) -> c_int; + fn get_sub() -> BinOp; + fn lookup(name: *const c_char) -> *mut c_void; + fn register_callback(cb: Option); + fn get_proc(name: *const c_char) -> Option; + fn call_opaque(f: *mut c_void, a: c_int, b: c_int) -> c_int; +} + +pub extern "C" fn add(a: c_int, b: c_int) -> c_int { + a + b +} + +// Correctly typed callback, Rust to C: `add` is signed with the discriminator C authenticates with +// in `apply`. +#[no_mangle] +pub unsafe fn typed_to_c() -> c_int { + unsafe { apply(add, 2, 3) } +} + +// Correctly typed function pointer, C to Rust: called with the discriminator C signed it with in +// `get_sub`. +#[no_mangle] +pub unsafe fn typed_from_c() -> c_int { + unsafe { get_sub()(9, 4) } +} + +// `void *` from C (signed with 0 in `lookup`). +#[no_mangle] +pub unsafe fn from_void_ptr() -> Option { + unsafe { ptrauth_c_cast(lookup(c"mul".as_ptr())) } +} + +// Generic callback slot, Rust to C (authenticated as `generic_cb_t` by the cast in +// `invoke_callback`). +#[no_mangle] +pub unsafe fn to_generic_slot() { + unsafe { register_callback(Some(ptrauth_c_cast::(add))) } +} + +// Generic callback from C (signed as `generic_cb_t` in `get_proc`). +#[no_mangle] +pub unsafe fn from_generic_slot() -> Option { + unsafe { ptrauth_c_cast(get_proc(c"sub".as_ptr())) } +} + +// `void *` user data, Rust to C (authenticated with 0 by the cast in `call_opaque`). +#[no_mangle] +pub unsafe fn to_void_ptr() -> c_int { + unsafe { call_opaque(ptrauth_c_cast::(add), 4, 5) } +} + +// A Rust-only round trip through another type needs no resign. +#[no_mangle] +pub unsafe fn rust_round_trip() -> c_int { + unsafe { + let erased: GenericCb = transmute::(add); + let back: BinOp = transmute(erased); + back(1, 1) + } +} diff --git a/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/rmake.rs b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/rmake.rs new file mode 100644 index 0000000000000..96ceda10e75d9 --- /dev/null +++ b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/rmake.rs @@ -0,0 +1,109 @@ +// C/Rust interop under function pointer type discrimination, checked on the IR level (no need for +// linker/libc). +// +// Rust signs a function pointer with the discriminator of the function it points to and never +// resigns implicitly, while Clang encodes a code address according to the C type of the slot +// holding it. Interop is correct when, at every boundary, both compilers use the same +// discriminator. The test reads the discriminators Clang uses for `int (*)(int, int)` and +// `void (*)(void)` from its IR, and checks that Rust uses exactly those: +// * for correctly typed callbacks, in both directions, without any resign; +// * through `ptrauth_c_cast`, for code addresses crossing a C slot that erased their type +// (`void *`, a generic callback type), in both directions. +// +// The test assumes that a pointer-authentication-enabled `clang` is available on the path. + +//@ only-pauthtest + +use run_make_support::path_helpers::source_root; +use run_make_support::{cc, llvm_filecheck, rfs, rustc}; + +/// Returns the body of the function `name` in the LLVM IR `ir`. +fn function_body<'a>(ir: &'a str, name: &str) -> &'a str { + let define = ir + .lines() + .find(|l| l.starts_with("define") && l.contains(&format!("@{name}("))) + .unwrap_or_else(|| panic!("no definition of `{name}` in:\n{ir}")); + let start = ir.find(define).unwrap(); + let end = start + ir[start..].find("\n}").unwrap(); + &ir[start..end] +} + +/// Returns the number following the first occurrence of `prefix` in `text`. +fn number_after(text: &str, prefix: &str) -> u64 { + let start = text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` not found in:\n{text}")) + + prefix.len(); + let digits: String = text[start..].chars().take_while(char::is_ascii_digit).collect(); + digits.parse().unwrap() +} + +/// Returns the (authenticated, signed) discriminators of the first `llvm.ptrauth.resign` call in +/// `body`. The resigned value may itself be a constant signed pointer, so the discriminators are +/// the last two of the call. +fn resign_discriminators(body: &str) -> (u64, u64) { + let call = body + .lines() + .find(|l| l.contains("@llvm.ptrauth.resign(")) + .unwrap_or_else(|| panic!("no `llvm.ptrauth.resign` call in:\n{body}")); + let prefix = "i32 0, i64 "; + let discriminators: Vec = + call.match_indices(prefix).map(|(i, _)| number_after(&call[i..], prefix)).collect(); + let &[.., from, to] = discriminators.as_slice() else { + panic!("expected two discriminators in `{call}`"); + }; + (from, to) +} + +fn main() { + let sibling = source_root().join("tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir"); + + cc().input("interop.c") + .args(&[ + "-target", + "aarch64-unknown-linux-pauthtest", + "-march=armv8.3-a+pauth", + "-fptrauth-function-pointer-type-discrimination", + "-O0", + "-S", + "-emit-llvm", + "-o", + "c.ll", + ]) + .run(); + let c_ir = rfs::read_to_string("c.ll"); + + // `apply` calls through `int (*)(int, int)`. `invoke_callback` casts `void (*)(void)` back to + // `int (*)(int, int)`, resigning between the two. + let binop = number_after(function_body(&c_ir, "apply"), "\"ptrauth\"(i32 0, i64 "); + let (generic, to) = resign_discriminators(function_body(&c_ir, "invoke_callback")); + assert_eq!(to, binop); + assert_ne!(binop, 0); + assert_ne!(generic, 0); + assert_ne!(binop, generic); + let defines = [format!("-DBINOP={binop}"), format!("-DGENERIC={generic}")]; + + llvm_filecheck().patterns(sibling.join("c.check")).args(&defines).stdin_buf(&c_ir).run(); + + rustc() + .target("aarch64-unknown-linux-pauthtest") + .input("interop.rs") + .crate_type("lib") + .edition("2021") + .emit("llvm-ir") + .opt_level("0") + .arg("-Zpointer-authentication=+function-pointer-type-discrimination") + .arg("-Cunsafe-allow-abi-mismatch=pointer-authentication") + .run(); + + // Functions are not emitted in source order: check each one with its own prefix. + let rust_ir = rfs::read("interop.ll"); + for prefix in + ["TO_C", "FROM_C", "FROM_VOID", "TO_GENERIC", "FROM_GENERIC", "TO_VOID", "ROUND_TRIP"] + { + llvm_filecheck() + .patterns(sibling.join("rust.check")) + .check_prefix(prefix) + .args(&defines) + .stdin_buf(&rust_ir) + .run(); + } +} diff --git a/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/rust.check b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/rust.check new file mode 100644 index 0000000000000..380dd2202a7a1 --- /dev/null +++ b/tests/run-make/pauth-fn-ptr-type-discrimination-interop-ir/rust.check @@ -0,0 +1,28 @@ +// Rust side: every boundary uses the discriminators Clang uses on the C side. `BINOP` is the +// discriminator of `int (*)(int, int)`, `GENERIC` the one of `void (*)(void)`, both read from +// Clang's IR. Functions are not emitted in source order, so each has its own prefix and FileCheck +// runs once per prefix. + +TO_C-LABEL: define {{.*}}@typed_to_c( +TO_C-NOT: llvm.ptrauth.resign +TO_C: @apply{{.*}}(ptr ptrauth (ptr @{{.*}}add, i32 0, i64 [[BINOP]]) + +FROM_C-LABEL: define {{.*}}@typed_from_c( +FROM_C-NOT: llvm.ptrauth.resign +FROM_C: call i32 %{{.*}}(i32 9, i32 4) {{.*}}[ "ptrauth"(i32 0, i64 [[BINOP]]) ] + +FROM_VOID-LABEL: define {{.*}}@from_void_ptr( +FROM_VOID: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 0, i32 0, i64 [[BINOP]]) + +TO_GENERIC-LABEL: define {{.*}}@to_generic_slot( +TO_GENERIC: call i64 @llvm.ptrauth.resign(i64 {{.*}}, i32 0, i64 [[BINOP]], i32 0, i64 [[GENERIC]]) + +FROM_GENERIC-LABEL: define {{.*}}@from_generic_slot( +FROM_GENERIC: call i64 @llvm.ptrauth.resign(i64 %{{.*}}, i32 0, i64 [[GENERIC]], i32 0, i64 [[BINOP]]) + +TO_VOID-LABEL: define {{.*}}@to_void_ptr( +TO_VOID: call i64 @llvm.ptrauth.resign(i64 {{.*}}, i32 0, i64 [[BINOP]], i32 0, i64 0) + +ROUND_TRIP-LABEL: define {{.*}}@rust_round_trip( +ROUND_TRIP-NOT: llvm.ptrauth.resign +ROUND_TRIP: call i32 {{.*}}(i32 1, i32 1) {{.*}}[ "ptrauth"(i32 0, i64 [[BINOP]]) ] diff --git a/tests/ui/abi/c-zst.aarch64-darwin.stderr b/tests/ui/abi/c-zst.aarch64-darwin.stderr index ea764cb2cc71e..c7fb8ef24ec49 100644 --- a/tests/ui/abi/c-zst.aarch64-darwin.stderr +++ b/tests/ui/abi/c-zst.aarch64-darwin.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/c-zst.powerpc-linux.stderr b/tests/ui/abi/c-zst.powerpc-linux.stderr index 8598792e93815..48e20c478edfa 100644 --- a/tests/ui/abi/c-zst.powerpc-linux.stderr +++ b/tests/ui/abi/c-zst.powerpc-linux.stderr @@ -68,6 +68,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/c-zst.s390x-linux.stderr b/tests/ui/abi/c-zst.s390x-linux.stderr index 8598792e93815..48e20c478edfa 100644 --- a/tests/ui/abi/c-zst.s390x-linux.stderr +++ b/tests/ui/abi/c-zst.s390x-linux.stderr @@ -68,6 +68,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/c-zst.sparc-linux.stderr b/tests/ui/abi/c-zst.sparc-linux.stderr index 8598792e93815..48e20c478edfa 100644 --- a/tests/ui/abi/c-zst.sparc-linux.stderr +++ b/tests/ui/abi/c-zst.sparc-linux.stderr @@ -68,6 +68,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/c-zst.sparc-none.stderr b/tests/ui/abi/c-zst.sparc-none.stderr index 8598792e93815..48e20c478edfa 100644 --- a/tests/ui/abi/c-zst.sparc-none.stderr +++ b/tests/ui/abi/c-zst.sparc-none.stderr @@ -68,6 +68,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/c-zst.sparc64-linux.stderr b/tests/ui/abi/c-zst.sparc64-linux.stderr index 8598792e93815..48e20c478edfa 100644 --- a/tests/ui/abi/c-zst.sparc64-linux.stderr +++ b/tests/ui/abi/c-zst.sparc64-linux.stderr @@ -68,6 +68,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/c-zst.x86_64-linux.stderr b/tests/ui/abi/c-zst.x86_64-linux.stderr index ea764cb2cc71e..c7fb8ef24ec49 100644 --- a/tests/ui/abi/c-zst.x86_64-linux.stderr +++ b/tests/ui/abi/c-zst.x86_64-linux.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr b/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr index efc74aab224a9..9149bd40f89da 100644 --- a/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr +++ b/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr @@ -79,6 +79,7 @@ error: fn_abi_of(pass_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/c-zst.rs:74:1 | diff --git a/tests/ui/abi/debug.generic.stderr b/tests/ui/abi/debug.generic.stderr index f973e774cdc18..d3087b2ec4af9 100644 --- a/tests/ui/abi/debug.generic.stderr +++ b/tests/ui/abi/debug.generic.stderr @@ -106,6 +106,7 @@ error: fn_abi_of(test) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:31:1 | @@ -196,6 +197,7 @@ error: fn_abi_of(test_unsized) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:37:1 | @@ -275,6 +277,7 @@ error: fn_abi_of(TestFnPtr) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:43:1 | @@ -344,6 +347,7 @@ error: fn_abi_of(test_generic) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:46:1 | @@ -420,6 +424,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -484,6 +489,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:65:1 | @@ -561,6 +567,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -632,6 +639,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:68:1 | @@ -702,6 +710,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -766,6 +775,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:71:1 | @@ -836,6 +846,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -900,6 +911,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:75:1 | @@ -992,6 +1004,7 @@ error: fn_abi_of(assoc_test) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:58:5 | diff --git a/tests/ui/abi/debug.loongarch64.stderr b/tests/ui/abi/debug.loongarch64.stderr index 65425ab57e171..43498c3b852d4 100644 --- a/tests/ui/abi/debug.loongarch64.stderr +++ b/tests/ui/abi/debug.loongarch64.stderr @@ -106,6 +106,7 @@ error: fn_abi_of(test) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:31:1 | @@ -196,6 +197,7 @@ error: fn_abi_of(test_unsized) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:37:1 | @@ -275,6 +277,7 @@ error: fn_abi_of(TestFnPtr) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:43:1 | @@ -344,6 +347,7 @@ error: fn_abi_of(test_generic) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:46:1 | @@ -420,6 +424,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -484,6 +489,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:65:1 | @@ -561,6 +567,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -632,6 +639,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:68:1 | @@ -702,6 +710,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -766,6 +775,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:71:1 | @@ -836,6 +846,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -900,6 +911,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:75:1 | @@ -992,6 +1004,7 @@ error: fn_abi_of(assoc_test) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:58:5 | diff --git a/tests/ui/abi/debug.riscv64.stderr b/tests/ui/abi/debug.riscv64.stderr index 65425ab57e171..43498c3b852d4 100644 --- a/tests/ui/abi/debug.riscv64.stderr +++ b/tests/ui/abi/debug.riscv64.stderr @@ -106,6 +106,7 @@ error: fn_abi_of(test) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:31:1 | @@ -196,6 +197,7 @@ error: fn_abi_of(test_unsized) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:37:1 | @@ -275,6 +277,7 @@ error: fn_abi_of(TestFnPtr) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:43:1 | @@ -344,6 +347,7 @@ error: fn_abi_of(test_generic) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:46:1 | @@ -420,6 +424,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -484,6 +489,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:65:1 | @@ -561,6 +567,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -632,6 +639,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:68:1 | @@ -702,6 +710,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -766,6 +775,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:71:1 | @@ -836,6 +846,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } right ABI = FnAbi { args: [ @@ -900,6 +911,7 @@ error: ABIs are not compatible fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:75:1 | @@ -992,6 +1004,7 @@ error: fn_abi_of(assoc_test) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: $SOME_BOOL, + ptrauth_discriminator: None, } --> $DIR/debug.rs:58:5 | diff --git a/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.apple.stderr b/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.apple.stderr index 683428514e4db..e92b519bfb395 100644 --- a/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.apple.stderr +++ b/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.apple.stderr @@ -67,6 +67,7 @@ error: fn_abi_of(i8) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:13:1 | @@ -142,6 +143,7 @@ error: fn_abi_of(u8) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:19:1 | @@ -217,6 +219,7 @@ error: fn_abi_of(i16) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:25:1 | @@ -292,6 +295,7 @@ error: fn_abi_of(u16) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:31:1 | @@ -367,6 +371,7 @@ error: fn_abi_of(i32) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:37:1 | @@ -442,6 +447,7 @@ error: fn_abi_of(u32) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:43:1 | diff --git a/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.other.stderr b/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.other.stderr index 2fc0528149667..58c9568514c18 100644 --- a/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.other.stderr +++ b/tests/ui/abi/numbers-arithmetic/x86-64-sysv64-arg-ext.other.stderr @@ -67,6 +67,7 @@ error: fn_abi_of(i8) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:13:1 | @@ -142,6 +143,7 @@ error: fn_abi_of(u8) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:19:1 | @@ -217,6 +219,7 @@ error: fn_abi_of(i16) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:25:1 | @@ -292,6 +295,7 @@ error: fn_abi_of(u16) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:31:1 | @@ -367,6 +371,7 @@ error: fn_abi_of(i32) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:37:1 | @@ -442,6 +447,7 @@ error: fn_abi_of(u32) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/x86-64-sysv64-arg-ext.rs:43:1 | diff --git a/tests/ui/abi/pass-indirectly-attr.rs b/tests/ui/abi/pass-indirectly-attr.rs index 72a5678b91753..bd6464087c2cd 100644 --- a/tests/ui/abi/pass-indirectly-attr.rs +++ b/tests/ui/abi/pass-indirectly-attr.rs @@ -1,6 +1,9 @@ //@ add-minicore //@ check-fail //@ normalize-stderr: "randomization_seed: \d+" -> "randomization_seed: $$SEED" +// The pointer authentication discriminator depends on the target's pointer authentication +// configuration, not on the calling convention. +//@ normalize-stderr: "ptrauth_discriminator: (None|Some\(\s+\d+,\s+\))" -> "ptrauth_discriminator: $$PTRAUTH_DISCRIMINATOR" #![feature(rustc_attrs)] #![crate_type = "lib"] diff --git a/tests/ui/abi/pass-indirectly-attr.stderr b/tests/ui/abi/pass-indirectly-attr.stderr index 25589665cf91d..aeedbbb77227b 100644 --- a/tests/ui/abi/pass-indirectly-attr.stderr +++ b/tests/ui/abi/pass-indirectly-attr.stderr @@ -1,5 +1,5 @@ error[E0692]: transparent struct cannot have other repr hints - --> $DIR/pass-indirectly-attr.rs:34:1 + --> $DIR/pass-indirectly-attr.rs:37:1 | LL | #[rustc_pass_indirectly_in_non_rustic_abis] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -81,8 +81,9 @@ error: fn_abi_of(extern_c) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: $PTRAUTH_DISCRIMINATOR, } - --> $DIR/pass-indirectly-attr.rs:19:1 + --> $DIR/pass-indirectly-attr.rs:22:1 | LL | pub extern "C" fn extern_c(_: Type) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -171,8 +172,9 @@ error: fn_abi_of(extern_rust) = FnAbi { fixed_count: 1, conv: Rust, can_unwind: false, + ptrauth_discriminator: $PTRAUTH_DISCRIMINATOR, } - --> $DIR/pass-indirectly-attr.rs:26:1 + --> $DIR/pass-indirectly-attr.rs:29:1 | LL | pub extern "Rust" fn extern_rust(_: Type) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/abi/rust-zst.aarch64-darwin.stderr b/tests/ui/abi/rust-zst.aarch64-darwin.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.aarch64-darwin.stderr +++ b/tests/ui/abi/rust-zst.aarch64-darwin.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/rust-zst.powerpc-linux.stderr b/tests/ui/abi/rust-zst.powerpc-linux.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.powerpc-linux.stderr +++ b/tests/ui/abi/rust-zst.powerpc-linux.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/rust-zst.s390x-linux.stderr b/tests/ui/abi/rust-zst.s390x-linux.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.s390x-linux.stderr +++ b/tests/ui/abi/rust-zst.s390x-linux.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/rust-zst.sparc-linux.stderr b/tests/ui/abi/rust-zst.sparc-linux.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.sparc-linux.stderr +++ b/tests/ui/abi/rust-zst.sparc-linux.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/rust-zst.sparc-none.stderr b/tests/ui/abi/rust-zst.sparc-none.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.sparc-none.stderr +++ b/tests/ui/abi/rust-zst.sparc-none.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/rust-zst.sparc64-linux.stderr b/tests/ui/abi/rust-zst.sparc64-linux.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.sparc64-linux.stderr +++ b/tests/ui/abi/rust-zst.sparc64-linux.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/rust-zst.x86_64-linux.stderr b/tests/ui/abi/rust-zst.x86_64-linux.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.x86_64-linux.stderr +++ b/tests/ui/abi/rust-zst.x86_64-linux.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr b/tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr index f4a3338ca287d..7a5a68dc459d3 100644 --- a/tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr +++ b/tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr @@ -57,6 +57,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/rust-zst.rs:64:1 | diff --git a/tests/ui/abi/sysv64-zst.stderr b/tests/ui/abi/sysv64-zst.stderr index f644f32fe86f9..87feeec2c12d6 100644 --- a/tests/ui/abi/sysv64-zst.stderr +++ b/tests/ui/abi/sysv64-zst.stderr @@ -59,6 +59,7 @@ error: fn_abi_of(pass_zst) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: None, } --> $DIR/sysv64-zst.rs:8:1 | diff --git a/tests/ui/attributes/doc_examples/rustc_dump_ptrauth_discriminator.rs b/tests/ui/attributes/doc_examples/rustc_dump_ptrauth_discriminator.rs new file mode 100644 index 0000000000000..48b0976d3e006 --- /dev/null +++ b/tests/ui/attributes/doc_examples/rustc_dump_ptrauth_discriminator.rs @@ -0,0 +1,7 @@ +//@ dont-require-annotations: ERROR +//@ compile-flags: --crate-type lib -Z ui-testing=no + +#![feature(rustc_attrs)] + +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn foo(_: i32) {} diff --git a/tests/ui/attributes/doc_examples/rustc_dump_ptrauth_discriminator.stderr b/tests/ui/attributes/doc_examples/rustc_dump_ptrauth_discriminator.stderr new file mode 100644 index 0000000000000..1273d7b29e324 --- /dev/null +++ b/tests/ui/attributes/doc_examples/rustc_dump_ptrauth_discriminator.stderr @@ -0,0 +1,14 @@ +error: ptrauth discriminator encoding: "FviE" + --> $DIR/rustc_dump_ptrauth_discriminator.rs:7:1 + | +7 | extern "C" fn foo(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/rustc_dump_ptrauth_discriminator.rs:7:1 + | +7 | extern "C" fn foo(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/c-variadic/pass-by-value-abi.aarch64.stderr b/tests/ui/c-variadic/pass-by-value-abi.aarch64.stderr index 22d1739a78ab3..47fca33c6b1c4 100644 --- a/tests/ui/c-variadic/pass-by-value-abi.aarch64.stderr +++ b/tests/ui/c-variadic/pass-by-value-abi.aarch64.stderr @@ -68,8 +68,9 @@ error: fn_abi_of(take_va_list) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: $PTRAUTH_DISCRIMINATOR, } - --> $DIR/pass-by-value-abi.rs:27:1 + --> $DIR/pass-by-value-abi.rs:30:1 | LL | pub extern "C" fn take_va_list(_: VaList<'_>) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/c-variadic/pass-by-value-abi.rs b/tests/ui/c-variadic/pass-by-value-abi.rs index 317840601c050..90763b60d5672 100644 --- a/tests/ui/c-variadic/pass-by-value-abi.rs +++ b/tests/ui/c-variadic/pass-by-value-abi.rs @@ -1,5 +1,8 @@ //@ check-fail //@ normalize-stderr: "randomization_seed: \d+" -> "randomization_seed: $$SEED" +// The pointer authentication discriminator depends on the target's pointer authentication +// configuration, not on the calling convention. +//@ normalize-stderr: "ptrauth_discriminator: (None|Some\(\s+\d+,\s+\))" -> "ptrauth_discriminator: $$PTRAUTH_DISCRIMINATOR" //@ normalize-stderr: "pointer is 0\.\.=\d+" -> "pointer is 0..=$$MAX" //@ normalize-stderr: "in_memory_order: \[[^\]]+\]" -> "in_memory_order: $$MEMORY_INDEX" //@ normalize-stderr: "offsets: \[[^\]]+\]" -> "offsets: $$OFFSETS" diff --git a/tests/ui/c-variadic/pass-by-value-abi.win.stderr b/tests/ui/c-variadic/pass-by-value-abi.win.stderr index ffbfa5f146eba..ef2326cf5043b 100644 --- a/tests/ui/c-variadic/pass-by-value-abi.win.stderr +++ b/tests/ui/c-variadic/pass-by-value-abi.win.stderr @@ -64,8 +64,9 @@ error: fn_abi_of(take_va_list) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: $PTRAUTH_DISCRIMINATOR, } - --> $DIR/pass-by-value-abi.rs:27:1 + --> $DIR/pass-by-value-abi.rs:30:1 | LL | pub extern "C" fn take_va_list(_: VaList<'_>) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/c-variadic/pass-by-value-abi.x86_64.stderr b/tests/ui/c-variadic/pass-by-value-abi.x86_64.stderr index e8b17cd9001e3..c302b6b9badcb 100644 --- a/tests/ui/c-variadic/pass-by-value-abi.x86_64.stderr +++ b/tests/ui/c-variadic/pass-by-value-abi.x86_64.stderr @@ -68,8 +68,9 @@ error: fn_abi_of(take_va_list) = FnAbi { fixed_count: 1, conv: C, can_unwind: false, + ptrauth_discriminator: $PTRAUTH_DISCRIMINATOR, } - --> $DIR/pass-by-value-abi.rs:27:1 + --> $DIR/pass-by-value-abi.rs:30:1 | LL | pub extern "C" fn take_va_list(_: VaList<'_>) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -146,8 +147,9 @@ error: fn_abi_of(take_va_list_sysv64) = FnAbi { SysV64, ), can_unwind: false, + ptrauth_discriminator: $PTRAUTH_DISCRIMINATOR, } - --> $DIR/pass-by-value-abi.rs:37:1 + --> $DIR/pass-by-value-abi.rs:40:1 | LL | pub extern "sysv64" fn take_va_list_sysv64(_: VaList<'_>) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -224,8 +226,9 @@ error: fn_abi_of(take_va_list_win64) = FnAbi { Win64, ), can_unwind: false, + ptrauth_discriminator: $PTRAUTH_DISCRIMINATOR, } - --> $DIR/pass-by-value-abi.rs:44:1 + --> $DIR/pass-by-value-abi.rs:47:1 | LL | pub extern "win64" fn take_va_list_win64(_: VaList<'_>) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/feature-gates/feature-gate-ptrauth_c_discriminator.rs b/tests/ui/feature-gates/feature-gate-ptrauth_c_discriminator.rs new file mode 100644 index 0000000000000..3658de438709b --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-ptrauth_c_discriminator.rs @@ -0,0 +1,6 @@ +#![crate_type = "lib"] + +pub struct NativeMethod { + #[rustc_ptrauth_c_discriminator(0)] //~ ERROR the `rustc_ptrauth_c_discriminator` attribute is an experimental feature [E0658] + pub fn_ptr: *const u8, +} diff --git a/tests/ui/feature-gates/feature-gate-ptrauth_c_discriminator.stderr b/tests/ui/feature-gates/feature-gate-ptrauth_c_discriminator.stderr new file mode 100644 index 0000000000000..eaeec6f219863 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-ptrauth_c_discriminator.stderr @@ -0,0 +1,13 @@ +error[E0658]: the `rustc_ptrauth_c_discriminator` attribute is an experimental feature + --> $DIR/feature-gate-ptrauth_c_discriminator.rs:4:7 + | +LL | #[rustc_ptrauth_c_discriminator(0)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #148640 for more information + = help: add `#![feature(ptrauth_c_discriminator)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/pointer_authentication/discriminator-abi-compat.rs b/tests/ui/pointer_authentication/discriminator-abi-compat.rs new file mode 100644 index 0000000000000..89a97d42aa00f --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-abi-compat.rs @@ -0,0 +1,506 @@ +// Test how function pointer type discriminator calculation interacts with function pointer ABI +// compatibility rules (https://doc.rust-lang.org/std/primitive.fn.html#abi-compatibility). +// +// Function pointers are signed with the discriminator of the function they point to, and a call +// authenticates with the discriminator of the type it is made through. +// +// The test is grouped into 3 sections, based on the type compatibility (marked by comments in +// code): +// +// 1. Types that are ABI-compatible , so the discriminators MUST match. A failure here is a +// soundness bug. +// 2. Not ABI-compatible types, but with equal discriminators, because the Clang encoding is coarser +// than Rust's rules, for example: every integer type encodes as `i`. These MUST match to match +// Clang. A failure here breaks interoperability with C. +// 3. Types that are not ABI-compatible, and distinct. Calls through these signatures are UB; +// distinct discriminators are what makes such a call trap. +// +// Each function's encoding and hash are checked by its annotations +// (#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)]). +// +// In sections 1 and 2, every function in a group has the same encoding; in section 3, each +// function differs from the group it resembles. +// +// On the rule that "any two fn (function pointer) types are ABI-compatible with each other": it is +// about function pointers passed as values, and is honoured, as every function pointer argument +// encodes as `P` (group 1.7). It does not make a call through a different signature valid: calling +// a `fn(i32)` through `fn()` is still UB, so the two signatures get distinct discriminators +// (group 3.1). + +#![crate_type = "lib"] +#![feature(rustc_attrs)] +#![feature(allocator_ext)] +#![allow(dead_code)] +#![allow(improper_ctypes_definitions)] + +use std::alloc::{AllocError, Allocator, Global, Layout}; +use std::marker::PhantomData; +use std::num::NonZero; +use std::ptr::NonNull; + +struct SomeStruct { + _x: i32, +} + +struct Unit; + +enum OneVariant { + A, +} + +#[repr(transparent)] +struct TrivialWrapper(()); + +#[repr(transparent)] +struct Wrapper(i32); + +#[repr(transparent)] +struct WrapperWithZst(i32, PhantomData); + +enum MyOption { + None, + Some(T), +} + +mod m1 { + pub struct S(pub i32); +} + +mod m2 { + pub struct S(pub u8); +} + +struct MyAlloc; + +unsafe impl Allocator for MyAlloc { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + Global.allocate(layout) + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + unsafe { Global.deallocate(ptr, layout) } + } +} + +#[repr(align(4))] +struct AlignedMarker; + +struct NotTransparent(i32); + +enum WithExtraField { + A(NonZero, i32), + B, +} + +enum ThreeVariants { + A(bool), + B, + C, +} + +// 1. Types that are ABI-compatible , so the discriminators MUST match. A failure here is a +// soundness bug. + +// 1.1 "*const T, *mut T, &T, &mut T, Box (specifically, only Box), and NonNull +// are all ABI-compatible with each other for all T. They are also ABI-compatible with each other +// for different T if they have the same metadata type." Here thin pointers (metadata `()`). +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p1_a(_: *const i32) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p1_b(_: *mut i32) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p1_c(_: &i32) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p1_d(_: &mut i32) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p1_e(_: Box) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p1_f(_: NonNull) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p1_g(_: *const SomeStruct) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) + +// 1.2 The same, for pointers whose metadata is `usize` (slices and `str`). +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p2_a(_: *const [i32]) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p2_b(_: &[u8]) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p2_c(_: *const str) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn p2_d(_: Box<[u16]>) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) + +// 1.3 "usize is ABI-compatible with the uN integer type of the same size, and likewise isize is +// ABI-compatible with the iN integer type of the same size." and "char is ABI-compatible with +// u32." +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn i1_a(_: usize) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn i1_b(_: u64) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn i1_c(_: isize) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn i1_d(_: i64) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn i1_e(_: char) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn i1_f(_: u32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) + +// 1.4 "Any two types with size 0 and alignment 1 are ABI-compatible.", including tuples and +// arrays of them, `repr(transparent)` wrappers of them, and `!`. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_a(_: ()) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_b(_: Unit) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_c(_: PhantomData) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_d(_: [u8; 0]) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_e(_: OneVariant) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_f(_: ((), PhantomData)) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_g(_: [(); 3]) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_h(_: TrivialWrapper) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn z1_i(_: !) {} +//~^ ERROR encoding: "FvvE" +//~| ERROR hash: 61000 (0xee48) + +// 1.5 "A repr(transparent) type T is ABI-compatible with its unique non-trivial field", and +// "i32 is ABI-compatible with NonZero, and similar for all other integer types." +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn w1_a(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn w1_b(_: Wrapper) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn w1_c(_: WrapperWithZst) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn w1_d(_: NonZero) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) + +// 1.6 "If T is guaranteed to be subject to the null pointer optimization, and E is an enum +// satisfying the following requirements, then T and E are ABI-compatible." (option-like enums) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn o1_a(_: Option<&i32>) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn o1_b(_: Option>) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn o1_c(_: MyOption>) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn o1_d(_: Option>) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn o1_e(_: Option) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) + +// 1.6 (continued) The same for an integer `T`. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn o2_a(_: NonZero) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn o2_b(_: Option>) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) + +// 1.7 "Any two fn (function pointer) types are ABI-compatible with each other if they have the +// same ABI string or the ABI string only differs in a trailing -unwind, independent of the rest of +// their signature." This is about passing function pointers as values. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn f1_a(_: fn()) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn f1_b(_: fn(i32) -> i32) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn f1_c(_: extern "C" fn()) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn f1_d(_: extern "C-unwind" fn(i32)) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) + +// 1.8 Return position: trivial-ABI return types, including `!`, are ABI-compatible with `()`. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r1_a() {} +//~^ ERROR encoding: "FvE" +//~| ERROR hash: 18983 (0x4a27) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r1_b() -> () {} +//~^ ERROR encoding: "FvE" +//~| ERROR hash: 18983 (0x4a27) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r1_c() -> ! { loop {} } +//~^ ERROR encoding: "FvE" +//~| ERROR hash: 18983 (0x4a27) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r1_d() -> Unit { Unit } +//~^ ERROR encoding: "FvE" +//~| ERROR hash: 18983 (0x4a27) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r1_e() -> PhantomData { PhantomData } +//~^ ERROR encoding: "FvE" +//~| ERROR hash: 18983 (0x4a27) + +// 1.8 (continued) Pointer-like return types. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r2_a() -> *const i32 { std::ptr::null() } +//~^ ERROR encoding: "FPE" +//~| ERROR hash: 34128 (0x8550) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r2_b() -> Option<&'static i32> { None } +//~^ ERROR encoding: "FPE" +//~| ERROR hash: 34128 (0x8550) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r2_c() -> Option> { None } +//~^ ERROR encoding: "FPE" +//~| ERROR hash: 34128 (0x8550) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r2_d() -> Option> { None } +//~^ ERROR encoding: "FPE" +//~| ERROR hash: 34128 (0x8550) + +// 1.8 (continued) Integer-like return types. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r3_a() -> u32 { 0 } +//~^ ERROR encoding: "FiE" +//~| ERROR hash: 42271 (0xa51f) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r3_b() -> char { 'a' } +//~^ ERROR encoding: "FiE" +//~| ERROR hash: 42271 (0xa51f) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn r3_c() -> NonZero { NonZero::new(1).unwrap() } +//~^ ERROR encoding: "FiE" +//~| ERROR hash: 42271 (0xa51f) + +// 1.9 ABI strings: a trailing `-unwind` does not matter. `"system"` is `"C"` on this target. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn a1_a(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C-unwind" fn a1_b(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "system" fn a1_c(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "system-unwind" fn a1_d(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) + +// 1.10 `unsafe` is not part of the ABI. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn s1_a(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +unsafe extern "C" fn s1_b(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) + +// 2. Not ABI-compatible types, but with equal discriminators, because the Clang encoding is coarser +// than Rust's rules, for example: every integer type encodes as `i`. These MUST match to match +// Clang. A failure here breaks interoperability with C. + +// 2.1 Clang encodes every integer type, `bool` and `char` as `i`, whatever its size. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c1_a(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c1_b(_: bool) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c1_c(_: u8) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c1_d(_: i16) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c1_e(_: NonZero) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) + +// 2.2 Every pointer-like type encodes as `P`, whatever its metadata: C has no wide pointers. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c2_a(_: *const i32) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c2_b(_: *const [i32]) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) + +// 2.3 Arrays are encoded without their length. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c3_a(_: [i32; 4]) {} +//~^ ERROR encoding: "FvAiE" +//~| ERROR hash: 35183 (0x896f) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c3_b(_: [i32; 8]) {} +//~^ ERROR encoding: "FvAiE" +//~| ERROR hash: 35183 (0x896f) + +// 2.4 Structs are encoded by name only, so two different structs with the same name collide. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c4_a(_: m1::S) {} +//~^ ERROR encoding: "Fv1SE" +//~| ERROR hash: 61901 (0xf1cd) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn c4_b(_: m2::S) {} +//~^ ERROR encoding: "Fv1SE" +//~| ERROR hash: 61901 (0xf1cd) + +// 3. Types that are not ABI-compatible, and distinct. Calls through these signatures are UB; +// distinct discriminators are what makes such a call trap. + +// 3.1 Different signatures. In particular, a `fn(i32)` called through `fn()` traps. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn d1_a() {} +//~^ ERROR encoding: "FvE" +//~| ERROR hash: 18983 (0x4a27) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn d1_b(_: i32) {} +//~^ ERROR encoding: "FviE" +//~| ERROR hash: 2712 (0xa98) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn d1_c() -> i32 { 0 } +//~^ ERROR encoding: "FiE" +//~| ERROR hash: 42271 (0xa51f) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn d1_d(_: *const i32) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn d1_e(_: f32) {} +//~^ ERROR encoding: "FvfE" +//~| ERROR hash: 21613 (0x546d) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn d1_f(_: f64) {} +//~^ ERROR encoding: "FvdE" +//~| ERROR hash: 7718 (0x1e26) + +// 3.2 Near misses of the rules in section 1. Each is distinct from the group it resembles: +// * `Box` with an allocator other than `Global` (1.1); +// * a ZST with alignment 4 (1.4); +// * a non-transparent wrapper (1.5); +// * `Option`, which has no niche (1.6); +// * `Option<*mut T>`, as a raw pointer has no niche (1.6) +// * an enum whose niche variant has a second field (1.6); +// * an enum with more than two variants (1.6). +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn n1_a(_: Box) {} +//~^ ERROR encoding: "Fv3BoxE" +//~| ERROR hash: 3916 (0xf4c) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn n1_b(_: AlignedMarker) {} +//~^ ERROR encoding: "Fv13AlignedMarkerE" +//~| ERROR hash: 49590 (0xc1b6) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn n1_c(_: NotTransparent) {} +//~^ ERROR encoding: "Fv14NotTransparentE" +//~| ERROR hash: 37756 (0x937c) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn n1_d(_: Option) {} +//~^ ERROR encoding: "Fv6OptionE" +//~| ERROR hash: 20395 (0x4fab) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn n1_e(_: Option<*mut i32>) {} +//~^ ERROR encoding: "Fv6OptionE" +//~| ERROR hash: 20395 (0x4fab) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn n1_f(_: WithExtraField) {} +//~^ ERROR encoding: "Fv14WithExtraFieldE" +//~| ERROR hash: 34575 (0x870f) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn n1_g(_: ThreeVariants) {} +//~^ ERROR encoding: "Fv13ThreeVariantsE" +//~| ERROR hash: 9871 (0x268f) + +// 3.3 Only an `Option` with the layout of its payload is peeled. `Option` has the layout of +// `fn()` (group 1.6), but it uses up the niche of the function pointer, so `Option>` +// needs a tag. It is not ABI-compatible with `fn()`. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn q1_a(_: Option) {} +//~^ ERROR encoding: "FvPE" +//~| ERROR hash: 10942 (0x2abe) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding, ptrauth_hash)] +extern "C" fn q1_b(_: Option>) {} +//~^ ERROR encoding: "Fv6OptionE" +//~| ERROR hash: 20395 (0x4fab) diff --git a/tests/ui/pointer_authentication/discriminator-abi-compat.stderr b/tests/ui/pointer_authentication/discriminator-abi-compat.stderr new file mode 100644 index 0000000000000..c590bac62e4bd --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-abi-compat.stderr @@ -0,0 +1,1022 @@ +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:107:1 + | +LL | extern "C" fn p1_a(_: *const i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:107:1 + | +LL | extern "C" fn p1_a(_: *const i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:111:1 + | +LL | extern "C" fn p1_b(_: *mut i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:111:1 + | +LL | extern "C" fn p1_b(_: *mut i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:115:1 + | +LL | extern "C" fn p1_c(_: &i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:115:1 + | +LL | extern "C" fn p1_c(_: &i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:119:1 + | +LL | extern "C" fn p1_d(_: &mut i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:119:1 + | +LL | extern "C" fn p1_d(_: &mut i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:123:1 + | +LL | extern "C" fn p1_e(_: Box) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:123:1 + | +LL | extern "C" fn p1_e(_: Box) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:127:1 + | +LL | extern "C" fn p1_f(_: NonNull) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:127:1 + | +LL | extern "C" fn p1_f(_: NonNull) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:131:1 + | +LL | extern "C" fn p1_g(_: *const SomeStruct) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:131:1 + | +LL | extern "C" fn p1_g(_: *const SomeStruct) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:137:1 + | +LL | extern "C" fn p2_a(_: *const [i32]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:137:1 + | +LL | extern "C" fn p2_a(_: *const [i32]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:141:1 + | +LL | extern "C" fn p2_b(_: &[u8]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:141:1 + | +LL | extern "C" fn p2_b(_: &[u8]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:145:1 + | +LL | extern "C" fn p2_c(_: *const str) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:145:1 + | +LL | extern "C" fn p2_c(_: *const str) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:149:1 + | +LL | extern "C" fn p2_d(_: Box<[u16]>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:149:1 + | +LL | extern "C" fn p2_d(_: Box<[u16]>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:157:1 + | +LL | extern "C" fn i1_a(_: usize) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:157:1 + | +LL | extern "C" fn i1_a(_: usize) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:161:1 + | +LL | extern "C" fn i1_b(_: u64) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:161:1 + | +LL | extern "C" fn i1_b(_: u64) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:165:1 + | +LL | extern "C" fn i1_c(_: isize) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:165:1 + | +LL | extern "C" fn i1_c(_: isize) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:169:1 + | +LL | extern "C" fn i1_d(_: i64) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:169:1 + | +LL | extern "C" fn i1_d(_: i64) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:173:1 + | +LL | extern "C" fn i1_e(_: char) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:173:1 + | +LL | extern "C" fn i1_e(_: char) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:177:1 + | +LL | extern "C" fn i1_f(_: u32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:177:1 + | +LL | extern "C" fn i1_f(_: u32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:184:1 + | +LL | extern "C" fn z1_a(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:184:1 + | +LL | extern "C" fn z1_a(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:188:1 + | +LL | extern "C" fn z1_b(_: Unit) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:188:1 + | +LL | extern "C" fn z1_b(_: Unit) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:192:1 + | +LL | extern "C" fn z1_c(_: PhantomData) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:192:1 + | +LL | extern "C" fn z1_c(_: PhantomData) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:196:1 + | +LL | extern "C" fn z1_d(_: [u8; 0]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:196:1 + | +LL | extern "C" fn z1_d(_: [u8; 0]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:200:1 + | +LL | extern "C" fn z1_e(_: OneVariant) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:200:1 + | +LL | extern "C" fn z1_e(_: OneVariant) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:204:1 + | +LL | extern "C" fn z1_f(_: ((), PhantomData)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:204:1 + | +LL | extern "C" fn z1_f(_: ((), PhantomData)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:208:1 + | +LL | extern "C" fn z1_g(_: [(); 3]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:208:1 + | +LL | extern "C" fn z1_g(_: [(); 3]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:212:1 + | +LL | extern "C" fn z1_h(_: TrivialWrapper) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:212:1 + | +LL | extern "C" fn z1_h(_: TrivialWrapper) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvvE" + --> $DIR/discriminator-abi-compat.rs:216:1 + | +LL | extern "C" fn z1_i(_: !) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61000 (0xee48) + --> $DIR/discriminator-abi-compat.rs:216:1 + | +LL | extern "C" fn z1_i(_: !) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:223:1 + | +LL | extern "C" fn w1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:223:1 + | +LL | extern "C" fn w1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:227:1 + | +LL | extern "C" fn w1_b(_: Wrapper) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:227:1 + | +LL | extern "C" fn w1_b(_: Wrapper) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:231:1 + | +LL | extern "C" fn w1_c(_: WrapperWithZst) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:231:1 + | +LL | extern "C" fn w1_c(_: WrapperWithZst) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:235:1 + | +LL | extern "C" fn w1_d(_: NonZero) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:235:1 + | +LL | extern "C" fn w1_d(_: NonZero) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:242:1 + | +LL | extern "C" fn o1_a(_: Option<&i32>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:242:1 + | +LL | extern "C" fn o1_a(_: Option<&i32>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:246:1 + | +LL | extern "C" fn o1_b(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:246:1 + | +LL | extern "C" fn o1_b(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:250:1 + | +LL | extern "C" fn o1_c(_: MyOption>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:250:1 + | +LL | extern "C" fn o1_c(_: MyOption>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:254:1 + | +LL | extern "C" fn o1_d(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:254:1 + | +LL | extern "C" fn o1_d(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:258:1 + | +LL | extern "C" fn o1_e(_: Option) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:258:1 + | +LL | extern "C" fn o1_e(_: Option) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:264:1 + | +LL | extern "C" fn o2_a(_: NonZero) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:264:1 + | +LL | extern "C" fn o2_a(_: NonZero) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:268:1 + | +LL | extern "C" fn o2_b(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:268:1 + | +LL | extern "C" fn o2_b(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:276:1 + | +LL | extern "C" fn f1_a(_: fn()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:276:1 + | +LL | extern "C" fn f1_a(_: fn()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:280:1 + | +LL | extern "C" fn f1_b(_: fn(i32) -> i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:280:1 + | +LL | extern "C" fn f1_b(_: fn(i32) -> i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:284:1 + | +LL | extern "C" fn f1_c(_: extern "C" fn()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:284:1 + | +LL | extern "C" fn f1_c(_: extern "C" fn()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:288:1 + | +LL | extern "C" fn f1_d(_: extern "C-unwind" fn(i32)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:288:1 + | +LL | extern "C" fn f1_d(_: extern "C-unwind" fn(i32)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvE" + --> $DIR/discriminator-abi-compat.rs:294:1 + | +LL | extern "C" fn r1_a() {} + | ^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 18983 (0x4a27) + --> $DIR/discriminator-abi-compat.rs:294:1 + | +LL | extern "C" fn r1_a() {} + | ^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvE" + --> $DIR/discriminator-abi-compat.rs:298:1 + | +LL | extern "C" fn r1_b() -> () {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 18983 (0x4a27) + --> $DIR/discriminator-abi-compat.rs:298:1 + | +LL | extern "C" fn r1_b() -> () {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvE" + --> $DIR/discriminator-abi-compat.rs:302:1 + | +LL | extern "C" fn r1_c() -> ! { loop {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 18983 (0x4a27) + --> $DIR/discriminator-abi-compat.rs:302:1 + | +LL | extern "C" fn r1_c() -> ! { loop {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvE" + --> $DIR/discriminator-abi-compat.rs:306:1 + | +LL | extern "C" fn r1_d() -> Unit { Unit } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 18983 (0x4a27) + --> $DIR/discriminator-abi-compat.rs:306:1 + | +LL | extern "C" fn r1_d() -> Unit { Unit } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvE" + --> $DIR/discriminator-abi-compat.rs:310:1 + | +LL | extern "C" fn r1_e() -> PhantomData { PhantomData } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 18983 (0x4a27) + --> $DIR/discriminator-abi-compat.rs:310:1 + | +LL | extern "C" fn r1_e() -> PhantomData { PhantomData } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FPE" + --> $DIR/discriminator-abi-compat.rs:316:1 + | +LL | extern "C" fn r2_a() -> *const i32 { std::ptr::null() } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 34128 (0x8550) + --> $DIR/discriminator-abi-compat.rs:316:1 + | +LL | extern "C" fn r2_a() -> *const i32 { std::ptr::null() } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FPE" + --> $DIR/discriminator-abi-compat.rs:320:1 + | +LL | extern "C" fn r2_b() -> Option<&'static i32> { None } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 34128 (0x8550) + --> $DIR/discriminator-abi-compat.rs:320:1 + | +LL | extern "C" fn r2_b() -> Option<&'static i32> { None } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FPE" + --> $DIR/discriminator-abi-compat.rs:324:1 + | +LL | extern "C" fn r2_c() -> Option> { None } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 34128 (0x8550) + --> $DIR/discriminator-abi-compat.rs:324:1 + | +LL | extern "C" fn r2_c() -> Option> { None } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FPE" + --> $DIR/discriminator-abi-compat.rs:328:1 + | +LL | extern "C" fn r2_d() -> Option> { None } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 34128 (0x8550) + --> $DIR/discriminator-abi-compat.rs:328:1 + | +LL | extern "C" fn r2_d() -> Option> { None } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FiE" + --> $DIR/discriminator-abi-compat.rs:334:1 + | +LL | extern "C" fn r3_a() -> u32 { 0 } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 42271 (0xa51f) + --> $DIR/discriminator-abi-compat.rs:334:1 + | +LL | extern "C" fn r3_a() -> u32 { 0 } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FiE" + --> $DIR/discriminator-abi-compat.rs:338:1 + | +LL | extern "C" fn r3_b() -> char { 'a' } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 42271 (0xa51f) + --> $DIR/discriminator-abi-compat.rs:338:1 + | +LL | extern "C" fn r3_b() -> char { 'a' } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FiE" + --> $DIR/discriminator-abi-compat.rs:342:1 + | +LL | extern "C" fn r3_c() -> NonZero { NonZero::new(1).unwrap() } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 42271 (0xa51f) + --> $DIR/discriminator-abi-compat.rs:342:1 + | +LL | extern "C" fn r3_c() -> NonZero { NonZero::new(1).unwrap() } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:348:1 + | +LL | extern "C" fn a1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:348:1 + | +LL | extern "C" fn a1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:352:1 + | +LL | extern "C-unwind" fn a1_b(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:352:1 + | +LL | extern "C-unwind" fn a1_b(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:356:1 + | +LL | extern "system" fn a1_c(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:356:1 + | +LL | extern "system" fn a1_c(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:360:1 + | +LL | extern "system-unwind" fn a1_d(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:360:1 + | +LL | extern "system-unwind" fn a1_d(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:366:1 + | +LL | extern "C" fn s1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:366:1 + | +LL | extern "C" fn s1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:370:1 + | +LL | unsafe extern "C" fn s1_b(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:370:1 + | +LL | unsafe extern "C" fn s1_b(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:380:1 + | +LL | extern "C" fn c1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:380:1 + | +LL | extern "C" fn c1_a(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:384:1 + | +LL | extern "C" fn c1_b(_: bool) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:384:1 + | +LL | extern "C" fn c1_b(_: bool) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:388:1 + | +LL | extern "C" fn c1_c(_: u8) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:388:1 + | +LL | extern "C" fn c1_c(_: u8) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:392:1 + | +LL | extern "C" fn c1_d(_: i16) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:392:1 + | +LL | extern "C" fn c1_d(_: i16) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:396:1 + | +LL | extern "C" fn c1_e(_: NonZero) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:396:1 + | +LL | extern "C" fn c1_e(_: NonZero) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:402:1 + | +LL | extern "C" fn c2_a(_: *const i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:402:1 + | +LL | extern "C" fn c2_a(_: *const i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:406:1 + | +LL | extern "C" fn c2_b(_: *const [i32]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:406:1 + | +LL | extern "C" fn c2_b(_: *const [i32]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvAiE" + --> $DIR/discriminator-abi-compat.rs:412:1 + | +LL | extern "C" fn c3_a(_: [i32; 4]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 35183 (0x896f) + --> $DIR/discriminator-abi-compat.rs:412:1 + | +LL | extern "C" fn c3_a(_: [i32; 4]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvAiE" + --> $DIR/discriminator-abi-compat.rs:416:1 + | +LL | extern "C" fn c3_b(_: [i32; 8]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 35183 (0x896f) + --> $DIR/discriminator-abi-compat.rs:416:1 + | +LL | extern "C" fn c3_b(_: [i32; 8]) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv1SE" + --> $DIR/discriminator-abi-compat.rs:422:1 + | +LL | extern "C" fn c4_a(_: m1::S) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61901 (0xf1cd) + --> $DIR/discriminator-abi-compat.rs:422:1 + | +LL | extern "C" fn c4_a(_: m1::S) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv1SE" + --> $DIR/discriminator-abi-compat.rs:426:1 + | +LL | extern "C" fn c4_b(_: m2::S) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 61901 (0xf1cd) + --> $DIR/discriminator-abi-compat.rs:426:1 + | +LL | extern "C" fn c4_b(_: m2::S) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvE" + --> $DIR/discriminator-abi-compat.rs:435:1 + | +LL | extern "C" fn d1_a() {} + | ^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 18983 (0x4a27) + --> $DIR/discriminator-abi-compat.rs:435:1 + | +LL | extern "C" fn d1_a() {} + | ^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FviE" + --> $DIR/discriminator-abi-compat.rs:439:1 + | +LL | extern "C" fn d1_b(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 2712 (0xa98) + --> $DIR/discriminator-abi-compat.rs:439:1 + | +LL | extern "C" fn d1_b(_: i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FiE" + --> $DIR/discriminator-abi-compat.rs:443:1 + | +LL | extern "C" fn d1_c() -> i32 { 0 } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 42271 (0xa51f) + --> $DIR/discriminator-abi-compat.rs:443:1 + | +LL | extern "C" fn d1_c() -> i32 { 0 } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:447:1 + | +LL | extern "C" fn d1_d(_: *const i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:447:1 + | +LL | extern "C" fn d1_d(_: *const i32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvfE" + --> $DIR/discriminator-abi-compat.rs:451:1 + | +LL | extern "C" fn d1_e(_: f32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 21613 (0x546d) + --> $DIR/discriminator-abi-compat.rs:451:1 + | +LL | extern "C" fn d1_e(_: f32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvdE" + --> $DIR/discriminator-abi-compat.rs:455:1 + | +LL | extern "C" fn d1_f(_: f64) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 7718 (0x1e26) + --> $DIR/discriminator-abi-compat.rs:455:1 + | +LL | extern "C" fn d1_f(_: f64) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv3BoxE" + --> $DIR/discriminator-abi-compat.rs:468:1 + | +LL | extern "C" fn n1_a(_: Box) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 3916 (0xf4c) + --> $DIR/discriminator-abi-compat.rs:468:1 + | +LL | extern "C" fn n1_a(_: Box) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv13AlignedMarkerE" + --> $DIR/discriminator-abi-compat.rs:472:1 + | +LL | extern "C" fn n1_b(_: AlignedMarker) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 49590 (0xc1b6) + --> $DIR/discriminator-abi-compat.rs:472:1 + | +LL | extern "C" fn n1_b(_: AlignedMarker) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv14NotTransparentE" + --> $DIR/discriminator-abi-compat.rs:476:1 + | +LL | extern "C" fn n1_c(_: NotTransparent) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 37756 (0x937c) + --> $DIR/discriminator-abi-compat.rs:476:1 + | +LL | extern "C" fn n1_c(_: NotTransparent) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv6OptionE" + --> $DIR/discriminator-abi-compat.rs:480:1 + | +LL | extern "C" fn n1_d(_: Option) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 20395 (0x4fab) + --> $DIR/discriminator-abi-compat.rs:480:1 + | +LL | extern "C" fn n1_d(_: Option) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv6OptionE" + --> $DIR/discriminator-abi-compat.rs:484:1 + | +LL | extern "C" fn n1_e(_: Option<*mut i32>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 20395 (0x4fab) + --> $DIR/discriminator-abi-compat.rs:484:1 + | +LL | extern "C" fn n1_e(_: Option<*mut i32>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv14WithExtraFieldE" + --> $DIR/discriminator-abi-compat.rs:488:1 + | +LL | extern "C" fn n1_f(_: WithExtraField) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 34575 (0x870f) + --> $DIR/discriminator-abi-compat.rs:488:1 + | +LL | extern "C" fn n1_f(_: WithExtraField) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv13ThreeVariantsE" + --> $DIR/discriminator-abi-compat.rs:492:1 + | +LL | extern "C" fn n1_g(_: ThreeVariants) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 9871 (0x268f) + --> $DIR/discriminator-abi-compat.rs:492:1 + | +LL | extern "C" fn n1_g(_: ThreeVariants) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvPE" + --> $DIR/discriminator-abi-compat.rs:500:1 + | +LL | extern "C" fn q1_a(_: Option) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 10942 (0x2abe) + --> $DIR/discriminator-abi-compat.rs:500:1 + | +LL | extern "C" fn q1_a(_: Option) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv6OptionE" + --> $DIR/discriminator-abi-compat.rs:504:1 + | +LL | extern "C" fn q1_b(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator hash: 20395 (0x4fab) + --> $DIR/discriminator-abi-compat.rs:504:1 + | +LL | extern "C" fn q1_b(_: Option>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 170 previous errors + diff --git a/tests/ui/pointer_authentication/discriminator-complex-encoding.aarch64_darwin.stderr b/tests/ui/pointer_authentication/discriminator-complex-encoding.aarch64_darwin.stderr new file mode 100644 index 0000000000000..7036457ec3390 --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-complex-encoding.aarch64_darwin.stderr @@ -0,0 +1,56 @@ +error: ptrauth discriminator encoding: "FvCfE" + --> $DIR/discriminator-complex-encoding.rs:40:1 + | +LL | extern "C" fn cf(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCdE" + --> $DIR/discriminator-complex-encoding.rs:44:1 + | +LL | extern "C" fn cd(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCiE" + --> $DIR/discriminator-complex-encoding.rs:48:1 + | +LL | extern "C" fn ci(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCDF16_E" + --> $DIR/discriminator-complex-encoding.rs:52:1 + | +LL | extern "C" fn ret_ch() -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCgE" + --> $DIR/discriminator-complex-encoding.rs:58:1 + | +LL | extern "C" fn ret_cq() -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCdCfE" + --> $DIR/discriminator-complex-encoding.rs:64:1 + | +LL | extern "C" fn cf_to_cd(_: Complex) -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCfCiCdE" + --> $DIR/discriminator-complex-encoding.rs:70:1 + | +LL | extern "C" fn mixed(_: Complex, _: Complex, _: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCfE" + --> $DIR/discriminator-complex-encoding.rs:74:1 + | +LL | extern "C" fn wrap(_: Wrap) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv7ComplexE" + --> $DIR/discriminator-complex-encoding.rs:78:1 + | +LL | extern "C" fn user_complex(_: user::Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 9 previous errors + diff --git a/tests/ui/pointer_authentication/discriminator-complex-encoding.aarch64_linux.stderr b/tests/ui/pointer_authentication/discriminator-complex-encoding.aarch64_linux.stderr new file mode 100644 index 0000000000000..a3c7c782445e0 --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-complex-encoding.aarch64_linux.stderr @@ -0,0 +1,56 @@ +error: ptrauth discriminator encoding: "FvCfE" + --> $DIR/discriminator-complex-encoding.rs:40:1 + | +LL | extern "C" fn cf(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCdE" + --> $DIR/discriminator-complex-encoding.rs:44:1 + | +LL | extern "C" fn cd(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCiE" + --> $DIR/discriminator-complex-encoding.rs:48:1 + | +LL | extern "C" fn ci(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCDF16_E" + --> $DIR/discriminator-complex-encoding.rs:52:1 + | +LL | extern "C" fn ret_ch() -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCeE" + --> $DIR/discriminator-complex-encoding.rs:58:1 + | +LL | extern "C" fn ret_cq() -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCdCfE" + --> $DIR/discriminator-complex-encoding.rs:64:1 + | +LL | extern "C" fn cf_to_cd(_: Complex) -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCfCiCdE" + --> $DIR/discriminator-complex-encoding.rs:70:1 + | +LL | extern "C" fn mixed(_: Complex, _: Complex, _: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCfE" + --> $DIR/discriminator-complex-encoding.rs:74:1 + | +LL | extern "C" fn wrap(_: Wrap) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv7ComplexE" + --> $DIR/discriminator-complex-encoding.rs:78:1 + | +LL | extern "C" fn user_complex(_: user::Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 9 previous errors + diff --git a/tests/ui/pointer_authentication/discriminator-complex-encoding.rs b/tests/ui/pointer_authentication/discriminator-complex-encoding.rs new file mode 100644 index 0000000000000..bdfc3853551c3 --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-complex-encoding.rs @@ -0,0 +1,78 @@ +//@ add-minicore +//@ revisions: aarch64_linux aarch64_darwin x86_64_linux +//@ [aarch64_linux] compile-flags: --target aarch64-unknown-linux-pauthtest +//@ [aarch64_linux] needs-llvm-components: aarch64 +//@ [aarch64_darwin] compile-flags: --target aarch64-apple-darwin +//@ [aarch64_darwin] needs-llvm-components: aarch64 +//@ [x86_64_linux] compile-flags: --target x86_64-unknown-linux-gnu +//@ [x86_64_linux] needs-llvm-components: x86 +//@ dont-require-annotations: ERROR + +// Test for `core::num::Complex` in the discriminator encoding. +// +// Clang's `encodeTypeForFunctionPointerAuth` encodes C `_Complex T` as `C` followed by the encoding +// of `T`. `Complex` follows the rule from `discriminator-float-encoding.rs`: `Ce` on AArch64 +// Linux, `Cg` elsewhere. + +#![crate_type = "lib"] +#![feature(no_core, rustc_attrs, f16, f128)] +#![no_core] +#![allow(improper_ctypes_definitions)] + +extern crate minicore; +use minicore::num::Complex; + +// A `repr(transparent)` wrapper encodes as its field. +#[repr(transparent)] +pub struct Wrap(Complex); + +// An ordinary `repr(C)` struct that happens to be named `Complex`: not `_Complex`. +pub mod user { + #[repr(C)] + pub struct Complex { + pub re: f32, + pub im: f32, + } +} + +// C: void (*)(float _Complex) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn cf(_: Complex) {} + +// C: void (*)(double _Complex) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn cd(_: Complex) {} + +// C: void (*)(int _Complex) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn ci(_: Complex) {} + +// C: _Float16 _Complex (*)(void) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn ret_ch() -> Complex { + loop {} +} + +// C: long double _Complex (*)(void) on AArch64 Linux, __float128 _Complex (*)(void) elsewhere +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn ret_cq() -> Complex { + loop {} +} + +// C: double _Complex (*)(float _Complex) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn cf_to_cd(_: Complex) -> Complex { + loop {} +} + +// C: void (*)(float _Complex, int _Complex, double _Complex) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn mixed(_: Complex, _: Complex, _: Complex) {} + +// Same as `cf`. +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn wrap(_: Wrap) {} + +// C: struct Complex { float re, im; }; void (*)(struct Complex) +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn user_complex(_: user::Complex) {} diff --git a/tests/ui/pointer_authentication/discriminator-complex-encoding.x86_64_linux.stderr b/tests/ui/pointer_authentication/discriminator-complex-encoding.x86_64_linux.stderr new file mode 100644 index 0000000000000..7036457ec3390 --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-complex-encoding.x86_64_linux.stderr @@ -0,0 +1,56 @@ +error: ptrauth discriminator encoding: "FvCfE" + --> $DIR/discriminator-complex-encoding.rs:40:1 + | +LL | extern "C" fn cf(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCdE" + --> $DIR/discriminator-complex-encoding.rs:44:1 + | +LL | extern "C" fn cd(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCiE" + --> $DIR/discriminator-complex-encoding.rs:48:1 + | +LL | extern "C" fn ci(_: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCDF16_E" + --> $DIR/discriminator-complex-encoding.rs:52:1 + | +LL | extern "C" fn ret_ch() -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCgE" + --> $DIR/discriminator-complex-encoding.rs:58:1 + | +LL | extern "C" fn ret_cq() -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FCdCfE" + --> $DIR/discriminator-complex-encoding.rs:64:1 + | +LL | extern "C" fn cf_to_cd(_: Complex) -> Complex { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCfCiCdE" + --> $DIR/discriminator-complex-encoding.rs:70:1 + | +LL | extern "C" fn mixed(_: Complex, _: Complex, _: Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FvCfE" + --> $DIR/discriminator-complex-encoding.rs:74:1 + | +LL | extern "C" fn wrap(_: Wrap) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "Fv7ComplexE" + --> $DIR/discriminator-complex-encoding.rs:78:1 + | +LL | extern "C" fn user_complex(_: user::Complex) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 9 previous errors + diff --git a/tests/ui/pointer_authentication/discriminator-float-encoding.aarch64_darwin.stderr b/tests/ui/pointer_authentication/discriminator-float-encoding.aarch64_darwin.stderr new file mode 100644 index 0000000000000..3c64787d13875 --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-float-encoding.aarch64_darwin.stderr @@ -0,0 +1,14 @@ +error: ptrauth discriminator encoding: "FDF16_DF16_E" + --> $DIR/discriminator-float-encoding.rs:27:1 + | +LL | extern "C" fn half(x: f16) -> f16 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FggE" + --> $DIR/discriminator-float-encoding.rs:32:1 + | +LL | extern "C" fn quad(x: f128) -> f128 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/pointer_authentication/discriminator-float-encoding.aarch64_linux.stderr b/tests/ui/pointer_authentication/discriminator-float-encoding.aarch64_linux.stderr new file mode 100644 index 0000000000000..ad6e8d7e8b383 --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-float-encoding.aarch64_linux.stderr @@ -0,0 +1,14 @@ +error: ptrauth discriminator encoding: "FDF16_DF16_E" + --> $DIR/discriminator-float-encoding.rs:27:1 + | +LL | extern "C" fn half(x: f16) -> f16 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FeeE" + --> $DIR/discriminator-float-encoding.rs:32:1 + | +LL | extern "C" fn quad(x: f128) -> f128 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/pointer_authentication/discriminator-float-encoding.rs b/tests/ui/pointer_authentication/discriminator-float-encoding.rs new file mode 100644 index 0000000000000..390937d569b3a --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-float-encoding.rs @@ -0,0 +1,34 @@ +//@ add-minicore +//@ revisions: aarch64_linux aarch64_darwin x86_64_linux +//@ [aarch64_linux] compile-flags: --target aarch64-unknown-linux-pauthtest +//@ [aarch64_linux] needs-llvm-components: aarch64 +//@ [aarch64_darwin] compile-flags: --target aarch64-apple-darwin +//@ [aarch64_darwin] needs-llvm-components: aarch64 +//@ [x86_64_linux] compile-flags: --target x86_64-unknown-linux-gnu +//@ [x86_64_linux] needs-llvm-components: x86 +//@ dont-require-annotations: ERROR + +// Test for 16 and 128 bit wide floating-point types in the discriminator encoding. +// +// Clang's `encodeTypeForFunctionPointerAuth` uses Itanium type codes: +// * `_Float16` is `DF16_` +// * `f128` is the C type with its representation: `long double` (`e`) on +// AArch64 Linux, where `long double` is IEEE quad precision, and +// `__float128` (`g`) elsewhere. + +#![crate_type = "lib"] +#![feature(no_core, rustc_attrs, f16, f128)] +#![no_core] +#![allow(improper_ctypes_definitions)] + +extern crate minicore; + +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn half(x: f16) -> f16 { + x +} + +#[rustc_dump_ptrauth_discriminator(ptrauth_encoding)] +extern "C" fn quad(x: f128) -> f128 { + x +} diff --git a/tests/ui/pointer_authentication/discriminator-float-encoding.x86_64_linux.stderr b/tests/ui/pointer_authentication/discriminator-float-encoding.x86_64_linux.stderr new file mode 100644 index 0000000000000..3c64787d13875 --- /dev/null +++ b/tests/ui/pointer_authentication/discriminator-float-encoding.x86_64_linux.stderr @@ -0,0 +1,14 @@ +error: ptrauth discriminator encoding: "FDF16_DF16_E" + --> $DIR/discriminator-float-encoding.rs:27:1 + | +LL | extern "C" fn half(x: f16) -> f16 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: ptrauth discriminator encoding: "FggE" + --> $DIR/discriminator-float-encoding.rs:32:1 + | +LL | extern "C" fn quad(x: f128) -> f128 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/pointer_authentication/ptrauth-c-discriminator-misplaced.rs b/tests/ui/pointer_authentication/ptrauth-c-discriminator-misplaced.rs new file mode 100644 index 0000000000000..2d4add5294014 --- /dev/null +++ b/tests/ui/pointer_authentication/ptrauth-c-discriminator-misplaced.rs @@ -0,0 +1,55 @@ +//@ add-minicore +//@ build-fail +//@ compile-flags: --target=aarch64-unknown-linux-pauthtest --crate-type=lib -Zpointer-authentication=+function-pointer-type-discrimination +//@ needs-llvm-components: aarch64 +//@ ignore-backends: gcc +// ignore-tidy-linelength + +// `#[rustc_ptrauth_c_discriminator(N)]` marks a slot: a pointer, a pointer-sized integer, or an array of +// them. +// Error out if it is used on: +// * a static of any other type, +// * on a field of any other type, +// * on overlapping union fields with different discriminators. + +#![feature(no_core, ptrauth_c_discriminator)] +#![no_std] +#![no_core] +#![allow(dead_code)] + +extern crate minicore; +use minicore::*; + +extern "C" fn f() {} + +#[repr(C)] +pub struct Pair { + a: *const u8, + b: *const u8, +} + +#[used] +#[rustc_ptrauth_c_discriminator(0)] +static mut PAIR: Pair = Pair { a: f as *const u8, b: 0 as *const u8 }; +//~^ ERROR `#[rustc_ptrauth_c_discriminator]` on a static needs a pointer or a pointer-sized integer, or an array of them, not `Pair` + +pub struct Small { + #[rustc_ptrauth_c_discriminator(0)] + pub tag: u8, + //~^ ERROR `#[rustc_ptrauth_c_discriminator]` needs a field that is a pointer or a pointer-sized integer, or an array of them, not `u8` +} + +#[used] +static mut SMALL: Small = Small { tag: 1 }; + +#[repr(C)] +pub union Overlap { + #[rustc_ptrauth_c_discriminator(0)] + pub a: *const u8, + #[rustc_ptrauth_c_discriminator(1)] + pub b: *const u8, +} + +#[used] +static mut OVERLAP: Overlap = Overlap { a: f as *const u8 }; +//~^ ERROR fields marked `#[rustc_ptrauth_c_discriminator]` with different discriminators overlap at offset 0 diff --git a/tests/ui/pointer_authentication/ptrauth-c-discriminator-misplaced.stderr b/tests/ui/pointer_authentication/ptrauth-c-discriminator-misplaced.stderr new file mode 100644 index 0000000000000..e698f0edbfa39 --- /dev/null +++ b/tests/ui/pointer_authentication/ptrauth-c-discriminator-misplaced.stderr @@ -0,0 +1,22 @@ +error: `#[rustc_ptrauth_c_discriminator]` on a static needs a pointer or a pointer-sized integer, or an array of them, not `Pair` + --> $DIR/ptrauth-c-discriminator-misplaced.rs:33:1 + | +LL | static mut PAIR: Pair = Pair { a: f as *const u8, b: 0 as *const u8 }; + | ^^^^^^^^^^^^^^^^^^^^^ + | + = help: put `#[rustc_ptrauth_c_discriminator]` on the fields of `Pair` that hold code addresses instead + +error: `#[rustc_ptrauth_c_discriminator]` needs a field that is a pointer or a pointer-sized integer, or an array of them, not `u8` + --> $DIR/ptrauth-c-discriminator-misplaced.rs:38:5 + | +LL | pub tag: u8, + | ^^^^^^^^^^^ + +error: fields marked `#[rustc_ptrauth_c_discriminator]` with different discriminators overlap at offset 0 + --> $DIR/ptrauth-c-discriminator-misplaced.rs:54:1 + | +LL | static mut OVERLAP: Overlap = Overlap { a: f as *const u8 }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/tests/ui/pointer_authentication/ptrauth-c-discriminator-range.rs b/tests/ui/pointer_authentication/ptrauth-c-discriminator-range.rs new file mode 100644 index 0000000000000..e4559a8e3b9f5 --- /dev/null +++ b/tests/ui/pointer_authentication/ptrauth-c-discriminator-range.rs @@ -0,0 +1,9 @@ +// The discriminator of `#[rustc_ptrauth_c_discriminator]` is 16 bits wide. + +#![feature(ptrauth_c_discriminator)] +#![crate_type = "lib"] + +pub struct NativeMethod { + #[rustc_ptrauth_c_discriminator(65536)] //~ ERROR malformed `rustc_ptrauth_c_discriminator` attribute input + pub fn_ptr: *const u8, +} diff --git a/tests/ui/pointer_authentication/ptrauth-c-discriminator-range.stderr b/tests/ui/pointer_authentication/ptrauth-c-discriminator-range.stderr new file mode 100644 index 0000000000000..037fe372abfc5 --- /dev/null +++ b/tests/ui/pointer_authentication/ptrauth-c-discriminator-range.stderr @@ -0,0 +1,17 @@ +error[E0539]: malformed `rustc_ptrauth_c_discriminator` attribute input + --> $DIR/ptrauth-c-discriminator-range.rs:7:7 + | +LL | #[rustc_ptrauth_c_discriminator(65536)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----^ + | | + | expected an integer literal in the range of 0..=65535 + | +help: must be of the form + | +LL - #[rustc_ptrauth_c_discriminator(65536)] +LL + #[rustc_ptrauth_c_discriminator(discriminator)] + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0539`. diff --git a/tests/ui/pointer_authentication/type_discrimination_not_supported_pointer_authentication.rs b/tests/ui/pointer_authentication/type_discrimination_not_supported_pointer_authentication.rs deleted file mode 100644 index 03f811d0c4881..0000000000000 --- a/tests/ui/pointer_authentication/type_discrimination_not_supported_pointer_authentication.rs +++ /dev/null @@ -1,11 +0,0 @@ -//@ check-fail -//@ needs-llvm-components: aarch64 - -//@ compile-flags: -Zpointer-authentication=+function-pointer-type-discrimination --crate-type=lib --target aarch64-unknown-linux-pauthtest - -#![feature(no_core)] -#![no_std] -#![no_main] -#![no_core] - -//~? ERROR function pointer type discrimination is not supported diff --git a/tests/ui/pointer_authentication/type_discrimination_not_supported_pointer_authentication.stderr b/tests/ui/pointer_authentication/type_discrimination_not_supported_pointer_authentication.stderr deleted file mode 100644 index c040b0cb61f66..0000000000000 --- a/tests/ui/pointer_authentication/type_discrimination_not_supported_pointer_authentication.stderr +++ /dev/null @@ -1,4 +0,0 @@ -error: function pointer type discrimination is not supported - -error: aborting due to 1 previous error -