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
6 changes: 4 additions & 2 deletions compiler/rustc_codegen_llvm/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use rustc_middle::mono::Visibility;
use rustc_middle::ty::TyCtxt;
use rustc_session::config::{DebugInfo, Offload};
use rustc_span::Symbol;
use rustc_target::spec::SanitizerSet;
use rustc_target::spec::{LlvmAbi, SanitizerSet};

use crate::builder::Builder;
use crate::builder::gpu_offload::OffloadGlobals;
Expand Down Expand Up @@ -163,7 +163,9 @@ pub(crate) fn compile_codegen_unit(
cx.add_objc_module_flags();
}

if cx.sess().pointer_authentication() {
if cx.sess().pointer_authentication()
&& cx.sess().target.llvm_abiname == LlvmAbi::Pauthtest
{
let cfg = cx.sess().pointer_auth_config.as_ref().unwrap();

let aarch64_elf_pauthabi_version =
Expand Down
19 changes: 9 additions & 10 deletions compiler/rustc_codegen_llvm/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2156,23 +2156,22 @@ 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 {
if self.sess().pointer_authentication_covers_all_abis() {
// A bare function symbol was never signed, so authenticating it would be invalid.
if !unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) } {
return None;
}
} else if fn_abi?.conv != CanonAbi::C {
return None;
}
// Filter out LLVM intrinsics.
if llvm::get_value_name(llfn).starts_with(b"llvm.") {
return None;
}

// FIXME(jchlanda) Operand bundles should only be attached to indirect function calls.
// However, function pointer signing is currently performed in `get_fn_addr`, which causes
// the logic to be applied too broadly, including to function values (not just pointers).
// As a result, direct calls using signed function values must also receive operand
// bundles.
// Once this is resolved, we should analyze each call and skip direct calls. See the
// discussion in the rust-lang issue: <https://github.com/rust-lang/rust/issues/152532>
// FIXME(jchlanda) The pauthtest ABI still signs known direct callees in `get_fn_addr`,
// so those calls must also receive operand bundles. See
// <https://github.com/rust-lang/rust/issues/152532>.
Some(llvm::OperandBundleBox::new(
"ptrauth",
&[
Expand Down
18 changes: 10 additions & 8 deletions compiler/rustc_codegen_llvm/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@ pub(crate) fn maybe_sign_fn_ptr<'ll, 'tcx>(
return llfn;
}

// Only free functions or methods
let def_id = instance.def_id();
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 { .. }) {
return llfn;
if !cx.sess().pointer_authentication_covers_all_abis() {
// Only free functions or methods
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 { .. }) {
return llfn;
}
}
// Ignore LLVM intrinsics
if llvm::get_value_name(llfn).starts_with(b"llvm.") {
Expand Down
9 changes: 6 additions & 3 deletions compiler/rustc_codegen_llvm/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use rustc_middle::mono::MonoItem;
use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
use rustc_middle::ty::{self, Instance};
use rustc_span::{Symbol, bug, span_bug};
use rustc_target::spec::Arch;
use rustc_target::spec::{Arch, BinaryFormat};
use tracing::{debug, instrument, trace};

use crate::common::CodegenCx;
Expand Down Expand Up @@ -166,7 +166,9 @@ fn codegen_static_initializer<'ll, 'tcx>(
.link_section
.map(|link_section| {
let s = link_section.as_str();
if s.starts_with(".init_array") || s.starts_with(".fini_array") {
if cx.sess().target.binary_format == BinaryFormat::Elf
&& (s.starts_with(".init_array") || s.starts_with(".fini_array"))
{
IsInitOrFini::Yes
} else {
IsInitOrFini::No
Expand Down Expand Up @@ -212,7 +214,8 @@ fn check_and_apply_linkage<'ll, 'tcx>(
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 { .. })
&& (cx.sess().pointer_authentication_covers_all_abis()
|| matches!(fn_sig.abi(), ExternAbi::C { .. } | ExternAbi::System { .. }))
{
should_sign = true;
}
Expand Down
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_llvm/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,20 @@ fn init_module<'ll, 'tcx>(tcx: TyCtxt<'tcx>, llcx: llvm::Context<'ll>, llmod: ll
}
}

if sess.target.is_arm64e_apple() {
// Match Clang's user-space ABI version so Apple-derived LLVMs emit versioned objects.
let version = cx.md_node_in_context(&[
llvm::LLVMValueAsMetadata(cx.get_const_i32(0)),
llvm::LLVMValueAsMetadata(cx.get_const_int(cx.type_i1(), 0)),
]);
llvm::add_module_flag_metadata(
llmod,
llvm::ModuleFlagMergeBehavior::AppendUnique,
"ptrauth.abi-version",
cx.md_node_in_context(&[version]),
);
}

// Pass on the control-flow protection flags to LLVM (equivalent to `-fcf-protection` in Clang).
if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
llvm::add_module_flag_u32(
Expand Down
8 changes: 8 additions & 0 deletions compiler/rustc_codegen_llvm/src/llvm/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2280,6 +2280,14 @@ unsafe extern "C" {
ValueLen: size_t,
);

pub(crate) fn LLVMRustAddModuleFlagMetadata<'ll>(
M: Module<'ll>,
MergeBehavior: ModuleFlagMergeBehavior,
Name: *const c_uchar, // See "PTR_LEN_STR".
NameLen: size_t,
Value: &'ll Metadata,
);

/// We can't use LLVM-C's `LLVMDIBuilderCreateCompileUnit` because it hardcodes
/// `DICompileUnit::DebugNameTableKind::Default`, but we want to be able to
/// pass other values.
Expand Down
11 changes: 11 additions & 0 deletions compiler/rustc_codegen_llvm/src/llvm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,17 @@ pub(crate) fn add_module_flag_str<'ll>(
}
}

pub(crate) fn add_module_flag_metadata<'ll>(
module: Module<'ll>,
merge_behavior: ModuleFlagMergeBehavior,
key: &str,
value: &'ll Metadata,
) {
unsafe {
LLVMRustAddModuleFlagMetadata(module, merge_behavior, key.as_ptr(), key.len(), value);
}
}

pub(crate) fn set_dllimport_storage_class<'ll>(v: Value<'ll>) {
unsafe {
LLVMSetDLLStorageClass(v, DLLStorageClass::DllImport);
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_ssa/src/back/apple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ pub(super) fn add_data_and_relocation(
target: &Target,
kind: SymbolExportKind,
) -> object::write::Result<()> {
let authenticated_pointer =
kind == SymbolExportKind::Text && target.llvm_target.starts_with("arm64e");
let authenticated_pointer = kind == SymbolExportKind::Text && target.is_arm64e_apple();

let data: &[u8] = match target.pointer_width {
_ if authenticated_pointer => &[0, 0, 0, 0, 0, 0, 0, 0x80],
Expand Down
7 changes: 1 addition & 6 deletions compiler/rustc_codegen_ssa/src/back/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ pub(crate) fn create_object_file(sess: &Session) -> Option<write::Object<'static
let mut file = write::Object::new(binary_format, architecture, endianness);
file.set_sub_architecture(sub_architecture);
if sess.target.is_like_darwin {
if macho_is_arm64e(&sess.target) {
if sess.target.is_arm64e_apple() {
file.set_macho_cpu_subtype(
object::macho::CPU_SUBTYPE_ARM64E | object::macho::CPU_SUBTYPE_PTRAUTH_ABI,
);
Expand Down Expand Up @@ -439,11 +439,6 @@ fn macho_object_build_version_for_target(sess: &Session) -> object::write::MachO
build_version
}

/// Is Apple's CPU subtype `arm64e`s
fn macho_is_arm64e(target: &Target) -> bool {
target.llvm_target.starts_with("arm64e")
}

pub(crate) enum MetadataPosition {
First,
Last,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
DUMMY_SP,
);
let start_fn =
cx.get_fn_addr(start_instance, cx.sess().pointer_authentication_functions());
cx.get_fn_addr(start_instance, cx.sess().pointer_authentication_direct_calls());

let i8_ty = cx.type_i8();
let arg_sigpipe = bx.const_u8(sigpipe);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ pub(crate) fn build_langcall<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
let instance = ty::Instance::mono(tcx, def_id);
(
bx.fn_abi_of_instance(instance, ty::List::empty()),
bx.get_fn_addr(instance, tcx.sess.pointer_authentication_functions()),
bx.get_fn_addr(instance, tcx.sess.pointer_authentication_direct_calls()),
instance,
)
}
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_codegen_ssa/src/mir/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
}
_ => (
false,
bx.get_fn_addr(drop_fn, bx.sess().pointer_authentication_functions()),
bx.get_fn_addr(drop_fn, bx.sess().pointer_authentication_direct_calls()),
bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
drop_fn,
),
Expand Down Expand Up @@ -1138,7 +1138,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
None,
Some(bx.get_fn_addr(
instance,
bx.sess().pointer_authentication_functions(),
bx.sess().pointer_authentication_direct_calls(),
)),
)
}
Expand Down Expand Up @@ -1465,7 +1465,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {

let fn_ptr = match (instance, llfn) {
(Some(instance), None) => {
bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions())
bx.get_fn_addr(instance, bx.sess().pointer_authentication_direct_calls())
}
(_, Some(llfn)) => llfn,
_ => span_bug!(fn_span, "no instance or llfn for call"),
Expand Down
14 changes: 12 additions & 2 deletions compiler/rustc_codegen_ssa/src/mir/operand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,12 @@ 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 = bx.scalar_to_backend_with_pac(
x,
scalar,
bx.immediate_backend_type(layout),
bx.sess().pointer_authentication_functions(),
);
OperandValue::Immediate(llval)
}
ConstValue::ZeroSized => return OperandRef::zero_sized(layout),
Expand Down Expand Up @@ -225,7 +230,12 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
alloc_range(start, size),
/*read_provenance*/ matches!(s.primitive(), abi::Primitive::Pointer(_)),
) {
Ok(val) => bx.scalar_to_backend(val, s, ty),
Ok(val) => bx.scalar_to_backend_with_pac(
val,
s,
ty,
bx.sess().pointer_authentication_functions(),
),
Err(_) => bx.const_poison(ty),
}
};
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/mir/rvalue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
args: ty::GenericArgs::empty(),
};
let fn_ptr =
bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions());
bx.get_fn_addr(instance, bx.sess().pointer_authentication_direct_calls());
let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
let fn_ty = bx.fn_decl_backend_type(fn_abi);
let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,13 @@ extern "C" void LLVMRustAddModuleFlagString(
MDString::get(unwrap(M)->getContext(), StringRef(Value, ValueLen)));
}

extern "C" void LLVMRustAddModuleFlagMetadata(
LLVMModuleRef M, LLVMRustModuleFlagMergeBehavior MergeBehavior,
const char *Name, size_t NameLen, LLVMMetadataRef Value) {
unwrap(M)->addModuleFlag(fromRust(MergeBehavior), StringRef(Name, NameLen),
unwrap(Value));
}

extern "C" LLVMValueRef LLVMRustGetLastInstruction(LLVMBasicBlockRef BB) {
auto Point = unwrap(BB)->rbegin();
if (Point != unwrap(BB)->rend())
Expand Down
35 changes: 34 additions & 1 deletion compiler/rustc_session/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ pub struct PointerAuthSchema {
}
impl PointerAuthSchema {
pub fn function_pointers_default(target: &Target) -> Self {
assert!(target.cfg_abi == CfgAbi::Pauthtest);
assert!(target.cfg_abi == CfgAbi::Pauthtest || target.is_arm64e_apple());
return Self {
is_address_discriminated: PointerAuthAddressDiscriminator::HardwareAddress(false),
discrimination_kind: PointerAuthDiscrimination::None,
Expand Down Expand Up @@ -156,6 +156,8 @@ pub struct PointerAuthConfig {
pub aarch64_jump_table_hardening: bool,
/// The ABI for C function pointers.
pub function_pointers: Option<PointerAuthSchema>,
/// Whether the function-pointer schema also covers Rust calling conventions.

@asl asl Nov 12, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I would probably suggest factoring out everything that touches Rust ABI in a separate PR and focus here on C / C++ interop first.

After all, it looks like you're defining Rust platform ABI on arm64e here which is likely a point to wider discussion.

@madsmtm @davidtwco What do you think?

View changes since the review

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thats totally fine with me!

pub covers_all_abis: bool,
/// The ABI for function addresses in .init_array and .fini_array
pub init_fini: Option<PointerAuthSchema>,
/// Use of pointer authentication intrinsics.
Expand All @@ -167,6 +169,25 @@ pub struct PointerAuthConfig {
pub vt_ptr_type_discrimination: bool,
}
impl PointerAuthConfig {
fn arm64e_apple(target: &Target) -> Self {
assert!(target.is_arm64e_apple());
Self {
return_addresses: true,
auth_traps: true,
indirect_gotos: true,
elf_got: false,
aarch64_jump_table_hardening: true,
// C function pointers must use Clang's IA/zero convention for interoperability.
function_pointers: Some(PointerAuthSchema::function_pointers_default(target)),
covers_all_abis: true,
init_fini: None,
intrinsics: true,
typeinfo_vt_ptr_discrimination: false,
vt_ptr_addr_discrimination: false,
vt_ptr_type_discrimination: false,
}
}

fn default(target: &Target) -> Self {
assert!(target.cfg_abi == CfgAbi::Pauthtest);
return Self {
Expand All @@ -176,6 +197,7 @@ impl PointerAuthConfig {
elf_got: false,
aarch64_jump_table_hardening: true,
function_pointers: Some(PointerAuthSchema::function_pointers_default(target)),
covers_all_abis: false,
init_fini: Some(PointerAuthSchema::init_fini_default(target)),
intrinsics: true,
typeinfo_vt_ptr_discrimination: true,
Expand Down Expand Up @@ -229,6 +251,9 @@ impl PointerAuthConfig {
pauth_abi_version
}
pub fn from_raw(raw: &[(PointerAuthOption, bool)], target: &Target) -> Option<Self> {
if target.is_arm64e_apple() {
return Some(Self::arm64e_apple(target));
}
if target.cfg_abi != CfgAbi::Pauthtest {
return None;
}
Expand Down Expand Up @@ -1282,6 +1307,14 @@ impl Session {
self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
}

pub fn pointer_authentication_covers_all_abis(&self) -> bool {
self.pointer_auth_config.as_ref().is_some_and(|cfg| cfg.covers_all_abis)
}

pub fn pointer_authentication_direct_calls(&self) -> Option<&PointerAuthSchema> {
if self.target.is_arm64e_apple() { None } else { self.pointer_authentication_functions() }
}

pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_target/src/spec/base/apple/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ impl OSVersion {
(Os::MacOs, crate::spec::Arch::AArch64, _) => (11, 0, 0),
(Os::IOs, crate::spec::Arch::AArch64, Env::MacAbi) => (14, 0, 0),
(Os::IOs, crate::spec::Arch::AArch64, Env::Sim) => (14, 0, 0),
(Os::IOs, _, _) if target.llvm_target.starts_with("arm64e") => (14, 0, 0),
(Os::IOs, _, _) if target.is_arm64e_apple() => (14, 0, 0),
// Mac Catalyst defaults to 13.1 in Clang.
(Os::IOs, _, Env::MacAbi) => (13, 1, 0),
(Os::TvOs, crate::spec::Arch::AArch64, Env::Sim) => (14, 0, 0),
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_target/src/spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2875,6 +2875,10 @@ impl DerefMut for Target {
}

impl Target {
pub fn is_arm64e_apple(&self) -> bool {
self.is_like_darwin && self.llvm_target.starts_with("arm64e-")
}

pub fn is_abi_supported(&self, abi: ExternAbi) -> bool {
let abi_map = AbiMap::from_target(self);
abi_map.canonize_abi(abi, false).is_mapped()
Expand Down
1 change: 1 addition & 0 deletions src/tools/compiletest/src/directives/directive_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[
"only-aarch64-unknown-uefi",
"only-apple",
"only-arm",
"only-arm64e-apple-darwin",
"only-arm64ec",
"only-armv7-unknown-linux-gnueabihf",
"only-avr",
Expand Down
Loading
Loading