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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#[allow(unused_imports)]
pub(crate) use self::inner::*;

#[cfg(loom)]
mod inner {
    #![allow(dead_code)]
    pub(crate) use loom::thread_local;

    #[cfg(feature = "alloc")]
    pub(crate) mod alloc {
        use super::sync::Arc;
        use core::{
            future::Future,
            pin::Pin,
            task::{Context, Poll},
        };
        pub(crate) use loom::alloc::*;

        #[derive(Debug)]
        #[pin_project::pin_project]
        pub(crate) struct TrackFuture<F> {
            #[pin]
            inner: F,
            track: Arc<()>,
        }

        impl<F: Future> Future for TrackFuture<F> {
            type Output = TrackFuture<F::Output>;
            fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
                let this = self.project();
                this.inner.poll(cx).map(|inner| TrackFuture {
                    inner,
                    track: this.track.clone(),
                })
            }
        }

        impl<F> TrackFuture<F> {
            /// Wrap a `Future` in a `TrackFuture` that participates in Loom's
            /// leak checking.
            #[track_caller]
            pub(crate) fn new(inner: F) -> Self {
                Self {
                    inner,
                    track: Arc::new(()),
                }
            }

            /// Stop tracking this future, and return the inner value.
            pub(crate) fn into_inner(self) -> F {
                self.inner
            }
        }

        #[track_caller]
        pub(crate) fn track_future<F: Future>(inner: F) -> TrackFuture<F> {
            TrackFuture::new(inner)
        }

        // PartialEq impl so that `assert_eq!(..., Ok(...))` works
        impl<F: PartialEq> PartialEq for TrackFuture<F> {
            fn eq(&self, other: &Self) -> bool {
                self.inner == other.inner
            }
        }
    }

    pub(crate) use loom::{cell, future, model, thread};

    pub(crate) mod sync {
        pub(crate) use loom::sync::*;

        pub(crate) mod spin {
            pub(crate) use loom::sync::MutexGuard;

            /// Mock version of mycelium's spinlock, but using
            /// `loom::sync::Mutex`. The API is slightly different, since the
            /// mycelium mutex does not support poisoning.
            #[derive(Debug)]
            pub(crate) struct Mutex<T>(loom::sync::Mutex<T>);

            impl<T> Mutex<T> {
                #[track_caller]
                pub(crate) fn new(t: T) -> Self {
                    Self(loom::sync::Mutex::new(t))
                }

                #[track_caller]
                pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
                    self.0.try_lock().ok()
                }

                #[track_caller]
                pub fn lock(&self) -> MutexGuard<'_, T> {
                    self.0.lock().expect("loom mutex will never poison")
                }
            }
        }
    }
}

#[cfg(not(loom))]
mod inner {
    #![allow(dead_code, unused_imports)]

    #[cfg(test)]
    pub(crate) use std::thread_local;

    pub(crate) mod sync {
        #[cfg(feature = "alloc")]
        pub use alloc::sync::*;
        pub use core::sync::*;

        pub use mycelium_util::sync::spin;
    }

    pub(crate) mod atomic {
        pub use portable_atomic::*;
    }

    pub(crate) use portable_atomic::hint;

    #[cfg(test)]
    pub(crate) mod thread {

        pub(crate) use std::thread::{yield_now, JoinHandle};

        pub(crate) fn spawn<F, T>(f: F) -> JoinHandle<T>
        where
            F: FnOnce() -> T + Send + 'static,
            T: Send + 'static,
        {
            use super::atomic::{AtomicUsize, Ordering::Relaxed};
            thread_local! {
                static CHILDREN: AtomicUsize = const { AtomicUsize::new(1) };
            }

            let track = super::alloc::track::Registry::current();
            let subscriber = tracing_02::Dispatch::default();
            let span = tracing_02::Span::current();
            let num = CHILDREN.with(|children| children.fetch_add(1, Relaxed));
            std::thread::spawn(move || {
                let _tracing = tracing_02::dispatch::set_default(&subscriber);
                let _span =
                    tracing_02::info_span!(parent: span.id(), "thread", message = num).entered();

                tracing_02::info!(num, "spawned child thread");
                let _tracking = track.map(|track| track.set_default());
                let res = f();
                tracing_02::info!(num, "child thread completed");

                res
            })
        }
    }

    #[cfg(test)]
    pub(crate) mod model {
        #[non_exhaustive]
        #[derive(Default)]
        pub(crate) struct Builder {
            pub(crate) max_threads: usize,
            pub(crate) max_branches: usize,
            pub(crate) max_permutations: Option<usize>,
            // pub(crate) max_duration: Option<Duration>,
            pub(crate) preemption_bound: Option<usize>,
            // pub(crate) checkpoint_file: Option<PathBuf>,
            pub(crate) checkpoint_interval: usize,
            pub(crate) location: bool,
            pub(crate) log: bool,
        }

