Skip to content

Commit f248abb

Browse files
authored
Rollup merge of #163799 - ivmarkov:fix-thread-memory-leak, r=joboet
std: keep value of `local_pointer!` until `thread_cleanup` is run ( **NOTE**: LLM **was** used to write the initial version of these ~26 lines of code, subsequently also edited by me during the review (`LocalPointer::__new` now delegates to the new `LocalPointer::__new_with_dtor`; I did hide the `keep_current` inside the initialization block of `CURRENT`). ) The PR fixes a memory leak specific for the ESP-IDF target which happens during thread destruction. The TL;DR is that the current code relies on behavior which is **not** mandated by the POSIX spec, and just happens to work fine on the few major platforms that use that code (bionic, openbsd). More details [in this comment and the ones that follow](esp-rs/esp-idf#522 (comment)). Note also that - **according to the LLM** - `glibc` and `musl` would leak too, **if** they were using pthread keys in the first place. So it is not like ESP-IDF is the outlier here. In fact, the LLM even suggested `#[cfg(all(target_family = "unix", not(target_thread_local)))]` instead of `#[cfg(target_os = "espidf")]`, but let's take small steps. I can't test on those other platforms anyway, as they are relatively exotic (gnux32, open-harmony - basically `glibc` and `musl` targets without Native-TLS support). CC @joboet CC @kyrias
2 parents 235ddab + acbf22b commit f248abb

6 files changed

Lines changed: 73 additions & 23 deletions

File tree

‎library/std/src/sys/thread_local/guard/key.rs‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
//! destructors for native TLS. Instead, we use one TLS key with a destructor
33
//! that will run all native TLS destructors in the destructor list.
44
5-
use crate::ptr;
6-
use crate::sys::thread_local::key::{LazyKey, set};
7-
85
#[cfg(target_thread_local)]
96
pub fn enable() {
7+
use crate::ptr;
108
use crate::sys::thread_local::destructors;
9+
use crate::sys::thread_local::key::{LazyKey, set};
1110

1211
static DTORS: LazyKey = LazyKey::new(Some(run));
1312

@@ -30,18 +29,26 @@ pub fn enable() {
3029
}
3130
}
3231

33-
/// On platforms with key-based TLS, the system runs the destructors for us.
34-
/// We still have to make sure that [`crate::rt::thread_cleanup`] is called,
35-
/// however. This is done by deferring the execution of a TLS destructor to
36-
/// the next round of destruction inside the TLS destructors.
3732
#[cfg(not(target_thread_local))]
38-
pub fn enable() {
33+
pub use key_based::{LOCAL_POINTER_NEEDS_DTOR, cleanup_pending, enable};
34+
35+
#[cfg(not(target_thread_local))]
36+
mod key_based {
37+
use crate::ptr;
38+
use crate::sys::thread_local::key::{LazyKey, get, set};
39+
3940
const DEFER: *mut u8 = ptr::without_provenance_mut(1);
4041
const RUN: *mut u8 = ptr::without_provenance_mut(2);
4142

4243
static CLEANUP: LazyKey = LazyKey::new(Some(run));
4344

44-
unsafe { set(CLEANUP.force(), DEFER) }
45+
/// On platforms with key-based TLS, the system runs the destructors for us.
46+
/// We still have to make sure that [`crate::rt::thread_cleanup`] is called,
47+
/// however. This is done by deferring the execution of a TLS destructor to
48+
/// the next round of destruction inside the TLS destructors.
49+
pub fn enable() {
50+
unsafe { set(CLEANUP.force(), DEFER) }
51+
}
4552

4653
unsafe extern "C" fn run(state: *mut u8) {
4754
if state == DEFER {
@@ -57,4 +64,16 @@ pub fn enable() {
5764
crate::rt::thread_cleanup();
5865
}
5966
}
67+
68+
/// Whether [`crate::rt::thread_cleanup`] has yet to run on this thread.
69+
pub fn cleanup_pending() -> bool {
70+
!unsafe { get(CLEANUP.force()) }.is_null()
71+
}
72+
73+
/// The OS may free the values of the keys without a destructor **before**
74+
/// [`crate::rt::thread_cleanup`] runs (e.g. ESP-IDF, glibc and musl free
75+
/// them in the first round of TLS destruction). Hence, local pointers need
76+
/// a destructor, which stores the value again for as long as
77+
/// [`cleanup_pending`] returns `true`.
78+
pub const LOCAL_POINTER_NEEDS_DTOR: bool = true;
6079
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//! Guards which run all TLS destructors themselves, and only then
2+
//! [`crate::rt::thread_cleanup`], never free the values of keys without a
3+
//! destructor before the cleanup. Hence, local pointers need no destructor.
4+
5+
pub const LOCAL_POINTER_NEEDS_DTOR: bool = false;
6+
7+
/// Only referenced by the `keep` destructor of `local_pointer!`, which is
8+
/// never registered here (`LOCAL_POINTER_NEEDS_DTOR` is `false`).
9+
pub fn cleanup_pending() -> bool {
10+
rtabort!("`cleanup_pending` called although `LOCAL_POINTER_NEEDS_DTOR` is false")
11+
}

‎library/std/src/sys/thread_local/mod.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,10 @@ pub(crate) mod guard {
104104
target_os = "windows" => {
105105
mod windows;
106106
pub(crate) use windows::enable;
107+
#[cfg(not(target_thread_local))]
108+
mod retained;
109+
#[cfg(not(target_thread_local))]
110+
pub(crate) use retained::{LOCAL_POINTER_NEEDS_DTOR, cleanup_pending};
107111
}
108112
any(
109113
all(target_family = "wasm", not(target_os = "wasi")),
@@ -130,6 +134,10 @@ pub(crate) mod guard {
130134
// `std` is the only runtime, so it just calls the destructor functions
131135
// itself when the time comes.
132136
pub(crate) fn enable() {}
137+
#[cfg(not(target_thread_local))]
138+
mod retained;
139+
#[cfg(not(target_thread_local))]
140+
pub(crate) use retained::{LOCAL_POINTER_NEEDS_DTOR, cleanup_pending};
133141
}
134142
target_os = "solid_asp3" => {
135143
mod solid;
@@ -138,6 +146,8 @@ pub(crate) mod guard {
138146
_ => {
139147
mod key;
140148
pub(crate) use key::enable;
149+
#[cfg(not(target_thread_local))]
150+
pub(crate) use key::{LOCAL_POINTER_NEEDS_DTOR, cleanup_pending};
141151
}
142152
}
143153
}

‎library/std/src/sys/thread_local/os.rs‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -253,8 +253,25 @@ unsafe extern "C" fn destroy_value<T: 'static, const ALIGN: usize>(ptr: *mut u8)
253253
#[rustc_macro_transparency = "semiopaque"]
254254
pub(crate) macro local_pointer {
255255
() => {},
256+
// A local pointer stays readable until `crate::rt::thread_cleanup` has run.
257+
// The guard decides whether the key needs a destructor for that, which
258+
// stores the value again for as long as the cleanup is pending.
256259
($vis:vis static $name:ident; $($rest:tt)*) => {
257-
$vis static $name: $crate::sys::thread_local::LocalPointer = $crate::sys::thread_local::LocalPointer::__new();
260+
$vis static $name: $crate::sys::thread_local::LocalPointer = {
261+
unsafe extern "C" fn keep(value: *mut u8) {
262+
if $crate::sys::thread_local::guard::cleanup_pending() {
263+
$name.set(value.cast());
264+
}
265+
}
266+
267+
$crate::sys::thread_local::LocalPointer::__new(
268+
if $crate::sys::thread_local::guard::LOCAL_POINTER_NEEDS_DTOR {
269+
Some(keep)
270+
} else {
271+
None
272+
},
273+
)
274+
};
258275
$crate::sys::thread_local::local_pointer! { $($rest)* }
259276
},
260277
}
@@ -264,8 +281,8 @@ pub(crate) struct LocalPointer {
264281
}
265282

266283
impl LocalPointer {
267-
pub const fn __new() -> LocalPointer {
268-
LocalPointer { key: LazyKey::new(None) }
284+
pub const fn __new(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> LocalPointer {
285+
LocalPointer { key: LazyKey::new(dtor) }
269286
}
270287

271288
pub fn get(&'static self) -> *mut () {

‎library/std/tests/thread_local/lib.rs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
#![feature(cfg_target_thread_local)]
2-
31
#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))]
42
mod tests;
53

‎library/std/tests/thread_local/tests.rs‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -353,22 +353,17 @@ fn join_orders_after_tls_destructors() {
353353

354354
// Test that thread::current is still available in TLS destructors.
355355
//
356-
// The test won't currently work without target_thread_local, aka with slow tls.
357-
// The runtime tries very hard to drop last the TLS variable that keeps the information about the
358-
// current thread, by using several tricks like deferring the drop to a later round of TLS destruction.
359-
// However, this only seems to work with fast tls.
360-
//
361-
// With slow TLS, it seems that multiple libc implementations will just set the value to null the first
362-
// time they encounter it, regardless of it having a destructor or not. This means that trying to
363-
// retrieve it later in a drop impl of another TLS variable will not work.
356+
// With slow TLS (i.e. without target_thread_local), multiple libc implementations set the value of
357+
// a key to null the first time they encounter it, regardless of it having a destructor or not. The
358+
// handle of the current thread is stored in a local pointer, which stays readable until it is
359+
// dropped in the last round of TLS destruction.
364360
//
365361
// ** Apple libc: https://github.com/apple-oss-distributions/libpthread/blob/c032e0b076700a0a47db75528a282b8d3a06531a/src/pthread_tsd.c#L293
366362
// Sets the variable to null if it has a destructor and the value is not null. However, all variables
367363
// created with pthread_key_create are marked as having a destructor, even if the fn ptr called with
368364
// it is null.
369365
// ** glibc: https://github.com/bminor/glibc/blob/e5893e6349541d871e8a25120bca014551d13ff5/nptl/nptl_deallocate_tsd.c#L59
370366
// ** musl: https://github.com/kraj/musl/blob/1880359b54ff7dd9f5016002bfdae4b136007dde/src/thread/pthread_key_create.c#L87
371-
#[cfg(target_thread_local)]
372367
#[test]
373368
fn thread_current_in_dtor() {
374369
use std::thread::Builder;

0 commit comments

Comments
 (0)