From 675ba3834574870c5bca4033578644b57b31dffd Mon Sep 17 00:00:00 2001 From: Oleksandr Babak Date: Sun, 31 Aug 2025 14:34:29 +0200 Subject: [PATCH 01/15] feat: add `from_fn_ptr` to `Waker` and `LocalWaker` --- library/core/src/task/wake.rs | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index bb7efe582f7a3..178717fe42eac 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -584,6 +584,28 @@ impl Waker { pub fn vtable(&self) -> &'static RawWakerVTable { self.waker.vtable } + + /// Constructs a `Waker` from a function pointer. + #[inline] + #[must_use] + #[unstable(feature = "waker_from_fn_ptr", issue = "146055")] + pub const fn from_fn_ptr(f: fn()) -> Self { + // SAFETY: Unsafe is used for transmutes, pointer came from `fn()` so it + // is sound to transmute it back to `fn()`. + static VTABLE: RawWakerVTable = unsafe { + RawWakerVTable::new( + |this| RawWaker::new(this, &VTABLE), + |this| transmute::<*const (), fn()>(this)(), + |this| transmute::<*const (), fn()>(this)(), + |_| {}, + ) + }; + let raw = RawWaker::new(f as *const (), &VTABLE); + + // SAFETY: `clone` is just a copy, `drop` is a no-op while `wake` and + // `wake_by_ref` just call the function pointer. + unsafe { Self::from_raw(raw) } + } } #[stable(feature = "futures_api", since = "1.36.0")] @@ -879,6 +901,28 @@ impl LocalWaker { pub fn vtable(&self) -> &'static RawWakerVTable { self.waker.vtable } + + /// Constructs a `LocalWaker` from a function pointer. + #[inline] + #[must_use] + #[unstable(feature = "waker_from_fn_ptr", issue = "146055")] + pub const fn from_fn_ptr(f: fn()) -> Self { + // SAFETY: Unsafe is used for transmutes, pointer came from `fn()` so it + // is sound to transmute it back to `fn()`. + static VTABLE: RawWakerVTable = unsafe { + RawWakerVTable::new( + |this| RawWaker::new(this, &VTABLE), + |this| transmute::<*const (), fn()>(this)(), + |this| transmute::<*const (), fn()>(this)(), + |_| {}, + ) + }; + let raw = RawWaker::new(f as *const (), &VTABLE); + + // SAFETY: `clone` is just a copy, `drop` is a no-op while `wake` and + // `wake_by_ref` just call the function pointer. + unsafe { Self::from_raw(raw) } + } } #[unstable(feature = "local_waker", issue = "118959")] impl Clone for LocalWaker { From 8537abbaf2548051eb4d7ddb44e3d926faf16e08 Mon Sep 17 00:00:00 2001 From: Noa Date: Wed, 27 Aug 2025 00:10:09 -0500 Subject: [PATCH 02/15] Stabilize `fmt::{from_fn, FromFn}` under feature `fmt_from_fn` --- library/alloc/src/fmt.rs | 2 +- library/core/src/fmt/builders.rs | 9 ++++----- library/core/src/fmt/mod.rs | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/library/alloc/src/fmt.rs b/library/alloc/src/fmt.rs index 82eaf7d87244d..4d6fe220a09ad 100644 --- a/library/alloc/src/fmt.rs +++ b/library/alloc/src/fmt.rs @@ -602,7 +602,7 @@ pub use core::fmt::{DebugAsHex, FormattingOptions, Sign}; pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Formatter, Result, Write}; -#[unstable(feature = "debug_closure_helpers", issue = "117729")] +#[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] pub use core::fmt::{FromFn, from_fn}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerExp, UpperExp}; diff --git a/library/core/src/fmt/builders.rs b/library/core/src/fmt/builders.rs index 665b05b12ec07..dba54353e03f2 100644 --- a/library/core/src/fmt/builders.rs +++ b/library/core/src/fmt/builders.rs @@ -1216,7 +1216,6 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// # Examples /// /// ``` -/// #![feature(debug_closure_helpers)] /// use std::fmt; /// /// let value = 'a'; @@ -1227,7 +1226,7 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// assert_eq!(format!("{}", wrapped), "'a'"); /// assert_eq!(format!("{:?}", wrapped), "'a'"); /// ``` -#[unstable(feature = "debug_closure_helpers", issue = "117729")] +#[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] #[must_use = "returns a type implementing Debug and Display, which do not have any effects unless they are used"] pub fn from_fn) -> fmt::Result>(f: F) -> FromFn { FromFn(f) @@ -1236,12 +1235,12 @@ pub fn from_fn) -> fmt::Result>(f: F) -> FromFn /// Implements [`fmt::Debug`] and [`fmt::Display`] using a function. /// /// Created with [`from_fn`]. -#[unstable(feature = "debug_closure_helpers", issue = "117729")] +#[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] pub struct FromFn(F) where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result; -#[unstable(feature = "debug_closure_helpers", issue = "117729")] +#[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] impl fmt::Debug for FromFn where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result, @@ -1251,7 +1250,7 @@ where } } -#[unstable(feature = "debug_closure_helpers", issue = "117729")] +#[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] impl fmt::Display for FromFn where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result, diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index fcd2e52101ff0..1d592ab6800d0 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -39,7 +39,7 @@ pub use num_buffer::{NumBuffer, NumBufferTrait}; #[stable(feature = "debug_builders", since = "1.2.0")] pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; -#[unstable(feature = "debug_closure_helpers", issue = "117729")] +#[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] pub use self::builders::{FromFn, from_fn}; /// The type returned by formatter methods. From f8d7b412045fa6cbeaacf765effa20f76273a777 Mon Sep 17 00:00:00 2001 From: Noa Date: Wed, 27 Aug 2025 00:11:46 -0500 Subject: [PATCH 03/15] Reword docs slightly --- library/core/src/fmt/builders.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/core/src/fmt/builders.rs b/library/core/src/fmt/builders.rs index dba54353e03f2..e97c1a8f77e45 100644 --- a/library/core/src/fmt/builders.rs +++ b/library/core/src/fmt/builders.rs @@ -1210,8 +1210,8 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { } } -/// Creates a type whose [`fmt::Debug`] and [`fmt::Display`] impls are provided with the function -/// `f`. +/// Creates a type whose [`fmt::Debug`] and [`fmt::Display`] impls are +/// forwarded to the provided closure. /// /// # Examples /// @@ -1232,7 +1232,7 @@ pub fn from_fn) -> fmt::Result>(f: F) -> FromFn FromFn(f) } -/// Implements [`fmt::Debug`] and [`fmt::Display`] using a function. +/// Implements [`fmt::Debug`] and [`fmt::Display`] via the provided closure. /// /// Created with [`from_fn`]. #[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] From 859ae05e938add34df930772557e5f2e795df96d Mon Sep 17 00:00:00 2001 From: Noa Date: Wed, 27 Aug 2025 00:32:49 -0500 Subject: [PATCH 04/15] Remove some feature(debug_closure_helpers) attributes --- compiler/rustc_hir/src/lib.rs | 2 +- compiler/rustc_hir_analysis/src/lib.rs | 2 +- compiler/rustc_target/src/lib.rs | 2 +- src/librustdoc/lib.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs index eb630fc801863..0d0a1f6b76a29 100644 --- a/compiler/rustc_hir/src/lib.rs +++ b/compiler/rustc_hir/src/lib.rs @@ -3,9 +3,9 @@ //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html // tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(debug_closure_helpers))] #![feature(associated_type_defaults)] #![feature(closure_track_caller)] -#![feature(debug_closure_helpers)] #![feature(exhaustive_patterns)] #![feature(never_type)] #![feature(variant_count)] diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 6659aff711107..56c0f4e7cee48 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -59,10 +59,10 @@ This API is completely unstable and subject to change. #![allow(internal_features)] #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] +#![cfg_attr(bootstrap, feature(debug_closure_helpers))] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] #![feature(assert_matches)] -#![feature(debug_closure_helpers)] #![feature(gen_blocks)] #![feature(if_let_guard)] #![feature(iter_intersperse)] diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs index 8c6a77cba8ba7..f664bbb874d67 100644 --- a/compiler/rustc_target/src/lib.rs +++ b/compiler/rustc_target/src/lib.rs @@ -9,9 +9,9 @@ // tidy-alphabetical-start #![allow(internal_features)] +#![cfg_attr(bootstrap, feature(debug_closure_helpers))] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] -#![feature(debug_closure_helpers)] #![feature(iter_intersperse)] #![feature(rustdoc_internals)] // tidy-alphabetical-end diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index c4f24e09ddbfa..b6ddd5329a7aa 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -1,4 +1,5 @@ // tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(debug_closure_helpers))] #![doc( html_root_url = "https://doc.rust-lang.org/nightly/", html_playground_url = "https://play.rust-lang.org/" @@ -7,7 +8,6 @@ #![feature(ascii_char_variants)] #![feature(assert_matches)] #![feature(box_patterns)] -#![feature(debug_closure_helpers)] #![feature(file_buffered)] #![feature(formatting_options)] #![feature(if_let_guard)] From 93c8bf13092e01603ff2bd4a5ce20eed79edfe35 Mon Sep 17 00:00:00 2001 From: Noa Date: Fri, 19 Sep 2025 13:27:11 -0500 Subject: [PATCH 05/15] Remove F: Fn bound from FromFn struct --- library/core/src/fmt/builders.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/library/core/src/fmt/builders.rs b/library/core/src/fmt/builders.rs index e97c1a8f77e45..4ea6c6ba8fb9c 100644 --- a/library/core/src/fmt/builders.rs +++ b/library/core/src/fmt/builders.rs @@ -1236,9 +1236,7 @@ pub fn from_fn) -> fmt::Result>(f: F) -> FromFn /// /// Created with [`from_fn`]. #[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] -pub struct FromFn(F) -where - F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result; +pub struct FromFn(F); #[stable(feature = "fmt_from_fn", since = "CURRENT_RUSTC_VERSION")] impl fmt::Debug for FromFn From 471f2ba64ed769013f87986bc5340d9edeecc3f0 Mon Sep 17 00:00:00 2001 From: Ayush Singh Date: Sun, 7 Sep 2025 22:05:59 +0530 Subject: [PATCH 06/15] library: std: sys: net: uefi: tcp: Implement write_vectored - A working vectored write implementation for TCP4. - Also introduces a small helper UefiBox intended to be used with heap allocated UEFI DSTs. - Tested on OVMF Signed-off-by: Ayush Singh --- .../std/src/sys/net/connection/uefi/mod.rs | 5 +- .../std/src/sys/net/connection/uefi/tcp.rs | 12 +++- .../std/src/sys/net/connection/uefi/tcp4.rs | 69 +++++++++++++++---- library/std/src/sys/pal/uefi/helpers.rs | 37 ++++++++++ 4 files changed, 107 insertions(+), 16 deletions(-) diff --git a/library/std/src/sys/net/connection/uefi/mod.rs b/library/std/src/sys/net/connection/uefi/mod.rs index 004f6d413a1f3..d76e3e576f330 100644 --- a/library/std/src/sys/net/connection/uefi/mod.rs +++ b/library/std/src/sys/net/connection/uefi/mod.rs @@ -82,12 +82,11 @@ impl TcpStream { } pub fn write_vectored(&self, buf: &[IoSlice<'_>]) -> io::Result { - // FIXME: UEFI does support vectored write, so implement that. - crate::io::default_write_vectored(|b| self.write(b), buf) + self.inner.write_vectored(buf, self.write_timeout()?) } pub fn is_write_vectored(&self) -> bool { - false + true } pub fn peer_addr(&self) -> io::Result { diff --git a/library/std/src/sys/net/connection/uefi/tcp.rs b/library/std/src/sys/net/connection/uefi/tcp.rs index aac97007bbfe5..16283e64fb35a 100644 --- a/library/std/src/sys/net/connection/uefi/tcp.rs +++ b/library/std/src/sys/net/connection/uefi/tcp.rs @@ -1,5 +1,5 @@ use super::tcp4; -use crate::io; +use crate::io::{self, IoSlice}; use crate::net::SocketAddr; use crate::ptr::NonNull; use crate::sys::{helpers, unsupported}; @@ -28,6 +28,16 @@ impl Tcp { } } + pub(crate) fn write_vectored( + &self, + buf: &[IoSlice<'_>], + timeout: Option, + ) -> io::Result { + match self { + Self::V4(client) => client.write_vectored(buf, timeout), + } + } + pub(crate) fn read(&self, buf: &mut [u8], timeout: Option) -> io::Result { match self { Self::V4(client) => client.read(buf, timeout), diff --git a/library/std/src/sys/net/connection/uefi/tcp4.rs b/library/std/src/sys/net/connection/uefi/tcp4.rs index 75862ff247b4f..ba0424454d738 100644 --- a/library/std/src/sys/net/connection/uefi/tcp4.rs +++ b/library/std/src/sys/net/connection/uefi/tcp4.rs @@ -1,7 +1,7 @@ use r_efi::efi::{self, Status}; use r_efi::protocols::tcp4; -use crate::io; +use crate::io::{self, IoSlice}; use crate::net::SocketAddrV4; use crate::ptr::NonNull; use crate::sync::atomic::{AtomicBool, Ordering}; @@ -108,11 +108,7 @@ impl Tcp4 { } pub(crate) fn write(&self, buf: &[u8], timeout: Option) -> io::Result { - let evt = unsafe { self.create_evt() }?; - let completion_token = - tcp4::CompletionToken { event: evt.as_ptr(), status: Status::SUCCESS }; let data_len = u32::try_from(buf.len()).unwrap_or(u32::MAX); - let fragment = tcp4::FragmentData { fragment_length: data_len, fragment_buffer: buf.as_ptr().cast::().cast_mut(), @@ -125,14 +121,63 @@ impl Tcp4 { fragment_table: [fragment], }; - let protocol = self.protocol.as_ptr(); - let mut token = tcp4::IoToken { - completion_token, - packet: tcp4::IoTokenPacket { - tx_data: (&raw mut tx_data).cast::>(), - }, + self.write_inner((&raw mut tx_data).cast(), timeout).map(|_| data_len as usize) + } + + pub(crate) fn write_vectored( + &self, + buf: &[IoSlice<'_>], + timeout: Option, + ) -> io::Result { + let mut data_length = 0u32; + let mut fragment_count = 0u32; + + // Calculate how many IoSlice in buf can be transmitted. + for i in buf { + // IoSlice length is always <= u32::MAX in UEFI. + match data_length + .checked_add(u32::try_from(i.as_slice().len()).expect("value is stored as a u32")) + { + Some(x) => data_length = x, + None => break, + } + fragment_count += 1; + } + + let tx_data_size = size_of::>() + + size_of::() * (fragment_count as usize); + let mut tx_data = helpers::UefiBox::::new(tx_data_size)?; + tx_data.write(tcp4::TransmitData { + push: r_efi::efi::Boolean::FALSE, + urgent: r_efi::efi::Boolean::FALSE, + data_length, + fragment_count, + fragment_table: [], + }); + unsafe { + // SAFETY: IoSlice and FragmentData are guaranteed to have same layout. + crate::ptr::copy_nonoverlapping( + buf.as_ptr().cast(), + (*tx_data.as_mut_ptr()).fragment_table.as_mut_ptr(), + fragment_count as usize, + ); }; + self.write_inner(tx_data.as_mut_ptr(), timeout).map(|_| data_length as usize) + } + + fn write_inner( + &self, + tx_data: *mut tcp4::TransmitData, + timeout: Option, + ) -> io::Result<()> { + let evt = unsafe { self.create_evt() }?; + let completion_token = + tcp4::CompletionToken { event: evt.as_ptr(), status: Status::SUCCESS }; + + let protocol = self.protocol.as_ptr(); + let mut token = tcp4::IoToken { completion_token, packet: tcp4::IoTokenPacket { tx_data } }; + let r = unsafe { ((*protocol).transmit)(protocol, &mut token) }; if r.is_error() { return Err(io::Error::from_raw_os_error(r.as_usize())); @@ -143,7 +188,7 @@ impl Tcp4 { if completion_token.status.is_error() { Err(io::Error::from_raw_os_error(completion_token.status.as_usize())) } else { - Ok(data_len as usize) + Ok(()) } } diff --git a/library/std/src/sys/pal/uefi/helpers.rs b/library/std/src/sys/pal/uefi/helpers.rs index c0d69c3e0029a..852e0d6b051bd 100644 --- a/library/std/src/sys/pal/uefi/helpers.rs +++ b/library/std/src/sys/pal/uefi/helpers.rs @@ -12,6 +12,7 @@ use r_efi::efi::{self, Guid}; use r_efi::protocols::{device_path, device_path_to_text, service_binding, shell}; +use crate::alloc::Layout; use crate::ffi::{OsStr, OsString}; use crate::io::{self, const_error}; use crate::marker::PhantomData; @@ -769,3 +770,39 @@ pub(crate) const fn ipv4_to_r_efi(addr: crate::net::Ipv4Addr) -> efi::Ipv4Addres pub(crate) const fn ipv4_from_r_efi(ip: efi::Ipv4Address) -> crate::net::Ipv4Addr { crate::net::Ipv4Addr::new(ip.addr[0], ip.addr[1], ip.addr[2], ip.addr[3]) } + +/// This type is intended for use with ZSTs. Since such types are unsized, a reference to such types +/// is not valid in Rust. Thus, only pointers should be used when interacting with such types. +pub(crate) struct UefiBox { + inner: NonNull, + size: usize, +} + +impl UefiBox { + pub(crate) fn new(len: usize) -> io::Result { + assert!(len >= size_of::()); + // UEFI always expects types to be 8 byte aligned. + let layout = Layout::from_size_align(len, 8).unwrap(); + let ptr = unsafe { crate::alloc::alloc(layout) }; + + match NonNull::new(ptr.cast()) { + Some(inner) => Ok(Self { inner, size: len }), + None => Err(io::Error::new(io::ErrorKind::OutOfMemory, "Allocation failed")), + } + } + + pub(crate) fn write(&mut self, data: T) { + unsafe { self.inner.write(data) } + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut T { + self.inner.as_ptr().cast() + } +} + +impl Drop for UefiBox { + fn drop(&mut self) { + let layout = Layout::from_size_align(self.size, 8).unwrap(); + unsafe { crate::alloc::dealloc(self.inner.as_ptr().cast(), layout) }; + } +} From 1bc898e2535a5751f2abf2f9b98331086087bdc7 Mon Sep 17 00:00:00 2001 From: Jamesbarford Date: Mon, 3 Nov 2025 11:54:43 +0000 Subject: [PATCH 07/15] test for aarch64-unknown-uefi --- .../src/directives/directive_names.rs | 1 + .../aarch64-unknown-uefi-chkstk-98254.rs | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 tests/ui/stack-probes/aarch64-unknown-uefi-chkstk-98254.rs diff --git a/src/tools/compiletest/src/directives/directive_names.rs b/src/tools/compiletest/src/directives/directive_names.rs index 3a46dbc704e87..d5a3745728e48 100644 --- a/src/tools/compiletest/src/directives/directive_names.rs +++ b/src/tools/compiletest/src/directives/directive_names.rs @@ -190,6 +190,7 @@ pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "only-aarch64", "only-aarch64-apple-darwin", "only-aarch64-unknown-linux-gnu", + "only-aarch64-unknown-uefi", "only-apple", "only-arm", "only-arm64ec", diff --git a/tests/ui/stack-probes/aarch64-unknown-uefi-chkstk-98254.rs b/tests/ui/stack-probes/aarch64-unknown-uefi-chkstk-98254.rs new file mode 100644 index 0000000000000..36273d5a5e3f0 --- /dev/null +++ b/tests/ui/stack-probes/aarch64-unknown-uefi-chkstk-98254.rs @@ -0,0 +1,16 @@ +//! Regression test for #98254, missing `__chkstk` symbol on `aarch64-unknown-uefi`. +//@ build-pass +//@ only-aarch64-unknown-uefi +//@ compile-flags: -Cpanic=abort +//@ compile-flags: -Clinker=rust-lld +#![no_std] +#![no_main] +#[panic_handler] +fn panic_handler(_info: &core::panic::PanicInfo) -> ! { + loop {} +} + +#[export_name = "efi_main"] +fn main() { + let b = [0; 1024]; +} From 4959d18a97c8b187db6fd0010546f46c3137e3c8 Mon Sep 17 00:00:00 2001 From: Paul Murphy Date: Thu, 28 Aug 2025 14:44:34 -0500 Subject: [PATCH 08/15] Rename -Zno-jump-tables to -Zjump-tables= Both gcc and llvm accept -fjump-tables as well as -fno-jump-tables. For consistency, allow rustc to accept -Zjump-tables=yes too. --- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- compiler/rustc_interface/src/tests.rs | 2 +- compiler/rustc_session/src/options.rs | 4 ++-- .../src/compiler-flags/jump-tables.md | 19 +++++++++++++++++++ .../src/compiler-flags/no-jump-tables.md | 19 ------------------- tests/assembly-llvm/x86_64-no-jump-tables.rs | 4 ++-- tests/codegen-llvm/no-jump-tables.rs | 10 ++++++---- 7 files changed, 31 insertions(+), 29 deletions(-) create mode 100644 src/doc/unstable-book/src/compiler-flags/jump-tables.md delete mode 100644 src/doc/unstable-book/src/compiler-flags/no-jump-tables.md diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 209b8efa2c3b3..d22f40fd05a96 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -229,7 +229,7 @@ fn instrument_function_attr<'ll>( } fn nojumptables_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> { - if !sess.opts.unstable_opts.no_jump_tables { + if sess.opts.unstable_opts.jump_tables { return None; } diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index be33db21d1df6..384c38d3c395a 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -814,6 +814,7 @@ fn test_unstable_options_tracking_hash() { tracked!(inline_mir_threshold, Some(123)); tracked!(instrument_mcount, true); tracked!(instrument_xray, Some(InstrumentXRay::default())); + tracked!(jump_tables, false); tracked!(link_directives, false); tracked!(link_only, true); tracked!(lint_llvm_ir, true); @@ -831,7 +832,6 @@ fn test_unstable_options_tracking_hash() { tracked!(mutable_noalias, false); tracked!(next_solver, NextSolverConfig { coherence: true, globally: true }); tracked!(no_generate_arange_section, true); - tracked!(no_jump_tables, true); tracked!(no_link, true); tracked!(no_profiler_runtime, true); tracked!(no_trait_vptr, true); diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index b89aec7d22a91..d10fd17677b73 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2395,6 +2395,8 @@ options! { `=skip-entry` `=skip-exit` Multiple options can be combined with commas."), + jump_tables: bool = (true, parse_bool, [TRACKED], + "allow jump table and lookup table generation from switch case lowering (default: yes)"), layout_seed: Option = (None, parse_opt_number, [TRACKED], "seed layout randomization"), link_directives: bool = (true, parse_bool, [TRACKED], @@ -2475,8 +2477,6 @@ options! { "omit DWARF address ranges that give faster lookups"), no_implied_bounds_compat: bool = (false, parse_bool, [TRACKED], "disable the compatibility version of the `implied_bounds_ty` query"), - no_jump_tables: bool = (false, parse_no_value, [TRACKED], - "disable the jump tables and lookup tables that can be generated from a switch case lowering"), no_leak_check: bool = (false, parse_no_value, [UNTRACKED], "disable the 'leak check' for subtyping; unsound, but useful for tests"), no_link: bool = (false, parse_no_value, [TRACKED], diff --git a/src/doc/unstable-book/src/compiler-flags/jump-tables.md b/src/doc/unstable-book/src/compiler-flags/jump-tables.md new file mode 100644 index 0000000000000..3abf703cd361a --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/jump-tables.md @@ -0,0 +1,19 @@ +# `jump-tables` + +The tracking issue for this feature is [#116592](https://github.com/rust-lang/rust/issues/116592) + +--- + +When set to no, this option enables the `-fno-jump-tables` flag for LLVM, which makes the +codegen backend avoid generating jump tables when lowering switches. + +When set to no, this option adds the LLVM `no-jump-tables=true` attribute to every function. + +Disabling jump tables can be used to help provide protection against +jump-oriented-programming (JOP) attacks, such as with the linux kernel's [IBT]. + +```sh +RUSTFLAGS="-Zjump-tables=no" cargo +nightly build -Z build-std +``` + +[IBT]: https://www.phoronix.com/news/Linux-IBT-By-Default-Tip diff --git a/src/doc/unstable-book/src/compiler-flags/no-jump-tables.md b/src/doc/unstable-book/src/compiler-flags/no-jump-tables.md deleted file mode 100644 index f096c20f4bd54..0000000000000 --- a/src/doc/unstable-book/src/compiler-flags/no-jump-tables.md +++ /dev/null @@ -1,19 +0,0 @@ -# `no-jump-tables` - -The tracking issue for this feature is [#116592](https://github.com/rust-lang/rust/issues/116592) - ---- - -This option enables the `-fno-jump-tables` flag for LLVM, which makes the -codegen backend avoid generating jump tables when lowering switches. - -This option adds the LLVM `no-jump-tables=true` attribute to every function. - -The option can be used to help provide protection against -jump-oriented-programming (JOP) attacks, such as with the linux kernel's [IBT]. - -```sh -RUSTFLAGS="-Zno-jump-tables" cargo +nightly build -Z build-std -``` - -[IBT]: https://www.phoronix.com/news/Linux-IBT-By-Default-Tip diff --git a/tests/assembly-llvm/x86_64-no-jump-tables.rs b/tests/assembly-llvm/x86_64-no-jump-tables.rs index bb10042d8f629..0108c8817e350 100644 --- a/tests/assembly-llvm/x86_64-no-jump-tables.rs +++ b/tests/assembly-llvm/x86_64-no-jump-tables.rs @@ -1,10 +1,10 @@ -// Test that jump tables are (not) emitted when the `-Zno-jump-tables` +// Test that jump tables are (not) emitted when the `-Zjump-tables=no` // flag is (not) set. //@ revisions: unset set //@ assembly-output: emit-asm //@ compile-flags: -Copt-level=3 -//@ [set] compile-flags: -Zno-jump-tables +//@ [set] compile-flags: -Zjump-tables=no //@ only-x86_64 //@ ignore-sgx diff --git a/tests/codegen-llvm/no-jump-tables.rs b/tests/codegen-llvm/no-jump-tables.rs index 8f607e38350de..00609cff38d93 100644 --- a/tests/codegen-llvm/no-jump-tables.rs +++ b/tests/codegen-llvm/no-jump-tables.rs @@ -1,11 +1,12 @@ // Test that the `no-jump-tables` function attribute are (not) emitted when -// the `-Zno-jump-tables` flag is (not) set. +// the `-Zjump-tables=no` flag is (not) set. //@ add-minicore -//@ revisions: unset set +//@ revisions: unset set_no set_yes //@ needs-llvm-components: x86 //@ compile-flags: --target x86_64-unknown-linux-gnu -//@ [set] compile-flags: -Zno-jump-tables +//@ [set_no] compile-flags: -Zjump-tables=no +//@ [set_yes] compile-flags: -Zjump-tables=yes #![crate_type = "lib"] #![feature(no_core, lang_items)] @@ -19,5 +20,6 @@ pub fn foo() { // CHECK: @foo() unnamed_addr #0 // unset-NOT: attributes #0 = { {{.*}}"no-jump-tables"="true"{{.*}} } - // set: attributes #0 = { {{.*}}"no-jump-tables"="true"{{.*}} } + // set_yes-NOT: attributes #0 = { {{.*}}"no-jump-tables"="true"{{.*}} } + // set_no: attributes #0 = { {{.*}}"no-jump-tables"="true"{{.*}} } } From bb9d800b780f370578a40620cc9cc46dae8fd868 Mon Sep 17 00:00:00 2001 From: Paul Murphy Date: Thu, 28 Aug 2025 15:22:35 -0500 Subject: [PATCH 09/15] Stabilize -Zjump-tables= into -Cjump-table= --- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- compiler/rustc_interface/src/tests.rs | 2 +- compiler/rustc_session/src/options.rs | 4 ++-- src/doc/rustc/src/codegen-options/index.md | 13 +++++++++++++ .../src/compiler-flags/jump-tables.md | 19 ------------------- tests/assembly-llvm/x86_64-no-jump-tables.rs | 4 ++-- tests/codegen-llvm/no-jump-tables.rs | 6 +++--- 7 files changed, 22 insertions(+), 28 deletions(-) delete mode 100644 src/doc/unstable-book/src/compiler-flags/jump-tables.md diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index d22f40fd05a96..ac20f9c64fa1a 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -229,7 +229,7 @@ fn instrument_function_attr<'ll>( } fn nojumptables_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> { - if sess.opts.unstable_opts.jump_tables { + if sess.opts.cg.jump_tables { return None; } diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 384c38d3c395a..6c08b37dec083 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -620,6 +620,7 @@ fn test_codegen_options_tracking_hash() { tracked!(force_frame_pointers, FramePointer::Always); tracked!(force_unwind_tables, Some(true)); tracked!(instrument_coverage, InstrumentCoverage::Yes); + tracked!(jump_tables, false); tracked!(link_dead_code, Some(true)); tracked!(linker_plugin_lto, LinkerPluginLto::LinkerPluginAuto); tracked!(llvm_args, vec![String::from("1"), String::from("2")]); @@ -814,7 +815,6 @@ fn test_unstable_options_tracking_hash() { tracked!(inline_mir_threshold, Some(123)); tracked!(instrument_mcount, true); tracked!(instrument_xray, Some(InstrumentXRay::default())); - tracked!(jump_tables, false); tracked!(link_directives, false); tracked!(link_only, true); tracked!(lint_llvm_ir, true); diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index d10fd17677b73..c9d73adf31d49 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2093,6 +2093,8 @@ options! { "instrument the generated code to support LLVM source-based code coverage reports \ (note, the compiler build config must include `profiler = true`); \ implies `-C symbol-mangling-version=v0`"), + jump_tables: bool = (true, parse_bool, [TRACKED], + "allow jump table and lookup table generation from switch case lowering (default: yes)"), link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED], "a single extra argument to append to the linker invocation (can be used several times)"), link_args: Vec = (Vec::new(), parse_list, [UNTRACKED], @@ -2395,8 +2397,6 @@ options! { `=skip-entry` `=skip-exit` Multiple options can be combined with commas."), - jump_tables: bool = (true, parse_bool, [TRACKED], - "allow jump table and lookup table generation from switch case lowering (default: yes)"), layout_seed: Option = (None, parse_opt_number, [TRACKED], "seed layout randomization"), link_directives: bool = (true, parse_bool, [TRACKED], diff --git a/src/doc/rustc/src/codegen-options/index.md b/src/doc/rustc/src/codegen-options/index.md index f2cf1d447aa5a..04901e5dda974 100644 --- a/src/doc/rustc/src/codegen-options/index.md +++ b/src/doc/rustc/src/codegen-options/index.md @@ -209,6 +209,19 @@ Note that while the `-C instrument-coverage` option is stable, the profile data format produced by the resulting instrumentation may change, and may not work with coverage tools other than those built and shipped with the compiler. +## jump-tables + +This option is used to allow or prevent the LLVM codegen backend from creating +jump tables when lowering switches. + +* `y`, `yes`, `on`, `true` or no value: allow jump tables (the default). +* `n`, `no`, `off` or `false`: disable jump tables. + +Disabling jump tables can be used to help provide protection against +jump-oriented-programming (JOP) attacks. However, this option makes +no guarantee any precompiled or external dependencies are compiled +with or without jump tables. + ## link-arg This flag lets you append a single extra argument to the linker invocation. diff --git a/src/doc/unstable-book/src/compiler-flags/jump-tables.md b/src/doc/unstable-book/src/compiler-flags/jump-tables.md deleted file mode 100644 index 3abf703cd361a..0000000000000 --- a/src/doc/unstable-book/src/compiler-flags/jump-tables.md +++ /dev/null @@ -1,19 +0,0 @@ -# `jump-tables` - -The tracking issue for this feature is [#116592](https://github.com/rust-lang/rust/issues/116592) - ---- - -When set to no, this option enables the `-fno-jump-tables` flag for LLVM, which makes the -codegen backend avoid generating jump tables when lowering switches. - -When set to no, this option adds the LLVM `no-jump-tables=true` attribute to every function. - -Disabling jump tables can be used to help provide protection against -jump-oriented-programming (JOP) attacks, such as with the linux kernel's [IBT]. - -```sh -RUSTFLAGS="-Zjump-tables=no" cargo +nightly build -Z build-std -``` - -[IBT]: https://www.phoronix.com/news/Linux-IBT-By-Default-Tip diff --git a/tests/assembly-llvm/x86_64-no-jump-tables.rs b/tests/assembly-llvm/x86_64-no-jump-tables.rs index 0108c8817e350..e469aee7ed945 100644 --- a/tests/assembly-llvm/x86_64-no-jump-tables.rs +++ b/tests/assembly-llvm/x86_64-no-jump-tables.rs @@ -1,10 +1,10 @@ -// Test that jump tables are (not) emitted when the `-Zjump-tables=no` +// Test that jump tables are (not) emitted when the `-Cjump-tables=no` // flag is (not) set. //@ revisions: unset set //@ assembly-output: emit-asm //@ compile-flags: -Copt-level=3 -//@ [set] compile-flags: -Zjump-tables=no +//@ [set] compile-flags: -Cjump-tables=no //@ only-x86_64 //@ ignore-sgx diff --git a/tests/codegen-llvm/no-jump-tables.rs b/tests/codegen-llvm/no-jump-tables.rs index 00609cff38d93..ff79c43dfc9c6 100644 --- a/tests/codegen-llvm/no-jump-tables.rs +++ b/tests/codegen-llvm/no-jump-tables.rs @@ -1,12 +1,12 @@ // Test that the `no-jump-tables` function attribute are (not) emitted when -// the `-Zjump-tables=no` flag is (not) set. +// the `-Cjump-tables=no` flag is (not) set. //@ add-minicore //@ revisions: unset set_no set_yes //@ needs-llvm-components: x86 //@ compile-flags: --target x86_64-unknown-linux-gnu -//@ [set_no] compile-flags: -Zjump-tables=no -//@ [set_yes] compile-flags: -Zjump-tables=yes +//@ [set_no] compile-flags: -Cjump-tables=no +//@ [set_yes] compile-flags: -Cjump-tables=yes #![crate_type = "lib"] #![feature(no_core, lang_items)] From a78ba93220401af94afbab46c90b811f94cd4453 Mon Sep 17 00:00:00 2001 From: Paul Murphy Date: Thu, 11 Sep 2025 11:56:27 -0500 Subject: [PATCH 10/15] Improve documentation of -Cjump-tables Be more verbose about what this option can and cannot do. --- src/doc/rustc/src/codegen-options/index.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/doc/rustc/src/codegen-options/index.md b/src/doc/rustc/src/codegen-options/index.md index 04901e5dda974..f0f991ed0c909 100644 --- a/src/doc/rustc/src/codegen-options/index.md +++ b/src/doc/rustc/src/codegen-options/index.md @@ -212,15 +212,23 @@ with coverage tools other than those built and shipped with the compiler. ## jump-tables This option is used to allow or prevent the LLVM codegen backend from creating -jump tables when lowering switches. +jump tables when lowering switches from Rust code. * `y`, `yes`, `on`, `true` or no value: allow jump tables (the default). * `n`, `no`, `off` or `false`: disable jump tables. +To prevent jump tables being created from Rust code, a target must ensure +all crates are compiled with jump tables disabled. + +Note, in many cases the Rust toolchain is distributed with precompiled +crates, such as the core and std crates, which could possibly include +jump tables. Furthermore, this option does not guarantee a target will +be free of jump tables. They could arise from external dependencies, +inline asm, or other complicated interactions when using crates which +are compiled with jump table support. + Disabling jump tables can be used to help provide protection against -jump-oriented-programming (JOP) attacks. However, this option makes -no guarantee any precompiled or external dependencies are compiled -with or without jump tables. +jump-oriented-programming (JOP) attacks. ## link-arg From b24b7bd6e6f784c67ce5df03d1e8611fdb7fe20a Mon Sep 17 00:00:00 2001 From: rustbot <47979223+rustbot@users.noreply.github.com> Date: Mon, 3 Nov 2025 18:01:33 +0100 Subject: [PATCH 11/15] Update books --- src/doc/book | 2 +- src/doc/edition-guide | 2 +- src/doc/reference | 2 +- src/doc/rust-by-example | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/doc/book b/src/doc/book index af415fc6c8a68..f660f341887c8 160000 --- a/src/doc/book +++ b/src/doc/book @@ -1 +1 @@ -Subproject commit af415fc6c8a6823dfb4595074f27d5a3e9e2fe49 +Subproject commit f660f341887c8bbcd6c24fbfdf5d2a262f523965 diff --git a/src/doc/edition-guide b/src/doc/edition-guide index e2ed891f00361..5c621253d8f2a 160000 --- a/src/doc/edition-guide +++ b/src/doc/edition-guide @@ -1 +1 @@ -Subproject commit e2ed891f00361efc26616d82590b1c85d7a8920e +Subproject commit 5c621253d8f2a5a4adb64a6365905db67dffe3a2 diff --git a/src/doc/reference b/src/doc/reference index 752eab01cebdd..e122eefff3fef 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit 752eab01cebdd6a2d90b53087298844c251859a1 +Subproject commit e122eefff3fef362eb7e0c08fb7ffbf5f9461905 diff --git a/src/doc/rust-by-example b/src/doc/rust-by-example index 2c9b490d70e53..160e6bbca70b0 160000 --- a/src/doc/rust-by-example +++ b/src/doc/rust-by-example @@ -1 +1 @@ -Subproject commit 2c9b490d70e535cf166bf17feba59e594579843f +Subproject commit 160e6bbca70b0c01aa4de88d19db7fc5ff8447c3 From 97e69d13e1d261685d3df6d9cf21613bbdfb3d75 Mon Sep 17 00:00:00 2001 From: Martin Nordholts Date: Mon, 3 Nov 2025 19:29:36 +0100 Subject: [PATCH 12/15] tidy: Fix false positives with absolute repo paths in `pal.rs` `check()` Fixes the bug: 1. git clone https://github.com/rust-lang/rust.git rust-improve-tests 2. cd rust-improve-tests 3. ./x test tidy Expected: No tidy errors found Actual: ``` thread 'pal (library)' (837175) panicked at src/tools/tidy/src/pal.rs:100:5: assertion failed: saw_target_arch ``` Since the git checkout dir contains the word "tests", the `pal.rs` `check()` used to erroneously ignore all paths. --- src/tools/tidy/src/pal.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index dfca2cda9a0f8..f03dde6257d76 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -68,14 +68,20 @@ const EXCEPTION_PATHS: &[&str] = &[ "library/std/src/io/error.rs", // Repr unpacked needed for UEFI ]; -pub fn check(path: &Path, tidy_ctx: TidyCtx) { - let mut check = tidy_ctx.start_check(CheckId::new("pal").path(path)); +pub fn check(library_path: &Path, tidy_ctx: TidyCtx) { + let mut check = tidy_ctx.start_check(CheckId::new("pal").path(library_path)); + + let root_path = library_path.parent().unwrap(); + // Let's double-check that this is the root path by making sure it has `x.py`. + assert!(root_path.join("x.py").is_file()); // Sanity check that the complex parsing here works. let mut saw_target_arch = false; let mut saw_cfg_bang = false; - walk(path, |path, _is_dir| filter_dirs(path), &mut |entry, contents| { + walk(library_path, |path, _is_dir| filter_dirs(path), &mut |entry, contents| { let file = entry.path(); + // We don't want the absolute path to matter, so make it relative. + let file = file.strip_prefix(root_path).unwrap(); let filestr = file.to_string_lossy().replace("\\", "/"); if !filestr.ends_with(".rs") { return; From fd1112557ea063727c3aa37cd95b36f741098f77 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 1 Nov 2025 08:55:44 +0100 Subject: [PATCH 13/15] CI: rfl: move to temporary commit to support `-Cjump-tables=n` Link: https://github.com/rust-lang/rust/pull/145974 Signed-off-by: Miguel Ojeda --- src/ci/docker/scripts/rfl-build.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ci/docker/scripts/rfl-build.sh b/src/ci/docker/scripts/rfl-build.sh index b7d7151b171d5..e7f86e10f55a5 100755 --- a/src/ci/docker/scripts/rfl-build.sh +++ b/src/ci/docker/scripts/rfl-build.sh @@ -2,7 +2,8 @@ set -euo pipefail -LINUX_VERSION=v6.17-rc5 +# https://github.com/rust-lang/rust/pull/145974 +LINUX_VERSION=842cfd8e5aff3157cb25481b2900b49c188d628a # Build rustc, rustdoc, cargo, clippy-driver and rustfmt ../x.py build --stage 2 library rustdoc clippy rustfmt From 4ab1fc5127bd66ba3f431e7aa886e4dc54340317 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 17 Nov 2024 23:30:20 +0000 Subject: [PATCH 14/15] Provide more context on `Fn` closure modifying binding When modifying a binding from inside of an `Fn` closure, point at the binding definition and suggest using an `std::sync` type that would allow the code to compile. ``` error[E0594]: cannot assign to `counter`, as it is a captured variable in a `Fn` closure --> f703.rs:6:9 | 4 | let mut counter = 0; | ----------- `counter` declared here, outside the closure 5 | let x: Box = Box::new(|| { | -- in this closure 6 | counter += 1; | ^^^^^^^^^^^^ cannot assign ``` --- .../src/diagnostics/mutability_errors.rs | 58 ++++++++++++++++--- .../async-closures/wrong-fn-kind.stderr | 2 + .../borrow-immutable-upvar-mutation.stderr | 7 +++ .../borrow-raw-address-of-mutability.stderr | 2 + tests/ui/borrowck/mutability-errors.stderr | 16 +++-- ...bility-violation-with-closure-21600.stderr | 5 ++ ...wrong-closure-arg-suggestion-125325.stderr | 5 ++ tests/ui/nll/closure-captures.stderr | 6 +- ...sures-mutated-upvar-from-fn-closure.stderr | 2 + 9 files changed, 90 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index e23c7eebeca1e..db746242ac05c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -150,8 +150,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } } } - PlaceRef { local: _, projection: [proj_base @ .., ProjectionElem::Deref] } => { - if the_place_err.local == ty::CAPTURE_STRUCT_LOCAL + PlaceRef { local, projection: [proj_base @ .., ProjectionElem::Deref] } => { + if local == ty::CAPTURE_STRUCT_LOCAL && proj_base.is_empty() && !self.upvars.is_empty() { @@ -165,10 +165,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ", as `Fn` closures cannot mutate their captured variables".to_string() } } else { - let source = self.borrowed_content_source(PlaceRef { - local: the_place_err.local, - projection: proj_base, - }); + let source = + self.borrowed_content_source(PlaceRef { local, projection: proj_base }); let pointer_type = source.describe_for_immutable_place(self.infcx.tcx); opt_source = Some(source); if let Some(desc) = self.describe_place(access_place.as_ref()) { @@ -532,6 +530,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { PlaceRef { local, projection: [ProjectionElem::Deref] } if local == ty::CAPTURE_STRUCT_LOCAL && !self.upvars.is_empty() => { + self.point_at_binding_outside_closure(&mut err, local, access_place); self.expected_fn_found_fn_mut_call(&mut err, span, act); } @@ -950,6 +949,50 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } } + /// When modifying a binding from inside of an `Fn` closure, point at the binding definition. + fn point_at_binding_outside_closure( + &self, + err: &mut Diag<'_>, + local: Local, + access_place: Place<'tcx>, + ) { + let place = access_place.as_ref(); + for (index, elem) in place.projection.into_iter().enumerate() { + if let ProjectionElem::Deref = elem { + if index == 0 { + if self.body.local_decls[local].is_ref_for_guard() { + continue; + } + if let LocalInfo::StaticRef { .. } = *self.body.local_decls[local].local_info() + { + continue; + } + } + if let Some(field) = self.is_upvar_field_projection(PlaceRef { + local, + projection: place.projection.split_at(index + 1).0, + }) { + let var_index = field.index(); + let upvar = self.upvars[var_index]; + if let Some(hir_id) = upvar.info.capture_kind_expr_id { + let node = self.infcx.tcx.hir_node(hir_id); + if let hir::Node::Expr(expr) = node + && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind + && let hir::def::Res::Local(hir_id) = path.res + && let hir::Node::Pat(pat) = self.infcx.tcx.hir_node(hir_id) + { + let name = upvar.to_string(self.infcx.tcx); + err.span_label( + pat.span, + format!("`{name}` declared here, outside the closure"), + ); + break; + } + } + } + } + } + } /// Targeted error when encountering an `FnMut` closure where an `Fn` closure was expected. fn expected_fn_found_fn_mut_call(&self, err: &mut Diag<'_>, sp: Span, act: &str) { err.span_label(sp, format!("cannot {act}")); @@ -962,6 +1005,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let def_id = tcx.hir_enclosing_body_owner(fn_call_id); let mut look_at_return = true; + err.span_label(closure_span, "in this closure"); // If the HIR node is a function or method call, get the DefId // of the callee function or method, the span, and args of the call expr let get_call_details = || { @@ -1032,7 +1076,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { if let Some(span) = arg { err.span_label(span, "change this to accept `FnMut` instead of `Fn`"); err.span_label(call_span, "expects `Fn` instead of `FnMut`"); - err.span_label(closure_span, "in this closure"); look_at_return = false; } } @@ -1059,7 +1102,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { sig.decl.output.span(), "change this to return `FnMut` instead of `Fn`", ); - err.span_label(closure_span, "in this closure"); } _ => {} } diff --git a/tests/ui/async-await/async-closures/wrong-fn-kind.stderr b/tests/ui/async-await/async-closures/wrong-fn-kind.stderr index 95f314214cc65..dd0f4da5dd32b 100644 --- a/tests/ui/async-await/async-closures/wrong-fn-kind.stderr +++ b/tests/ui/async-await/async-closures/wrong-fn-kind.stderr @@ -25,6 +25,8 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `F LL | fn needs_async_fn(_: impl AsyncFn()) {} | -------------- change this to accept `FnMut` instead of `Fn` ... +LL | let mut x = 1; + | ----- `x` declared here, outside the closure LL | needs_async_fn(async || { | -------------- ^^^^^^^^ | | | diff --git a/tests/ui/borrowck/borrow-immutable-upvar-mutation.stderr b/tests/ui/borrowck/borrow-immutable-upvar-mutation.stderr index a0eaf1f163b02..4e40ebf738e3b 100644 --- a/tests/ui/borrowck/borrow-immutable-upvar-mutation.stderr +++ b/tests/ui/borrowck/borrow-immutable-upvar-mutation.stderr @@ -4,6 +4,8 @@ error[E0594]: cannot assign to `x`, as it is a captured variable in a `Fn` closu LL | fn to_fn>(f: F) -> F { | - change this to accept `FnMut` instead of `Fn` ... +LL | let mut x = 0; + | ----- `x` declared here, outside the closure LL | let _f = to_fn(|| x = 42); | ----- -- ^^^^^^ cannot assign | | | @@ -16,6 +18,8 @@ error[E0596]: cannot borrow `y` as mutable, as it is a captured variable in a `F LL | fn to_fn>(f: F) -> F { | - change this to accept `FnMut` instead of `Fn` ... +LL | let mut y = 0; + | ----- `y` declared here, outside the closure LL | let _g = to_fn(|| set(&mut y)); | ----- -- ^^^^^^ cannot borrow as mutable | | | @@ -28,6 +32,9 @@ error[E0594]: cannot assign to `z`, as it is a captured variable in a `Fn` closu LL | fn to_fn>(f: F) -> F { | - change this to accept `FnMut` instead of `Fn` ... +LL | let mut z = 0; + | ----- `z` declared here, outside the closure +... LL | to_fn(|| z = 42); | ----- -- ^^^^^^ cannot assign | | | diff --git a/tests/ui/borrowck/borrow-raw-address-of-mutability.stderr b/tests/ui/borrowck/borrow-raw-address-of-mutability.stderr index f81a8c99376f0..c4b97950727ac 100644 --- a/tests/ui/borrowck/borrow-raw-address-of-mutability.stderr +++ b/tests/ui/borrowck/borrow-raw-address-of-mutability.stderr @@ -40,6 +40,8 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `F LL | fn make_fn(f: F) -> F { f } | - change this to accept `FnMut` instead of `Fn` ... +LL | let mut x = 0; + | ----- `x` declared here, outside the closure LL | let f = make_fn(|| { | ------- -- in this closure | | diff --git a/tests/ui/borrowck/mutability-errors.stderr b/tests/ui/borrowck/mutability-errors.stderr index 3cab3ccb993c9..7307e1f2a86b2 100644 --- a/tests/ui/borrowck/mutability-errors.stderr +++ b/tests/ui/borrowck/mutability-errors.stderr @@ -139,7 +139,9 @@ error[E0594]: cannot assign to `x`, as it is a captured variable in a `Fn` closu | LL | fn fn_ref(f: F) -> F { f } | - change this to accept `FnMut` instead of `Fn` -... +LL | +LL | fn ref_closure(mut x: (i32,)) { + | ----- `x` declared here, outside the closure LL | fn_ref(|| { | ------ -- in this closure | | @@ -152,7 +154,9 @@ error[E0594]: cannot assign to `x.0`, as `Fn` closures cannot mutate their captu | LL | fn fn_ref(f: F) -> F { f } | - change this to accept `FnMut` instead of `Fn` -... +LL | +LL | fn ref_closure(mut x: (i32,)) { + | ----- `x` declared here, outside the closure LL | fn_ref(|| { | ------ -- in this closure | | @@ -166,7 +170,9 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `F | LL | fn fn_ref(f: F) -> F { f } | - change this to accept `FnMut` instead of `Fn` -... +LL | +LL | fn ref_closure(mut x: (i32,)) { + | ----- `x` declared here, outside the closure LL | fn_ref(|| { | ------ -- in this closure | | @@ -180,7 +186,9 @@ error[E0596]: cannot borrow `x.0` as mutable, as `Fn` closures cannot mutate the | LL | fn fn_ref(f: F) -> F { f } | - change this to accept `FnMut` instead of `Fn` -... +LL | +LL | fn ref_closure(mut x: (i32,)) { + | ----- `x` declared here, outside the closure LL | fn_ref(|| { | ------ -- in this closure | | diff --git a/tests/ui/closures/aliasability-violation-with-closure-21600.stderr b/tests/ui/closures/aliasability-violation-with-closure-21600.stderr index 2d2397a2141d9..2f4135b12fa5a 100644 --- a/tests/ui/closures/aliasability-violation-with-closure-21600.stderr +++ b/tests/ui/closures/aliasability-violation-with-closure-21600.stderr @@ -4,6 +4,9 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `F LL | fn call_it(f: F) where F: Fn() { f(); } | - change this to accept `FnMut` instead of `Fn` ... +LL | let mut x = A; + | ----- `x` declared here, outside the closure +... LL | call_it(|| x.gen_mut()); | ------- -- ^ cannot borrow as mutable | | | @@ -16,6 +19,8 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `F LL | fn call_it(f: F) where F: Fn() { f(); } | - change this to accept `FnMut` instead of `Fn` ... +LL | let mut x = A; + | ----- `x` declared here, outside the closure LL | call_it(|| { | ------- -- in this closure | | diff --git a/tests/ui/closures/wrong-closure-arg-suggestion-125325.stderr b/tests/ui/closures/wrong-closure-arg-suggestion-125325.stderr index e0cce8c4b3143..f419f7c1b44d3 100644 --- a/tests/ui/closures/wrong-closure-arg-suggestion-125325.stderr +++ b/tests/ui/closures/wrong-closure-arg-suggestion-125325.stderr @@ -4,6 +4,8 @@ error[E0594]: cannot assign to `x`, as it is a captured variable in a `Fn` closu LL | fn assoc_func(&self, _f: impl Fn()) -> usize { | --------- change this to accept `FnMut` instead of `Fn` ... +LL | let mut x = (); + | ----- `x` declared here, outside the closure LL | s.assoc_func(|| x = ()); | --------------^^^^^^- | | | | @@ -17,6 +19,9 @@ error[E0594]: cannot assign to `x`, as it is a captured variable in a `Fn` closu LL | fn func(_f: impl Fn()) -> usize { | --------- change this to accept `FnMut` instead of `Fn` ... +LL | let mut x = (); + | ----- `x` declared here, outside the closure +... LL | func(|| x = ()) | ---- -- ^^^^^^ cannot assign | | | diff --git a/tests/ui/nll/closure-captures.stderr b/tests/ui/nll/closure-captures.stderr index 828974c517e60..80ac033351aaa 100644 --- a/tests/ui/nll/closure-captures.stderr +++ b/tests/ui/nll/closure-captures.stderr @@ -47,7 +47,9 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `F | LL | fn fn_ref(f: F) -> F { f } | - change this to accept `FnMut` instead of `Fn` -... +LL | +LL | fn two_closures_ref_mut(mut x: i32) { + | ----- `x` declared here, outside the closure LL | fn_ref(|| { | ------ -- in this closure | | @@ -89,6 +91,8 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `F LL | fn fn_ref(f: F) -> F { f } | - change this to accept `FnMut` instead of `Fn` ... +LL | fn two_closures_ref(x: i32) { + | - `x` declared here, outside the closure LL | fn_ref(|| { | ------ -- in this closure | | diff --git a/tests/ui/unboxed-closures/unboxed-closures-mutated-upvar-from-fn-closure.stderr b/tests/ui/unboxed-closures/unboxed-closures-mutated-upvar-from-fn-closure.stderr index cbe42861d5ee2..f82faeea516f8 100644 --- a/tests/ui/unboxed-closures/unboxed-closures-mutated-upvar-from-fn-closure.stderr +++ b/tests/ui/unboxed-closures/unboxed-closures-mutated-upvar-from-fn-closure.stderr @@ -4,6 +4,8 @@ error[E0594]: cannot assign to `counter`, as it is a captured variable in a `Fn` LL | fn call(f: F) where F : Fn() { | - change this to accept `FnMut` instead of `Fn` ... +LL | let mut counter = 0; + | ----------- `counter` declared here, outside the closure LL | call(|| { | ---- -- in this closure | | From 75835fb8255df8ccfab39ed1d2dec6f28d23d97e Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Mon, 3 Nov 2025 17:17:14 -0800 Subject: [PATCH 15/15] Repoint Waker::from_fn_ptr from feature request issue to tracking issue --- library/core/src/task/wake.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index 178717fe42eac..480b3c4577eb6 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -588,7 +588,7 @@ impl Waker { /// Constructs a `Waker` from a function pointer. #[inline] #[must_use] - #[unstable(feature = "waker_from_fn_ptr", issue = "146055")] + #[unstable(feature = "waker_from_fn_ptr", issue = "148457")] pub const fn from_fn_ptr(f: fn()) -> Self { // SAFETY: Unsafe is used for transmutes, pointer came from `fn()` so it // is sound to transmute it back to `fn()`. @@ -905,7 +905,7 @@ impl LocalWaker { /// Constructs a `LocalWaker` from a function pointer. #[inline] #[must_use] - #[unstable(feature = "waker_from_fn_ptr", issue = "146055")] + #[unstable(feature = "waker_from_fn_ptr", issue = "148457")] pub const fn from_fn_ptr(f: fn()) -> Self { // SAFETY: Unsafe is used for transmutes, pointer came from `fn()` so it // is sound to transmute it back to `fn()`.