        impl Builder {
            pub(crate) fn new() -> Self {
                Self::default()
            }

            pub(crate) fn check(&self, f: impl FnOnce()) {
                let _trace = crate::util::test::trace_init();
                let _span = tracing_02::info_span!(
                    "test",
                    message = std::thread::current().name().unwrap_or("<unnamed>")
                )
                .entered();
                let registry = super::alloc::track::Registry::default();
                let _tracking = registry.set_default();

                tracing_02::info!("started test...");
                f();
                tracing_02::info!("test completed successfully!");

                registry.check();
            }
        }
    }

    #[cfg(test)]
    pub(crate) fn model(f: impl FnOnce()) {
        model::Builder::new().check(f)
    }

    pub(crate) mod cell {
        #[derive(Debug)]
        pub(crate) struct UnsafeCell<T: ?Sized>(core::cell::UnsafeCell<T>);

        impl<T> UnsafeCell<T> {
            pub const fn new(data: T) -> UnsafeCell<T> {
                UnsafeCell(core::cell::UnsafeCell::new(data))
            }
        }

        impl<T: ?Sized> UnsafeCell<T> {
            #[inline(always)]
            pub fn with<F, R>(&self, f: F) -> R
            where
                F: FnOnce(*const T) -> R,
            {
                f(self.0.get())
            }

            #[inline(always)]
            pub fn with_mut<F, R>(&self, f: F) -> R
            where
                F: FnOnce(*mut T) -> R,
            {
                f(self.0.get())
            }

            #[inline(always)]
            pub(crate) fn get(&self) -> ConstPtr<T> {
                ConstPtr(self.0.get())
            }

            #[inline(always)]
            pub(crate) fn get_mut(&self) -> MutPtr<T> {
                MutPtr(self.0.get())
            }
        }

        #[derive(Debug)]
        pub(crate) struct ConstPtr<T: ?Sized>(*const T);

        impl<T: ?Sized> ConstPtr<T> {
            #[inline(always)]
            pub(crate) unsafe fn deref(&self) -> &T {
                &*self.0
            }

            #[inline(always)]
            pub fn with<F, R>(&self, f: F) -> R
            where
                F: FnOnce(*const T) -> R,
            {
                f(self.0)
            }
        }

        #[derive(Debug)]
        pub(crate) struct MutPtr<T: ?Sized>(*mut T);

        impl<T: ?Sized> MutPtr<T> {
            // Clippy knows that it's Bad and Wrong to construct a mutable reference
            // from an immutable one...but this function is intended to simulate a raw
            // pointer, so we have to do that here.
            #[allow(clippy::mut_from_ref)]
            #[inline(always)]
            pub(crate) unsafe fn deref(&self) -> &mut T {
                &mut *self.0
            }

            #[inline(always)]
            pub fn with<F, R>(&self, f: F) -> R
            where
                F: FnOnce(*mut T) -> R,
            {
                f(self.0)
            }
        }
    }

    pub(crate) mod alloc {
        #[cfg(test)]
        use core::{
            future::Future,
            pin::Pin,
            task::{Context, Poll},
        };

        #[cfg(test)]
        use std::sync::Arc;
        #[cfg(test)]
        pub(in crate::loom) mod track {
            use std::{
                cell::RefCell,
                sync::{
                    atomic::{AtomicBool, Ordering},
                    Arc, Mutex, Weak,
                },
            };

            #[derive(Clone, Debug, Default)]
            pub(crate) struct Registry(Arc<Mutex<RegistryInner>>);

            #[derive(Debug, Default)]
            struct RegistryInner {
                tracks: Vec<Weak<TrackData>>,
                next_id: usize,
            }

            #[derive(Debug)]
            pub(super) struct TrackData {
                was_leaked: AtomicBool,
                type_name: &'static str,
                location: &'static core::panic::Location<'static>,
                id: usize,
            }

            thread_local! {
                static REGISTRY: RefCell<Option<Registry>> = const { RefCell::new(None) };
            }

            impl Registry {
                pub(in crate::loom) fn current() -> Option<Registry> {
                    REGISTRY.with(|current| current.borrow().clone())
                }

                pub(in crate::loom) fn set_default(&self) -> impl Drop {
                    struct Unset(Option<Registry>);
                    impl Drop for Unset {
                        fn drop(&mut self) {
                            let _ =
                                REGISTRY.try_with(|current| *current.borrow_mut() = self.0.take());
                        }
                    }

                    REGISTRY.with(|current| {
                        let mut current = current.borrow_mut();
                        let unset = Unset(current.clone());
                        *current = Some(self.clone());
                        unset
                    })
                }

