Skip to content

Commit c966a68

Browse files
committed
deallocate thread-local statics when the thread dies
1 parent 2987c76 commit c966a68

File tree

6 files changed

+63
-32
lines changed

6 files changed

+63
-32
lines changed

src/machine.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,10 @@ pub enum MiriMemoryKind {
6464
Global,
6565
/// Memory for extern statics.
6666
/// This memory may leak.
67-
ExternGlobal,
67+
ExternStatic,
68+
/// Memory for thread-local statics.
69+
/// This memory may leak.
70+
Tls,
6871
}
6972

7073
impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
@@ -80,7 +83,7 @@ impl MayLeak for MiriMemoryKind {
8083
use self::MiriMemoryKind::*;
8184
match self {
8285
Rust | C | WinHeap | Env => false,
83-
Machine | Global | ExternGlobal => true,
86+
Machine | Global | ExternStatic | Tls => true,
8487
}
8588
}
8689
}
@@ -94,8 +97,9 @@ impl fmt::Display for MiriMemoryKind {
9497
WinHeap => write!(f, "Windows heap"),
9598
Machine => write!(f, "machine-managed memory"),
9699
Env => write!(f, "environment variable"),
97-
Global => write!(f, "global"),
98-
ExternGlobal => write!(f, "extern global"),
100+
Global => write!(f, "global (static or const)"),
101+
ExternStatic => write!(f, "extern static"),
102+
Tls => write!(f, "thread-local static"),
99103
}
100104
}
101105
}
@@ -175,7 +179,7 @@ impl MemoryExtra {
175179
// "__cxa_thread_atexit_impl"
176180
// This should be all-zero, pointer-sized.
177181
let layout = this.machine.layouts.usize;
178-
let place = this.allocate(layout, MiriMemoryKind::ExternGlobal.into());
182+
let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
179183
this.write_scalar(Scalar::from_machine_usize(0, this), place.into())?;
180184
Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
181185
// "environ"
@@ -185,7 +189,7 @@ impl MemoryExtra {
185189
// "_tls_used"
186190
// This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
187191
let layout = this.machine.layouts.u8;
188-
let place = this.allocate(layout, MiriMemoryKind::ExternGlobal.into());
192+
let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
189193
this.write_scalar(Scalar::from_u8(0), place.into())?;
190194
Self::add_extern_static(this, "_tls_used", place.ptr);
191195
}

src/shims/env.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -383,9 +383,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
383383
this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
384384
} else {
385385
// No `environ` allocated yet, let's do that.
386-
// This is memory backing an extern static, hence `ExternGlobal`, not `Env`.
386+
// This is memory backing an extern static, hence `ExternStatic`, not `Env`.
387387
let layout = this.machine.layouts.usize;
388-
let place = this.allocate(layout, MiriMemoryKind::ExternGlobal.into());
388+
let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
389389
this.machine.env_vars.environ = Some(place);
390390
}
391391

src/shims/tls.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
364364

365365
// All dtors done!
366366
this.machine.tls.delete_all_thread_tls(active_thread);
367-
this.thread_terminated();
367+
this.thread_terminated()?;
368368

369369
Ok(())
370370
}

src/stacked_borrows.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -469,10 +469,10 @@ impl Stacks {
469469
// `Global` memory can be referenced by global pointers from `tcx`.
470470
// Thus we call `global_base_ptr` such that the global pointers get the same tag
471471
// as what we use here.
472-
// `ExternGlobal` is used for extern statics, and thus must also be listed here.
472+
// `ExternStatic` is used for extern statics, and thus must also be listed here.
473473
// `Env` we list because we can get away with precise tracking there.
474474
// The base pointer is not unique, so the base permission is `SharedReadWrite`.
475-
MemoryKind::Machine(MiriMemoryKind::Global | MiriMemoryKind::ExternGlobal | MiriMemoryKind::Env) =>
475+
MemoryKind::Machine(MiriMemoryKind::Global | MiriMemoryKind::ExternStatic | MiriMemoryKind::Tls | MiriMemoryKind::Env) =>
476476
(extra.borrow_mut().global_base_ptr(id), Permission::SharedReadWrite),
477477
// Everything else we handle entirely untagged for now.
478478
// FIXME: experiment with more precise tracking.

src/thread.rs

+35-21
Original file line numberDiff line numberDiff line change
@@ -410,18 +410,31 @@ impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
410410
None
411411
}
412412

