Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions compiler/rustc_attr_ir/src/attribute_docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down
14 changes: 14 additions & 0 deletions compiler/rustc_attr_ir/src/data_structures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<RustcDumpPtrauthDiscriminatorKind>),

/// Represents the [`rustc_dump_symbol_name`](./attribute.rustc_dump_symbol_name.html) attribute.
RustcDumpSymbolName(Span),

Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_attr_ir/src/encode_cross_crate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -144,6 +146,7 @@ impl AttributeKind {
RustcDumpItemBounds => No,
RustcDumpLayout(..) => No,
RustcDumpObjectLifetimeDefaults => No,
RustcDumpPtrauthDiscriminator(..) => No,
RustcDumpSymbolName(..) => Yes,
RustcDumpUserArgs => No,
RustcDumpVariances => No,
Expand Down Expand Up @@ -319,6 +322,7 @@ impl AttributeKind {
ProcMacroAttribute => false,
ProcMacroDerive { .. } => false,
ProfilerRuntime => false,
PtrauthCDiscriminator { .. } => false,
RecursionLimit { .. } => false,
ReexportTestHarnessMain(..) => false,
RegisterTool { .. } => false,
Expand Down Expand Up @@ -363,6 +367,7 @@ impl AttributeKind {
RustcDumpItemBounds => false,
RustcDumpLayout(..) => false,
RustcDumpObjectLifetimeDefaults => false,
RustcDumpPtrauthDiscriminator(..) => false,
RustcDumpSymbolName(..) => false,
RustcDumpUserArgs => false,
RustcDumpVariances => false,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/attributes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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<AttributeKind> {
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 })
}
}
54 changes: 53 additions & 1 deletion compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -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<Self::Item> =
|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<Item = Self::Item> {
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 {
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -197,6 +198,7 @@ attribute_parsers!(
Combine<RustcAllowConstFnUnstableParser>,
Combine<RustcCleanParser>,
Combine<RustcDumpLayoutParser>,
Combine<RustcDumpPtrauthDiscriminatorParser>,
Combine<RustcMirParser>,
Combine<RustcThenThisWouldNeedParser>,
Combine<TargetFeatureParser>,
Expand Down Expand Up @@ -230,6 +232,7 @@ attribute_parsers!(
Single<PathAttributeParser>,
Single<PatternComplexityLimitParser>,
Single<ProcMacroDeriveParser>,
Single<PtrauthCDiscriminatorParser>,
Single<RecursionLimitParser>,
Single<ReexportTestHarnessMainParser>,
Single<RustcAbiParser>,
Expand Down
15 changes: 15 additions & 0 deletions compiler/rustc_codegen_gcc/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_codegen_gcc/src/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down
43 changes: 33 additions & 10 deletions compiler/rustc_codegen_llvm/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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, '_> {
Expand Down Expand Up @@ -2156,11 +2184,9 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
) -> Option<llvm::OperandBundleBox<'ll>> {
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;
Expand All @@ -2175,10 +2201,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
// discussion in the rust-lang issue: <https://github.com/rust-lang/rust/issues/152532>
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)],
))
}

Expand Down
24 changes: 17 additions & 7 deletions compiler/rustc_codegen_llvm/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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)
}

/*
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading