]> git.lizzy.rs Git - rust.git/blob - src/data_race.rs
Fix nits
[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         let l_slice = l.as_slice();
699         let r_slice = r.as_slice();
700         l_slice
701             .iter()
702             .zip(r_slice.iter())
703             .enumerate()
704             .find_map(|(idx, (&l, &r))| if l > r { Some(idx) } else { None })
705             .or_else(|| {
706                 if l_slice.len() > r_slice.len() {
707                     // By invariant, if l_slice is longer
708                     // then one element must be larger.
709                     // This just validates that this is true
710                     // and reports earlier elements first.
711                     let l_remainder_slice = &l_slice[r_slice.len()..];
712                     let idx = l_remainder_slice
713                         .iter()
714                         .enumerate()
715                         .find_map(|(idx, &r)| if r == 0 { None } else { Some(idx) })
716                         .expect("Invalid VClock Invariant");
717                     Some(idx)
718                 } else {
719                     None
720                 }
721             })
722             .map(|idx| VectorIdx::new(idx))
723     }
724
725     /// Report a data-race found in the program.
726     /// This finds the two racing threads and the type
727     /// of data-race that occurred. This will also
728     /// return info about the memory location the data-race
729     /// occurred in.
730     #[cold]
731     #[inline(never)]
732     fn report_data_race<'tcx>(
733         global: &MemoryExtra,
734         range: &MemoryCellClocks,
735         action: &str,
736         is_atomic: bool,
737         pointer: Pointer<Tag>,
738         len: Size,
739     ) -> InterpResult<'tcx> {
740         let (current_index, current_clocks) = global.current_thread_state();
741         let write_clock;
742         let (other_action, other_thread, other_clock) = if range.write
743             > current_clocks.clock[range.write_index]
744         {
745             // Convert the write action into the vector clock it
746             // represents for diagnostic purposes.
747             write_clock = VClock::new_with_index(range.write_index, range.write);
748             (range.write_type.get_descriptor(), range.write_index, &write_clock)
749         } else if let Some(idx) = Self::find_gt_index(&range.read, &current_clocks.clock) {
750             ("READ", idx, &range.read)
751         } else if !is_atomic {
752             if let Some(atomic) = range.atomic() {
753                 if let Some(idx) = Self::find_gt_index(&atomic.write_vector, &current_clocks.clock)
754                 {
755                     ("ATOMIC_STORE", idx, &atomic.write_vector)
756                 } else if let Some(idx) =
757                     Self::find_gt_index(&atomic.read_vector, &current_clocks.clock)
758                 {
759                     ("ATOMIC_LOAD", idx, &atomic.read_vector)
760                 } else {
761                     unreachable!(
762                         "Failed to report data-race for non-atomic operation: no race found"
763                     )
764                 }
765             } else {
766                 unreachable!(
767                     "Failed to report data-race for non-atomic operation: no atomic component"
768                 )
769             }
770         } else {
771             unreachable!("Failed to report data-race for atomic operation")
772         };
773
774         // Load elaborated thread information about the racing thread actions.
775         let current_thread_info = global.print_thread_metadata(current_index);
776         let other_thread_info = global.print_thread_metadata(other_thread);
777
778         // Throw the data-race detection.
779         throw_ub_format!(
780             "Data race detected between {} on {} and {} on {}, memory({:?},offset={},size={})\
781             \n\t\t -current vector clock = {:?}\
782             \n\t\t -conflicting timestamp = {:?}",
783             action,
784             current_thread_info,
785             other_action,
786             other_thread_info,
787             pointer.alloc_id,
788             pointer.offset.bytes(),
789             len.bytes(),
790             current_clocks.clock,
791             other_clock
792         )
793     }
794
795     /// Detect data-races for an unsynchronized read operation, will not perform
796     /// data-race detection if `multi-threaded` is false, either due to no threads
797     /// being created or if it is temporarily disabled during a racy read or write
798     /// operation for which data-race detection is handled separately, for example
799     /// atomic read operations.
800     pub fn read<'tcx>(&self, pointer: Pointer<Tag>, len: Size) -> InterpResult<'tcx> {
801         if self.global.multi_threaded.get() {
802             let (index, clocks) = self.global.current_thread_state();
803             let mut alloc_ranges = self.alloc_ranges.borrow_mut();
804             for (_, range) in alloc_ranges.iter_mut(pointer.offset, len) {
805                 if let Err(DataRace) = range.read_race_detect(&*clocks, index) {
806                     // Report data-race.
807                     return Self::report_data_race(
808                         &self.global,
809                         range,
810                         "READ",
811                         false,
812                         pointer,
813                         len,
814                     );
815                 }
816             }
817             Ok(())
818         } else {
819             Ok(())
820         }
821     }
822
823     // Shared code for detecting data-races on unique access to a section of memory
824     fn unique_access<'tcx>(
825         &mut self,
826         pointer: Pointer<Tag>,
827         len: Size,
828         write_type: WriteType,
829     ) -> InterpResult<'tcx> {
830         if self.global.multi_threaded.get() {
831             let (index, clocks) = self.global.current_thread_state();
832             for (_, range) in self.alloc_ranges.get_mut().iter_mut(pointer.offset, len) {
833                 if let Err(DataRace) = range.write_race_detect(&*clocks, index, write_type) {
834                     // Report data-race
835                     return Self::report_data_race(
836                         &self.global,
837                         range,
838                         write_type.get_descriptor(),
839                         false,
840                         pointer,
841                         len,
842                     );
843                 }
844             }
845             Ok(())
846         } else {
847             Ok(())
848         }
849     }
850
851     /// Detect data-races for an unsynchronized write operation, will not perform
852     /// data-race threads if `multi-threaded` is false, either due to no threads
853     /// being created or if it is temporarily disabled during a racy read or write
854     /// operation
855     pub fn write<'tcx>(&mut self, pointer: Pointer<Tag>, len: Size) -> InterpResult<'tcx> {
856         self.unique_access(pointer, len, WriteType::Write)
857     }
858
859     /// Detect data-races for an unsynchronized deallocate operation, will not perform
860     /// data-race threads if `multi-threaded` is false, either due to no threads
861     /// being created or if it is temporarily disabled during a racy read or write
862     /// operation
863     pub fn deallocate<'tcx>(&mut self, pointer: Pointer<Tag>, len: Size) -> InterpResult<'tcx> {
864         self.unique_access(pointer, len, WriteType::Deallocate)
865     }
866 }
867
868 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {}
869 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: MiriEvalContextExt<'mir, 'tcx> {
870     // Temporarily allow data-races to occur, this should only be
871     // used if either one of the appropriate `validate_atomic` functions
872     // will be called to treat a memory access as atomic or if the memory
873     // being accessed should be treated as internal state, that cannot be
874     // accessed by the interpreted program.
875     #[inline]
876     fn allow_data_races_ref<R>(&self, op: impl FnOnce(&MiriEvalContext<'mir, 'tcx>) -> R) -> R {
877         let this = self.eval_context_ref();
878         let old = if let Some(data_race) = &this.memory.extra.data_race {
879             data_race.multi_threaded.replace(false)
880         } else {
881             false
882         };
883         let result = op(this);
884         if let Some(data_race) = &this.memory.extra.data_race {
885             data_race.multi_threaded.set(old);
886         }
887         result
888     }
889
890     /// Same as `allow_data_races_ref`, this temporarily disables any data-race detection and
891     /// so should only be used for atomic operations or internal state that the program cannot
892     /// access.
893     #[inline]
894     fn allow_data_races_mut<R>(
895         &mut self,
896         op: impl FnOnce(&mut MiriEvalContext<'mir, 'tcx>) -> R,
897     ) -> R {
898         let this = self.eval_context_mut();
899         let old = if let Some(data_race) = &this.memory.extra.data_race {
900             data_race.multi_threaded.replace(false)
901         } else {
902             false
903         };
904         let result = op(this);
905         if let Some(data_race) = &this.memory.extra.data_race {
906             data_race.multi_threaded.set(old);
907         }
908         result
909     }
910
911     /// Generic atomic operation implementation,
912     /// this accesses memory via get_raw instead of
913     /// get_raw_mut, due to issues calling get_raw_mut
914     /// for atomic loads from read-only memory.
915     /// FIXME: is this valid, or should get_raw_mut be used for
916     /// atomic-stores/atomic-rmw?
917     fn validate_atomic_op<A: Debug + Copy>(
918         &self,
919         place: MPlaceTy<'tcx, Tag>,
920         atomic: A,
921         description: &str,
922         mut op: impl FnMut(
923             &mut MemoryCellClocks,
924             &mut ThreadClockSet,
925             VectorIdx,
926             A,
927         ) -> Result<(), DataRace>,
928     ) -> InterpResult<'tcx> {
929         let this = self.eval_context_ref();
930         if let Some(data_race) = &this.memory.extra.data_race {
931             if data_race.multi_threaded.get() {
932                 // Load and log the atomic operation.
933                 let place_ptr = place.ptr.assert_ptr();
934                 let size = place.layout.size;
935                 let alloc_meta =
936                     &this.memory.get_raw(place_ptr.alloc_id)?.extra.data_race.as_ref().unwrap();
937                 log::trace!(
938                     "Atomic op({}) with ordering {:?} on memory({:?}, offset={}, size={})",
939                     description,
940                     &atomic,
941                     place_ptr.alloc_id,
942                     place_ptr.offset.bytes(),
943                     size.bytes()
944                 );
945
946                 // Perform the atomic operation.
947                 let data_race = &alloc_meta.global;
948                 data_race.maybe_perform_sync_operation(|index, mut clocks| {
949                     for (_, range) in
950                         alloc_meta.alloc_ranges.borrow_mut().iter_mut(place_ptr.offset, size)
951                     {
952                         if let Err(DataRace) = op(range, &mut *clocks, index, atomic) {
953                             mem::drop(clocks);
954                             return VClockAlloc::report_data_race(
955                                 &alloc_meta.global,
956                                 range,
957                                 description,
958                                 true,
959                                 place_ptr,
960                                 size,
961                             ).map(|_| true);
962                         }
963                     }
964
965                     // This conservatively assumes all operations have release semantics
966                     Ok(true)
967                 })?;
968
969                 // Log changes to atomic memory.
970                 if log::log_enabled!(log::Level::Trace) {
971                     for (_, range) in alloc_meta.alloc_ranges.borrow().iter(place_ptr.offset, size)
972                     {
973                         log::trace!(
974                             "Updated atomic memory({:?}, offset={}, size={}) to {:#?}",
975                             place.ptr.assert_ptr().alloc_id,
976                             place_ptr.offset.bytes(),
977                             size.bytes(),
978                             range.atomic_ops
979                         );
980                     }
981                 }
982             }
983         }
984         Ok(())
985     }
986 }
987
988 /// Extra metadata associated with a thread.
989 #[derive(Debug, Clone, Default)]
990 struct ThreadExtraState {
991     /// The current vector index in use by the
992     /// thread currently, this is set to None
993     /// after the vector index has been re-used
994     /// and hence the value will never need to be
995     /// read during data-race reporting.
996     vector_index: Option<VectorIdx>,
997
998     /// The name of the thread, updated for better
999     /// diagnostics when reporting detected data
1000     /// races.
1001     thread_name: Option<Box<str>>,
1002
1003     /// Thread termination vector clock, this
1004     /// is set on thread termination and is used
1005     /// for joining on threads since the vector_index
1006     /// may be re-used when the join operation occurs.
1007     termination_vector_clock: Option<VClock>,
1008 }
1009
1010 /// Global data-race detection state, contains the currently
1011 /// executing thread as well as the vector-clocks associated
1012 /// with each of the threads.
1013 #[derive(Debug, Clone)]
1014 pub struct GlobalState {
1015     /// Set to true once the first additional
1016     /// thread has launched, due to the dependency
1017     /// between before and after a thread launch.
1018     /// Any data-races must be recorded after this
1019     /// so concurrent execution can ignore recording
1020     /// any data-races.
1021     multi_threaded: Cell<bool>,
1022
1023     /// Mapping of a vector index to a known set of thread
1024     /// clocks, this is not directly mapping from a thread id
1025     /// since it may refer to multiple threads.
1026     vector_clocks: RefCell<IndexVec<VectorIdx, ThreadClockSet>>,
1027
1028     /// Mapping of a given vector index to the current thread
1029     /// that the execution is representing, this may change
1030     /// if a vector index is re-assigned to a new thread.
1031     vector_info: RefCell<IndexVec<VectorIdx, ThreadId>>,
1032
1033     /// The mapping of a given thread to associated thread metadata.
1034     thread_info: RefCell<IndexVec<ThreadId, ThreadExtraState>>,
1035
1036     /// The current vector index being executed.
1037     current_index: Cell<VectorIdx>,
1038
1039     /// Potential vector indices that could be re-used on thread creation
1040     /// values are inserted here on after the thread has terminated and
1041     /// been joined with, and hence may potentially become free
1042     /// for use as the index for a new thread.
1043     /// Elements in this set may still require the vector index to
1044     /// report data-races, and can only be re-used after all
1045     /// active vector-clocks catch up with the threads timestamp.
1046     reuse_candidates: RefCell<FxHashSet<VectorIdx>>,
1047
1048     /// Counts the number of threads that are currently active
1049     /// if the number of active threads reduces to 1 and then
1050     /// a join operation occurs with the remaining main thread
1051     /// then multi-threaded execution may be disabled.
1052     active_thread_count: Cell<usize>,
1053
1054     /// This contains threads that have terminated, but not yet joined
1055     /// and so cannot become re-use candidates until a join operation
1056     /// occurs.
1057     /// The associated vector index will be moved into re-use candidates
1058     /// after the join operation occurs.
1059     terminated_threads: RefCell<FxHashMap<ThreadId, VectorIdx>>,
1060 }
1061
1062 impl GlobalState {
1063     /// Create a new global state, setup with just thread-id=0
1064     /// advanced to timestamp = 1.
1065     pub fn new() -> Self {
1066         let global_state = GlobalState {
1067             multi_threaded: Cell::new(false),
1068             vector_clocks: RefCell::new(IndexVec::new()),
1069             vector_info: RefCell::new(IndexVec::new()),
1070             thread_info: RefCell::new(IndexVec::new()),
1071             current_index: Cell::new(VectorIdx::new(0)),
1072             active_thread_count: Cell::new(1),
1073             reuse_candidates: RefCell::new(FxHashSet::default()),
1074             terminated_threads: RefCell::new(FxHashMap::default()),
1075         };
1076
1077         // Setup the main-thread since it is not explicitly created:
1078         // uses vector index and thread-id 0, also the rust runtime gives
1079         // the main-thread a name of "main".
1080         let index = global_state.vector_clocks.borrow_mut().push(ThreadClockSet::default());
1081         global_state.vector_info.borrow_mut().push(ThreadId::new(0));
1082         global_state.thread_info.borrow_mut().push(ThreadExtraState {
1083             vector_index: Some(index),
1084             thread_name: Some("main".to_string().into_boxed_str()),
1085             termination_vector_clock: None,
1086         });
1087
1088         global_state
1089     }
1090
1091     // Try to find vector index values that can potentially be re-used
1092     // by a new thread instead of a new vector index being created.
1093     fn find_vector_index_reuse_candidate(&self) -> Option<VectorIdx> {
1094         let mut reuse = self.reuse_candidates.borrow_mut();
1095         let vector_clocks = self.vector_clocks.borrow();
1096         let vector_info = self.vector_info.borrow();
1097         let terminated_threads = self.terminated_threads.borrow();
1098         for &candidate in reuse.iter() {
1099             let target_timestamp = vector_clocks[candidate].clock[candidate];
1100             if vector_clocks.iter_enumerated().all(|(clock_idx, clock)| {
1101                 // The thread happens before the clock, and hence cannot report
1102                 // a data-race with this the candidate index.
1103                 let no_data_race = clock.clock[candidate] >= target_timestamp;
1104
1105                 // The vector represents a thread that has terminated and hence cannot
1106                 // report a data-race with the candidate index.
1107                 let thread_id = vector_info[clock_idx];
1108                 let vector_terminated =
1109                     reuse.contains(&clock_idx) || terminated_threads.contains_key(&thread_id);
1110
1111                 // The vector index cannot report a race with the candidate index
1112                 // and hence allows the candidate index to be re-used.
1113                 no_data_race || vector_terminated
1114             }) {
1115                 // All vector clocks for each vector index are equal to
1116                 // the target timestamp, and the thread is known to have
1117                 // terminated, therefore this vector clock index cannot
1118                 // report any more data-races.
1119                 assert!(reuse.remove(&candidate));
1120                 return Some(candidate);
1121             }
1122         }
1123         None
1124     }
1125
1126     // Hook for thread creation, enabled multi-threaded execution and marks
1127     // the current thread timestamp as happening-before the current thread.
1128     #[inline]
1129     pub fn thread_created(&self, thread: ThreadId) {
1130         let current_index = self.current_index();
1131
1132         // Increment the number of active threads.
1133         let active_threads = self.active_thread_count.get();
1134         self.active_thread_count.set(active_threads + 1);
1135
1136         // Enable multi-threaded execution, there are now two threads
1137         // so data-races are now possible.
1138         self.multi_threaded.set(true);
1139
1140         // Load and setup the associated thread metadata
1141         let mut thread_info = self.thread_info.borrow_mut();
1142         thread_info.ensure_contains_elem(thread, Default::default);
1143
1144         // Assign a vector index for the thread, attempting to re-use an old
1145         // vector index that can no longer report any data-races if possible.
1146         let created_index = if let Some(reuse_index) = self.find_vector_index_reuse_candidate() {
1147             // Now re-configure the re-use candidate, increment the clock
1148             // for the new sync use of the vector.
1149             let mut vector_clocks = self.vector_clocks.borrow_mut();
1150             vector_clocks[reuse_index].increment_clock(reuse_index);
1151
1152             // Locate the old thread the vector was associated with and update
1153             // it to represent the new thread instead.
1154             let mut vector_info = self.vector_info.borrow_mut();
1155             let old_thread = vector_info[reuse_index];
1156             vector_info[reuse_index] = thread;
1157
1158             // Mark the thread the vector index was associated with as no longer
1159             // representing a thread index.
1160             thread_info[old_thread].vector_index = None;
1161
1162             reuse_index
1163         } else {
1164             // No vector re-use candidates available, instead create
1165             // a new vector index.
1166             let mut vector_info = self.vector_info.borrow_mut();
1167             vector_info.push(thread)
1168         };
1169
1170         // Mark the chosen vector index as in use by the thread.
1171         thread_info[thread].vector_index = Some(created_index);
1172
1173         // Create a thread clock set if applicable.
1174         let mut vector_clocks = self.vector_clocks.borrow_mut();
1175         if created_index == vector_clocks.next_index() {
1176             vector_clocks.push(ThreadClockSet::default());
1177         }
1178
1179         // Now load the two clocks and configure the initial state.
1180         let (current, created) = vector_clocks.pick2_mut(current_index, created_index);
1181
1182         // Join the created with current, since the current threads
1183         // previous actions happen-before the created thread.
1184         created.join_with(current);
1185
1186         // Advance both threads after the synchronized operation.
1187         // Both operations are considered to have release semantics.
1188         current.increment_clock(current_index);
1189         created.increment_clock(created_index);
1190     }
1191
1192     /// Hook on a thread join to update the implicit happens-before relation
1193     /// between the joined thread and the current thread.
1194     #[inline]
1195     pub fn thread_joined(&self, current_thread: ThreadId, join_thread: ThreadId) {
1196         let mut clocks_vec = self.vector_clocks.borrow_mut();
1197         let thread_info = self.thread_info.borrow();
1198
1199         // Load the vector clock of the current thread.
1200         let current_index = thread_info[current_thread]
1201             .vector_index
1202             .expect("Performed thread join on thread with no assigned vector");
1203         let current = &mut clocks_vec[current_index];
1204
1205         // Load the associated vector clock for the terminated thread.
1206         let join_clock = thread_info[join_thread]
1207             .termination_vector_clock
1208             .as_ref()
1209             .expect("Joined with thread but thread has not terminated");
1210
1211
1212         // The join thread happens-before the current thread
1213         // so update the current vector clock.
1214         // Is not a release operation so the clock is not incremented.
1215         current.clock.join(join_clock);
1216
1217         // Check the number of active threads, if the value is 1
1218         // then test for potentially disabling multi-threaded execution.
1219         let active_threads = self.active_thread_count.get();
1220         if active_threads == 1 {
1221             // May potentially be able to disable multi-threaded execution.
1222             let current_clock = &clocks_vec[current_index];
1223             if clocks_vec
1224                 .iter_enumerated()
1225                 .all(|(idx, clocks)| clocks.clock[idx] <= current_clock.clock[idx])
1226             {
1227                 // All thread terminations happen-before the current clock
1228                 // therefore no data-races can be reported until a new thread
1229                 // is created, so disable multi-threaded execution.
1230                 self.multi_threaded.set(false);
1231             }
1232         }
1233
1234         // If the thread is marked as terminated but not joined
1235         // then move the thread to the re-use set.
1236         let mut termination = self.terminated_threads.borrow_mut();
1237         if let Some(index) = termination.remove(&join_thread) {
1238             let mut reuse = self.reuse_candidates.borrow_mut();
1239             reuse.insert(index);
1240         }
1241     }
1242
1243     /// On thread termination, the vector-clock may re-used
1244     /// in the future once all remaining thread-clocks catch
1245     /// up with the time index of the terminated thread.
1246     /// This assigns thread termination with a unique index
1247     /// which will be used to join the thread
1248     /// This should be called strictly before any calls to
1249     /// `thread_joined`.
1250     #[inline]
1251     pub fn thread_terminated(&self) {
1252         let current_index = self.current_index();
1253
1254         // Increment the clock to a unique termination timestamp.
1255         let mut vector_clocks = self.vector_clocks.borrow_mut();
1256         let current_clocks = &mut vector_clocks[current_index];
1257         current_clocks.increment_clock(current_index);
1258
1259         // Load the current thread id for the executing vector.
1260         let vector_info = self.vector_info.borrow();
1261         let current_thread = vector_info[current_index];
1262
1263         // Load the current thread metadata, and move to a terminated
1264         // vector state. Setting up the vector clock all join operations
1265         // will use.
1266         let mut thread_info = self.thread_info.borrow_mut();
1267         let current = &mut thread_info[current_thread];
1268         current.termination_vector_clock = Some(current_clocks.clock.clone());
1269
1270         // Add this thread as a candidate for re-use after a thread join
1271         // occurs.
1272         let mut termination = self.terminated_threads.borrow_mut();
1273         termination.insert(current_thread, current_index);
1274
1275         // Reduce the number of active threads, now that a thread has
1276         // terminated.
1277         let mut active_threads = self.active_thread_count.get();
1278         active_threads -= 1;
1279         self.active_thread_count.set(active_threads);
1280     }
1281
1282     /// Hook for updating the local tracker of the currently
1283     /// enabled thread, should always be updated whenever
1284     /// `active_thread` in thread.rs is updated.
1285     #[inline]
1286     pub fn thread_set_active(&self, thread: ThreadId) {
1287         let thread_info = self.thread_info.borrow();
1288         let vector_idx = thread_info[thread]
1289             .vector_index
1290             .expect("Setting thread active with no assigned vector");
1291         self.current_index.set(vector_idx);
1292     }
1293
1294     /// Hook for updating the local tracker of the threads name
1295     /// this should always mirror the local value in thread.rs
1296     /// the thread name is used for improved diagnostics
1297     /// during a data-race.
1298     #[inline]
1299     pub fn thread_set_name(&self, thread: ThreadId, name: String) {
1300         let name = name.into_boxed_str();
1301         let mut thread_info = self.thread_info.borrow_mut();
1302         thread_info[thread].thread_name = Some(name);
1303     }
1304
1305     /// Attempt to perform a synchronized operation, this
1306     /// will perform no operation if multi-threading is
1307     /// not currently enabled.
1308     /// Otherwise it will increment the clock for the current
1309     /// vector before and after the operation for data-race
1310     /// detection between any happens-before edges the
1311     /// operation may create.
1312     fn maybe_perform_sync_operation<'tcx>(
1313         &self,
1314         op: impl FnOnce(VectorIdx, RefMut<'_, ThreadClockSet>) -> InterpResult<'tcx, bool>,
1315     ) -> InterpResult<'tcx> {
1316         if self.multi_threaded.get() {
1317             let (index, clocks) = self.current_thread_state_mut();
1318             if op(index, clocks)? {
1319                 let (_, mut clocks) = self.current_thread_state_mut();
1320                 clocks.increment_clock(index);
1321             }
1322         }
1323         Ok(())
1324     }
1325
1326     /// Internal utility to identify a thread stored internally
1327     /// returns the id and the name for better diagnostics.
1328     fn print_thread_metadata(&self, vector: VectorIdx) -> String {
1329         let thread = self.vector_info.borrow()[vector];
1330         let thread_name = &self.thread_info.borrow()[thread].thread_name;
1331         if let Some(name) = thread_name {
1332             let name: &str = name;
1333             format!("Thread(id = {:?}, name = {:?})", thread.to_u32(), &*name)
1334         } else {
1335             format!("Thread(id = {:?})", thread.to_u32())
1336         }
1337     }
1338
1339     /// Acquire a lock, express that the previous call of
1340     /// `validate_lock_release` must happen before this.
1341     /// As this is an acquire operation, the thread timestamp is not
1342     /// incremented.
1343     pub fn validate_lock_acquire(&self, lock: &VClock, thread: ThreadId) {
1344         let (_, mut clocks) = self.load_thread_state_mut(thread);
1345         clocks.clock.join(&lock);
1346     }
1347
1348     /// Release a lock handle, express that this happens-before
1349     /// any subsequent calls to `validate_lock_acquire`.
1350     /// For normal locks this should be equivalent to `validate_lock_release_shared`
1351     /// since an acquire operation should have occurred before, however
1352     /// for futex & condvar operations this is not the case and this
1353     /// operation must be used.
1354     pub fn validate_lock_release(&self, lock: &mut VClock, thread: ThreadId) {
1355         let (index, mut clocks) = self.load_thread_state_mut(thread);
1356         lock.clone_from(&clocks.clock);
1357         clocks.increment_clock(index);
1358     }
1359
1360     /// Release a lock handle, express that this happens-before
1361     /// any subsequent calls to `validate_lock_acquire` as well
1362     /// as any previous calls to this function after any
1363     /// `validate_lock_release` calls.
1364     /// For normal locks this should be equivalent to `validate_lock_release`.
1365     /// This function only exists for joining over the set of concurrent readers
1366     /// in a read-write lock and should not be used for anything else.
1367     pub fn validate_lock_release_shared(&self, lock: &mut VClock, thread: ThreadId) {
1368         let (index, mut clocks) = self.load_thread_state_mut(thread);
1369         lock.join(&clocks.clock);
1370         clocks.increment_clock(index);
1371     }
1372
1373     /// Load the vector index used by the given thread as well as the set of vector clocks
1374     /// used by the thread.
1375     #[inline]
1376     fn load_thread_state_mut(&self, thread: ThreadId) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1377         let index = self.thread_info.borrow()[thread]
1378             .vector_index
1379             .expect("Loading thread state for thread with no assigned vector");
1380         let ref_vector = self.vector_clocks.borrow_mut();
1381         let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1382         (index, clocks)
1383     }
1384
1385     /// Load the current vector clock in use and the current set of thread clocks
1386     /// in use for the vector.
1387     #[inline]
1388     fn current_thread_state(&self) -> (VectorIdx, Ref<'_, ThreadClockSet>) {
1389         let index = self.current_index();
1390         let ref_vector = self.vector_clocks.borrow();
1391         let clocks = Ref::map(ref_vector, |vec| &vec[index]);
1392         (index, clocks)
1393     }
1394
1395     /// Load the current vector clock in use and the current set of thread clocks
1396     /// in use for the vector mutably for modification.
1397     #[inline]
1398     fn current_thread_state_mut(&self) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1399         let index = self.current_index();
1400         let ref_vector = self.vector_clocks.borrow_mut();
1401         let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1402         (index, clocks)
1403     }
1404
1405     /// Return the current thread, should be the same
1406     /// as the data-race active thread.
1407     #[inline]
1408     fn current_index(&self) -> VectorIdx {
1409         self.current_index.get()
1410     }
1411 }