]> git.lizzy.rs Git - rust.git/blob - src/concurrency/data_race.rs
some clippy-induced cleanup
[rust.git] / src / concurrency / data_race.rs
1 //! Implementation of a data-race detector using Lamport Timestamps / Vector-clocks
2 //! based on the Dynamic Race Detection for C++:
3 //! <https://www.doc.ic.ac.uk/~afd/homepages/papers/pdfs/2017/POPL.pdf>
4 //! which does not report false-positives when fences are used, and gives better
5 //! accuracy in presence of read-modify-write operations.
6 //!
7 //! The implementation contains modifications to correctly model the changes to the memory model in C++20
8 //! regarding the weakening of release sequences: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0982r1.html>.
9 //! Relaxed stores now unconditionally block all currently active release sequences and so per-thread tracking of release
10 //! sequences is not needed.
11 //!
12 //! The implementation also models races with memory allocation and deallocation via treating allocation and
13 //! deallocation as a type of write internally for detecting data-races.
14 //!
15 //! Weak memory orders are explored but not all weak behaviours are exhibited, so it can still miss data-races
16 //! but should not report false-positives
17 //!
18 //! Data-race definition from(<https://en.cppreference.com/w/cpp/language/memory_model#Threads_and_data_races>):
19 //! a data race occurs between two memory accesses if they are on different threads, at least one operation
20 //! is non-atomic, at least one operation is a write and neither access happens-before the other. Read the link
21 //! for full definition.
22 //!
23 //! This re-uses vector indexes for threads that are known to be unable to report data-races, this is valid
24 //! because it only re-uses vector indexes once all currently-active (not-terminated) threads have an internal
25 //! vector clock that happens-after the join operation of the candidate thread. Threads that have not been joined
26 //! on are not considered. Since the thread's vector clock will only increase and a data-race implies that
27 //! there is some index x where clock\[x\] > thread_clock, when this is true clock\[candidate-idx\] > thread_clock
28 //! can never hold and hence a data-race can never be reported in that vector index again.
29 //! This means that the thread-index can be safely re-used, starting on the next timestamp for the newly created
30 //! thread.
31 //!
32 //! The timestamps used in the data-race detector assign each sequence of non-atomic operations
33 //! followed by a single atomic or concurrent operation a single timestamp.
34 //! Write, Read, Write, ThreadJoin will be represented by a single timestamp value on a thread.
35 //! This is because extra increment operations between the operations in the sequence are not
36 //! required for accurate reporting of data-race values.
37 //!
38 //! As per the paper a threads timestamp is only incremented after a release operation is performed
39 //! so some atomic operations that only perform acquires do not increment the timestamp. Due to shared
40 //! code some atomic operations may increment the timestamp when not necessary but this has no effect
41 //! on the data-race detection code.
42 //!
43 //! FIXME:
44 //! currently we have our own local copy of the currently active thread index and names, this is due
45 //! in part to the inability to access the current location of threads.active_thread inside the AllocExtra
46 //! read, write and deallocate functions and should be cleaned up in the future.
47
48 use std::{
49     cell::{Cell, Ref, RefCell, RefMut},
50     fmt::Debug,
51     mem,
52 };
53
54 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_index::vec::{Idx, IndexVec};
56 use rustc_middle::{mir, ty::layout::TyAndLayout};
57 use rustc_target::abi::Size;
58
59 use crate::*;
60
61 use super::weak_memory::EvalContextExt as _;
62
63 pub type AllocExtra = VClockAlloc;
64
65 /// Valid atomic read-write operations, alias of atomic::Ordering (not non-exhaustive).
66 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
67 pub enum AtomicRwOp {
68     Relaxed,
69     Acquire,
70     Release,
71     AcqRel,
72     SeqCst,
73 }
74
75 /// Valid atomic read operations, subset of atomic::Ordering.
76 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
77 pub enum AtomicReadOp {
78     Relaxed,
79     Acquire,
80     SeqCst,
81 }
82
83 /// Valid atomic write operations, subset of atomic::Ordering.
84 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
85 pub enum AtomicWriteOp {
86     Relaxed,
87     Release,
88     SeqCst,
89 }
90
91 /// Valid atomic fence operations, subset of atomic::Ordering.
92 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
93 pub enum AtomicFenceOp {
94     Acquire,
95     Release,
96     AcqRel,
97     SeqCst,
98 }
99
100 /// The current set of vector clocks describing the state
101 /// of a thread, contains the happens-before clock and
102 /// additional metadata to model atomic fence operations.
103 #[derive(Clone, Default, Debug)]
104 pub(super) struct ThreadClockSet {
105     /// The increasing clock representing timestamps
106     /// that happen-before this thread.
107     pub(super) clock: VClock,
108
109     /// The set of timestamps that will happen-before this
110     /// thread once it performs an acquire fence.
111     fence_acquire: VClock,
112
113     /// The last timestamp of happens-before relations that
114     /// have been released by this thread by a fence.
115     fence_release: VClock,
116
117     /// Timestamps of the last SC fence performed by each
118     /// thread, updated when this thread performs an SC fence
119     pub(super) fence_seqcst: VClock,
120
121     /// Timestamps of the last SC write performed by each
122     /// thread, updated when this thread performs an SC fence
123     pub(super) write_seqcst: VClock,
124
125     /// Timestamps of the last SC fence performed by each
126     /// thread, updated when this thread performs an SC read
127     pub(super) read_seqcst: VClock,
128 }
129
130 impl ThreadClockSet {
131     /// Apply the effects of a release fence to this
132     /// set of thread vector clocks.
133     #[inline]
134     fn apply_release_fence(&mut self) {
135         self.fence_release.clone_from(&self.clock);
136     }
137
138     /// Apply the effects of an acquire fence to this
139     /// set of thread vector clocks.
140     #[inline]
141     fn apply_acquire_fence(&mut self) {
142         self.clock.join(&self.fence_acquire);
143     }
144
145     /// Increment the happens-before clock at a
146     /// known index.
147     #[inline]
148     fn increment_clock(&mut self, index: VectorIdx) {
149         self.clock.increment_index(index);
150     }
151
152     /// Join the happens-before clock with that of
153     /// another thread, used to model thread join
154     /// operations.
155     fn join_with(&mut self, other: &ThreadClockSet) {
156         self.clock.join(&other.clock);
157     }
158 }
159
160 /// Error returned by finding a data race
161 /// should be elaborated upon.
162 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
163 pub struct DataRace;
164
165 /// Externally stored memory cell clocks
166 /// explicitly to reduce memory usage for the
167 /// common case where no atomic operations
168 /// exists on the memory cell.
169 #[derive(Clone, PartialEq, Eq, Default, Debug)]
170 struct AtomicMemoryCellClocks {
171     /// The clock-vector of the timestamp of the last atomic
172     /// read operation performed by each thread.
173     /// This detects potential data-races between atomic read
174     /// and non-atomic write operations.
175     read_vector: VClock,
176
177     /// The clock-vector of the timestamp of the last atomic
178     /// write operation performed by each thread.
179     /// This detects potential data-races between atomic write
180     /// and non-atomic read or write operations.
181     write_vector: VClock,
182
183     /// Synchronization vector for acquire-release semantics
184     /// contains the vector of timestamps that will
185     /// happen-before a thread if an acquire-load is
186     /// performed on the data.
187     sync_vector: VClock,
188 }
189
190 /// Type of write operation: allocating memory
191 /// non-atomic writes and deallocating memory
192 /// are all treated as writes for the purpose
193 /// of the data-race detector.
194 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
195 enum WriteType {
196     /// Allocate memory.
197     Allocate,
198
199     /// Standard unsynchronized write.
200     Write,
201
202     /// Deallocate memory.
203     /// Note that when memory is deallocated first, later non-atomic accesses
204     /// will be reported as use-after-free, not as data races.
205     /// (Same for `Allocate` above.)
206     Deallocate,
207 }
208 impl WriteType {
209     fn get_descriptor(self) -> &'static str {
210         match self {
211             WriteType::Allocate => "Allocate",
212             WriteType::Write => "Write",
213             WriteType::Deallocate => "Deallocate",
214         }
215     }
216 }
217
218 /// Memory Cell vector clock metadata
219 /// for data-race detection.
220 #[derive(Clone, PartialEq, Eq, Debug)]
221 struct MemoryCellClocks {
222     /// The vector-clock timestamp of the last write
223     /// corresponding to the writing threads timestamp.
224     write: VTimestamp,
225
226     /// The identifier of the vector index, corresponding to a thread
227     /// that performed the last write operation.
228     write_index: VectorIdx,
229
230     /// The type of operation that the write index represents,
231     /// either newly allocated memory, a non-atomic write or
232     /// a deallocation of memory.
233     write_type: WriteType,
234
235     /// The vector-clock of the timestamp of the last read operation
236     /// performed by a thread since the last write operation occurred.
237     /// It is reset to zero on each write operation.
238     read: VClock,
239
240     /// Atomic acquire & release sequence tracking clocks.
241     /// For non-atomic memory in the common case this
242     /// value is set to None.
243     atomic_ops: Option<Box<AtomicMemoryCellClocks>>,
244 }
245
246 impl MemoryCellClocks {
247     /// Create a new set of clocks representing memory allocated
248     ///  at a given vector timestamp and index.
249     fn new(alloc: VTimestamp, alloc_index: VectorIdx) -> Self {
250         MemoryCellClocks {
251             read: VClock::default(),
252             write: alloc,
253             write_index: alloc_index,
254             write_type: WriteType::Allocate,
255             atomic_ops: None,
256         }
257     }
258
259     /// Load the internal atomic memory cells if they exist.
260     #[inline]
261     fn atomic(&self) -> Option<&AtomicMemoryCellClocks> {
262         self.atomic_ops.as_deref()
263     }
264
265     /// Load or create the internal atomic memory metadata
266     /// if it does not exist.
267     #[inline]
268     fn atomic_mut(&mut self) -> &mut AtomicMemoryCellClocks {
269         self.atomic_ops.get_or_insert_with(Default::default)
270     }
271
272     /// Update memory cell data-race tracking for atomic
273     /// load acquire semantics, is a no-op if this memory was
274     /// not used previously as atomic memory.
275     fn load_acquire(
276         &mut self,
277         clocks: &mut ThreadClockSet,
278         index: VectorIdx,
279     ) -> Result<(), DataRace> {
280         self.atomic_read_detect(clocks, index)?;
281         if let Some(atomic) = self.atomic() {
282             clocks.clock.join(&atomic.sync_vector);
283         }
284         Ok(())
285     }
286
287     /// Checks if the memory cell access is ordered with all prior atomic reads and writes
288     fn race_free_with_atomic(&self, clocks: &ThreadClockSet) -> bool {
289         if let Some(atomic) = self.atomic() {
290             atomic.read_vector <= clocks.clock && atomic.write_vector <= clocks.clock
291         } else {
292             true
293         }
294     }
295
296     /// Update memory cell data-race tracking for atomic
297     /// load relaxed semantics, is a no-op if this memory was
298     /// not used previously as atomic memory.
299     fn load_relaxed(
300         &mut self,
301         clocks: &mut ThreadClockSet,
302         index: VectorIdx,
303     ) -> Result<(), DataRace> {
304         self.atomic_read_detect(clocks, index)?;
305         if let Some(atomic) = self.atomic() {
306             clocks.fence_acquire.join(&atomic.sync_vector);
307         }
308         Ok(())
309     }
310
311     /// Update the memory cell data-race tracking for atomic
312     /// store release semantics.
313     fn store_release(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
314         self.atomic_write_detect(clocks, index)?;
315         let atomic = self.atomic_mut();
316         atomic.sync_vector.clone_from(&clocks.clock);
317         Ok(())
318     }
319
320     /// Update the memory cell data-race tracking for atomic
321     /// store relaxed semantics.
322     fn store_relaxed(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
323         self.atomic_write_detect(clocks, index)?;
324
325         // The handling of release sequences was changed in C++20 and so
326         // the code here is different to the paper since now all relaxed
327         // stores block release sequences. The exception for same-thread
328         // relaxed stores has been removed.
329         let atomic = self.atomic_mut();
330         atomic.sync_vector.clone_from(&clocks.fence_release);
331         Ok(())
332     }
333
334     /// Update the memory cell data-race tracking for atomic
335     /// store release semantics for RMW operations.
336     fn rmw_release(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
337         self.atomic_write_detect(clocks, index)?;
338         let atomic = self.atomic_mut();
339         atomic.sync_vector.join(&clocks.clock);
340         Ok(())
341     }
342
343     /// Update the memory cell data-race tracking for atomic
344     /// store relaxed semantics for RMW operations.
345     fn rmw_relaxed(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
346         self.atomic_write_detect(clocks, index)?;
347         let atomic = self.atomic_mut();
348         atomic.sync_vector.join(&clocks.fence_release);
349         Ok(())
350     }
351
352     /// Detect data-races with an atomic read, caused by a non-atomic write that does
353     /// not happen-before the atomic-read.
354     fn atomic_read_detect(
355         &mut self,
356         clocks: &ThreadClockSet,
357         index: VectorIdx,
358     ) -> Result<(), DataRace> {
359         log::trace!("Atomic read with vectors: {:#?} :: {:#?}", self, clocks);
360         if self.write <= clocks.clock[self.write_index] {
361             let atomic = self.atomic_mut();
362             atomic.read_vector.set_at_index(&clocks.clock, index);
363             Ok(())
364         } else {
365             Err(DataRace)
366         }
367     }
368
369     /// Detect data-races with an atomic write, either with a non-atomic read or with
370     /// a non-atomic write.
371     fn atomic_write_detect(
372         &mut self,
373         clocks: &ThreadClockSet,
374         index: VectorIdx,
375     ) -> Result<(), DataRace> {
376         log::trace!("Atomic write with vectors: {:#?} :: {:#?}", self, clocks);
377         if self.write <= clocks.clock[self.write_index] && self.read <= clocks.clock {
378             let atomic = self.atomic_mut();
379             atomic.write_vector.set_at_index(&clocks.clock, index);
380             Ok(())
381         } else {
382             Err(DataRace)
383         }
384     }
385
386     /// Detect races for non-atomic read operations at the current memory cell
387     /// returns true if a data-race is detected.
388     fn read_race_detect(
389         &mut self,
390         clocks: &ThreadClockSet,
391         index: VectorIdx,
392     ) -> Result<(), DataRace> {
393         log::trace!("Unsynchronized read with vectors: {:#?} :: {:#?}", self, clocks);
394         if self.write <= clocks.clock[self.write_index] {
395             let race_free = if let Some(atomic) = self.atomic() {
396                 atomic.write_vector <= clocks.clock
397             } else {
398                 true
399             };
400             if race_free {
401                 self.read.set_at_index(&clocks.clock, index);
402                 Ok(())
403             } else {
404                 Err(DataRace)
405             }
406         } else {
407             Err(DataRace)
408         }
409     }
410
411     /// Detect races for non-atomic write operations at the current memory cell
412     /// returns true if a data-race is detected.
413     fn write_race_detect(
414         &mut self,
415         clocks: &ThreadClockSet,
416         index: VectorIdx,
417         write_type: WriteType,
418     ) -> Result<(), DataRace> {
419         log::trace!("Unsynchronized write with vectors: {:#?} :: {:#?}", self, clocks);
420         if self.write <= clocks.clock[self.write_index] && self.read <= clocks.clock {
421             let race_free = if let Some(atomic) = self.atomic() {
422                 atomic.write_vector <= clocks.clock && atomic.read_vector <= clocks.clock
423             } else {
424                 true
425             };
426             if race_free {
427                 self.write = clocks.clock[index];
428                 self.write_index = index;
429                 self.write_type = write_type;
430                 self.read.set_zero_vector();
431                 Ok(())
432             } else {
433                 Err(DataRace)
434             }
435         } else {
436             Err(DataRace)
437         }
438     }
439 }
440
441 /// Evaluation context extensions.
442 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {}
443 pub trait EvalContextExt<'mir, 'tcx: 'mir>: MiriEvalContextExt<'mir, 'tcx> {
444     /// Temporarily allow data-races to occur. This should only be used in
445     /// one of these cases:
446     /// - One of the appropriate `validate_atomic` functions will be called to
447     /// to treat a memory access as atomic.
448     /// - The memory being accessed should be treated as internal state, that
449     /// cannot be accessed by the interpreted program.
450     /// - Execution of the interpreted program execution has halted.
451     #[inline]
452     fn allow_data_races_ref<R>(&self, op: impl FnOnce(&MiriEvalContext<'mir, 'tcx>) -> R) -> R {
453         let this = self.eval_context_ref();
454         if let Some(data_race) = &this.machine.data_race {
455             data_race.ongoing_action_data_race_free.set(true);
456         }
457         let result = op(this);
458         if let Some(data_race) = &this.machine.data_race {
459             data_race.ongoing_action_data_race_free.set(false);
460         }
461         result
462     }
463
464     /// Same as `allow_data_races_ref`, this temporarily disables any data-race detection and
465     /// so should only be used for atomic operations or internal state that the program cannot
466     /// access.
467     #[inline]
468     fn allow_data_races_mut<R>(
469         &mut self,
470         op: impl FnOnce(&mut MiriEvalContext<'mir, 'tcx>) -> R,
471     ) -> R {
472         let this = self.eval_context_mut();
473         if let Some(data_race) = &this.machine.data_race {
474             data_race.ongoing_action_data_race_free.set(true);
475         }
476         let result = op(this);
477         if let Some(data_race) = &this.machine.data_race {
478             data_race.ongoing_action_data_race_free.set(false);
479         }
480         result
481     }
482
483     /// Atomic variant of read_scalar_at_offset.
484     fn read_scalar_at_offset_atomic(
485         &self,
486         op: &OpTy<'tcx, Tag>,
487         offset: u64,
488         layout: TyAndLayout<'tcx>,
489         atomic: AtomicReadOp,
490     ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
491         let this = self.eval_context_ref();
492         let value_place = this.deref_operand_and_offset(op, offset, layout)?;
493         this.read_scalar_atomic(&value_place, atomic)
494     }
495
496     /// Atomic variant of write_scalar_at_offset.
497     fn write_scalar_at_offset_atomic(
498         &mut self,
499         op: &OpTy<'tcx, Tag>,
500         offset: u64,
501         value: impl Into<ScalarMaybeUninit<Tag>>,
502         layout: TyAndLayout<'tcx>,
503         atomic: AtomicWriteOp,
504     ) -> InterpResult<'tcx> {
505         let this = self.eval_context_mut();
506         let value_place = this.deref_operand_and_offset(op, offset, layout)?;
507         this.write_scalar_atomic(value.into(), &value_place, atomic)
508     }
509
510     /// Perform an atomic read operation at the memory location.
511     fn read_scalar_atomic(
512         &self,
513         place: &MPlaceTy<'tcx, Tag>,
514         atomic: AtomicReadOp,
515     ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
516         let this = self.eval_context_ref();
517         // This will read from the last store in the modification order of this location. In case
518         // weak memory emulation is enabled, this may not be the store we will pick to actually read from and return.
519         // This is fine with StackedBorrow and race checks because they don't concern metadata on
520         // the *value* (including the associated provenance if this is an AtomicPtr) at this location.
521         // Only metadata on the location itself is used.
522         let scalar = this.allow_data_races_ref(move |this| this.read_scalar(&place.into()))?;
523         this.validate_overlapping_atomic(place)?;
524         this.buffered_atomic_read(place, atomic, scalar, || {
525             this.validate_atomic_load(place, atomic)
526         })
527     }
528
529     /// Perform an atomic write operation at the memory location.
530     fn write_scalar_atomic(
531         &mut self,
532         val: ScalarMaybeUninit<Tag>,
533         dest: &MPlaceTy<'tcx, Tag>,
534         atomic: AtomicWriteOp,
535     ) -> InterpResult<'tcx> {
536         let this = self.eval_context_mut();
537         this.validate_overlapping_atomic(dest)?;
538         this.allow_data_races_mut(move |this| this.write_scalar(val, &(*dest).into()))?;
539         this.validate_atomic_store(dest, atomic)?;
540         // FIXME: it's not possible to get the value before write_scalar. A read_scalar will cause
541         // side effects from a read the program did not perform. So we have to initialise
542         // the store buffer with the value currently being written
543         // ONCE this is fixed please remove the hack in buffered_atomic_write() in weak_memory.rs
544         // https://github.com/rust-lang/miri/issues/2164
545         this.buffered_atomic_write(val, dest, atomic, val)
546     }
547
548     /// Perform an atomic operation on a memory location.
549     fn atomic_op_immediate(
550         &mut self,
551         place: &MPlaceTy<'tcx, Tag>,
552         rhs: &ImmTy<'tcx, Tag>,
553         op: mir::BinOp,
554         neg: bool,
555         atomic: AtomicRwOp,
556     ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
557         let this = self.eval_context_mut();
558
559         this.validate_overlapping_atomic(place)?;
560         let old = this.allow_data_races_mut(|this| this.read_immediate(&place.into()))?;
561
562         // Atomics wrap around on overflow.
563         let val = this.binary_op(op, &old, rhs)?;
564         let val = if neg { this.unary_op(mir::UnOp::Not, &val)? } else { val };
565         this.allow_data_races_mut(|this| this.write_immediate(*val, &(*place).into()))?;
566
567         this.validate_atomic_rmw(place, atomic)?;
568
569         this.buffered_atomic_rmw(
570             val.to_scalar_or_uninit(),
571             place,
572             atomic,
573             old.to_scalar_or_uninit(),
574         )?;
575         Ok(old)
576     }
577
578     /// Perform an atomic exchange with a memory place and a new
579     /// scalar value, the old value is returned.
580     fn atomic_exchange_scalar(
581         &mut self,
582         place: &MPlaceTy<'tcx, Tag>,
583         new: ScalarMaybeUninit<Tag>,
584         atomic: AtomicRwOp,
585     ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
586         let this = self.eval_context_mut();
587
588         this.validate_overlapping_atomic(place)?;
589         let old = this.allow_data_races_mut(|this| this.read_scalar(&place.into()))?;
590         this.allow_data_races_mut(|this| this.write_scalar(new, &(*place).into()))?;
591
592         this.validate_atomic_rmw(place, atomic)?;
593
594         this.buffered_atomic_rmw(new, place, atomic, old)?;
595         Ok(old)
596     }
597
598     /// Perform an conditional atomic exchange with a memory place and a new
599     /// scalar value, the old value is returned.
600     fn atomic_min_max_scalar(
601         &mut self,
602         place: &MPlaceTy<'tcx, Tag>,
603         rhs: ImmTy<'tcx, Tag>,
604         min: bool,
605         atomic: AtomicRwOp,
606     ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
607         let this = self.eval_context_mut();
608
609         this.validate_overlapping_atomic(place)?;
610         let old = this.allow_data_races_mut(|this| this.read_immediate(&place.into()))?;
611         let lt = this.binary_op(mir::BinOp::Lt, &old, &rhs)?.to_scalar()?.to_bool()?;
612
613         let new_val = if min {
614             if lt { &old } else { &rhs }
615         } else {
616             if lt { &rhs } else { &old }
617         };
618
619         this.allow_data_races_mut(|this| this.write_immediate(**new_val, &(*place).into()))?;
620
621         this.validate_atomic_rmw(place, atomic)?;
622
623         this.buffered_atomic_rmw(
624             new_val.to_scalar_or_uninit(),
625             place,
626             atomic,
627             old.to_scalar_or_uninit(),
628         )?;
629
630         // Return the old value.
631         Ok(old)
632     }
633
634     /// Perform an atomic compare and exchange at a given memory location.
635     /// On success an atomic RMW operation is performed and on failure
636     /// only an atomic read occurs. If `can_fail_spuriously` is true,
637     /// then we treat it as a "compare_exchange_weak" operation, and
638     /// some portion of the time fail even when the values are actually
639     /// identical.
640     fn atomic_compare_exchange_scalar(
641         &mut self,
642         place: &MPlaceTy<'tcx, Tag>,
643         expect_old: &ImmTy<'tcx, Tag>,
644         new: ScalarMaybeUninit<Tag>,
645         success: AtomicRwOp,
646         fail: AtomicReadOp,
647         can_fail_spuriously: bool,
648     ) -> InterpResult<'tcx, Immediate<Tag>> {
649         use rand::Rng as _;
650         let this = self.eval_context_mut();
651
652         this.validate_overlapping_atomic(place)?;
653         // Failure ordering cannot be stronger than success ordering, therefore first attempt
654         // to read with the failure ordering and if successful then try again with the success
655         // read ordering and write in the success case.
656         // Read as immediate for the sake of `binary_op()`
657         let old = this.allow_data_races_mut(|this| this.read_immediate(&(place.into())))?;
658         // `binary_op` will bail if either of them is not a scalar.
659         let eq = this.binary_op(mir::BinOp::Eq, &old, expect_old)?;
660         // If the operation would succeed, but is "weak", fail some portion
661         // of the time, based on `success_rate`.
662         let success_rate = 1.0 - this.machine.cmpxchg_weak_failure_rate;
663         let cmpxchg_success = eq.to_scalar()?.to_bool()?
664             && if can_fail_spuriously {
665                 this.machine.rng.get_mut().gen_bool(success_rate)
666             } else {
667                 true
668             };
669         let res = Immediate::ScalarPair(
670             old.to_scalar_or_uninit(),
671             Scalar::from_bool(cmpxchg_success).into(),
672         );
673
674         // Update ptr depending on comparison.
675         // if successful, perform a full rw-atomic validation
676         // otherwise treat this as an atomic load with the fail ordering.
677         if cmpxchg_success {
678             this.allow_data_races_mut(|this| this.write_scalar(new, &(*place).into()))?;
679             this.validate_atomic_rmw(place, success)?;
680             this.buffered_atomic_rmw(new, place, success, old.to_scalar_or_uninit())?;
681         } else {
682             this.validate_atomic_load(place, fail)?;
683             // A failed compare exchange is equivalent to a load, reading from the latest store
684             // in the modification order.
685             // Since `old` is only a value and not the store element, we need to separately
686             // find it in our store buffer and perform load_impl on it.
687             this.perform_read_on_buffered_latest(place, fail, old.to_scalar_or_uninit())?;
688         }
689
690         // Return the old value.
691         Ok(res)
692     }
693
694     /// Update the data-race detector for an atomic read occurring at the
695     /// associated memory-place and on the current thread.
696     fn validate_atomic_load(
697         &self,
698         place: &MPlaceTy<'tcx, Tag>,
699         atomic: AtomicReadOp,
700     ) -> InterpResult<'tcx> {
701         let this = self.eval_context_ref();
702         this.validate_overlapping_atomic(place)?;
703         this.validate_atomic_op(
704             place,
705             atomic,
706             "Atomic Load",
707             move |memory, clocks, index, atomic| {
708                 if atomic == AtomicReadOp::Relaxed {
709                     memory.load_relaxed(&mut *clocks, index)
710                 } else {
711                     memory.load_acquire(&mut *clocks, index)
712                 }
713             },
714         )
715     }
716
717     /// Update the data-race detector for an atomic write occurring at the
718     /// associated memory-place and on the current thread.
719     fn validate_atomic_store(
720         &mut self,
721         place: &MPlaceTy<'tcx, Tag>,
722         atomic: AtomicWriteOp,
723     ) -> InterpResult<'tcx> {
724         let this = self.eval_context_mut();
725         this.validate_overlapping_atomic(place)?;
726         this.validate_atomic_op(
727             place,
728             atomic,
729             "Atomic Store",
730             move |memory, clocks, index, atomic| {
731                 if atomic == AtomicWriteOp::Relaxed {
732                     memory.store_relaxed(clocks, index)
733                 } else {
734                     memory.store_release(clocks, index)
735                 }
736             },
737         )
738     }
739
740     /// Update the data-race detector for an atomic read-modify-write occurring
741     /// at the associated memory place and on the current thread.
742     fn validate_atomic_rmw(
743         &mut self,
744         place: &MPlaceTy<'tcx, Tag>,
745         atomic: AtomicRwOp,
746     ) -> InterpResult<'tcx> {
747         use AtomicRwOp::*;
748         let acquire = matches!(atomic, Acquire | AcqRel | SeqCst);
749         let release = matches!(atomic, Release | AcqRel | SeqCst);
750         let this = self.eval_context_mut();
751         this.validate_overlapping_atomic(place)?;
752         this.validate_atomic_op(place, atomic, "Atomic RMW", move |memory, clocks, index, _| {
753             if acquire {
754                 memory.load_acquire(clocks, index)?;
755             } else {
756                 memory.load_relaxed(clocks, index)?;
757             }
758             if release {
759                 memory.rmw_release(clocks, index)
760             } else {
761                 memory.rmw_relaxed(clocks, index)
762             }
763         })
764     }
765
766     /// Update the data-race detector for an atomic fence on the current thread.
767     fn validate_atomic_fence(&mut self, atomic: AtomicFenceOp) -> InterpResult<'tcx> {
768         let this = self.eval_context_mut();
769         if let Some(data_race) = &mut this.machine.data_race {
770             data_race.maybe_perform_sync_operation(|index, mut clocks| {
771                 log::trace!("Atomic fence on {:?} with ordering {:?}", index, atomic);
772
773                 // Apply data-race detection for the current fences
774                 // this treats AcqRel and SeqCst as the same as an acquire
775                 // and release fence applied in the same timestamp.
776                 if atomic != AtomicFenceOp::Release {
777                     // Either Acquire | AcqRel | SeqCst
778                     clocks.apply_acquire_fence();
779                 }
780                 if atomic != AtomicFenceOp::Acquire {
781                     // Either Release | AcqRel | SeqCst
782                     clocks.apply_release_fence();
783                 }
784                 if atomic == AtomicFenceOp::SeqCst {
785                     data_race.last_sc_fence.borrow_mut().set_at_index(&clocks.clock, index);
786                     clocks.fence_seqcst.join(&data_race.last_sc_fence.borrow());
787                     clocks.write_seqcst.join(&data_race.last_sc_write.borrow());
788                 }
789
790                 // Increment timestamp in case of release semantics.
791                 Ok(atomic != AtomicFenceOp::Acquire)
792             })
793         } else {
794             Ok(())
795         }
796     }
797 }
798
799 /// Vector clock metadata for a logical memory allocation.
800 #[derive(Debug, Clone)]
801 pub struct VClockAlloc {
802     /// Assigning each byte a MemoryCellClocks.
803     alloc_ranges: RefCell<RangeMap<MemoryCellClocks>>,
804 }
805
806 impl VClockAlloc {
807     /// Create a new data-race detector for newly allocated memory.
808     pub fn new_allocation(
809         global: &GlobalState,
810         len: Size,
811         kind: MemoryKind<MiriMemoryKind>,
812     ) -> VClockAlloc {
813         let (alloc_timestamp, alloc_index) = match kind {
814             // User allocated and stack memory should track allocation.
815             MemoryKind::Machine(
816                 MiriMemoryKind::Rust | MiriMemoryKind::C | MiriMemoryKind::WinHeap,
817             )
818             | MemoryKind::Stack => {
819                 let (alloc_index, clocks) = global.current_thread_state();
820                 let alloc_timestamp = clocks.clock[alloc_index];
821                 (alloc_timestamp, alloc_index)
822             }
823             // Other global memory should trace races but be allocated at the 0 timestamp.
824             MemoryKind::Machine(
825                 MiriMemoryKind::Global
826                 | MiriMemoryKind::Machine
827                 | MiriMemoryKind::Runtime
828                 | MiriMemoryKind::ExternStatic
829                 | MiriMemoryKind::Tls,
830             )
831             | MemoryKind::CallerLocation => (0, VectorIdx::MAX_INDEX),
832         };
833         VClockAlloc {
834             alloc_ranges: RefCell::new(RangeMap::new(
835                 len,
836                 MemoryCellClocks::new(alloc_timestamp, alloc_index),
837             )),
838         }
839     }
840
841     // Find an index, if one exists where the value
842     // in `l` is greater than the value in `r`.
843     fn find_gt_index(l: &VClock, r: &VClock) -> Option<VectorIdx> {
844         log::trace!("Find index where not {:?} <= {:?}", l, r);
845         let l_slice = l.as_slice();
846         let r_slice = r.as_slice();
847         l_slice
848             .iter()
849             .zip(r_slice.iter())
850             .enumerate()
851             .find_map(|(idx, (&l, &r))| if l > r { Some(idx) } else { None })
852             .or_else(|| {
853                 if l_slice.len() > r_slice.len() {
854                     // By invariant, if l_slice is longer
855                     // then one element must be larger.
856                     // This just validates that this is true
857                     // and reports earlier elements first.
858                     let l_remainder_slice = &l_slice[r_slice.len()..];
859                     let idx = l_remainder_slice
860                         .iter()
861                         .enumerate()
862                         .find_map(|(idx, &r)| if r == 0 { None } else { Some(idx) })
863                         .expect("Invalid VClock Invariant");
864                     Some(idx + r_slice.len())
865                 } else {
866                     None
867                 }
868             })
869             .map(VectorIdx::new)
870     }
871
872     /// Report a data-race found in the program.
873     /// This finds the two racing threads and the type
874     /// of data-race that occurred. This will also
875     /// return info about the memory location the data-race
876     /// occurred in.
877     #[cold]
878     #[inline(never)]
879     fn report_data_race<'tcx>(
880         global: &GlobalState,
881         range: &MemoryCellClocks,
882         action: &str,
883         is_atomic: bool,
884         ptr_dbg: Pointer<AllocId>,
885     ) -> InterpResult<'tcx> {
886         let (current_index, current_clocks) = global.current_thread_state();
887         let write_clock;
888         let (other_action, other_thread, other_clock) = if range.write
889             > current_clocks.clock[range.write_index]
890         {
891             // Convert the write action into the vector clock it
892             // represents for diagnostic purposes.
893             write_clock = VClock::new_with_index(range.write_index, range.write);
894             (range.write_type.get_descriptor(), range.write_index, &write_clock)
895         } else if let Some(idx) = Self::find_gt_index(&range.read, &current_clocks.clock) {
896             ("Read", idx, &range.read)
897         } else if !is_atomic {
898             if let Some(atomic) = range.atomic() {
899                 if let Some(idx) = Self::find_gt_index(&atomic.write_vector, &current_clocks.clock)
900                 {
901                     ("Atomic Store", idx, &atomic.write_vector)
902                 } else if let Some(idx) =
903                     Self::find_gt_index(&atomic.read_vector, &current_clocks.clock)
904                 {
905                     ("Atomic Load", idx, &atomic.read_vector)
906                 } else {
907                     unreachable!(
908                         "Failed to report data-race for non-atomic operation: no race found"
909                     )
910                 }
911             } else {
912                 unreachable!(
913                     "Failed to report data-race for non-atomic operation: no atomic component"
914                 )
915             }
916         } else {
917             unreachable!("Failed to report data-race for atomic operation")
918         };
919
920         // Load elaborated thread information about the racing thread actions.
921         let current_thread_info = global.print_thread_metadata(current_index);
922         let other_thread_info = global.print_thread_metadata(other_thread);
923
924         // Throw the data-race detection.
925         throw_ub_format!(
926             "Data race detected between {} on {} and {} on {} at {:?} (current vector clock = {:?}, conflicting timestamp = {:?})",
927             action,
928             current_thread_info,
929             other_action,
930             other_thread_info,
931             ptr_dbg,
932             current_clocks.clock,
933             other_clock
934         )
935     }
936
937     /// Detect racing atomic read and writes (not data races)
938     /// on every byte of the current access range
939     pub(super) fn race_free_with_atomic(&self, range: AllocRange, global: &GlobalState) -> bool {
940         if global.race_detecting() {
941             let (_, clocks) = global.current_thread_state();
942             let alloc_ranges = self.alloc_ranges.borrow();
943             for (_, range) in alloc_ranges.iter(range.start, range.size) {
944                 if !range.race_free_with_atomic(&clocks) {
945                     return false;
946                 }
947             }
948         }
949         true
950     }
951
952     /// Detect data-races for an unsynchronized read operation, will not perform
953     /// data-race detection if `race_detecting()` is false, either due to no threads
954     /// being created or if it is temporarily disabled during a racy read or write
955     /// operation for which data-race detection is handled separately, for example
956     /// atomic read operations.
957     pub fn read<'tcx>(
958         &self,
959         alloc_id: AllocId,
960         range: AllocRange,
961         global: &GlobalState,
962     ) -> InterpResult<'tcx> {
963         if global.race_detecting() {
964             let (index, clocks) = global.current_thread_state();
965             let mut alloc_ranges = self.alloc_ranges.borrow_mut();
966             for (offset, range) in alloc_ranges.iter_mut(range.start, range.size) {
967                 if let Err(DataRace) = range.read_race_detect(&*clocks, index) {
968                     // Report data-race.
969                     return Self::report_data_race(
970                         global,
971                         range,
972                         "Read",
973                         false,
974                         Pointer::new(alloc_id, offset),
975                     );
976                 }
977             }
978             Ok(())
979         } else {
980             Ok(())
981         }
982     }
983
984     // Shared code for detecting data-races on unique access to a section of memory
985     fn unique_access<'tcx>(
986         &mut self,
987         alloc_id: AllocId,
988         range: AllocRange,
989         write_type: WriteType,
990         global: &mut GlobalState,
991     ) -> InterpResult<'tcx> {
992         if global.race_detecting() {
993             let (index, clocks) = global.current_thread_state();
994             for (offset, range) in self.alloc_ranges.get_mut().iter_mut(range.start, range.size) {
995                 if let Err(DataRace) = range.write_race_detect(&*clocks, index, write_type) {
996                     // Report data-race
997                     return Self::report_data_race(
998                         global,
999                         range,
1000                         write_type.get_descriptor(),
1001                         false,
1002                         Pointer::new(alloc_id, offset),
1003                     );
1004                 }
1005             }
1006             Ok(())
1007         } else {
1008             Ok(())
1009         }
1010     }
1011
1012     /// Detect data-races for an unsynchronized write operation, will not perform
1013     /// data-race threads if `race_detecting()` is false, either due to no threads
1014     /// being created or if it is temporarily disabled during a racy read or write
1015     /// operation
1016     pub fn write<'tcx>(
1017         &mut self,
1018         alloc_id: AllocId,
1019         range: AllocRange,
1020         global: &mut GlobalState,
1021     ) -> InterpResult<'tcx> {
1022         self.unique_access(alloc_id, range, WriteType::Write, global)
1023     }
1024
1025     /// Detect data-races for an unsynchronized deallocate operation, will not perform
1026     /// data-race threads if `race_detecting()` is false, either due to no threads
1027     /// being created or if it is temporarily disabled during a racy read or write
1028     /// operation
1029     pub fn deallocate<'tcx>(
1030         &mut self,
1031         alloc_id: AllocId,
1032         range: AllocRange,
1033         global: &mut GlobalState,
1034     ) -> InterpResult<'tcx> {
1035         self.unique_access(alloc_id, range, WriteType::Deallocate, global)
1036     }
1037 }
1038
1039 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {}
1040 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: MiriEvalContextExt<'mir, 'tcx> {
1041     /// Generic atomic operation implementation
1042     fn validate_atomic_op<A: Debug + Copy>(
1043         &self,
1044         place: &MPlaceTy<'tcx, Tag>,
1045         atomic: A,
1046         description: &str,
1047         mut op: impl FnMut(
1048             &mut MemoryCellClocks,
1049             &mut ThreadClockSet,
1050             VectorIdx,
1051             A,
1052         ) -> Result<(), DataRace>,
1053     ) -> InterpResult<'tcx> {
1054         let this = self.eval_context_ref();
1055         if let Some(data_race) = &this.machine.data_race {
1056             if data_race.race_detecting() {
1057                 let size = place.layout.size;
1058                 let (alloc_id, base_offset, _tag) = this.ptr_get_alloc_id(place.ptr)?;
1059                 // Load and log the atomic operation.
1060                 // Note that atomic loads are possible even from read-only allocations, so `get_alloc_extra_mut` is not an option.
1061                 let alloc_meta = this.get_alloc_extra(alloc_id)?.data_race.as_ref().unwrap();
1062                 log::trace!(
1063                     "Atomic op({}) with ordering {:?} on {:?} (size={})",
1064                     description,
1065                     &atomic,
1066                     place.ptr,
1067                     size.bytes()
1068                 );
1069
1070                 // Perform the atomic operation.
1071                 data_race.maybe_perform_sync_operation(|index, mut clocks| {
1072                     for (offset, range) in
1073                         alloc_meta.alloc_ranges.borrow_mut().iter_mut(base_offset, size)
1074                     {
1075                         if let Err(DataRace) = op(range, &mut *clocks, index, atomic) {
1076                             mem::drop(clocks);
1077                             return VClockAlloc::report_data_race(
1078                                 data_race,
1079                                 range,
1080                                 description,
1081                                 true,
1082                                 Pointer::new(alloc_id, offset),
1083                             )
1084                             .map(|_| true);
1085                         }
1086                     }
1087
1088                     // This conservatively assumes all operations have release semantics
1089                     Ok(true)
1090                 })?;
1091
1092                 // Log changes to atomic memory.
1093                 if log::log_enabled!(log::Level::Trace) {
1094                     for (_offset, range) in alloc_meta.alloc_ranges.borrow().iter(base_offset, size)
1095                     {
1096                         log::trace!(
1097                             "Updated atomic memory({:?}, size={}) to {:#?}",
1098                             place.ptr,
1099                             size.bytes(),
1100                             range.atomic_ops
1101                         );
1102                     }
1103                 }
1104             }
1105         }
1106         Ok(())
1107     }
1108 }
1109
1110 /// Extra metadata associated with a thread.
1111 #[derive(Debug, Clone, Default)]
1112 struct ThreadExtraState {
1113     /// The current vector index in use by the
1114     /// thread currently, this is set to None
1115     /// after the vector index has been re-used
1116     /// and hence the value will never need to be
1117     /// read during data-race reporting.
1118     vector_index: Option<VectorIdx>,
1119
1120     /// The name of the thread, updated for better
1121     /// diagnostics when reporting detected data
1122     /// races.
1123     thread_name: Option<Box<str>>,
1124
1125     /// Thread termination vector clock, this
1126     /// is set on thread termination and is used
1127     /// for joining on threads since the vector_index
1128     /// may be re-used when the join operation occurs.
1129     termination_vector_clock: Option<VClock>,
1130 }
1131
1132 /// Global data-race detection state, contains the currently
1133 /// executing thread as well as the vector-clocks associated
1134 /// with each of the threads.
1135 // FIXME: it is probably better to have one large RefCell, than to have so many small ones.
1136 #[derive(Debug, Clone)]
1137 pub struct GlobalState {
1138     /// Set to true once the first additional
1139     /// thread has launched, due to the dependency
1140     /// between before and after a thread launch.
1141     /// Any data-races must be recorded after this
1142     /// so concurrent execution can ignore recording
1143     /// any data-races.
1144     multi_threaded: Cell<bool>,
1145
1146     /// A flag to mark we are currently performing
1147     /// a data race free action (such as atomic access)
1148     /// to supress the race detector
1149     ongoing_action_data_race_free: Cell<bool>,
1150
1151     /// Mapping of a vector index to a known set of thread
1152     /// clocks, this is not directly mapping from a thread id
1153     /// since it may refer to multiple threads.
1154     vector_clocks: RefCell<IndexVec<VectorIdx, ThreadClockSet>>,
1155
1156     /// Mapping of a given vector index to the current thread
1157     /// that the execution is representing, this may change
1158     /// if a vector index is re-assigned to a new thread.
1159     vector_info: RefCell<IndexVec<VectorIdx, ThreadId>>,
1160
1161     /// The mapping of a given thread to associated thread metadata.
1162     thread_info: RefCell<IndexVec<ThreadId, ThreadExtraState>>,
1163
1164     /// The current vector index being executed.
1165     current_index: Cell<VectorIdx>,
1166
1167     /// Potential vector indices that could be re-used on thread creation
1168     /// values are inserted here on after the thread has terminated and
1169     /// been joined with, and hence may potentially become free
1170     /// for use as the index for a new thread.
1171     /// Elements in this set may still require the vector index to
1172     /// report data-races, and can only be re-used after all
1173     /// active vector-clocks catch up with the threads timestamp.
1174     reuse_candidates: RefCell<FxHashSet<VectorIdx>>,
1175
1176     /// Counts the number of threads that are currently active
1177     /// if the number of active threads reduces to 1 and then
1178     /// a join operation occurs with the remaining main thread
1179     /// then multi-threaded execution may be disabled.
1180     active_thread_count: Cell<usize>,
1181
1182     /// This contains threads that have terminated, but not yet joined
1183     /// and so cannot become re-use candidates until a join operation
1184     /// occurs.
1185     /// The associated vector index will be moved into re-use candidates
1186     /// after the join operation occurs.
1187     terminated_threads: RefCell<FxHashMap<ThreadId, VectorIdx>>,
1188
1189     /// The timestamp of last SC fence performed by each thread
1190     last_sc_fence: RefCell<VClock>,
1191
1192     /// The timestamp of last SC write performed by each thread
1193     last_sc_write: RefCell<VClock>,
1194 }
1195
1196 impl GlobalState {
1197     /// Create a new global state, setup with just thread-id=0
1198     /// advanced to timestamp = 1.
1199     pub fn new() -> Self {
1200         let mut global_state = GlobalState {
1201             multi_threaded: Cell::new(false),
1202             ongoing_action_data_race_free: Cell::new(false),
1203             vector_clocks: RefCell::new(IndexVec::new()),
1204             vector_info: RefCell::new(IndexVec::new()),
1205             thread_info: RefCell::new(IndexVec::new()),
1206             current_index: Cell::new(VectorIdx::new(0)),
1207             active_thread_count: Cell::new(1),
1208             reuse_candidates: RefCell::new(FxHashSet::default()),
1209             terminated_threads: RefCell::new(FxHashMap::default()),
1210             last_sc_fence: RefCell::new(VClock::default()),
1211             last_sc_write: RefCell::new(VClock::default()),
1212         };
1213
1214         // Setup the main-thread since it is not explicitly created:
1215         // uses vector index and thread-id 0, also the rust runtime gives
1216         // the main-thread a name of "main".
1217         let index = global_state.vector_clocks.get_mut().push(ThreadClockSet::default());
1218         global_state.vector_info.get_mut().push(ThreadId::new(0));
1219         global_state.thread_info.get_mut().push(ThreadExtraState {
1220             vector_index: Some(index),
1221             thread_name: Some("main".to_string().into_boxed_str()),
1222             termination_vector_clock: None,
1223         });
1224
1225         global_state
1226     }
1227
1228     // We perform data race detection when there are more than 1 active thread
1229     // and we have not temporarily disabled race detection to perform something
1230     // data race free
1231     fn race_detecting(&self) -> bool {
1232         self.multi_threaded.get() && !self.ongoing_action_data_race_free.get()
1233     }
1234
1235     pub fn ongoing_action_data_race_free(&self) -> bool {
1236         self.ongoing_action_data_race_free.get()
1237     }
1238
1239     // Try to find vector index values that can potentially be re-used
1240     // by a new thread instead of a new vector index being created.
1241     fn find_vector_index_reuse_candidate(&self) -> Option<VectorIdx> {
1242         let mut reuse = self.reuse_candidates.borrow_mut();
1243         let vector_clocks = self.vector_clocks.borrow();
1244         let vector_info = self.vector_info.borrow();
1245         let terminated_threads = self.terminated_threads.borrow();
1246         for &candidate in reuse.iter() {
1247             let target_timestamp = vector_clocks[candidate].clock[candidate];
1248             if vector_clocks.iter_enumerated().all(|(clock_idx, clock)| {
1249                 // The thread happens before the clock, and hence cannot report
1250                 // a data-race with this the candidate index.
1251                 let no_data_race = clock.clock[candidate] >= target_timestamp;
1252
1253                 // The vector represents a thread that has terminated and hence cannot
1254                 // report a data-race with the candidate index.
1255                 let thread_id = vector_info[clock_idx];
1256                 let vector_terminated =
1257                     reuse.contains(&clock_idx) || terminated_threads.contains_key(&thread_id);
1258
1259                 // The vector index cannot report a race with the candidate index
1260                 // and hence allows the candidate index to be re-used.
1261                 no_data_race || vector_terminated
1262             }) {
1263                 // All vector clocks for each vector index are equal to
1264                 // the target timestamp, and the thread is known to have
1265                 // terminated, therefore this vector clock index cannot
1266                 // report any more data-races.
1267                 assert!(reuse.remove(&candidate));
1268                 return Some(candidate);
1269             }
1270         }
1271         None
1272     }
1273
1274     // Hook for thread creation, enabled multi-threaded execution and marks
1275     // the current thread timestamp as happening-before the current thread.
1276     #[inline]
1277     pub fn thread_created(&mut self, thread: ThreadId) {
1278         let current_index = self.current_index();
1279
1280         // Increment the number of active threads.
1281         let active_threads = self.active_thread_count.get();
1282         self.active_thread_count.set(active_threads + 1);
1283
1284         // Enable multi-threaded execution, there are now two threads
1285         // so data-races are now possible.
1286         self.multi_threaded.set(true);
1287
1288         // Load and setup the associated thread metadata
1289         let mut thread_info = self.thread_info.borrow_mut();
1290         thread_info.ensure_contains_elem(thread, Default::default);
1291
1292         // Assign a vector index for the thread, attempting to re-use an old
1293         // vector index that can no longer report any data-races if possible.
1294         let created_index = if let Some(reuse_index) = self.find_vector_index_reuse_candidate() {
1295             // Now re-configure the re-use candidate, increment the clock
1296             // for the new sync use of the vector.
1297             let vector_clocks = self.vector_clocks.get_mut();
1298             vector_clocks[reuse_index].increment_clock(reuse_index);
1299
1300             // Locate the old thread the vector was associated with and update
1301             // it to represent the new thread instead.
1302             let vector_info = self.vector_info.get_mut();
1303             let old_thread = vector_info[reuse_index];
1304             vector_info[reuse_index] = thread;
1305
1306             // Mark the thread the vector index was associated with as no longer
1307             // representing a thread index.
1308             thread_info[old_thread].vector_index = None;
1309
1310             reuse_index
1311         } else {
1312             // No vector re-use candidates available, instead create
1313             // a new vector index.
1314             let vector_info = self.vector_info.get_mut();
1315             vector_info.push(thread)
1316         };
1317
1318         log::trace!("Creating thread = {:?} with vector index = {:?}", thread, created_index);
1319
1320         // Mark the chosen vector index as in use by the thread.
1321         thread_info[thread].vector_index = Some(created_index);
1322
1323         // Create a thread clock set if applicable.
1324         let vector_clocks = self.vector_clocks.get_mut();
1325         if created_index == vector_clocks.next_index() {
1326             vector_clocks.push(ThreadClockSet::default());
1327         }
1328
1329         // Now load the two clocks and configure the initial state.
1330         let (current, created) = vector_clocks.pick2_mut(current_index, created_index);
1331
1332         // Join the created with current, since the current threads
1333         // previous actions happen-before the created thread.
1334         created.join_with(current);
1335
1336         // Advance both threads after the synchronized operation.
1337         // Both operations are considered to have release semantics.
1338         current.increment_clock(current_index);
1339         created.increment_clock(created_index);
1340     }
1341
1342     /// Hook on a thread join to update the implicit happens-before relation
1343     /// between the joined thread and the current thread.
1344     #[inline]
1345     pub fn thread_joined(&mut self, current_thread: ThreadId, join_thread: ThreadId) {
1346         let clocks_vec = self.vector_clocks.get_mut();
1347         let thread_info = self.thread_info.get_mut();
1348
1349         // Load the vector clock of the current thread.
1350         let current_index = thread_info[current_thread]
1351             .vector_index
1352             .expect("Performed thread join on thread with no assigned vector");
1353         let current = &mut clocks_vec[current_index];
1354
1355         // Load the associated vector clock for the terminated thread.
1356         let join_clock = thread_info[join_thread]
1357             .termination_vector_clock
1358             .as_ref()
1359             .expect("Joined with thread but thread has not terminated");
1360
1361         // The join thread happens-before the current thread
1362         // so update the current vector clock.
1363         // Is not a release operation so the clock is not incremented.
1364         current.clock.join(join_clock);
1365
1366         // Check the number of active threads, if the value is 1
1367         // then test for potentially disabling multi-threaded execution.
1368         let active_threads = self.active_thread_count.get();
1369         if active_threads == 1 {
1370             // May potentially be able to disable multi-threaded execution.
1371             let current_clock = &clocks_vec[current_index];
1372             if clocks_vec
1373                 .iter_enumerated()
1374                 .all(|(idx, clocks)| clocks.clock[idx] <= current_clock.clock[idx])
1375             {
1376                 // All thread terminations happen-before the current clock
1377                 // therefore no data-races can be reported until a new thread
1378                 // is created, so disable multi-threaded execution.
1379                 self.multi_threaded.set(false);
1380             }
1381         }
1382
1383         // If the thread is marked as terminated but not joined
1384         // then move the thread to the re-use set.
1385         let termination = self.terminated_threads.get_mut();
1386         if let Some(index) = termination.remove(&join_thread) {
1387             let reuse = self.reuse_candidates.get_mut();
1388             reuse.insert(index);
1389         }
1390     }
1391
1392     /// On thread termination, the vector-clock may re-used
1393     /// in the future once all remaining thread-clocks catch
1394     /// up with the time index of the terminated thread.
1395     /// This assigns thread termination with a unique index
1396     /// which will be used to join the thread
1397     /// This should be called strictly before any calls to
1398     /// `thread_joined`.
1399     #[inline]
1400     pub fn thread_terminated(&mut self) {
1401         let current_index = self.current_index();
1402
1403         // Increment the clock to a unique termination timestamp.
1404         let vector_clocks = self.vector_clocks.get_mut();
1405         let current_clocks = &mut vector_clocks[current_index];
1406         current_clocks.increment_clock(current_index);
1407
1408         // Load the current thread id for the executing vector.
1409         let vector_info = self.vector_info.get_mut();
1410         let current_thread = vector_info[current_index];
1411
1412         // Load the current thread metadata, and move to a terminated
1413         // vector state. Setting up the vector clock all join operations
1414         // will use.
1415         let thread_info = self.thread_info.get_mut();
1416         let current = &mut thread_info[current_thread];
1417         current.termination_vector_clock = Some(current_clocks.clock.clone());
1418
1419         // Add this thread as a candidate for re-use after a thread join
1420         // occurs.
1421         let termination = self.terminated_threads.get_mut();
1422         termination.insert(current_thread, current_index);
1423
1424         // Reduce the number of active threads, now that a thread has
1425         // terminated.
1426         let mut active_threads = self.active_thread_count.get();
1427         active_threads -= 1;
1428         self.active_thread_count.set(active_threads);
1429     }
1430
1431     /// Hook for updating the local tracker of the currently
1432     /// enabled thread, should always be updated whenever
1433     /// `active_thread` in thread.rs is updated.
1434     #[inline]
1435     pub fn thread_set_active(&self, thread: ThreadId) {
1436         let thread_info = self.thread_info.borrow();
1437         let vector_idx = thread_info[thread]
1438             .vector_index
1439             .expect("Setting thread active with no assigned vector");
1440         self.current_index.set(vector_idx);
1441     }
1442
1443     /// Hook for updating the local tracker of the threads name
1444     /// this should always mirror the local value in thread.rs
1445     /// the thread name is used for improved diagnostics
1446     /// during a data-race.
1447     #[inline]
1448     pub fn thread_set_name(&mut self, thread: ThreadId, name: String) {
1449         let name = name.into_boxed_str();
1450         let thread_info = self.thread_info.get_mut();
1451         thread_info[thread].thread_name = Some(name);
1452     }
1453
1454     /// Attempt to perform a synchronized operation, this
1455     /// will perform no operation if multi-threading is
1456     /// not currently enabled.
1457     /// Otherwise it will increment the clock for the current
1458     /// vector before and after the operation for data-race
1459     /// detection between any happens-before edges the
1460     /// operation may create.
1461     fn maybe_perform_sync_operation<'tcx>(
1462         &self,
1463         op: impl FnOnce(VectorIdx, RefMut<'_, ThreadClockSet>) -> InterpResult<'tcx, bool>,
1464     ) -> InterpResult<'tcx> {
1465         if self.multi_threaded.get() {
1466             let (index, clocks) = self.current_thread_state_mut();
1467             if op(index, clocks)? {
1468                 let (_, mut clocks) = self.current_thread_state_mut();
1469                 clocks.increment_clock(index);
1470             }
1471         }
1472         Ok(())
1473     }
1474
1475     /// Internal utility to identify a thread stored internally
1476     /// returns the id and the name for better diagnostics.
1477     fn print_thread_metadata(&self, vector: VectorIdx) -> String {
1478         let thread = self.vector_info.borrow()[vector];
1479         let thread_name = &self.thread_info.borrow()[thread].thread_name;
1480         if let Some(name) = thread_name {
1481             let name: &str = name;
1482             format!("Thread(id = {:?}, name = {:?})", thread.to_u32(), name)
1483         } else {
1484             format!("Thread(id = {:?})", thread.to_u32())
1485         }
1486     }
1487
1488     /// Acquire a lock, express that the previous call of
1489     /// `validate_lock_release` must happen before this.
1490     /// As this is an acquire operation, the thread timestamp is not
1491     /// incremented.
1492     pub fn validate_lock_acquire(&self, lock: &VClock, thread: ThreadId) {
1493         let (_, mut clocks) = self.load_thread_state_mut(thread);
1494         clocks.clock.join(lock);
1495     }
1496
1497     /// Release a lock handle, express that this happens-before
1498     /// any subsequent calls to `validate_lock_acquire`.
1499     /// For normal locks this should be equivalent to `validate_lock_release_shared`
1500     /// since an acquire operation should have occurred before, however
1501     /// for futex & condvar operations this is not the case and this
1502     /// operation must be used.
1503     pub fn validate_lock_release(&self, lock: &mut VClock, thread: ThreadId) {
1504         let (index, mut clocks) = self.load_thread_state_mut(thread);
1505         lock.clone_from(&clocks.clock);
1506         clocks.increment_clock(index);
1507     }
1508
1509     /// Release a lock handle, express that this happens-before
1510     /// any subsequent calls to `validate_lock_acquire` as well
1511     /// as any previous calls to this function after any
1512     /// `validate_lock_release` calls.
1513     /// For normal locks this should be equivalent to `validate_lock_release`.
1514     /// This function only exists for joining over the set of concurrent readers
1515     /// in a read-write lock and should not be used for anything else.
1516     pub fn validate_lock_release_shared(&self, lock: &mut VClock, thread: ThreadId) {
1517         let (index, mut clocks) = self.load_thread_state_mut(thread);
1518         lock.join(&clocks.clock);
1519         clocks.increment_clock(index);
1520     }
1521
1522     /// Load the vector index used by the given thread as well as the set of vector clocks
1523     /// used by the thread.
1524     #[inline]
1525     fn load_thread_state_mut(&self, thread: ThreadId) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1526         let index = self.thread_info.borrow()[thread]
1527             .vector_index
1528             .expect("Loading thread state for thread with no assigned vector");
1529         let ref_vector = self.vector_clocks.borrow_mut();
1530         let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1531         (index, clocks)
1532     }
1533
1534     /// Load the current vector clock in use and the current set of thread clocks
1535     /// in use for the vector.
1536     #[inline]
1537     pub(super) fn current_thread_state(&self) -> (VectorIdx, Ref<'_, ThreadClockSet>) {
1538         let index = self.current_index();
1539         let ref_vector = self.vector_clocks.borrow();
1540         let clocks = Ref::map(ref_vector, |vec| &vec[index]);
1541         (index, clocks)
1542     }
1543
1544     /// Load the current vector clock in use and the current set of thread clocks
1545     /// in use for the vector mutably for modification.
1546     #[inline]
1547     pub(super) fn current_thread_state_mut(&self) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1548         let index = self.current_index();
1549         let ref_vector = self.vector_clocks.borrow_mut();
1550         let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1551         (index, clocks)
1552     }
1553
1554     /// Return the current thread, should be the same
1555     /// as the data-race active thread.
1556     #[inline]
1557     fn current_index(&self) -> VectorIdx {
1558         self.current_index.get()
1559     }
1560
1561     // SC ATOMIC STORE rule in the paper.
1562     pub(super) fn sc_write(&self) {
1563         let (index, clocks) = self.current_thread_state();
1564         self.last_sc_write.borrow_mut().set_at_index(&clocks.clock, index);
1565     }
1566
1567     // SC ATOMIC READ rule in the paper.
1568     pub(super) fn sc_read(&self) {
1569         let (.., mut clocks) = self.current_thread_state_mut();
1570         clocks.read_seqcst.join(&self.last_sc_fence.borrow());
1571     }
1572 }