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