-
-
Notifications
You must be signed in to change notification settings - Fork 15.4k
[WIP] pac ty disc #158567
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
jchlanda
wants to merge
22
commits into
rust-lang:main
Choose a base branch
from
jchlanda:jakub/pac_ty_disc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
[WIP] pac ty disc #158567
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
933b982
Teach builder how to issue llvm.ptrauth.resign
jchlanda 981d41b
Introduce function pointer type encoder
jchlanda 4a7c9dd
Extend FnAbi to hold type_discriminator
jchlanda 976ef7e
Add FPTR_TYPE_DISCR to the supported set of features
jchlanda dca628f
Teach static initializer how to handle fn ptr discriminators
jchlanda 18fcf86
Extend transmute to handle fn ptr discriminators
jchlanda 1bf9879
Extend minicore with items required by fn ptr ty discriminator tests
jchlanda 4daa841
Add fn ptr type discrimination tests
jchlanda 779ed32
Update SIMD vector encoding and extend the testing for it
jchlanda dacec7c
Init/fini entries don't participate in fn ty discrimination
jchlanda 024f26a
Unify creation of discrimination data and fill in missing `get_fn_add…
jchlanda 67b93c1
Update the main document with changes to [patch] section
jchlanda 7aeb893
Adapt tests to `// ignore-tidy-file-linelength` directive
jchlanda d571964
PR feedback: Introduce function pointer type encoder
jchlanda 7134f59
PR feedback: Extend FnAbi to hold type_discriminator
jchlanda 911b2b4
PR feedback: Teach static initializer how to handle fn ptr discrimina…
jchlanda eb16c2d
PR feedback: Unify creation of discrimination data and fill in missin…
jchlanda 7bd76dd
PR feedback: Extend transmute to handle fn ptr discriminators
jchlanda cfe92fc
PR feedback: Unify creation of discrimination data and fill in missing
jchlanda f9b08db
PR feedback: Encoder
jchlanda 54893fd
PR Feedback: To Encoder - Retire Complex
jchlanda cff5996
PR Feedback: To Encoder - Treat data pointer the same as fn in Option…
jchlanda File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,7 @@ use std::ops::Range; | |
| use rustc_abi::{Align, ExternAbi, HasDataLayout, Primitive, Scalar, Size, WrappingRange}; | ||
| use rustc_codegen_ssa::common; | ||
| use rustc_codegen_ssa::traits::*; | ||
| use rustc_data_structures::fx::FxHashMap; | ||
| use rustc_hir::LangItem; | ||
| use rustc_hir::attrs::Linkage; | ||
| use rustc_hir::def::DefKind; | ||
|
|
@@ -13,8 +14,9 @@ use rustc_middle::mir::interpret::{ | |
| read_target_uint, | ||
| }; | ||
| use rustc_middle::mono::MonoItem; | ||
| use rustc_middle::ptrauth::compute_fn_ptr_type_discriminator_for; | ||
| use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf}; | ||
| use rustc_middle::ty::{self, Instance}; | ||
| use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; | ||
| use rustc_middle::{bug, span_bug}; | ||
| use rustc_span::Symbol; | ||
| use rustc_target::spec::Arch; | ||
|
|
@@ -37,11 +39,152 @@ pub(crate) enum IsInitOrFini { | |
| Yes, | ||
| No, | ||
| } | ||
|
|
||
| /// Maps offsets within a static allocation to the function pointer | ||
| /// discriminator that should be applied when authenticating the relocation | ||
| /// emitted at that offset. | ||
| /// | ||
| /// Offsets are relative to the beginning of the allocation. | ||
| pub(crate) struct FnPtrDiscriminatorAtOffset { | ||
| map: FxHashMap<Size, u64>, | ||
| } | ||
|
|
||
| /// Recursively walks a type layout and records the offsets of all extern "C" | ||
| /// function pointer fields together with their computed type discriminators. | ||
| /// | ||
| /// Traversal currently supports: | ||
| /// - direct function pointers | ||
| /// - transparent wrappers | ||
| /// - structs | ||
| /// - tuples | ||
| /// - arrays | ||
| /// | ||
| /// Offsets are accumulated relative to the containing object. | ||
| fn collect_fn_ptr_discriminators<'tcx>( | ||
| tcx: TyCtxt<'tcx>, | ||
| typing_env: ty::TypingEnv<'tcx>, | ||
| ty: Ty<'tcx>, | ||
| ) -> FnPtrDiscriminatorAtOffset { | ||
| let mut map = FxHashMap::default(); | ||
|
|
||
| collect_fn_ptr_discriminators_inner(tcx, typing_env, ty, Size::ZERO, &mut map); | ||
|
|
||
| FnPtrDiscriminatorAtOffset { map } | ||
| } | ||
|
|
||
| fn collect_fn_ptr_discriminators_inner<'tcx>( | ||
| tcx: TyCtxt<'tcx>, | ||
| typing_env: ty::TypingEnv<'tcx>, | ||
| ty: Ty<'tcx>, | ||
| base_offset: Size, | ||
| map: &mut FxHashMap<Size, u64>, | ||
| ) { | ||
| // Direct function pointer. | ||
| if let Some(disc) = compute_fn_ptr_type_discriminator_for(tcx, ty) { | ||
| map.insert(base_offset, disc.into()); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| match ty.kind() { | ||
| ty::Adt(def, args) if def.repr().transparent() => { | ||
| let variant = def.non_enum_variant(); | ||
|
|
||
| let Some((_, field)) = variant.fields.iter_enumerated().next() else { | ||
| return; | ||
| }; | ||
|
|
||
| let field_ty = tcx.normalize_erasing_regions(typing_env, field.ty(tcx, args)); | ||
|
|
||
| collect_fn_ptr_discriminators_inner(tcx, typing_env, field_ty, base_offset, map); | ||
| } | ||
| ty::Adt(def, args) if def.is_struct() => { | ||
| let Ok(layout) = tcx.layout_of(typing_env.as_query_input(ty)) else { | ||
| return; | ||
| }; | ||
|
|
||
| let variant = def.non_enum_variant(); | ||
|
|
||
| for (idx, field_def) in variant.fields.iter_enumerated() { | ||
| let field_ty = tcx.normalize_erasing_regions(typing_env, field_def.ty(tcx, args)); | ||
|
|
||
| let field_offset = layout.fields.offset(idx.into()); | ||
|
|
||
| collect_fn_ptr_discriminators_inner( | ||
| tcx, | ||
| typing_env, | ||
| field_ty, | ||
| base_offset + field_offset, | ||
| map, | ||
| ); | ||
| } | ||
| } | ||
| ty::Tuple(fields) => { | ||
| let Ok(layout) = tcx.layout_of(typing_env.as_query_input(ty)) else { | ||
| return; | ||
| }; | ||
|
|
||
| for (idx, field_ty) in fields.iter().enumerate() { | ||
| let field_offset = layout.fields.offset(idx); | ||
|
|
||
| collect_fn_ptr_discriminators_inner( | ||
| tcx, | ||
| typing_env, | ||
| field_ty, | ||
| base_offset + field_offset, | ||
| map, | ||
| ); | ||
| } | ||
| } | ||
| ty::Array(elem_ty, len) => { | ||
| let count = match len.try_to_target_usize(tcx) { | ||
| Some(v) => v, | ||
| None => return, | ||
| }; | ||
|
|
||
| let Ok(elem_layout) = tcx.layout_of(typing_env.as_query_input(*elem_ty)) else { | ||
| return; | ||
| }; | ||
|
|
||
| let stride = elem_layout.size; | ||
|
|
||
| // Collect discriminator of one element, so we don't have to recompute it for all the | ||
| // elements in the array. | ||
| let mut elem_map = FxHashMap::default(); | ||
|
|
||
| collect_fn_ptr_discriminators_inner( | ||
| tcx, | ||
| typing_env, | ||
| *elem_ty, | ||
| Size::ZERO, | ||
| &mut elem_map, | ||
| ); | ||
|
|
||
| // SAFETY: We immediately collect into a Vec and sort by offset. | ||
| // The HashMap iteration order is irrelevant and must not affect determinism. | ||
| #[allow(rustc::potential_query_instability)] | ||
| let mut entries: Vec<(Size, u64)> = elem_map.into_iter().collect(); | ||
| entries.sort_unstable_by_key(|(offset, _)| *offset); | ||
|
|
||
| // Replicate for every array slot. | ||
| for i in 0..count { | ||
| let elem_base = base_offset + stride * i; | ||
|
|
||
| for (inner_offset, discr) in entries.iter().copied() { | ||
| map.insert(elem_base + inner_offset, discr); | ||
| } | ||
| } | ||
| } | ||
| _ => {} | ||
| } | ||
| } | ||
|
|
||
| pub(crate) fn const_alloc_to_llvm<'ll>( | ||
| cx: &CodegenCx<'ll, '_>, | ||
| alloc: &Allocation, | ||
| is_static: IsStatic, | ||
| is_init_fini: IsInitOrFini, | ||
| fn_ptr_discriminators: Option<&FnPtrDiscriminatorAtOffset>, | ||
| ) -> &'ll Value { | ||
| // 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 | ||
|
|
@@ -121,14 +264,24 @@ pub(crate) fn const_alloc_to_llvm<'ll>( | |
| as u64; | ||
|
|
||
| let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx); | ||
| let schema = if cx.sess().pointer_authentication() { | ||
| let mut schema = if cx.sess().pointer_authentication() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do we need
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because we then retrieve the discriminator and store it in the schema. |
||
| match is_init_fini { | ||
| IsInitOrFini::Yes => cx.sess().pointer_authentication_init_fini(), | ||
| IsInitOrFini::No => cx.sess().pointer_authentication_functions(), | ||
| } | ||
| } else { | ||
| None | ||
| }; | ||
| let discr = fn_ptr_discriminators | ||
| .as_ref() | ||
| .and_then(|m| m.map.get(&Size::from_bytes(offset as u64))); | ||
|
|
||
| // Init/fini entries must not participate in function pointer type discrimination. | ||
| if let (Some(schema), Some(discr)) = (schema.as_mut(), discr) | ||
| && is_init_fini == IsInitOrFini::No | ||
| { | ||
| schema.constant_discriminator = *discr as u16; | ||
| } | ||
| llvals.push(cx.scalar_to_backend_with_pac( | ||
| InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx), | ||
| Scalar::Initialized { | ||
|
|
@@ -160,6 +313,15 @@ fn codegen_static_initializer<'ll, 'tcx>( | |
| cx: &CodegenCx<'ll, 'tcx>, | ||
| def_id: DefId, | ||
| ) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> { | ||
| let fn_ptr_discriminators = if cx.sess().pointer_authentication_fn_ptr_type_discrimination() { | ||
| let instance = Instance::mono(cx.tcx, def_id); | ||
| let ty = instance.ty(cx.tcx, cx.typing_env()); | ||
|
|
||
| Some(collect_fn_ptr_discriminators(cx.tcx, cx.typing_env(), ty)) | ||
| } else { | ||
| None | ||
| }; | ||
|
|
||
| let alloc = cx.tcx.eval_static_initializer(def_id)?; | ||
| let attrs = cx.tcx.codegen_fn_attrs(def_id); | ||
| // FIXME(jchlanda) Decide if this could be better served by `ctor` crate. See the discussion | ||
|
|
@@ -175,7 +337,16 @@ 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)) | ||
| Ok(( | ||
| const_alloc_to_llvm( | ||
| cx, | ||
| alloc.inner(), | ||
| IsStatic::Yes, | ||
| is_in_init_fini, | ||
| fn_ptr_discriminators.as_ref(), | ||
| ), | ||
| alloc, | ||
| )) | ||
| } | ||
|
|
||
| fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) { | ||
|
|
@@ -837,7 +1008,7 @@ impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> { | |
| fn static_addr_of(&self, alloc: ConstAllocation<'_>, kind: Option<&str>) -> &'ll Value { | ||
| // 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, None); | ||
|
|
||
| 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 | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a test for this (ensuring that it's not supported) or is it infeasible to reach this path?
View changes since the review
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is not a user facing function, so the only way it could be triggered is if we wrote incorrect code within the compiler itself, hence the
bug!. The relevant call chain for this function starts insidecodegen_transmuteand is guarded by a function pointer support check.