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