Skip to content

Compute metadata and layout for unsafe binders - #166291

Open
jackh726 wants to merge 5 commits into
rust-lang:mainfrom
jackh726:unsafe-binders-metadata
Open

jackh726 wants to merge 5 commits into
rust-lang:mainfrom
jackh726:unsafe-binders-metadata

Conversation

@jackh726

@jackh726 jackh726 commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Based on #166290
Split from #163515

Closes #154871

r? adwinwhite

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. WG-trait-system-refactor The Rustc Trait System Refactor Initiative (-Znext-solver) labels Nov 21, 2026
@jackh726

Copy link
Copy Markdown
Member Author

Disclosure: An LLM was used to help generate the tests and to experiment with early prototypes of the pointee normalization code (though I wrote the code in this PR from scratch).

@jackh726 jackh726 added the llm-assisted An LLM-assisted PR as defined by the LLM policy. Requires ahead-of-time consent by assignee. label Nov 21, 2026
@rust-log-analyzer

This comment has been minimized.

@rust-cloud-vms
rust-cloud-vms Bot force-pushed the unsafe-binders-metadata branch from 6510d77 to 509f5d7 Compare November 24, 2026 02:55
@jackh726
jackh726 marked this pull request as ready for review November 24, 2026 02:57
@rustbot

rustbot commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

This PR changes a file inside tests/crashes. If a crash was fixed, please move into the corresponding ui subdir and add 'Fixes #' to the PR description to autoclose the issue upon merge.

Some changes occurred to the CTFE machinery

cc @RalfJung, @oli-obk, @lcnr

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 24, 2026
@rust-log-analyzer

This comment has been minimized.

