]> git.lizzy.rs Git - rust.git/blob - src/thread.rs
Many small changes to clean up code.
[rust.git] / src / thread.rs
1 //! Implements threads.
2
3 use std::convert::TryInto;
4 use std::cell::RefCell;
5 use std::convert::TryFrom;
6 use std::num::NonZeroU32;
7
8 use log::trace;
9
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_hir::def_id::DefId;
12 use rustc_index::vec::{Idx, IndexVec};
13 use rustc_middle::{
14     middle::codegen_fn_attrs::CodegenFnAttrFlags,
15     mir,
16     ty::{self, Instance},
17 };
18
19 use crate::*;
20
21 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
22 pub enum SchedulingAction {
23     /// Execute step on the active thread.
24     ExecuteStep,
25     /// Execute destructors of the active thread.
26     ExecuteDtors,
27     /// Stop the program.
28     Stop,
29 }
30
31 /// A thread identifier.
32 #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
33 pub struct ThreadId(usize);
34
35 /// The main thread. When it terminates, the whole application terminates.
36 const MAIN_THREAD: ThreadId = ThreadId(0);
37
38 impl ThreadId {
39     pub fn to_u128(self) -> u128 {
40         self.0.try_into().unwrap()
41     }
42 }
43
44 impl Idx for ThreadId {
45     fn new(idx: usize) -> Self {
46         ThreadId(idx)
47     }
48     fn index(self) -> usize {
49         self.0
50     }
51 }
52
53 impl From<u64> for ThreadId {
54     fn from(id: u64) -> Self {
55         Self(usize::try_from(id).unwrap())
56     }
57 }
58
59 impl From<u32> for ThreadId {
60     fn from(id: u32) -> Self {
61         Self(usize::try_from(id).unwrap())
62     }
63 }
64
65 impl ThreadId {
66     pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
67         Scalar::from_u32(u32::try_from(self.0).unwrap())
68     }
69 }
70
71 /// An identifier of a set of blocked threads. 0 is used to indicate the absence
72 /// of a blockset identifier and, therefore, is not a valid identifier.
73 #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
74 pub struct BlockSetId(NonZeroU32);
75
76 impl From<u32> for BlockSetId {
77     fn from(id: u32) -> Self {
78         Self(NonZeroU32::new(id).expect("0 is not a valid blockset id"))
79     }
80 }
81
82 impl BlockSetId {
83     pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
84         Scalar::from_u32(self.0.get())
85     }
86 }
87
88 /// The state of a thread.
89 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
90 pub enum ThreadState {
91     /// The thread is enabled and can be executed.
92     Enabled,
93     /// The thread tried to join the specified thread and is blocked until that
94     /// thread terminates.
95     BlockedOnJoin(ThreadId),
96     /// The thread is blocked and belongs to the given blockset.
97     Blocked(BlockSetId),
98     /// The thread has terminated its execution (we do not delete terminated
99     /// threads).
100     Terminated,
101 }
102
103 /// The join status of a thread.
104 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
105 enum ThreadJoinStatus {
106     /// The thread can be joined.
107     Joinable,
108     /// A thread is detached if its join handle was destroyed and no other
109     /// thread can join it.
110     Detached,
111     /// The thread was already joined by some thread and cannot be joined again.
112     Joined,
113 }
114
115 /// A thread.
116 pub struct Thread<'mir, 'tcx> {
117     state: ThreadState,
118     /// Name of the thread.
119     thread_name: Option<Vec<u8>>,
120     /// The virtual call stack.
121     stack: Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>>,
122     /// The join status.
123     join_status: ThreadJoinStatus,
124 }
125
126 impl<'mir, 'tcx> Thread<'mir, 'tcx> {
127     /// Check if the thread is done executing (no more stack frames). If yes,
128     /// change the state to terminated and return `true`.
129     fn check_terminated(&mut self) -> bool {
130         if self.state == ThreadState::Enabled {
131             if self.stack.is_empty() {
132                 self.state = ThreadState::Terminated;
133                 return true;
134             }
135         }
136         false
137     }
138 }
139
140 impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
141     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142         if let Some(ref name) = self.thread_name {
143             write!(f, "{}", String::from_utf8_lossy(name))?;
144         } else {
145             write!(f, "<unnamed>")?;
146         }
147         write!(f, "({:?}, {:?})", self.state, self.join_status)
148     }
149 }
150
151 impl<'mir, 'tcx> Default for Thread<'mir, 'tcx> {
152     fn default() -> Self {
153         Self {
154             state: ThreadState::Enabled,
155             thread_name: None,
156             stack: Vec::new(),
157             join_status: ThreadJoinStatus::Joinable,
158         }
159     }
160 }
161
162 /// A set of threads.
163 #[derive(Debug)]
164 pub struct ThreadManager<'mir, 'tcx> {
165     /// Identifier of the currently active thread.
166     active_thread: ThreadId,
167     /// Threads used in the program.
168     ///
169     /// Note that this vector also contains terminated threads.
170     threads: IndexVec<ThreadId, Thread<'mir, 'tcx>>,
171     /// A counter used to generate unique identifiers for blocksets.
172     blockset_counter: u32,
173     /// A mapping from a thread-local static to an allocation id of a thread
174     /// specific allocation.
175     thread_local_alloc_ids: RefCell<FxHashMap<(DefId, ThreadId), AllocId>>,
176     /// A flag that indicates that we should change the active thread.
177     yield_active_thread: bool,
178 }
179
180 impl<'mir, 'tcx> Default for ThreadManager<'mir, 'tcx> {
181     fn default() -> Self {
182         let mut threads = IndexVec::new();
183         // Create the main thread and add it to the list of threads.
184         let mut main_thread = Thread::default();
185         // The main thread can *not* be joined on.
186         main_thread.join_status = ThreadJoinStatus::Detached;
187         threads.push(main_thread);
188         Self {
189             active_thread: ThreadId::new(0),
190             threads: threads,
191             blockset_counter: 0,
192             thread_local_alloc_ids: Default::default(),
193             yield_active_thread: false,
194         }
195     }
196 }
197
198 impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
199     /// Check if we have an allocation for the given thread local static for the
200     /// active thread.
201     fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<AllocId> {
202         self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
203     }
204
205     /// Set the allocation id as the allocation id of the given thread local
206     /// static for the active thread.
207     ///
208     /// Panics if a thread local is initialized twice for the same thread.
209     fn set_thread_local_alloc_id(&self, def_id: DefId, new_alloc_id: AllocId) {
210         self.thread_local_alloc_ids
211             .borrow_mut()
212             .insert((def_id, self.active_thread), new_alloc_id)
213             .unwrap_none();
214     }
215
216     /// Borrow the stack of the active thread.
217     fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
218         &self.threads[self.active_thread].stack
219     }
220
221     /// Mutably borrow the stack of the active thread.
222     fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
223         &mut self.threads[self.active_thread].stack
224     }
225
226     /// Create a new thread and returns its id.
227     fn create_thread(&mut self) -> ThreadId {
228         let new_thread_id = ThreadId::new(self.threads.len());
229         self.threads.push(Default::default());
230         new_thread_id
231     }
232
233     /// Set an active thread and return the id of the thread that was active before.
234     fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
235         let active_thread_id = self.active_thread;
236         self.active_thread = id;
237         assert!(self.active_thread.index() < self.threads.len());
238         active_thread_id
239     }
240
241     /// Get the id of the currently active thread.
242     fn get_active_thread_id(&self) -> ThreadId {
243         self.active_thread
244     }
245
246     /// Get the total number of threads that were ever spawn by this program.
247     fn get_total_thread_count(&self) -> usize {
248         self.threads.len()
249     }
250
251     /// Has the given thread terminated?
252     fn has_terminated(&self, thread_id: ThreadId) -> bool {
253         self.threads[thread_id].state == ThreadState::Terminated
254     }
255
256     /// Enable the thread for execution. The thread must be terminated.
257     fn enable_thread(&mut self, thread_id: ThreadId) {
258         assert!(self.has_terminated(thread_id));
259         self.threads[thread_id].state = ThreadState::Enabled;
260     }
261
262     /// Get a mutable borrow of the currently active thread.
263     fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
264         &mut self.threads[self.active_thread]
265     }
266
267     /// Get a shared borrow of the currently active thread.
268     fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
269         &self.threads[self.active_thread]
270     }
271
272     /// Mark the thread as detached, which means that no other thread will try
273     /// to join it and the thread is responsible for cleaning up.
274     fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
275         if self.threads[id].join_status != ThreadJoinStatus::Joinable {
276             throw_ub_format!("trying to detach thread that was already detached or joined");
277         }
278         self.threads[id].join_status = ThreadJoinStatus::Detached;
279         Ok(())
280     }
281
282     /// Mark that the active thread tries to join the thread with `joined_thread_id`.
283     fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
284         if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
285             throw_ub_format!("trying to join a detached or already joined thread");
286         }
287         if joined_thread_id == self.active_thread {
288             throw_ub_format!("trying to join itself");
289         }
290         assert!(
291             self.threads
292                 .iter()
293                 .all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
294             "a joinable thread already has threads waiting for its termination"
295         );
296         // Mark the joined thread as being joined so that we detect if other
297         // threads try to join it.
298         self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
299         if self.threads[joined_thread_id].state != ThreadState::Terminated {
300             // The joined thread is still running, we need to wait for it.
301             self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
302             trace!(
303                 "{:?} blocked on {:?} when trying to join",
304                 self.active_thread,
305                 joined_thread_id
306             );
307         }
308         Ok(())
309     }
310
311     /// Set the name of the active thread.
312     fn set_thread_name(&mut self, new_thread_name: Vec<u8>) {
313         self.active_thread_mut().thread_name = Some(new_thread_name);
314     }
315
316     /// Get the name of the active thread.
317     fn get_thread_name(&self) -> InterpResult<'tcx, &[u8]> {
318         if let Some(ref thread_name) = self.active_thread_ref().thread_name {
319             Ok(thread_name)
320         } else {
321             throw_ub_format!("thread {:?} has no name set", self.active_thread)
322         }
323     }
324
325     /// Allocate a new blockset id.
326     fn create_blockset(&mut self) -> BlockSetId {
327         self.blockset_counter = self.blockset_counter.checked_add(1).unwrap();
328         self.blockset_counter.into()
329     }
330
331     /// Block the currently active thread and put it into the given blockset.
332     fn block_active_thread(&mut self, set: BlockSetId) {
333         let state = &mut self.active_thread_mut().state;
334         assert_eq!(*state, ThreadState::Enabled);
335         *state = ThreadState::Blocked(set);
336     }
337
338     /// Unblock any one thread from the given blockset if it contains at least
339     /// one. Return the id of the unblocked thread.
340     fn unblock_some_thread(&mut self, set: BlockSetId) -> Option<ThreadId> {
341         for (id, thread) in self.threads.iter_enumerated_mut() {
342             if thread.state == ThreadState::Blocked(set) {
343                 trace!("unblocking {:?} in blockset {:?}", id, set);
344                 thread.state = ThreadState::Enabled;
345                 return Some(id);
346             }
347         }
348         None
349     }
350
351     /// Change the active thread to some enabled thread.
352     fn yield_active_thread(&mut self) {
353         self.yield_active_thread = true;
354     }
355
356     /// Decide which action to take next and on which thread.
357     ///
358     /// The currently implemented scheduling policy is the one that is commonly
359     /// used in stateless model checkers such as Loom: run the active thread as
360     /// long as we can and switch only when we have to (the active thread was
361     /// blocked, terminated, or has explicitly asked to be preempted).
362     fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
363         if self.threads[self.active_thread].check_terminated() {
364             // Check if we need to unblock any threads.
365             for (i, thread) in self.threads.iter_enumerated_mut() {
366                 if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
367                     trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
368                     thread.state = ThreadState::Enabled;
369                 }
370             }
371             return Ok(SchedulingAction::ExecuteDtors);
372         }
373         if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
374             // The main thread terminated; stop the program.
375             if self.threads.iter().any(|thread| thread.state != ThreadState::Terminated) {
376                 // FIXME: This check should be either configurable or just emit
377                 // a warning. For example, it seems normal for a program to
378                 // terminate without waiting for its detached threads to
379                 // terminate. However, this case is not trivial to support
380                 // because we also probably do not want to consider the memory
381                 // owned by these threads as leaked.
382                 throw_unsup_format!("the main thread terminated without waiting for other threads");
383             }
384             return Ok(SchedulingAction::Stop);
385         }
386         if self.threads[self.active_thread].state == ThreadState::Enabled
387             && !self.yield_active_thread
388         {
389             // The currently active thread is still enabled, just continue with it.
390             return Ok(SchedulingAction::ExecuteStep);
391         }
392         // We need to pick a new thread for execution.
393         for (id, thread) in self.threads.iter_enumerated() {
394             if thread.state == ThreadState::Enabled {
395                 if !self.yield_active_thread || id != self.active_thread {
396                     self.active_thread = id;
397                     break;
398                 }
399             }
400         }
401         self.yield_active_thread = false;
402         if self.threads[self.active_thread].state == ThreadState::Enabled {
403             return Ok(SchedulingAction::ExecuteStep);
404         }
405         // We have not found a thread to execute.
406         if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
407             unreachable!();
408         } else {
409             throw_machine_stop!(TerminationInfo::Deadlock);
410         }
411     }
412 }
413
414 // Public interface to thread management.
415 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
416 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
417     /// A workaround for thread-local statics until
418     /// https://github.com/rust-lang/rust/issues/70685 is fixed: change the
419     /// thread-local allocation id with a freshly generated allocation id for
420     /// the currently active thread.
421     fn remap_thread_local_alloc_ids(
422         &self,
423         val: &mut mir::interpret::ConstValue<'tcx>,
424     ) -> InterpResult<'tcx> {
425         let this = self.eval_context_ref();
426         match *val {
427             mir::interpret::ConstValue::Scalar(Scalar::Ptr(ref mut ptr)) => {
428                 let alloc_id = ptr.alloc_id;
429                 let alloc = this.tcx.alloc_map.lock().get(alloc_id);
430                 let tcx = this.tcx;
431                 let is_thread_local = |def_id| {
432                     tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
433                 };
434                 match alloc {
435                     Some(GlobalAlloc::Static(def_id)) if is_thread_local(def_id) => {
436                         ptr.alloc_id = this.get_or_create_thread_local_alloc_id(def_id)?;
437                     }
438                     _ => {}
439                 }
440             }
441             _ => {
442                 // FIXME: Handling only `Scalar` seems to work for now, but at
443                 // least in principle thread-locals could be in any constant, so
444                 // we should also consider other cases. However, once
445                 // https://github.com/rust-lang/rust/issues/70685 gets fixed,
446                 // this code will have to be rewritten anyway.
447             }
448         }
449         Ok(())
450     }
451
452     /// Get a thread-specific allocation id for the given thread-local static.
453     /// If needed, allocate a new one.
454     ///
455     /// FIXME: This method should be replaced as soon as
456     /// https://github.com/rust-lang/rust/issues/70685 gets fixed.
457     fn get_or_create_thread_local_alloc_id(&self, def_id: DefId) -> InterpResult<'tcx, AllocId> {
458         let this = self.eval_context_ref();
459         let tcx = this.tcx;
460         if let Some(new_alloc_id) = this.machine.threads.get_thread_local_alloc_id(def_id) {
461             // We already have a thread-specific allocation id for this
462             // thread-local static.
463             Ok(new_alloc_id)
464         } else {
465             // We need to allocate a thread-specific allocation id for this
466             // thread-local static.
467             //
468             // At first, we invoke the `const_eval_raw` query and extract the
469             // allocation from it. Unfortunately, we have to duplicate the code
470             // from `Memory::get_global_alloc` that does this.
471             //
472             // Then we store the retrieved allocation back into the `alloc_map`
473             // to get a fresh allocation id, which we can use as a
474             // thread-specific allocation id for the thread-local static.
475             if tcx.is_foreign_item(def_id) {
476                 throw_unsup_format!("foreign thread-local statics are not supported");
477             }
478             // Invoke the `const_eval_raw` query.
479             let instance = Instance::mono(tcx.tcx, def_id);
480             let gid = GlobalId { instance, promoted: None };
481             let raw_const =
482                 tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
483                     // no need to report anything, the const_eval call takes care of that
484                     // for statics
485                     assert!(tcx.is_static(def_id));
486                     err
487                 })?;
488             let id = raw_const.alloc_id;
489             // Extract the allocation from the query result.
490             let mut alloc_map = tcx.alloc_map.lock();
491             let allocation = alloc_map.unwrap_memory(id);
492             // Create a new allocation id for the same allocation in this hacky
493             // way. Internally, `alloc_map` deduplicates allocations, but this
494             // is fine because Miri will make a copy before a first mutable
495             // access.
496             let new_alloc_id = alloc_map.create_memory_alloc(allocation);
497             this.machine.threads.set_thread_local_alloc_id(def_id, new_alloc_id);
498             Ok(new_alloc_id)
499         }
500     }
501
502     #[inline]
503     fn create_thread(&mut self) -> InterpResult<'tcx, ThreadId> {
504         let this = self.eval_context_mut();
505         Ok(this.machine.threads.create_thread())
506     }
507
508     #[inline]
509     fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
510         let this = self.eval_context_mut();
511         this.machine.threads.detach_thread(thread_id)
512     }
513
514     #[inline]
515     fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
516         let this = self.eval_context_mut();
517         this.machine.threads.join_thread(joined_thread_id)
518     }
519
520     #[inline]
521     fn set_active_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx, ThreadId> {
522         let this = self.eval_context_mut();
523         Ok(this.machine.threads.set_active_thread_id(thread_id))
524     }
525
526     #[inline]
527     fn get_active_thread(&self) -> InterpResult<'tcx, ThreadId> {
528         let this = self.eval_context_ref();
529         Ok(this.machine.threads.get_active_thread_id())
530     }
531
532     #[inline]
533     fn get_total_thread_count(&self) -> InterpResult<'tcx, usize> {
534         let this = self.eval_context_ref();
535         Ok(this.machine.threads.get_total_thread_count())
536     }
537
538     #[inline]
539     fn has_terminated(&self, thread_id: ThreadId) -> InterpResult<'tcx, bool> {
540         let this = self.eval_context_ref();
541         Ok(this.machine.threads.has_terminated(thread_id))
542     }
543
544     #[inline]
545     fn enable_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
546         let this = self.eval_context_mut();
547         this.machine.threads.enable_thread(thread_id);
548         Ok(())
549     }
550
551     #[inline]
552     fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
553         let this = self.eval_context_ref();
554         this.machine.threads.active_thread_stack()
555     }
556
557     #[inline]
558     fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
559         let this = self.eval_context_mut();
560         this.machine.threads.active_thread_stack_mut()
561     }
562
563     #[inline]
564     fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) -> InterpResult<'tcx, ()> {
565         let this = self.eval_context_mut();
566         Ok(this.machine.threads.set_thread_name(new_thread_name))
567     }
568
569     #[inline]
570     fn get_active_thread_name<'c>(&'c self) -> InterpResult<'tcx, &'c [u8]>
571     where
572         'mir: 'c,
573     {
574         let this = self.eval_context_ref();
575         this.machine.threads.get_thread_name()
576     }
577
578     #[inline]
579     fn create_blockset(&mut self) -> InterpResult<'tcx, BlockSetId> {
580         let this = self.eval_context_mut();
581         Ok(this.machine.threads.create_blockset())
582     }
583
584     #[inline]
585     fn block_active_thread(&mut self, set: BlockSetId) -> InterpResult<'tcx> {
586         let this = self.eval_context_mut();
587         Ok(this.machine.threads.block_active_thread(set))
588     }
589
590     #[inline]
591     fn unblock_some_thread(&mut self, set: BlockSetId) -> InterpResult<'tcx, Option<ThreadId>> {
592         let this = self.eval_context_mut();
593         Ok(this.machine.threads.unblock_some_thread(set))
594     }
595
596     #[inline]
597     fn yield_active_thread(&mut self) -> InterpResult<'tcx> {
598         let this = self.eval_context_mut();
599         this.machine.threads.yield_active_thread();
600         Ok(())
601     }
602
603     /// Decide which action to take next and on which thread.
604     #[inline]
605     fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
606         let this = self.eval_context_mut();
607         this.machine.threads.schedule()
608     }
609 }