1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//! Raw-pointer TLS binding for the malloc face (Phase 12.3, §2.2 of
//! `MALLOC_PLAN_PHASE12-13.md`).
//!
//! This is the reentrancy-safe TLS routing that replaces the Phase 11
//! `RefCell<Option<Heap>>` binding for the global face. The keystone move:
//! the heap is NOT owned by the TLS slot (RAII-dropped on thread exit); it
//! is a slot in the global [`HeapRegistry`], and the TLS slot caches only a
//! raw `*mut HeapCore` to it. Thread exit does NOT drop the heap; the
//! [`AbandonGuard`] abandons its segments back to the registry and recycles
//! the slot.
//!
//! ## Why raw `Cell<*mut HeapCore>` (no `RefCell`)
//!
//! `RefCell<Option<Heap>>` turns reentrancy into a refusal: under libtest's
//! parallel harness the global allocator is called while a borrow is already
//! held (e.g. panic infrastructure, capture buffers) → `try_borrow_mut`
//! returns `Err` → the malloc face returns null → the process aborts. The
//! raw-pointer `Cell` has no borrow state: reading it is always a single
//! load, never fails. Reentrancy is structurally excluded by M5 (no
//! `Vec`/`Box`/`std::alloc` on the alloc path), so there is no reentrant
//! mutation to guard against.
//!
//! ## Soundness of the raw pointer
//!
//! `*mut HeapCore` is sound to cache and dereference under the
//! **single-writer invariant**: the ONLY mutator of a heap's bins is its
//! owning thread (the one that won the `FREE → LIVE` CAS in `claim`).
//! `current()` is called only on the owning thread (it reads its own TLS),
//! so the `&mut HeapCore` it yields is exclusive. No other thread writes
//! these bins; cross-thread frees go through the [`ThreadFreeStack`], not
//! the bins directly. The registry's atomic protocol (M5-clean bootstrap,
//! claim/recycle CAS) establishes the single writer; this file relies on
//! that, it does not re-establish it.
//!
//! ## TLS destructor ordering
//!
//! `LOCAL` and `GUARD` are both `thread_local!`s. Rust destroys thread-locals
//! in reverse-declaration order per-thread, but the standard does not
//! guarantee cross-key ordering against arbitrary other TLS keys the runtime
//! may have registered. The guard therefore holds its OWN copy of the heap
//! pointer (set in [`bind_slow`]) and NEVER reads `LOCAL` in its `Drop`. If
//! `LOCAL` is already torn down when the guard drops, the guard's copy still
//! has the pointer it needs to abandon+recycle. (If the guard's OWN slot is
//! torn down first, `LOCAL`'s drop is a no-op — `Cell` has no drop glue.)
//!
//! ## Never-null (M10)
//!
//! [`current()`] returns a non-null `*mut HeapCore` in every case:
//! - the cached pointer is set → return it;
//! - the cached pointer is null (first call) → [`bind_slow`] claims a slot
//! and publishes it, or on registry exhaustion falls back to the
//! primordial heap;
//! - the TLS slot is destroyed (thread teardown) → [`fallback_ptr`] returns
//! the always-live process-global fallback heap.
//!
//! So the malloc face never returns null for a serviceable request (M10).
//!
//! [`HeapRegistry`]: crate::registry::HeapRegistry
//! [`ThreadFreeStack`]: crate::heap::thread_free::ThreadFreeStack
// The crate is `#![deny(unsafe_code)]` with `alloc-global` on (see
// `src/lib.rs`); this is the documented raw-pointer TLS seam (Phase 12.3).
// `allow` lifts the crate-level `deny` for this file only — `unsafe`
// anywhere else in the crate is a hard error. The `unsafe` surface here is:
// * dereferencing the cached `*mut HeapCore` into `&mut HeapCore` (sound
// under the single-writer invariant documented above), and
// * calling `HeapRegistry::recycle` / `abandon_segments` (which are
// `unsafe fn`s whose contract is "pointer previously returned by
// `claim`").
// Every `unsafe` block carries a `// SAFETY:` proof.
use Cell;
use cratefallback;
use crate;
thread_local!
/// The per-thread abandon guard. See the module docs for the TLS destructor
/// ordering reasoning.
/// The hot accessor: return the current thread's heap pointer, never null.
///
/// Fast path: a single TLS load + null check. On first call (null) it calls
/// [`bind_slow`] (cold); if the TLS is torn down (thread teardown) it calls
/// [`fallback_ptr`] (cold) — the process-global fallback heap, also never
/// null.
///
/// This is the un-tagged variant, for callers that do not need to
/// distinguish own-thread vs fallback (the malloc face uses
/// [`current_for_alloc`] instead). Kept `pub` as the canonical accessor for
/// future direct-API consumers and tests.
///
/// Inlined so the fast path collapses to a TLS-get + branch in the callers.
// The malloc face uses `current_for_alloc` (tagged). Kept for direct API.
/// Which heap [`current_for_alloc`] resolved to. The malloc face uses this to
/// decide whether to take the lock-free own-thread fast path ([`Own`]) or
/// the spinlock-guarded fallback path ([`Fallback`]). Carrying the tag in
/// the return value avoids a second `fallback::heap_ptr()` call (which would
/// needlessly initialise the fallback even when the fast path won).
/// The malloc-face entry: resolve the current heap AND whether it is the
/// fallback, in one pass. Used by [`SeferMalloc`](super::SeferMalloc) to
/// avoid a redundant `fallback::heap_ptr()` comparison (which would
/// needlessly initialise the fallback on every alloc).
///
/// Under `alloc-decommit`, [`current_for_alloc_with_config`] is used
/// instead (it threads the config into the TLS bind). This function is
/// kept for `not(alloc-decommit)` builds and direct-API consumers.
/// Like [`current_for_alloc`] but plumbs `config` into the newly claimed
/// `HeapCore` on first call (the TLS bind slow path). On subsequent calls
/// (TLS pointer already set) the fast path returns the cached pointer
/// without touching the config.
///
/// **Config is taken by reference** so the hot fast path (TLS pointer
/// cached) never materialises the ~40-byte `LargeCacheConfig` value on the
/// stack. The 40-byte copy happens only on the cold `bind_slow` branch,
/// where it is amortised across the thread's lifetime.
///
/// Only present under `alloc-decommit` — without that feature the config
/// concept does not exist and [`current_for_alloc`] is used directly.
/// Bind a registry slot to this thread: claim, publish the pointer into
/// `LOCAL`, arm the [`AbandonGuard`] with a copy, install the cross-thread
/// TFS (under `alloc-xthread`), and return the pointer (or, on registry
/// exhaustion, the fallback marker). `#[cold]` — runs once per thread.
///
/// On registry exhaustion (every slot is LIVE and the free pool is empty —
/// pathological: > `MAX_HEAPS` simultaneous threads), returns
/// [`CurrentHeap::Fallback`] (the malloc face then routes through the
/// always-live primordial heap — never null, M10).
/// The tagged variant of [`bind_slow`], used by [`current_for_alloc`] so the
/// malloc face knows whether it got an own-thread slot or the fallback (and
/// therefore whether to take the lock-free path or the spinlock path).
/// Like [`bind_slow_tagged`] but uses [`HeapRegistry::claim_with_config`] so
/// the newly materialised `HeapCore` is configured with `config`. On a
/// re-claim the existing `HeapCore` is reused as-is.
///
/// Only present under `alloc-decommit`.
/// Shared post-claim logic: install the cross-thread TFS (under
/// `alloc-xthread`), publish the pointer into `LOCAL`, arm the
/// `AbandonGuard`, and return the tagged result. Called from both
/// [`bind_slow_tagged`] and [`bind_slow_tagged_with_config`].
/// The fallback heap pointer — the process-global always-live heap. Used
/// when the TLS is destroyed (thread teardown) or the registry is exhausted.
/// Never null (M10). `#[cold]` — these windows are rare.