413-
/// Handles thread termination of the active thread: wakes up threads joining on this one,
414-
/// and deallocated thread-local statics.
415-
///
416-
/// This is called from `tls.rs` after handling the TLS dtors.
417-
fn thread_terminated(&mut self) {
413+
/// Wakes up threads joining on the active one and deallocates thread-local statics.
414+
/// The `AllocId` that can now be freed is returned.
415+
fn thread_terminated(&mut self) -> Vec<AllocId> {
416+
let mut free_tls_statics = Vec::new();
417+
{
418+
let mut thread_local_statics = self.thread_local_alloc_ids.borrow_mut();
419+
thread_local_statics.retain(|&(_def_id, thread), &mut alloc_id| {
420+
if thread != self.active_thread {
421+
// Keep this static around.
422+
return true;
423+
}
424+
// Delete this static from the map and from memory.
425+
// We cannot free directly here as we cannot use `?` in this context.
426+
free_tls_statics.push(alloc_id);
427+
return false;
428+
});
429+
}
430+
// Check if we need to unblock any threads.
418431
for (i, thread) in self.threads.iter_enumerated_mut() {
419-
// Check if we need to unblock any threads.
420432
if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
421433
trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
422434
thread.state = ThreadState::Enabled;
423435
}
424436
}
437+
return free_tls_statics;
425438
}
426439

427440
/// Decide which action to take next and on which thread.
@@ -503,8 +516,8 @@ impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mi
503516
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
504517
/// Get a thread-specific allocation id for the given thread-local static.
505518
/// If needed, allocate a new one.
506-
fn get_or_create_thread_local_alloc_id(&self, def_id: DefId) -> InterpResult<'tcx, AllocId> {
507-
let this = self.eval_context_ref();
519+
fn get_or_create_thread_local_alloc_id(&mut self, def_id: DefId) -> InterpResult<'tcx, AllocId> {
520+
let this = self.eval_context_mut();
508521
let tcx = this.tcx;
509522
if let Some(new_alloc_id) = this.machine.threads.get_thread_local_alloc_id(def_id) {
510523
// We already have a thread-specific allocation id for this
@@ -513,21 +526,13 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
513526
} else {
514527
// We need to allocate a thread-specific allocation id for this
515528
// thread-local static.
516-
//
517-
// At first, we compute the initial value for this static.
518-
// Then we store the retrieved allocation back into the `alloc_map`
519-
// to get a fresh allocation id, which we can use as a
520-
// thread-specific allocation id for the thread-local static.
521-
// On first access to that allocation, it will be copied over to the machine memory.
529+
// First, we compute the initial value for this static.
522530
if tcx.is_foreign_item(def_id) {
523531
throw_unsup_format!("foreign thread-local statics are not supported");
524532
}
525533
let allocation = interpret::get_static(*tcx, def_id)?;
526-
// Create a new allocation id for the same allocation in this hacky
527-
// way. Internally, `alloc_map` deduplicates allocations, but this
528-
// is fine because Miri will make a copy before a first mutable
529-
// access.
530-
let new_alloc_id = tcx.create_memory_alloc(allocation);
534+
// Create a fresh allocation with this content.
535+
let new_alloc_id = this.memory.allocate_with(allocation.clone(), MiriMemoryKind::Tls.into()).alloc_id;
531536
this.machine.threads.set_thread_local_alloc_id(def_id, new_alloc_id);
532537
Ok(new_alloc_id)
533538
}
@@ -668,8 +673,17 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
668673
this.machine.threads.schedule()
669674
}
670675

676+
/// Handles thread termination of the active thread: wakes up threads joining on this one,
677+
/// and deallocated thread-local statics.
678+
///
679+
/// This is called from `tls.rs` after handling the TLS dtors.
671680
#[inline]
672-
fn thread_terminated(&mut self) {
673-
self.eval_context_mut().machine.threads.thread_terminated()
681+
fn thread_terminated(&mut self) -> InterpResult<'tcx> {
682+
let this = self.eval_context_mut();
683+
for alloc_id in this.machine.threads.thread_terminated() {
684+
let ptr = this.memory.global_base_pointer(alloc_id.into())?;
685+
this.memory.deallocate(ptr, None, MiriMemoryKind::Tls.into())?;
686+
}
687+
Ok(())
674688
}
675689
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// ignore-windows: Concurrency on Windows is not supported yet.
2+
3+
//! Ensure that thread-local statics get deallocated when the thread dies.
4+
5+
#![feature(thread_local)]
6+
7+
#[thread_local]
8+
static mut TLS: u8 = 0;
9+
10+
fn main() { unsafe {
11+
let dangling_ptr = std::thread::spawn(|| &TLS as *const u8 as usize).join().unwrap();
12+
let _val = *(dangling_ptr as *const u8);
13+
} }

0 commit comments

Comments
 (0)