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