Comment on lines +552 to +553
&ty::UnsafeBinder(inner) => {
self.check_wide_ptr_meta(meta, inner.skip_binder())?;

@RalfJung RalfJung Nov 24, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Shouldn't struct_tail_for_codegen recurse below UnsafeBinder to return the actual tail type?

View changes since the review

Comment on lines +271 to +274
// `unsafe<..> X` means `X` is `ManuallyDrop<Y>` or `Copy` (and thus metadata is `()`, because `trait Copy: Sized`).
let Some(bound_ty) = as_manually_drop(binder.skip_binder()) else {
return PointeeStep::Metadata(Ty::new_unit(cx));
};

@adwinwhite adwinwhite Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

unsafe<'a> (MD<A<'a>>, MD<dyn Trait + 'a>) would have metadata type () under this?

The comments doesn't cover mutable refs either.
Overall it feels fragile to rely on details of GuaranteedNoDrop 🤔

View changes since the review

Comment on lines +242 to +253
/// If we encounter an `unsafe<..> X` type, then we need to be a bit clever in
/// the metadata that we return. There are a couple things to consider:
/// - If we see nested unsafe binders, we combine both into a single under binder,
/// which may bind some inner metadata ty.
/// - If we see nested `ManuallyDrop` types, then we just collapse them into as single one.
/// - If the eventual metadata ty is a `dyn Trait + 'a`, then the metadata is
/// `DynMetadata<unsafe<'a> ManuallyDrop<dyn Trait + 'a>>`, not `DynMetadata<dyn Trait + 'a>`.
/// This is because the `unsafe<'a> DynMetadata<dyn Trait + 'a>` doesn't
/// implement the necessary `Pointee::Metadata` bounds. Furthermore, we can't
/// return `DynMetadata<unsafe<'a> dyn Trait + 'a>` because that type is not well-formed.
/// We also don't return `DynMetadata<dyn Trait + 'static>`, because we don't
/// want to lie about lifetimes lie that.

@adwinwhite adwinwhite Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For an unsafe binder containing trait object to be well-formed, the trait object is guaranteed to be wrapped in a ManualDrop, right 🤔 ? So it's quite natural to return DynMetadata<unsafe<'a> MD<dyn Trait + 'a>> for unsafe<'a> MD<dyn Trait + 'a>.
We could phase it as we track all bound regions and peel all wrappers until we reach the tail trait object, then we wrap the tail trait object with MD and bind it.

I'm a little unsure about the collapsing part. unsafe<'a> unsafe<'b> MD<dyn Trait<'a> + 'b> and unsafe<'a, 'b> MD<dyn Trait<'a> + 'b> should mean the same thing. But the collapsing is visible to users via ptr::metadata/from_raw_parts. We can recover both &unsafe<'a> unsafe<'b> MD<dyn Trait<'a> + 'b> and &unsafe<'a, 'b> MD<dyn Trait<'a> + 'b> from DynMetadata<unsafe<'a, 'b> MD<dyn Trait<'a> + 'b>. Is this something we want to support intentionally?

View changes since the review

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

For an unsafe binder containing trait object to be well-formed, the trait object is guaranteed to be wrapped in a ManualDrop, right 🤔 ?

I mean, somewhere, yeah. For example, this is WF: unsafe<'a, 'b> MD<(&'b u8, dyn Tr<'a> + 'a)>

So it's quite natural to return DynMetadata<unsafe<'a> MD<dyn Trait + 'a>> for unsafe<'a> MD<dyn Trait + 'a>. We could phase it as we track all bound regions and peel all wrappers until we reach the tail trait object, then we wrap the tail trait object with MD and bind it.

Yes, basically.

I'm a little unsure about the collapsing part. unsafe<'a> unsafe<'b> MD<dyn Trait<'a> + 'b> and unsafe<'a, 'b> MD<dyn Trait<'a> + 'b> should mean the same thing.

A minor point on the first: that's not actually WF, because we don't treat unsafe binders as Copy. But, the point still stands that we can nesting.

But the collapsing is visible to users via ptr::metadata/from_raw_parts. We can recover both &unsafe<'a> unsafe<'b> MD<dyn Trait<'a> + 'b> and &unsafe<'a, 'b> MD<dyn Trait<'a> + 'b> from DynMetadata<unsafe<'a, 'b> MD<dyn Trait<'a> + 'b>. Is this something we want to support intentionally?

shrug I don't really know. I'm happy to leave a FIXME somewhere, but would rather not try to block this PR on that question. (The goal is to get something working that people can test, and refine the semantics.)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A minor point on the first: that's not actually WF, because we don't treat unsafe binders as Copy.

Oh, right. Unsafe binders should impl GuaranteedNoDrop though? Then it would be WF. Probably not in the scope of this PR.

I'm happy to leave a FIXME somewhere, but would rather not try to block this PR on that question. (The goal is to get something working that people can test, and refine the semantics.)

make sense :>

@adwinwhite

Copy link
Copy Markdown
Contributor

if let ty::Adt(def, args) = metadata.kind()
&& tcx.is_lang_item(def.did(), LangItem::DynMetadata)
&& let ty::Dynamic(data, _) = args.type_at(0).kind()
{
mk_dyn_vtable(data.principal())

We also need to support seeing through unsafe binders here?

@adwinwhite

Copy link
Copy Markdown
Contributor

@rustbot author

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 25, 2026
@rust-cloud-vms
rust-cloud-vms Bot force-pushed the unsafe-binders-metadata branch from 509f5d7 to 47d68ec Compare November 26, 2026 02:43
@jackh726 jackh726 added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 26, 2026
@rust-log-analyzer

Copy link
Copy Markdown
Collaborator

The job test-x86_64-gnu-llvm-22 failed! Check out the build log: (web) (plain enhanced) (plain)

Click to see the possible cause of the failure (guessed by this bot)

---- [mir-opt] tests/mir-opt/gvn_on_unsafe_binder.rs stdout ----
------rustc stdout------------------------------

------rustc stderr------------------------------
warning: unused variable: `binder`
##[warning]  --> /checkout/tests/mir-opt/gvn_on_unsafe_binder.rs:16:13
   |
16 |         let binder: unsafe<'a> &'a i32 = wrap_binder!(&x);
   |             ^^^^^^ help: if this is intentional, prefix it with an underscore: `_binder`
   |
   = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default

##[error]error: internal compiler error: compiler/rustc_mir_transform/src/validate.rs:81:25: broken MIR in Item(DefId(0:4 ~ gvn_on_unsafe_binder[e85f]::test)) (after pass PostAnalysisNormalize) at bb0[5]:
                                WrapUnsafeBinder does not produce a ty::UnsafeBinder
  --> /checkout/tests/mir-opt/gvn_on_unsafe_binder.rs:16:42
   |
16 |         let binder: unsafe<'a> &'a i32 = wrap_binder!(&x);
   |                                          ^^^^^^^^^^^^^^^^


thread 'rustc' (179537) panicked at compiler/rustc_mir_transform/src/validate.rs:81:25:
Box<dyn Any>
stack backtrace:
   0: std::panicking::begin_panic::<rustc_span::macros::ExplicitBug>
   1: rustc_span::macros::bug_impl
   2: <rustc_mir_transform::validate::CfgChecker>::fail::<alloc::string::String>
   3: <rustc_mir_transform::validate::Validator as rustc_mir_transform::pass_manager::MirPass>::run_pass
   4: rustc_mir_transform::pass_manager::run_passes_inner
   5: rustc_mir_transform::run_analysis_to_runtime_passes
   6: rustc_mir_transform::mir_drops_elaborated_and_const_checked
      [... omitted 2 frames ...]
   7: <rustc_middle::ty::context::TyCtxt>::par_hir_body_owners::<rustc_interface::passes::run_required_analyses::{closure#2}::{closure#0}>::{closure#0}
   8: rustc_data_structures::sync::parallel::par_for_each_in::<rustc_span::def_id::LocalDefId, [rustc_span::def_id::LocalDefId], <rustc_middle::ty::context::TyCtxt>::par_hir_body_owners<rustc_interface::passes::run_required_analyses::{closure#2}::{closure#0}>::{closure#0}>
   9: <rustc_session::session::Session>::time::<(), rustc_interface::passes::run_required_analyses::{closure#2}>
  10: rustc_interface::passes::run_required_analyses
      [... omitted 2 frames ...]
  11: rustc_interface::passes::full_analysis
  12: <std::thread::local::LocalKey<core::cell::Cell<*const ()>>>::with::<rustc_middle::ty::context::tls::enter_context<<rustc_middle::ty::context::GlobalCtxt>::enter<rustc_interface::passes::create_and_enter_global_ctxt<core::option::Option<rustc_interface::queries::Linker>, rustc_driver_impl::compiler_entrypoint::{closure#0}::{closure#1}>::{closure#3}, core::option::Option<rustc_interface::queries::Linker>>::{closure#1}, core::option::Option<rustc_interface::queries::Linker>>::{closure#0}, core::option::Option<rustc_interface::queries::Linker>>
  13: <rustc_middle::ty::context::TyCtxt>::create_global_ctxt::<core::option::Option<rustc_interface::queries::Linker>, rustc_interface::passes::create_and_enter_global_ctxt<core::option::Option<rustc_interface::queries::Linker>, rustc_driver_impl::compiler_entrypoint::{closure#0}::{closure#1}>::{closure#3}>
  14: rustc_interface::passes::create_and_enter_global_ctxt::<core::option::Option<rustc_interface::queries::Linker>, rustc_driver_impl::compiler_entrypoint::{closure#0}::{closure#1}>
  15: rustc_span::create_session_globals_then::<(), rustc_interface::util::run_in_thread_with_globals<rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<(), rustc_driver_impl::compiler_entrypoint::{closure#0}>::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}::{closure#0}>
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md

note: please make sure that you have updated to the latest nightly

note: rustc 1.102.0-nightly (71bc12ff7 2026-11-25) running on x86_64-unknown-linux-gnu

note: compiler flags: -Z simulate-remapped-rust-src-base=/rustc/FAKE_PREFIX -Z translate-remapped-path-to-local-path=no -Z ignore-directory-in-diagnostics-source-blocks=/cargo -Z ignore-directory-in-diagnostics-source-blocks=/checkout/vendor -Z threads=1 -C opt-level=1 -Z dump-mir=GVN | GVN -Z validate-mir -Z lint-mir -Z dump-mir-exclude-pass-number -Z mir-include-spans=false --crate-type rlib -Z mir-opt-level=0 -Z mir-enable-passes=+GVN -Z dump-mir-dir=/checkout/obj/build/x86_64-unknown-linux-gnu/test/mir-opt/gvn_on_unsafe_binder -C prefer-dynamic -Z next-solver=coherence -C rpath -C debuginfo=0 -Z next-solver

query stack during panic:
#0 [mir_drops_elaborated_and_const_checked] elaborating drops for `test`
#1 [required_analysis] running required analysis passes on crate `gvn_on_unsafe_binder`
end of query stack
error: aborting due to 1 previous error; 1 warning emitted


------------------------------------------

error: compilation failed!
status: exit status: 101
command: env -u RUSTC_LOG_COLOR LD_LIBRARY_PATH="/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib:/checkout/obj/build/x86_64-unknown-linux-gnu/test/mir-opt/gvn_on_unsafe_binder/auxiliary:" RUSTC_ICE="0" RUST_BACKTRACE="short" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/tests/mir-opt/gvn_on_unsafe_binder.rs" "-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX" "-Ztranslate-remapped-path-to-local-path=no" "-Z" "ignore-directory-in-diagnostics-source-blocks=/cargo" "-Z" "ignore-directory-in-diagnostics-source-blocks=/checkout/vendor" "--sysroot" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2" "--target=i686-unknown-linux-gnu" "--check-cfg" "cfg(test,FALSE)" "-O" "-Zthreads=1" "-Copt-level=1" "-Zdump-mir=GVN | GVN" "-Zvalidate-mir" "-Zlint-mir" "-Zdump-mir-exclude-pass-number" "-Zmir-include-spans=false" "--crate-type=rlib" "-Zmir-opt-level=0" "-Zmir-enable-passes=+GVN" "-Zdump-mir-dir=/checkout/obj/build/x86_64-unknown-linux-gnu/test/mir-opt/gvn_on_unsafe_binder" "--emit" "mir" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/mir-opt/gvn_on_unsafe_binder" "-Znext-solver=coherence" "-A" "internal_features" "-A" "incomplete_features" "-A" "unused_parens" "-A" "unused_braces" "-Crpath" "-Cdebuginfo=0" "--edition=2015" "-Znext-solver"
stdout: none
--- stderr -------------------------------
warning: unused variable: `binder`
##[warning]  --> /checkout/tests/mir-opt/gvn_on_unsafe_binder.rs:16:13
   |
16 |         let binder: unsafe<'a> &'a i32 = wrap_binder!(&x);
   |             ^^^^^^ help: if this is intentional, prefix it with an underscore: `_binder`
   |
   = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default

##[error]error: internal compiler error: compiler/rustc_mir_transform/src/validate.rs:81:25: broken MIR in Item(DefId(0:4 ~ gvn_on_unsafe_binder[e85f]::test)) (after pass PostAnalysisNormalize) at bb0[5]:
                                WrapUnsafeBinder does not produce a ty::UnsafeBinder
  --> /checkout/tests/mir-opt/gvn_on_unsafe_binder.rs:16:42
   |
16 |         let binder: unsafe<'a> &'a i32 = wrap_binder!(&x);
   |                                          ^^^^^^^^^^^^^^^^


thread 'rustc' (179537) panicked at compiler/rustc_mir_transform/src/validate.rs:81:25:
Box<dyn Any>
stack backtrace:
   0: std::panicking::begin_panic::<rustc_span::macros::ExplicitBug>
   1: rustc_span::macros::bug_impl
   2: <rustc_mir_transform::validate::CfgChecker>::fail::<alloc::string::String>
   3: <rustc_mir_transform::validate::Validator as rustc_mir_transform::pass_manager::MirPass>::run_pass
   4: rustc_mir_transform::pass_manager::run_passes_inner
   5: rustc_mir_transform::run_analysis_to_runtime_passes
   6: rustc_mir_transform::mir_drops_elaborated_and_const_checked
      [... omitted 2 frames ...]
   7: <rustc_middle::ty::context::TyCtxt>::par_hir_body_owners::<rustc_interface::passes::run_required_analyses::{closure#2}::{closure#0}>::{closure#0}
   8: rustc_data_structures::sync::parallel::par_for_each_in::<rustc_span::def_id::LocalDefId, [rustc_span::def_id::LocalDefId], <rustc_middle::ty::context::TyCtxt>::par_hir_body_owners<rustc_interface::passes::run_required_analyses::{closure#2}::{closure#0}>::{closure#0}>
   9: <rustc_session::session::Session>::time::<(), rustc_interface::passes::run_required_analyses::{closure#2}>
  10: rustc_interface::passes::run_required_analyses
      [... omitted 2 frames ...]
  11: rustc_interface::passes::full_analysis
  12: <std::thread::local::LocalKey<core::cell::Cell<*const ()>>>::with::<rustc_middle::ty::context::tls::enter_context<<rustc_middle::ty::context::GlobalCtxt>::enter<rustc_interface::passes::create_and_enter_global_ctxt<core::option::Option<rustc_interface::queries::Linker>, rustc_driver_impl::compiler_entrypoint::{closure#0}::{closure#1}>::{closure#3}, core::option::Option<rustc_interface::queries::Linker>>::{closure#1}, core::option::Option<rustc_interface::queries::Linker>>::{closure#0}, core::option::Option<rustc_interface::queries::Linker>>
  13: <rustc_middle::ty::context::TyCtxt>::create_global_ctxt::<core::option::Option<rustc_interface::queries::Linker>, rustc_interface::passes::create_and_enter_global_ctxt<core::option::Option<rustc_interface::queries::Linker>, rustc_driver_impl::compiler_entrypoint::{closure#0}::{closure#1}>::{closure#3}>
  14: rustc_interface::passes::create_and_enter_global_ctxt::<core::option::Option<rustc_interface::queries::Linker>, rustc_driver_impl::compiler_entrypoint::{closure#0}::{closure#1}>
  15: rustc_span::create_session_globals_then::<(), rustc_interface::util::run_in_thread_with_globals<rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<(), rustc_driver_impl::compiler_entrypoint::{closure#0}>::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}::{closure#0}>
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md

note: please make sure that you have updated to the latest nightly

note: rustc 1.102.0-nightly (71bc12ff7 2026-11-25) running on x86_64-unknown-linux-gnu

note: compiler flags: -Z simulate-remapped-rust-src-base=/rustc/FAKE_PREFIX -Z translate-remapped-path-to-local-path=no -Z ignore-directory-in-diagnostics-source-blocks=/cargo -Z ignore-directory-in-diagnostics-source-blocks=/checkout/vendor -Z threads=1 -C opt-level=1 -Z dump-mir=GVN | GVN -Z validate-mir -Z lint-mir -Z dump-mir-exclude-pass-number -Z mir-include-spans=false --crate-type rlib -Z mir-opt-level=0 -Z mir-enable-passes=+GVN -Z dump-mir-dir=/checkout/obj/build/x86_64-unknown-linux-gnu/test/mir-opt/gvn_on_unsafe_binder -C prefer-dynamic -Z next-solver=coherence -C rpath -C debuginfo=0 -Z next-solver

query stack during panic:
#0 [mir_drops_elaborated_and_const_checked] elaborating drops for `test`
#1 [required_analysis] running required analysis passes on crate `gvn_on_unsafe_binder`
end of query stack

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm-assisted An LLM-assisted PR as defined by the LLM policy. Requires ahead-of-time consent by assignee. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. WG-trait-system-refactor The Rustc Trait System Refactor Initiative (-Znext-solver)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[ICE]: ptr::null with unsafe binder

5 participants