                #[track_caller]
                pub(super) fn start_tracking<T>() -> Option<Arc<TrackData>> {
                    // we don't use `Option::map` here because it creates a
                    // closure, which breaks `#[track_caller]`, since the caller
                    // of `insert` becomes the closure, which cannot have a
                    // `#[track_caller]` attribute on it.
                    #[allow(clippy::manual_map)]
                    match Self::current() {
                        Some(registry) => Some(registry.insert::<T>()),
                        _ => None,
                    }
                }

                #[track_caller]
                pub(super) fn insert<T>(&self) -> Arc<TrackData> {
                    let mut inner = self.0.lock().unwrap();
                    let id = inner.next_id;
                    inner.next_id += 1;
                    let location = core::panic::Location::caller();
                    let type_name = std::any::type_name::<T>();
                    let data = Arc::new(TrackData {
                        type_name,
                        location,
                        id,
                        was_leaked: AtomicBool::new(false),
                    });
                    let weak = Arc::downgrade(&data);
                    trace!(
                        target: "maitake::alloc",
                        id,
                        "type" = %type_name,
                        %location,
                        "started tracking allocation",
                    );
                    inner.tracks.push(weak);
                    data
                }

                pub(in crate::loom) fn check(&self) {
                    let leaked = self
                        .0
                        .lock()
                        .unwrap()
                        .tracks
                        .iter()
                        .filter_map(|weak| {
                            let data = weak.upgrade()?;
                            data.was_leaked.store(true, Ordering::SeqCst);
                            Some(format!(
                                " - id {}, {} allocated at {}",
                                data.id, data.type_name, data.location
                            ))
                        })
                        .collect::<Vec<_>>();
                    if !leaked.is_empty() {
                        let leaked = leaked.join("\n  ");
                        panic!("the following allocations were leaked:\n  {leaked}");
                    }
                }
            }

            impl Drop for TrackData {
                fn drop(&mut self) {
                    if !self.was_leaked.load(Ordering::SeqCst) {
                        trace!(
                            target: "maitake::alloc",
                            id = self.id,
                            "type" = %self.type_name,
                            location = %self.location,
                            "dropped all references to a tracked allocation",
                        );
                    }
                }
            }
        }

        #[cfg(test)]
        #[derive(Debug)]
        #[pin_project::pin_project]
        pub(crate) struct TrackFuture<F> {
            #[pin]
            inner: F,
            track: Option<Arc<track::TrackData>>,
        }

        #[cfg(test)]
        impl<F: Future> Future for TrackFuture<F> {
            type Output = TrackFuture<F::Output>;
            fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
                let this = self.project();
                this.inner.poll(cx).map(|inner| TrackFuture {
                    inner,
                    track: this.track.clone(),
                })
            }
        }

        #[cfg(test)]
        impl<F> TrackFuture<F> {
            /// Wrap a `Future` in a `TrackFuture` that participates in Loom's
            /// leak checking.
            #[track_caller]
            pub(crate) fn new(inner: F) -> Self {
                let track = track::Registry::start_tracking::<F>();
                Self { inner, track }
            }

            /// Stop tracking this future, and return the inner value.
            pub(crate) fn into_inner(self) -> F {
                self.inner
            }
        }

        #[cfg(test)]
        #[track_caller]
        pub(crate) fn track_future<F: Future>(inner: F) -> TrackFuture<F> {
            TrackFuture::new(inner)
        }

        // PartialEq impl so that `assert_eq!(..., Ok(...))` works
        #[cfg(test)]
        impl<F: PartialEq> PartialEq for TrackFuture<F> {
            fn eq(&self, other: &Self) -> bool {
                self.inner == other.inner
            }
        }

        /// Track allocations, detecting leaks
        #[derive(Debug, Default)]
        pub struct Track<T> {
            value: T,

            #[cfg(test)]
            track: Option<Arc<track::TrackData>>,
        }

        impl<T> Track<T> {
            /// Track a value for leaks
            #[inline(always)]
            #[track_caller]
            pub fn new(value: T) -> Track<T> {
                Track {
                    value,

                    #[cfg(test)]
                    track: track::Registry::start_tracking::<T>(),
                }
            }

            /// Get a reference to the value
            #[inline(always)]
            pub fn get_ref(&self) -> &T {
                &self.value
            }

            /// Get a mutable reference to the value
            #[inline(always)]
            pub fn get_mut(&mut self) -> &mut T {
                &mut self.value
            }

            /// Stop tracking the value for leaks
            #[inline(always)]
            pub fn into_inner(self) -> T {
                self.value
            }
        }
    }

    #[cfg(test)]
    pub(crate) mod future {
        pub(crate) use tokio_test::block_on;
    }

    #[cfg(test)]
    pub(crate) fn traceln(args: std::fmt::Arguments) {
        eprintln!("{args}");
    }

    #[cfg(not(test))]
    pub(crate) fn traceln(_: core::fmt::Arguments) {}
}