Runtime: a program's exit handler reaches no destroyed thread-local

exit destroys the exiting thread's thread-locals before it runs the exit handlers (macOS, the
GNU C library), and LocalKey::with on a destroyed one panics, which in a handler aborts the
process. The exits lane case an_exit_handler_s_common_calls_answer_as_on_any_thread aborted
there on both: "cannot access a Thread Local Storage value during or after destruction" in
calls_at_exit on the M3, and on lavapipe at warm::pass::warming from PipelineMemo::compute,
in the handler's new_compute_pipeline_state.

Every runtime thread-local whose type needs dropping that a program's call reaches is now read
with try_with, with what the thread does once it can keep nothing:
- the making budget's turn (pipeline/budget.rs): program_turn takes none there, holds_turn is
  false, and a turn's give-back and lend read the note with try_with;
- the driver facts' expectation (driver_facts.rs): expecting runs the call alone, its messages
  relayed;
- the creation log's split (pipeline/creation_log.rs): none noted;
- the warm pass (warm/pass.rs): none;
- a relayed compile's held sink messages (device/compiles.rs): the call alone, its messages
  delivered as raised;
- a lowering's refusal (render/deferral.rs): lowering::refusing is false there, so a notice of
  a kind the device refuses while lowering is announced, as anywhere else;
