Skip to main content

miri/shims/unix/
thread.rs

1use rustc_abi::ExternAbi;
2
3use crate::concurrency::thread::ThreadLookupError;
4use crate::*;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum ThreadNameResult {
8    Ok,
9    NameTooLong,
10}
11
12impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
13pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
14    fn pthread_create(
15        &mut self,
16        thread: &OpTy<'tcx>,
17        _attr: &OpTy<'tcx>,
18        start_routine: &OpTy<'tcx>,
19        arg: &OpTy<'tcx>,
20    ) -> InterpResult<'tcx, ()> {
21        let this = self.eval_context_mut();
22
23        let thread_info_place = this.deref_pointer_as(thread, this.libc_ty_layout("pthread_t"))?;
24
25        let start_routine = this.read_pointer(start_routine)?;
26
27        let func_arg = this.read_immediate(arg)?;
28
29        this.start_regular_thread(
30            Some(thread_info_place),
31            start_routine,
32            ExternAbi::C { unwind: false },
33            func_arg,
34            this.machine.layouts.unit_ptr_mut,
35        )?;
36
37        interp_ok(())
38    }
39
40    fn pthread_join(
41        &mut self,
42        thread: &OpTy<'tcx>,
43        retval: &OpTy<'tcx>,
44        return_dest: &MPlaceTy<'tcx>,
45    ) -> InterpResult<'tcx> {
46        let this = self.eval_context_mut();
47
48        if !this.ptr_is_null(this.read_pointer(retval)?)? {
49            // FIXME: implement reading the thread function's return place.
50            throw_unsup_format!("Miri supports pthread_join only with retval==NULL");
51        }
52
53        let thread = this.read_scalar(thread)?.to_int(this.libc_ty_layout("pthread_t").size)?;
54        // Joining a terminated thread is valid.
55        let thread = match this.thread_id_try_from(thread) {
56            Ok(id) | Err(ThreadLookupError::Terminated(id)) => id,
57            Err(ThreadLookupError::InvalidId) =>
58                throw_ub_format!("pthread_join: invalid pthread_t handle"),
59        };
60
61        this.join_thread_exclusive(
62            thread,
63            /* success_retval */ Scalar::from_u32(0),
64            return_dest,
65        )
66    }
67
68    fn pthread_detach(&mut self, thread: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
69        let this = self.eval_context_mut();
70
71        let thread = this.read_scalar(thread)?.to_int(this.libc_ty_layout("pthread_t").size)?;
72        // Detaching a terminated thread is valid.
73        let thread = match this.thread_id_try_from(thread) {
74            Ok(id) | Err(ThreadLookupError::Terminated(id)) => id,
75            Err(ThreadLookupError::InvalidId) =>
76                throw_ub_format!("pthread_detach: invalid pthread_t handle"),
77        };
78        this.detach_thread(thread, /*allow_terminated_joined*/ false)?;
79
80        interp_ok(Scalar::from_u32(0))
81    }
82
83    fn pthread_self(&mut self) -> InterpResult<'tcx, Scalar> {
84        let this = self.eval_context_mut();
85
86        let thread_id = this.active_thread();
87        interp_ok(Scalar::from_uint(thread_id.to_u32(), this.libc_ty_layout("pthread_t").size))
88    }
89
90    /// Set the name of the specified thread. If the name including the null terminator
91    /// is longer or equals to `name_max_len`, then if `truncate` is set the truncated name
92    /// is used as the thread name, otherwise [`ThreadNameResult::NameTooLong`] is returned.
93    /// If the specified thread wasn't found, UB is raised.
94    fn pthread_setname_np(
95        &mut self,
96        thread: Scalar,
97        name: Scalar,
98        name_max_len: u64,
99        truncate: bool,
100    ) -> InterpResult<'tcx, ThreadNameResult> {
101        let this = self.eval_context_mut();
102
103        let thread = thread.to_int(this.libc_ty_layout("pthread_t").size)?;
104        let Ok(thread) = this.thread_id_try_from(thread) else {
105            // On Linux this has been observed to segfault. FreeBSD documents an error code
106            // for this condition but it is not clear whether they *guarantee* that error.
107            throw_ub_format!("pthread_setname_np: invalid pthread_t handle");
108        };
109        let name = name.to_pointer(this);
110        let mut name = this.read_c_str(name)?.to_owned();
111
112        // Comparing with `>=` to account for null terminator.
113        if name.len().to_u64() >= name_max_len {
114            if truncate {
115                name.truncate(name_max_len.saturating_sub(1).try_into().unwrap());
116            } else {
117                return interp_ok(ThreadNameResult::NameTooLong);
118            }
119        }
120
121        this.set_thread_name(thread, name);
122
123        interp_ok(ThreadNameResult::Ok)
124    }
125
126    /// Get the name of the specified thread. If the thread name doesn't fit
127    /// the buffer, then if `truncate` is set the truncated name is written out,
128    /// otherwise [`ThreadNameResult::NameTooLong`] is returned. If the specified
129    /// thread wasn't found, UB is raised.
130    fn pthread_getname_np(
131        &mut self,
132        thread: Scalar,
133        name_out: Scalar,
134        len: Scalar,
135        truncate: bool,
136    ) -> InterpResult<'tcx, ThreadNameResult> {
137        let this = self.eval_context_mut();
138
139        let thread = thread.to_int(this.libc_ty_layout("pthread_t").size)?;
140        let Ok(thread) = this.thread_id_try_from(thread) else {
141            // On Linux this has been observed to segfault. FreeBSD documents an error code
142            // for this condition but it is not clear whether they *guarantee* that error.
143            throw_ub_format!("pthread_getname_np: invalid pthread_t handle");
144        };
145        let name_out = name_out.to_pointer(this);
146        let len = len.to_target_usize(this)?;
147
148        // FIXME: we should use the program name if the thread name is not set
149        let name = this.get_thread_name(thread).unwrap_or(b"<unnamed>").to_owned();
150        let name = match truncate {
151            true => &name[..name.len().min(len.try_into().unwrap_or(usize::MAX).saturating_sub(1))],
152            false => &name,
153        };
154
155        let (success, _written) = this.write_c_str(name, name_out, len)?;
156        let res = if success { ThreadNameResult::Ok } else { ThreadNameResult::NameTooLong };
157
158        interp_ok(res)
159    }
160
161    fn sched_yield(&mut self) -> InterpResult<'tcx, ()> {
162        let this = self.eval_context_mut();
163
164        this.yield_active_thread();
165
166        interp_ok(())
167    }
168}