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