- the debug-build checks of kept resident uses (binding.rs) and of slot rebinds (the
  translator's bind/graphics.rs): skipped.

dirty_pages, shards, resource_ids and contexts already read theirs with try_with; the rest hold
Copy values with no destructor. docs/API.md's accepted differences under "Process exit" say what
an exit handler's calls keep no state for.
This commit is contained in:
Anees Iqbal committed 2026-11-11 14:55:15 -08:00
1 parent 8a339f1e21
commit aba4034dca
11 files changed
+102 -38

No files matched your search

+9 -4
View File
@@ -2569,8 +2569,10 @@ pub(super) fn command_uses_into(
let keeps = uses_into(call, kept, (index, indirect), into)?;
if cfg!(debug_assertions) && keeps {
// Made whole over the last check's storage: a draw's allocations are bounded in builds
// with debug assertions too (`runtime_lane::frame_costs`).
WHOLE_USES.with_borrow_mut(|whole| {
// with debug assertions too (`runtime_lane::frame_costs`). None past the thread's
// thread-locals' end (a program's exit handler, `this_thread.rs`).
let checked = WHOLE_USES.try_with(|whole| {
let whole = &mut *whole.borrow_mut();
let made = (&**plan, None, command, tables);
uses_into(call, made, (index, indirect), whole)?;
let same = (into.uses == whole.uses && into.sources == whole.sources)
@@ -2580,8 +2582,11 @@ pub(super) fn command_uses_into(
"a command kept uses of what the encoder made resident not its own"
);
Ok::<_, Error>(())
})?;
KEPT_RESIDENT_CHECKS.with(|checks| checks.set(checks.get() + 1));
});
if let Ok(checked) = checked {
checked?;
KEPT_RESIDENT_CHECKS.with(|checks| checks.set(checks.get() + 1));
}
}
Ok(())
}
@@ -3602,7 +3602,7 @@ impl Device {
if refuses {
met_each();
}
if refuses && crate::render::lowering::current().is_some() {
if refuses && crate::render::lowering::refusing() {
let (object, reason) = describe();
crate::render::lowering::refuse(DegradeNotice::new(degradation, object, reason));
return;
@@ -283,10 +283,17 @@ pub(crate) fn holding<R>(call: impl FnOnce() -> R) -> (R, Vec<(MessageSink, Debu
let _ = HELD.try_with(|held| *held.borrow_mut() = outer);
}
}
let restore = Restore(HELD.with(|held| held.borrow_mut().replace(Vec::new())));
// Past this thread's thread-locals' end (a program's exit handler, `this_thread.rs`), `call`
// alone: its messages are delivered as they are raised.
let Ok(outer) = HELD.try_with(|held| held.borrow_mut().replace(Vec::new())) else {
return (call(), Vec::new());
};
let restore = Restore(outer);
let made = call();
let messages = HELD
.with(|held| held.borrow_mut().take())
.try_with(|held| held.borrow_mut().take())
.ok()
.flatten()
.unwrap_or_default();
drop(restore);
(made, messages)
@@ -74,7 +74,8 @@ thread_local! {
/// `MVKBaseObject::reportMessage`), so a message reported on another thread, or after the call
/// returns, relays. A pipeline making the runtime hands to a thread of its own at the
/// user-initiated class (`device/compiles.rs`) takes the expectation with it ([`expected_here`],
/// [`withheld_for_here`]). With no diagnostics, `call` alone.
/// [`withheld_for_here`]). With no diagnostics, or past this thread's thread-locals' end (a
/// program's exit handler, `this_thread.rs`), `call` alone, its messages relayed.
pub(crate) fn expecting<T>(
diagnostics: Vec<DriverDiagnostic>,
call: impl FnOnce() -> T,
@@ -89,15 +90,20 @@ pub(crate) fn expecting<T>(
let _ = EXPECTED.try_with(|expected| expected.borrow_mut().take());
}
}
EXPECTED.with(|expected| {
let set = EXPECTED.try_with(|expected| {
*expected.borrow_mut() = Some(Expected {
diagnostics,
withheld: 0,
})
});
if set.is_err() {
return (call(), 0);
}
let clear = Clear;
let result = call();
let withheld = EXPECTED.with(|expected| expected.borrow().as_ref().map_or(0, |e| e.withheld));
let withheld = EXPECTED
.try_with(|expected| expected.borrow().as_ref().map_or(0, |e| e.withheld))
.unwrap_or(0);
drop(clear);
(result, withheld)
}
@@ -166,9 +166,11 @@ pub(crate) fn waited_in_pool(waited: Duration) {
}
/// Whether this thread holds a turn now: a making's waits for another making assert it does
/// not (`making.rs`, the module docs' "no making waits on another while it holds a turn").
/// not (`making.rs`, the module docs' "no making waits on another while it holds a turn"). None
/// past its thread-locals' end ([`program_turn`]).
pub(crate) fn holds_turn() -> bool {
HELD.with(|held| held.borrow().is_some())
HELD.try_with(|held| held.borrow().is_some())
.unwrap_or(false)
}
/// A new ticket: later than every ticket drawn before it.
@@ -365,7 +367,10 @@ impl Drop for Turn {
fn drop(&mut self) {
// A turn lent and taken again at a rank that rose meanwhile may be of the other kind
// ([`Again`]): the thread's note says which it holds now.
let held = HELD.with(|held| held.borrow_mut().take());
let held = HELD
.try_with(|held| held.borrow_mut().take())
.ok()
.flatten();
self.budget
.give_back(held.map_or(self.ahead, |held| held.ahead));
}
@@ -497,7 +502,8 @@ impl Budget {
}
drop(state);
let budget = Arc::clone(self);
HELD.with(|held| {
// Past the thread's thread-locals' end no program's making asks ([`program_turn`]).
let _ = HELD.try_with(|held| {
*held.borrow_mut() = Some(Held {
budget,
ahead,
@@ -528,10 +534,14 @@ impl Budget {
}
/// A turn for a making this thread waits for, asked for now (the module docs): first in a host
/// step; `None` where this thread
/// holds one already (a pool's piece, a helper's making).
/// step; `None` where this thread holds one already (a pool's piece, a helper's making), or is
/// past its thread-locals' end (a program's exit handler, `this_thread.rs`), where it could note
/// none, and its making takes none.
pub(crate) fn program_turn() -> Option<Turn> {
if holds_turn() {
if HELD
.try_with(|held| held.borrow().is_some())
.unwrap_or(true)
{
return None;
}
thread_turn_in(process(), ticket())
@@ -586,7 +596,11 @@ pub(crate) fn helper_turn<M>(
/// holder of the thread's [`Turn`] gives back the turn it holds then at its end. Its wait counts
/// in the making's wait ([`take_waited`]).
pub(crate) fn without_turn<T>(wait: impl FnOnce() -> T) -> T {
let Some(held) = HELD.with(|held| held.borrow_mut().take()) else {
let Some(held) = HELD
.try_with(|held| held.borrow_mut().take())
.ok()
.flatten()
else {
return wait();
};
held.budget.give_back(held.ahead);
@@ -615,7 +629,7 @@ impl Drop for Again {
.budget
.take_held(Asker::Thread(urgency, ticket, asked));
// The piece's asks stay its turn's, for a later lend.
HELD.with(|held| {
let _ = HELD.try_with(|held| {
if let Some(held) = held.borrow_mut().as_mut() {
held.asked = self.0.asked.clone();
}
@@ -151,13 +151,15 @@ thread_local! {
/// Whether this thread notes the split of a making's time now: its line is timed
/// ([`Line::made`]). Each part's timing is taken only then.
pub(crate) fn splitting() -> bool {
SPLIT.with(|split| split.borrow().is_some())
SPLIT
.try_with(|split| split.borrow().is_some())
.unwrap_or(false)
}
/// Note a part of the making this thread's line times, which took `took`; nothing where none is
/// timed.
pub(crate) fn note(part: impl FnOnce() -> String, took: Duration) {
SPLIT.with(|split| {
let _ = SPLIT.try_with(|split| {
if let Some(parts) = split.borrow_mut().as_mut() {
parts.push((part(), took));
}
@@ -181,11 +183,18 @@ pub(crate) fn take_record() -> Option<bool> {
/// Run `make`, noting the split of its time on this thread ([`note`]): what it made and the
/// parts noted, the split of a making that encloses it (a line timed around this one) put back
/// after it.
/// after it. Past the thread's thread-locals' end (a program's exit handler, `this_thread.rs`),
/// none is noted.
fn split_of<T>(make: impl FnOnce() -> T) -> (T, Vec<(String, Duration)>) {
let enclosing = SPLIT.replace(Some(Vec::new()));
let Ok(enclosing) = SPLIT.try_with(|split| split.replace(Some(Vec::new()))) else {
return (make(), Vec::new());
};
let made = make();
let parts = SPLIT.replace(enclosing).unwrap_or_default();
let parts = SPLIT
.try_with(|split| split.replace(enclosing))
.ok()
.flatten()
.unwrap_or_default();
(made, parts)
}
@@ -1019,16 +1019,26 @@ pub(crate) mod lowering {
LOWERING.with(Cell::get)
}
/// Refuse the call being lowered for `notice`, a kind the device refuses while lowering: the
/// first such notice of the call is kept.
/// Whether a call is being lowered on this thread and a refusal of it can be kept: past the
/// thread's thread-locals' end (a program's exit handler, `this_thread.rs`) none can, and a
/// notice is announced as anywhere else.
pub(crate) fn refusing() -> bool {
current().is_some() && REFUSED.try_with(|_| ()).is_ok()
}
/// Refuse the call being lowered for `notice`, a kind the device refuses while lowering, where
/// [`refusing`]: the first such notice of the call is kept.
pub(crate) fn refuse(notice: DegradeNotice) {
REFUSED.with(|refused| {
let _ = REFUSED.try_with(|refused| {
refused.borrow_mut().get_or_insert(notice);
});
}
/// The notice that refused the call being lowered, if one did, let go of here.
pub(crate) fn take_refusal() -> Option<DegradeNotice> {
REFUSED.with(|refused| refused.borrow_mut().take())
REFUSED
.try_with(|refused| refused.borrow_mut().take())
.ok()
.flatten()
}
}
+11 -6
View File
@@ -72,13 +72,15 @@ thread_local! {
}
/// Whether this thread works for a warm pass now: the pass's thread, or a pool's piece it handed.
/// Past the thread's thread-locals' end (a program's exit handler, `this_thread.rs`), none.
pub(crate) fn warming() -> bool {
PASS.with(|pass| pass.borrow().is_some())
PASS.try_with(|pass| pass.borrow().is_some())
.unwrap_or(false)
}
/// The pass this thread works for now, which a piece it hands the pool works for too.
pub(crate) fn pass() -> Option<Arc<Pass>> {
PASS.with(|pass| pass.borrow().clone())
PASS.try_with(|pass| pass.borrow().clone()).ok().flatten()
}
/// Run `f` on this thread as part of `pass`, as it returns or unwinds restoring what the thread
@@ -88,10 +90,13 @@ pub(crate) fn within<T>(pass: &Arc<Pass>, f: impl FnOnce() -> T) -> T {
struct Restore(Option<Arc<Pass>>);
impl Drop for Restore {
fn drop(&mut self) {
PASS.with(|pass| *pass.borrow_mut() = self.0.clone());
let _ = PASS.try_with(|pass| *pass.borrow_mut() = self.0.clone());
}
}
let earlier = PASS.with(|current| current.replace(Some(Arc::clone(pass))));
let earlier = PASS
.try_with(|current| current.replace(Some(Arc::clone(pass))))
.ok()
.flatten();
let _restore = Restore(earlier);
f()
}
@@ -99,7 +104,7 @@ pub(crate) fn within<T>(pass: &Arc<Pass>, f: impl FnOnce() -> T) -> T {
/// Count `bytes` of driver data a making added toward this thread's pass, if it works for one
/// (`shader_cache/driver.rs`).
pub(crate) fn added_pipeline_bytes(bytes: u64) {
PASS.with(|pass| {
let _ = PASS.try_with(|pass| {
if let Some(pass) = &*pass.borrow() {
pass.bytes.fetch_add(bytes, Ordering::Relaxed);
}
@@ -110,7 +115,7 @@ pub(crate) fn added_pipeline_bytes(bytes: u64) {
/// pass makes none of (`pipeline/objects.rs`): its translations are kept, its objects and
/// pipelines not made. The pass counts the record as translated, not failed.
pub(crate) fn translation_only() -> crate::Error {
PASS.with(|pass| {
let _ = PASS.try_with(|pass| {
if let Some(pass) = &*pass.borrow() {
pass.translation_only.store(true, Ordering::Relaxed);
}
@@ -382,7 +382,7 @@ static CALLS_AT_EXIT: Mutex<Option<(Device, Vec<u8>)>> = Mutex::new(None);
/// An exit handler the calls cases register once the program's own thread made its common calls
/// ([`common_calls`]), as a program registers its own: the same calls again, on the exiting
/// thread, whose thread-locals the exit destroyed before it ran the handlers (macOS), those the
/// thread, whose thread-locals the exit destroyed before it ran the handlers (macOS, the GNU C library), those the
/// runtime made for that thread's earlier calls among them. Its line says whether the device's
/// hook ran before it (`hook_ran`) and what each call answered. Its pipeline's region (two threads
/// a threadgroup) is not the earlier one's (one), so its creation makes it on this thread.
@@ -1776,7 +1776,7 @@ fn an_exit_handler_registered_after_the_device_runs_its_work_to_completion() {
/// thread ([`common_calls`]: a buffer, a texture and a compute pipeline made, a copy through the
/// texture and a dispatch encoded, committed and waited for, what they wrote read back), after the
/// program's own thread made them before the exit, so the runtime's thread-locals for them were
/// made there and the exit destroyed them before it ran the handlers (macOS). Each call answers
/// made there and the exit destroyed them before it ran the handlers (macOS, the GNU C library). Each call answers
/// as on any other thread, and the process exits cleanly. Where the program registered no handler
/// after a later pipeline making, every call runs and its work completes, on every device. Where
/// it made a pipeline after the handler, the handler's making answers that the process is exiting
+4 -2
View File
@@ -2918,9 +2918,11 @@ impl BindingPlan {
commands: &mut DrawCommands,
) -> Result<bool, BindError> {
// Made again in a scratch of the thread's, whose lists keep their room from check to
// check, so the check allocates nothing past its first.
// check, so the check allocates nothing past its first; none past the thread's
// thread-locals' end (a program's exit handler, which runs after them).
#[cfg(debug_assertions)]
REBINDS_MADE_AGAIN.with_borrow_mut(|again| {
let _ = REBINDS_MADE_AGAIN.try_with(|again| {
let again = &mut *again.borrow_mut();
let made = self.slot_rebinds_into(&rebinds.slots, again);
assert!(made && again == rebinds, "slot rebinds another plan made");
});
+6
View File
@@ -5313,6 +5313,12 @@ each item named states the rule in full.
waits for those in progress, and leaves the rest of the runtime running, so the handler's other
work is submitted and completes, as Metal's exit runs it. A making its work needs that had not
begun answers the same.
- **An exit handler's calls keep none of the runtime's state for their thread**: `exit` destroys
the exiting thread's thread-locals before it runs the handlers (macOS, the GNU C library). There
a pipeline's making takes no turn of the process's making budget, the driver's messages a making
is measured to report reach the device's message sink rather than being withheld, and a notice
of a kind the device's options refuse while lowering is announced, and refuses no call, where
the handler's own thread lowers it.
- **On a CPU device (lavapipe, SwiftShader), an exit handler the program registered before a
later pipeline making finds the process exiting**: its waits answer `WaitWouldDeadlock` of
`DeadlockCause::Exiting` and the work it commits stays pending, where Metal's exit runs it. A