use crate::heap::HeapData;
use core::{cell::Cell, ffi::c_void, ptr};
pub(crate) type Key = usize;
pub(crate) const NO_KEY: Key = usize::MAX;
thread_local! {
static EXITED: Cell<bool> = const { Cell::new(false) };
static BINDING: Cell<bool> = const { Cell::new(false) };
static SPARE: Cell<usize> = const { Cell::new(NO_SPARE) };
}
pub(crate) fn binding() -> bool {
BINDING.with(Cell::get)
}
pub(crate) fn set_binding(on: bool) {
BINDING.with(|binding| binding.set(on));
}
const NO_SPARE: usize = usize::MAX;
pub(crate) fn spare() -> usize {
SPARE.with(|last| match last.get() {
NO_SPARE => ptr::from_ref(last).addr().wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 48,
spare => spare,
})
}
pub(crate) fn set_spare(spare: usize) {
SPARE.with(|last| last.set(spare));
}
pub(crate) fn exiting() -> bool {
EXITED.with(Cell::get)
}
pub(crate) fn create_key() -> Option<Key> {
let mut key = 0;
if unsafe { libc::pthread_key_create(&raw mut key, Some(release_heap)) } != 0 {
return None;
}
let key = key as Key;
if !slot::probe(key) {
unsafe { libc::pthread_key_delete(key as _) };
return None;
}
Some(key)
}
pub(crate) fn delete_key(key: Key) {
unsafe { libc::pthread_key_delete(key as _) };
}
#[inline(always)]
pub(crate) fn get(key: Key) -> Option<&'static HeapData> {
slot::get(key)
}
pub(crate) fn lookup(key: Key) -> Option<&'static HeapData> {
slot::lookup(key)
}
pub(crate) fn bind(key: Key, data: &'static HeapData) -> bool {
if unsafe { libc::pthread_setspecific(key as _, ptr::from_ref(data).cast()) } != 0 {
return false;
}
slot::set(key, data);
true
}
unsafe extern "C" fn release_heap(value: *mut c_void) {
if value.is_null() {
return;
}
unsafe { (*value.cast::<HeapData>()).give_up() };
slot::clear();
EXITED.with(|exited| exited.set(true));
}
#[cfg(all(
target_vendor = "apple",
target_arch = "aarch64",
not(miri),
not(bcmalloc_portable_tls)
))]
mod slot {
use super::Key;
use crate::heap::HeapData;
use core::{arch::asm, ptr};
#[inline(always)]
fn table() -> *const *const HeapData {
let register: usize;
unsafe {
asm!(
"mrs {}, tpidrro_el0",
out(reg) register,
options(nomem, nostack, pure, preserves_flags)
);
}
ptr::with_exposed_provenance(register & !7)
}
#[inline(always)]
fn read(key: Key) -> *const HeapData {
if key == super::NO_KEY {
return ptr::null();
}
unsafe { *table().add(key) }
}
#[inline(always)]
pub(super) fn get(key: Key) -> Option<&'static HeapData> {
unsafe { read(key).as_ref() }
}
pub(super) fn lookup(key: Key) -> Option<&'static HeapData> {
get(key)
}
pub(super) const fn set(_key: Key, _data: &HeapData) {}
pub(super) const fn clear() {}
pub(super) fn probe(key: Key) -> bool {
static MARKER: u8 = 0;
let marker: *const u8 = &raw const MARKER;
unsafe { libc::pthread_setspecific(key as _, marker.cast()) };
let found = read(key).cast::<u8>() == marker;
unsafe { libc::pthread_setspecific(key as _, ptr::null()) };
found
}
}
#[cfg(not(all(
target_vendor = "apple",
target_arch = "aarch64",
not(miri),
not(bcmalloc_portable_tls)
)))]
mod slot {
use super::Key;
use crate::heap::HeapData;
use core::{cell::Cell, ptr};
const EMPTY: Key = super::NO_KEY - 1;
thread_local! {
static CURRENT: Cell<(Key, *const HeapData)> = const { Cell::new((EMPTY, ptr::null())) };
}
#[inline(always)]
pub(super) fn get(key: Key) -> Option<&'static HeapData> {
let (bound, data) = CURRENT.with(Cell::get);
(bound == key).then(|| unsafe { &*data })
}
pub(super) fn lookup(key: Key) -> Option<&'static HeapData> {
if key == super::NO_KEY {
return None;
}
let data = unsafe { libc::pthread_getspecific(key as _).cast::<HeapData>().as_ref() }?;
CURRENT.with(|current| current.set((key, ptr::from_ref(data))));
Some(data)
}
pub(super) fn set(key: Key, data: &HeapData) {
CURRENT.with(|current| current.set((key, ptr::from_ref(data))));
}
pub(super) fn clear() {
CURRENT.with(|current| current.set((EMPTY, ptr::null())));
}
pub(super) const fn probe(_key: Key) -> bool {
true
}
}
#[cfg(all(test, not(loom)))]
mod test {
use super::*;
use crate::testing::TestRegion;
use std::thread;
#[test]
fn a_thread_finds_the_heap_it_bound_and_others_do_not() {
let test = TestRegion::new(8, 2);
let region = test.region();
let key = create_key().expect("a key");
assert!(get(key).is_none());
let data = region.heap().expect("a free heap").leak();
assert!(bind(key, unsafe { &*ptr::from_ref(data) }));
assert_eq!(get(key).map(ptr::from_ref), Some(ptr::from_ref(data)));
thread::scope(|scope| {
scope.spawn(|| assert!(get(key).is_none()));
});
unsafe { libc::pthread_setspecific(key as _, ptr::null()) };
slot::clear();
data.release_claim();
delete_key(key);
}
#[test]
fn exiting_threads_release_their_heap_and_know_they_are_gone() {
let test = TestRegion::new(8, 2);
let region = test.region();
let key = create_key().expect("a key");
let data = region.heap().expect("a free heap").leak();
assert!(data.is_claimed());
struct Handoff(*const HeapData);
unsafe impl Send for Handoff {}
let handoff = Handoff(ptr::from_ref(data));
thread::spawn(move || {
let handoff = handoff;
assert!(!exiting());
assert!(bind(key, unsafe { &*handoff.0 }));
assert_eq!(get(key).map(ptr::from_ref), Some(handoff.0));
})
.join()
.unwrap();
assert!(!data.is_claimed(), "the destructor must release the claim");
assert!(!exiting(), "only the exited thread is marked");
delete_key(key);
}
}