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