1
0
Fork 0
forked from wry/wry

all: remove thread_local feature

This commit is contained in:
Julian Orth 2024-02-22 22:45:46 +01:00
parent 0c3c03b130
commit 53aa762239
9 changed files with 82 additions and 77 deletions

View file

@ -61,7 +61,7 @@ impl Drop for Client {
} }
thread_local! { thread_local! {
pub(crate) static CLIENT: std::cell::Cell<*const Client> = const { std::cell::Cell::new(ptr::null()) }; pub(crate) static CLIENT: Cell<*const Client> = const { Cell::new(ptr::null()) };
} }
unsafe fn with_client<T, F: FnOnce(&Client) -> T>(data: *const u8, f: F) -> T { unsafe fn with_client<T, F: FnOnce(&Client) -> T>(data: *const u8, f: F) -> T {

View file

@ -88,12 +88,12 @@ impl ClientMemOffset {
} }
let mref = MemRef { let mref = MemRef {
mem: &*self.mem, mem: &*self.mem,
outer: MEM, outer: MEM.get(),
}; };
MEM = &mref; MEM.set(&mref);
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
let res = f(&*self.data); let res = f(&*self.data);
MEM = mref.outer; MEM.set(mref.outer);
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
match self.mem.failed.get() { match self.mem.failed.get() {
true => Err(ClientMemError::Sigbus), true => Err(ClientMemError::Sigbus),
@ -116,8 +116,9 @@ struct MemRef {
outer: *const MemRef, outer: *const MemRef,
} }
#[thread_local] thread_local! {
static mut MEM: *const MemRef = ptr::null(); static MEM: Cell<*const MemRef> = const { Cell::new(ptr::null()) };
}
unsafe fn kill() -> ! { unsafe fn kill() -> ! {
c::signal(c::SIGBUS, c::SIG_DFL); c::signal(c::SIGBUS, c::SIG_DFL);
@ -127,7 +128,7 @@ unsafe fn kill() -> ! {
unsafe extern "C" fn sigbus(sig: i32, info: &c::siginfo_t, _ucontext: *mut c::c_void) { unsafe extern "C" fn sigbus(sig: i32, info: &c::siginfo_t, _ucontext: *mut c::c_void) {
assert_eq!(sig, c::SIGBUS); assert_eq!(sig, c::SIGBUS);
let mut memr_ptr = MEM; let mut memr_ptr = MEM.get();
while !memr_ptr.is_null() { while !memr_ptr.is_null() {
let memr = &*memr_ptr; let memr = &*memr_ptr;
let mem = &*memr.mem; let mem = &*memr.mem;

View file

@ -15,7 +15,7 @@ use {
}, },
}, },
ahash::AHashMap, ahash::AHashMap,
std::rc::Rc, std::{cell::Cell, rc::Rc},
}; };
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -36,8 +36,9 @@ impl Drop for EglContext {
} }
} }
#[thread_local] thread_local! {
static mut CURRENT: EGLContext = EGLContext::none(); static CURRENT: Cell<EGLContext> = const { Cell::new(EGLContext::none()) };
}
impl EglContext { impl EglContext {
pub fn reset_status(&self) -> Option<ResetStatus> { pub fn reset_status(&self) -> Option<ResetStatus> {
@ -63,7 +64,7 @@ impl EglContext {
f: F, f: F,
) -> Result<T, RenderError> { ) -> Result<T, RenderError> {
unsafe { unsafe {
if CURRENT == self.ctx { if CURRENT.get() == self.ctx {
return f(); return f();
} }
self.with_current_slow(f) self.with_current_slow(f)
@ -84,15 +85,15 @@ impl EglContext {
{ {
return Err(RenderError::MakeCurrent); return Err(RenderError::MakeCurrent);
} }
let prev = CURRENT; let prev = CURRENT.get();
CURRENT = self.ctx; CURRENT.set(self.ctx);
let res = f(); let res = f();
if (self.dpy.egl.eglMakeCurrent)(self.dpy.dpy, EGLSurface::none(), EGLSurface::none(), prev) if (self.dpy.egl.eglMakeCurrent)(self.dpy.dpy, EGLSurface::none(), EGLSurface::none(), prev)
== EGL_FALSE == EGL_FALSE
{ {
panic!("Could not restore EGLContext"); panic!("Could not restore EGLContext");
} }
CURRENT = prev; CURRENT.set(prev);
res res
} }
} }

View file

@ -27,26 +27,25 @@ pub static TEST_CONFIG_ENTRY: ConfigEntry = ConfigEntry {
handle_msg, handle_msg,
}; };
#[thread_local] thread_local! {
static mut CONFIG: *const TestConfig = ptr::null(); static CONFIG: Cell<*const TestConfig> = const { Cell::new(ptr::null()) };
}
pub fn with_test_config<T, F>(f: F) -> T pub fn with_test_config<T, F>(f: F) -> T
where where
F: FnOnce(Rc<TestConfig>) -> T, F: FnOnce(Rc<TestConfig>) -> T,
{ {
unsafe { let tc = Rc::new(TestConfig {
let tc = Rc::new(TestConfig { srv: Cell::new(None),
srv: Cell::new(None), responses: Default::default(),
responses: Default::default(), invoked_shortcuts: Default::default(),
invoked_shortcuts: Default::default(), graphics_initialized: Cell::new(false),
graphics_initialized: Cell::new(false), });
}); let old = CONFIG.get();
let old = CONFIG; CONFIG.set(tc.deref());
CONFIG = tc.deref(); let res = f(tc.clone());
let res = f(tc.clone()); CONFIG.set(old);
CONFIG = old; res
res
}
} }
unsafe extern "C" fn init( unsafe extern "C" fn init(
@ -56,7 +55,7 @@ unsafe extern "C" fn init(
_msg: *const u8, _msg: *const u8,
_size: usize, _size: usize,
) -> *const u8 { ) -> *const u8 {
let tc = CONFIG; let tc = CONFIG.get();
assert!(tc.is_not_null()); assert!(tc.is_not_null());
Rc::increment_strong_count(tc); Rc::increment_strong_count(tc);
{ {

View file

@ -13,8 +13,9 @@ use {
static LEVEL: AtomicUsize = AtomicUsize::new(Level::Info as usize); static LEVEL: AtomicUsize = AtomicUsize::new(Level::Info as usize);
#[thread_local] thread_local! {
static FILE: CloneCell<Option<Rc<OwnedFd>>> = CloneCell::new(None); static FILE: CloneCell<Option<Rc<OwnedFd>>> = CloneCell::new(None);
}
pub fn install() { pub fn install() {
log::set_logger(&Logger).unwrap(); log::set_logger(&Logger).unwrap();
@ -27,11 +28,11 @@ pub fn set_level(level: Level) {
} }
pub fn set_file(file: Rc<OwnedFd>) { pub fn set_file(file: Rc<OwnedFd>) {
FILE.set(Some(file)); FILE.with(|f| f.set(Some(file)));
} }
pub fn unset_file() { pub fn unset_file() {
FILE.set(None); FILE.with(|f| f.set(None));
} }
struct Logger; struct Logger;
@ -65,7 +66,7 @@ impl Log for Logger {
record.args(), record.args(),
) )
}; };
let mut fd = match FILE.get() { let mut fd = match FILE.with(|f| f.get()) {
Some(f) => f.borrow(), Some(f) => f.borrow(),
_ => Fd::new(2), _ => Fd::new(2),
}; };

View file

@ -52,27 +52,27 @@ mod leaks {
std::{ std::{
alloc::{GlobalAlloc, Layout}, alloc::{GlobalAlloc, Layout},
any, any,
cell::Cell,
marker::PhantomData, marker::PhantomData,
mem, ptr, mem, ptr,
}, },
uapi::c, uapi::c,
}; };
#[thread_local] thread_local! {
static mut MAP: *mut AHashMap<u64, Tracked> = ptr::null_mut(); static MAP: Cell<*mut AHashMap<u64, Tracked>> = const { Cell::new(ptr::null_mut()) };
static ID: Cell<u64> = const { Cell::new(0) };
#[thread_local] }
static mut ID: u64 = 0;
pub fn init() { pub fn init() {
unsafe { unsafe {
if INITIALIZED { if INITIALIZED {
return; return;
} }
MAP = Box::into_raw(Box::new(AHashMap::new())); MAP.set(Box::into_raw(Box::new(AHashMap::new())));
ALLOCATIONS = Box::into_raw(Box::new(AHashMap::new())); ALLOCATIONS.set(Box::into_raw(Box::new(AHashMap::new())));
IN_ALLOCATOR = 0; IN_ALLOCATOR.set(0);
INITIALIZED = true; INITIALIZED.set(true);
} }
} }
@ -151,7 +151,7 @@ mod leaks {
pub fn log_leaked() { pub fn log_leaked() {
unsafe { unsafe {
IN_ALLOCATOR += 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() + 1);
let mut map: AHashMap<ClientId, Vec<(u64, Tracked)>> = AHashMap::new(); let mut map: AHashMap<ClientId, Vec<(u64, Tracked)>> = AHashMap::new();
for (id, obj) in MAP.deref_mut().drain() { for (id, obj) in MAP.deref_mut().drain() {
map.entry(obj.client).or_default().push((id, obj)); map.entry(obj.client).or_default().push((id, obj));
@ -176,7 +176,7 @@ mod leaks {
} }
} }
} }
IN_ALLOCATOR -= 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() - 1);
} }
} }
// //
@ -210,8 +210,8 @@ mod leaks {
fn default() -> Self { fn default() -> Self {
Self { Self {
id: unsafe { id: unsafe {
let id = ID; let id = ID.get();
ID += 1; ID.set(id + 1);
id id
}, },
_phantom: Default::default(), _phantom: Default::default(),
@ -227,7 +227,7 @@ mod leaks {
tv_nsec: 0, tv_nsec: 0,
}; };
uapi::clock_gettime(c::CLOCK_REALTIME, &mut time).unwrap(); uapi::clock_gettime(c::CLOCK_REALTIME, &mut time).unwrap();
IN_ALLOCATOR += 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() + 1);
MAP.deref_mut().insert( MAP.deref_mut().insert(
self.id, self.id,
Tracked { Tracked {
@ -237,7 +237,7 @@ mod leaks {
time: (time.tv_sec as i64, time.tv_nsec as u32), time: (time.tv_sec as i64, time.tv_nsec as u32),
}, },
); );
IN_ALLOCATOR -= 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() - 1);
} }
} }
} }
@ -262,20 +262,17 @@ mod leaks {
pub backtrace: Backtrace, pub backtrace: Backtrace,
} }
#[thread_local] thread_local! {
static mut ALLOCATIONS: *mut AHashMap<*mut u8, Allocation> = ptr::null_mut(); static ALLOCATIONS: Cell<*mut AHashMap<*mut u8, Allocation>> = const { Cell::new(ptr::null_mut()) };
static IN_ALLOCATOR: Cell<u32> = const { Cell::new(1) };
#[thread_local] static INITIALIZED: Cell<bool> = const { Cell::new(false) };
static mut IN_ALLOCATOR: u32 = 1; }
#[thread_local]
static mut INITIALIZED: bool = false;
unsafe impl GlobalAlloc for TracingAllocator { unsafe impl GlobalAlloc for TracingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 { unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let res = c::calloc(layout.size(), 1) as *mut u8; let res = c::calloc(layout.size(), 1) as *mut u8;
if IN_ALLOCATOR == 0 { if IN_ALLOCATOR.get() == 0 {
IN_ALLOCATOR = 1; IN_ALLOCATOR.set(1);
ALLOCATIONS.deref_mut().insert( ALLOCATIONS.deref_mut().insert(
res, res,
Allocation { Allocation {
@ -301,7 +298,7 @@ mod leaks {
fn find_allocations_pointing_to(addr: *mut u8) -> Vec<(Allocation, usize)> { fn find_allocations_pointing_to(addr: *mut u8) -> Vec<(Allocation, usize)> {
unsafe { unsafe {
IN_ALLOCATOR += 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() + 1);
let mut res = vec![]; let mut res = vec![];
for allocation in ALLOCATIONS.deref().values() { for allocation in ALLOCATIONS.deref().values() {
let num = allocation.len / mem::size_of::<usize>(); let num = allocation.len / mem::size_of::<usize>();
@ -313,14 +310,14 @@ mod leaks {
} }
} }
} }
IN_ALLOCATOR -= 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() - 1);
res res
} }
} }
fn find_allocation_containing(addr: usize) -> Option<Allocation> { fn find_allocation_containing(addr: usize) -> Option<Allocation> {
unsafe { unsafe {
IN_ALLOCATOR += 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() + 1);
let mut res = None; let mut res = None;
for allocation in ALLOCATIONS.deref().values() { for allocation in ALLOCATIONS.deref().values() {
let aaddr = allocation.addr as usize; let aaddr = allocation.addr as usize;
@ -329,7 +326,7 @@ mod leaks {
break; break;
} }
} }
IN_ALLOCATOR -= 1; IN_ALLOCATOR.set(IN_ALLOCATOR.get() - 1);
res res
} }
} }

View file

@ -4,9 +4,11 @@ use {
bstr::{BStr, BString, ByteSlice}, bstr::{BStr, BString, ByteSlice},
log::{Level, Log, Metadata, Record}, log::{Level, Log, Metadata, Record},
std::{ std::{
cell::Cell,
fs::DirBuilder, fs::DirBuilder,
io::Write, io::Write,
os::unix::{ffi::OsStringExt, fs::DirBuilderExt}, os::unix::{ffi::OsStringExt, fs::DirBuilderExt},
ptr,
sync::{ sync::{
atomic::{AtomicU32, Ordering::Relaxed}, atomic::{AtomicU32, Ordering::Relaxed},
Arc, Arc,
@ -16,8 +18,9 @@ use {
uapi::{c, format_ustr, Errno, Fd, OwnedFd}, uapi::{c, format_ustr, Errno, Fd, OwnedFd},
}; };
#[thread_local] thread_local! {
static mut BUFFER: Vec<u8> = Vec::new(); static BUFFER: Cell<*mut Vec<u8>> = const { Cell::new(ptr::null_mut()) };
}
pub struct Logger { pub struct Logger {
level: AtomicU32, level: AtomicU32,
@ -141,7 +144,12 @@ impl Log for LogWrapper {
if record.level() as u32 > self.logger.level.load(Relaxed) { if record.level() as u32 > self.logger.level.load(Relaxed) {
return; return;
} }
let buffer = unsafe { &mut BUFFER }; let mut buffer = BUFFER.get();
if buffer.is_null() {
buffer = Box::into_raw(Box::default());
BUFFER.set(buffer);
}
let buffer = unsafe { &mut *buffer };
buffer.clear(); buffer.clear();
let now = SystemTime::now(); let now = SystemTime::now();
let _ = if let Some(mp) = record.module_path() { let _ = if let Some(mp) = record.module_path() {

View file

@ -1,6 +1,5 @@
#![feature( #![feature(
c_variadic, // https://github.com/rust-lang/rust/issues/44930 c_variadic, // https://github.com/rust-lang/rust/issues/44930
thread_local, // https://github.com/rust-lang/rust/issues/29594
)] )]
#![allow( #![allow(
clippy::len_zero, clippy::len_zero,

View file

@ -4,18 +4,17 @@ use {
region::{extents, rects_to_bands, subtract, union}, region::{extents, rects_to_bands, subtract, union},
RectRaw, RectRaw,
}, },
once_cell::unsync::Lazy,
smallvec::SmallVec, smallvec::SmallVec,
std::{mem, ops::Deref, rc::Rc}, std::{mem, ops::Deref, rc::Rc},
}; };
#[thread_local] thread_local! {
static EMPTY: Lazy<Rc<Region>> = Lazy::new(|| { static EMPTY: Rc<Region> =
Rc::new(Region { Rc::new(Region {
rects: Default::default(), rects: Default::default(),
extents: Default::default(), extents: Default::default(),
}) });
}); }
impl Region { impl Region {
pub fn new(rect: Rect) -> Rc<Self> { pub fn new(rect: Rect) -> Rc<Self> {
@ -28,7 +27,7 @@ impl Region {
} }
pub fn empty() -> Rc<Self> { pub fn empty() -> Rc<Self> {
EMPTY.clone() EMPTY.with(|e| e.clone())
} }
pub fn from_rects(rects: &[Rect]) -> Rc<Self> { pub fn from_rects(rects: &[Rect]) -> Rc<Self> {