1#![cfg_attr(
18 all(feature = "std", not(test)),
19 expect(dead_code, reason = "not used, but typechecked")
20)]
21
22use core::cell::UnsafeCell;
23use core::mem::MaybeUninit;
24use core::ops::{Deref, DerefMut};
25use core::sync::atomic::{AtomicU8, Ordering};
26
27pub struct OnceLock<T> {
28 val: UnsafeCell<MaybeUninit<T>>,
29 state: AtomicU8,
30 mutex: raw::Mutex,
31}
32
33unsafe impl<T: Send> Send for OnceLock<T> {}
34unsafe impl<T: Sync> Sync for OnceLock<T> {}
35
36const UNINITIALIZED: u8 = 0;
37const INITIALIZING: u8 = 1;
38const INITIALIZED: u8 = 2;
39
40impl<T> OnceLock<T> {
41 pub const fn new() -> OnceLock<T> {
42 OnceLock {
43 state: AtomicU8::new(UNINITIALIZED),
44 val: UnsafeCell::new(MaybeUninit::uninit()),
45 mutex: raw::Mutex::new(),
46 }
47 }
48
49 pub fn get_or_init(&self, f: impl FnOnce() -> T) -> &T {
50 if let Some(ret) = self.get() {
51 return ret;
52 }
53 self.try_init::<()>(|| Ok(f())).unwrap()
54 }
55
56 pub fn get_or_try_init<E>(&self, f: impl FnOnce() -> Result<T, E>) -> Result<&T, E> {
57 if let Some(ret) = self.get() {
58 return Ok(ret);
59 }
60 self.try_init(f)
61 }
62
63 fn get(&self) -> Option<&T> {
64 if self.state.load(Ordering::Acquire) == INITIALIZED {
65 Some(unsafe { (*self.val.get()).assume_init_ref() })
67 } else {
68 None
69 }
70 }
71
72 #[cold]
73 fn try_init<E>(&self, f: impl FnOnce() -> Result<T, E>) -> Result<&T, E> {
74 let _guard = OnceLockGuard::new(&self.mutex);
75
76 match self.state.load(Ordering::Acquire) {
78 UNINITIALIZED => {
79 self.state.store(INITIALIZING, Ordering::Release);
80 match f() {
81 Ok(val) => {
82 let ret = unsafe { &*(*self.val.get()).write(val) };
84 self.state.store(INITIALIZED, Ordering::Release);
85 Ok(ret)
86 }
87 Err(e) => {
88 self.state.store(UNINITIALIZED, Ordering::Release);
89 Err(e)
90 }
91 }
92 }
93 INITIALIZED => {
94 Ok(unsafe { (*self.val.get()).assume_init_ref() })
96 }
97 _ => panic!("concurrent initialization"),
98 }
99 }
100}
101
102impl<T> Drop for OnceLock<T> {
103 fn drop(&mut self) {
104 if self.state.load(Ordering::Acquire) == INITIALIZED {
105 unsafe { (*self.val.get()).assume_init_drop() };
107 }
108 }
109}
110
111impl<T> Default for OnceLock<T> {
112 fn default() -> OnceLock<T> {
113 OnceLock::new()
114 }
115}
116
117struct OnceLockGuard<'a> {
118 lock: &'a raw::Mutex,
119}
120
121impl<'a> OnceLockGuard<'a> {
122 fn new(lock: &'a raw::Mutex) -> OnceLockGuard<'a> {
123 lock.lock();
124 OnceLockGuard { lock }
125 }
126}
127
128impl Drop for OnceLockGuard<'_> {
129 fn drop(&mut self) {
130 unsafe {
132 self.lock.unlock();
133 }
134 }
135}
136
137#[derive(Debug)]
138pub struct Mutex<T> {
139 val: UnsafeCell<T>,
140 lock: raw::Mutex,
141}
142
143unsafe impl<T: Send> Send for Mutex<T> {}
144unsafe impl<T: Send> Sync for Mutex<T> {}
145
146impl<T> Mutex<T> {
147 pub const fn new(val: T) -> Mutex<T> {
148 Mutex {
149 val: UnsafeCell::new(val),
150 lock: raw::Mutex::new(),
151 }
152 }
153
154 pub fn lock(&self) -> impl DerefMut<Target = T> + '_ {
155 self.lock.lock();
156 MutexGuard { lock: self }
157 }
158}
159
160impl<T: Default> Default for Mutex<T> {
161 fn default() -> Mutex<T> {
162 Mutex::new(T::default())
163 }
164}
165
166struct MutexGuard<'a, T> {
167 lock: &'a Mutex<T>,
168}
169
170impl<T> Deref for MutexGuard<'_, T> {
171 type Target = T;
172
173 fn deref(&self) -> &T {
174 unsafe { &*self.lock.val.get() }
176 }
177}
178
179impl<T> DerefMut for MutexGuard<'_, T> {
180 fn deref_mut(&mut self) -> &mut T {
181 unsafe { &mut *self.lock.val.get() }
183 }
184}
185
186impl<T> Drop for MutexGuard<'_, T> {
187 fn drop(&mut self) {
188 unsafe {
191 self.lock.lock.unlock();
192 }
193 }
194}
195
196#[derive(Debug)]
197pub struct RwLock<T> {
198 val: UnsafeCell<T>,
199 lock: raw::RwLock,
200}
201
202unsafe impl<T: Send> Send for RwLock<T> {}
203unsafe impl<T: Send + Sync> Sync for RwLock<T> {}
204
205impl<T> RwLock<T> {
206 pub const fn new(val: T) -> RwLock<T> {
207 RwLock {
208 val: UnsafeCell::new(val),
209 lock: raw::RwLock::new(),
210 }
211 }
212
213 pub fn read(&self) -> impl Deref<Target = T> + '_ {
214 self.lock.read();
215 RwLockReadGuard { lock: self }
216 }
217
218 pub fn write(&self) -> impl DerefMut<Target = T> + '_ {
219 self.lock.write();
220 RwLockWriteGuard { lock: self }
221 }
222}
223
224impl<T: Default> Default for RwLock<T> {
225 fn default() -> RwLock<T> {
226 RwLock::new(T::default())
227 }
228}
229
230struct RwLockReadGuard<'a, T> {
231 lock: &'a RwLock<T>,
232}
233
234impl<T> Deref for RwLockReadGuard<'_, T> {
235 type Target = T;
236
237 fn deref(&self) -> &T {
238 unsafe { &*self.lock.val.get() }
240 }
241}
242
243impl<T> Drop for RwLockReadGuard<'_, T> {
244 fn drop(&mut self) {
245 unsafe {
248 self.lock.lock.read_unlock();
249 }
250 }
251}
252
253struct RwLockWriteGuard<'a, T> {
254 lock: &'a RwLock<T>,
255}
256
257impl<T> Deref for RwLockWriteGuard<'_, T> {
258 type Target = T;
259
260 fn deref(&self) -> &T {
261 unsafe { &*self.lock.val.get() }
263 }
264}
265
266impl<T> DerefMut for RwLockWriteGuard<'_, T> {
267 fn deref_mut(&mut self) -> &mut T {
268 unsafe { &mut *self.lock.val.get() }
270 }
271}
272
273impl<T> Drop for RwLockWriteGuard<'_, T> {
274 fn drop(&mut self) {
275 unsafe {
278 self.lock.lock.write_unlock();
279 }
280 }
281}
282
283#[cfg(not(has_custom_sync))]
284use panic_on_contention as raw;
285#[cfg(not(has_custom_sync))]
286mod panic_on_contention {
287 use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
288
289 #[derive(Debug)]
290 pub struct Mutex {
291 locked: AtomicBool,
292 }
293
294 impl Mutex {
295 pub const fn new() -> Mutex {
296 Mutex {
297 locked: AtomicBool::new(false),
298 }
299 }
300
301 pub fn lock(&self) {
302 if self.locked.swap(true, Ordering::Acquire) {
303 panic!(
304 "concurrent lock request, must use `std` or `custom-sync-primitives` features to avoid panicking"
305 );
306 }
307 }
308
309 pub unsafe fn unlock(&self) {
310 self.locked.store(false, Ordering::Release);
311 }
312 }
313
314 #[derive(Debug)]
315 pub struct RwLock {
316 state: AtomicU32,
317 }
318
319 impl RwLock {
320 pub const fn new() -> RwLock {
321 RwLock {
322 state: AtomicU32::new(0),
323 }
324 }
325
326 pub fn read(&self) {
327 const READER_LIMIT: u32 = u32::MAX / 2;
328 match self
329 .state
330 .try_update(Ordering::Acquire, Ordering::Acquire, |x| match x {
331 u32::MAX => None,
332 n => {
333 let next = n + 1;
334 if next < READER_LIMIT {
335 Some(next)
336 } else {
337 None
338 }
339 }
340 }) {
341 Ok(_) => {}
342 Err(_) => panic!(
343 "concurrent read request while locked for writing, must use `std` or `custom-sync-primitives` features to avoid panic"
344 ),
345 }
346 }
347
348 pub unsafe fn read_unlock(&self) {
349 self.state.fetch_sub(1, Ordering::Release);
350 }
351
352 pub fn write(&self) {
353 match self
354 .state
355 .compare_exchange(0, u32::MAX, Ordering::Acquire, Ordering::Relaxed)
356 {
357 Ok(0) => {}
358 _ => panic!(
359 "concurrent write request, must use `std` or `custom-sync-primitives` features to avoid panicking"
360 ),
361 }
362 }
363
364 pub unsafe fn write_unlock(&self) {
365 match self.state.swap(0, Ordering::Release) {
366 u32::MAX => {}
367 _ => unreachable!(),
368 }
369 }
370 }
371}
372
373#[cfg(has_custom_sync)]
374use custom_capi as raw;
375#[cfg(has_custom_sync)]
376mod custom_capi {
377 use crate::runtime::vm::capi;
378 use core::cell::UnsafeCell;
379
380 #[derive(Debug)]
381 pub struct Mutex {
382 storage: UnsafeCell<usize>,
383 }
384
385 impl Mutex {
386 pub const fn new() -> Mutex {
387 Mutex {
388 storage: UnsafeCell::new(0),
389 }
390 }
391
392 pub fn lock(&self) {
393 unsafe {
394 capi::wasmtime_sync_lock_acquire(self.storage.get());
395 }
396 }
397
398 pub unsafe fn unlock(&self) {
399 unsafe {
400 capi::wasmtime_sync_lock_release(self.storage.get());
401 }
402 }
403 }
404
405 impl Drop for Mutex {
406 fn drop(&mut self) {
407 unsafe {
410 capi::wasmtime_sync_lock_free(self.storage.get());
411 }
412 }
413 }
414
415 #[derive(Debug)]
416 pub struct RwLock {
417 storage: UnsafeCell<usize>,
418 }
419
420 impl RwLock {
421 pub const fn new() -> RwLock {
422 RwLock {
423 storage: UnsafeCell::new(0),
424 }
425 }
426
427 pub fn read(&self) {
428 unsafe {
429 capi::wasmtime_sync_rwlock_read(self.storage.get());
430 }
431 }
432
433 pub unsafe fn read_unlock(&self) {
434 unsafe {
435 capi::wasmtime_sync_rwlock_read_release(self.storage.get());
436 }
437 }
438
439 pub fn write(&self) {
440 unsafe {
441 capi::wasmtime_sync_rwlock_write(self.storage.get());
442 }
443 }
444
445 pub unsafe fn write_unlock(&self) {
446 unsafe {
447 capi::wasmtime_sync_rwlock_write_release(self.storage.get());
448 }
449 }
450 }
451
452 impl Drop for RwLock {
453 fn drop(&mut self) {
454 unsafe {
455 capi::wasmtime_sync_rwlock_free(self.storage.get());
456 }
457 }
458 }
459}
460
461#[cfg(test)]
462mod tests {
463 use super::*;
464
465 #[test]
466 fn smoke_once_lock() {
467 let lock = OnceLock::new();
468 assert!(lock.get().is_none());
469 assert_eq!(*lock.get_or_init(|| 1), 1);
470 assert_eq!(*lock.get_or_init(|| 2), 1);
471 assert_eq!(*lock.get_or_init(|| 3), 1);
472 assert_eq!(lock.get_or_try_init::<()>(|| Ok(3)), Ok(&1));
473
474 let lock = OnceLock::new();
475 assert_eq!(lock.get_or_try_init::<()>(|| Ok(3)), Ok(&3));
476 assert_eq!(*lock.get_or_init(|| 1), 3);
477
478 let lock = OnceLock::new();
479 assert_eq!(lock.get_or_try_init(|| Err(())), Err(()));
480 assert_eq!(*lock.get_or_init(|| 1), 1);
481 }
482
483 #[test]
484 fn smoke_mutex() {
485 let lock = Mutex::new(1);
486 assert_eq!(*lock.lock(), 1);
487 *lock.lock() = 2;
488 assert_eq!(*lock.lock(), 2);
489 }
490
491 #[test]
492 fn smoke_rwlock() {
493 let lock = RwLock::new(1);
494 assert_eq!(*lock.read(), 1);
495
496 let a = lock.read();
497 let b = lock.read();
498 assert_eq!(*a, 1);
499 assert_eq!(*b, 1);
500 drop((a, b));
501
502 assert_eq!(*lock.write(), 1);
503
504 *lock.write() = 4;
505 assert_eq!(*lock.read(), 4);
506 assert_eq!(*lock.write(), 4);
507
508 let a = lock.read();
509 let b = lock.read();
510 assert_eq!(*a, 4);
511 assert_eq!(*b, 4);
512 drop((a, b));
513 }
514
515 #[test]
516 #[should_panic(expected = "concurrent write request")]
517 fn rwlock_panic_read_then_write() {
518 let lock = RwLock::new(1);
519 let _a = lock.read();
520 let _b = lock.write();
521 }
522
523 #[test]
524 #[should_panic(expected = "concurrent read request")]
525 fn rwlock_panic_write_then_read() {
526 let lock = RwLock::new(1);
527 let _a = lock.write();
528 let _b = lock.read();
529 }
530
531 #[test]
532 #[should_panic(expected = "concurrent write request")]
533 fn rwlock_panic_write_then_write() {
534 let lock = RwLock::new(1);
535 let _a = lock.write();
536 let _b = lock.write();
537 }
538}