Skip to main content

miri/shims/unix/
thread.rs

1use rustc_abi::ExternAbi;
2use rustc_target::spec::Os;
3
4use crate::concurrency::thread::ThreadLookupError;
5use crate::*;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum ThreadNameResult {
9    Ok,
10    NameTooLong,
11}
12
13// # pthread_attr_t
14
15struct PthreadAttr {
16    /// `None` represents that the stack size has not been explicitly set.
17    stack_size: Option<u64>,
18}
19
20impl MetaObj for PthreadAttr {}
21
22/// Returns the thread attribute data stored at the address that `attr_ptr` points to.
23fn attr_get_data<'tcx, 'a>(
24    ecx: &'a mut MiriInterpCx<'tcx>,
25    attr_ptr: &OpTy<'tcx>,
26) -> InterpResult<'tcx, &'a mut PthreadAttr>
27where
28    'tcx: 'a,
29{
30    let attr = ecx.deref_pointer(attr_ptr)?;
31    ecx.get_or_insert_meta(&attr, |_ecx| {
32        throw_ub_format!("`pthread_attr_t` has not been initialized or has been tampered with")
33    })
34}
35
36impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
37pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
38    fn pthread_attr_init(
39        &mut self,
40        attr_op: &OpTy<'tcx>,
41        dest: &MPlaceTy<'tcx>,
42    ) -> InterpResult<'tcx> {
43        let ecx = self.eval_context_mut();
44        let attr = ecx.deref_pointer(attr_op)?;
45        ecx.insert_meta(&attr, Box::new(PthreadAttr { stack_size: None }))?;
46        ecx.write_int(0, dest)
47    }
48
49    fn pthread_attr_destroy(
50        &mut self,
51        attr_op: &OpTy<'tcx>,
52        dest: &MPlaceTy<'tcx>,
53    ) -> InterpResult<'tcx> {
54        let ecx = self.eval_context_mut();
55        let attr = ecx.deref_pointer(attr_op)?;
56        ecx.remove_meta::<PthreadAttr>(&attr)?.ok_or_else(|| {
57            err_ub_format!("`pthread_attr_t` has not been initialized or has been tampered with")
58        })?;
59        ecx.write_int(0, dest)
60    }
61
62    fn pthread_attr_setstacksize(
63        &mut self,
64        attr_op: &OpTy<'tcx>,
65        stack_size_op: &OpTy<'tcx>,
66        dest: &MPlaceTy<'tcx>,
67    ) -> InterpResult<'tcx> {
68        let ecx = self.eval_context_mut();
69        let stack_size = ecx.read_target_usize(stack_size_op)?;
70
71        // Check the attribute object even if the size is invalid.
72        attr_get_data(ecx, attr_op)?;
73
74        // Check that the size is valid.
75        let os = &ecx.tcx.sess.target.os;
76        // NetBSD has no `PTHREAD_STACK_MIN` constant.
77        if *os != Os::NetBsd
78            && stack_size < ecx.eval_libc("PTHREAD_STACK_MIN").to_target_usize(ecx)?
79        {
80            return ecx.write_scalar(ecx.eval_libc("EINVAL"), dest);
81        }
82        // macOS additionally requires the size to be a multiple of the page size.
83        if *os == Os::MacOs && !stack_size.is_multiple_of(ecx.machine.page_size) {
84            return ecx.write_scalar(ecx.eval_libc("EINVAL"), dest);
85        }
86
87        // Update size in `attr`.
88        attr_get_data(ecx, attr_op)?.stack_size = Some(stack_size);
89        ecx.write_scalar(Scalar::from_i32(0), dest)
90    }
91
92    fn pthread_create(
93        &mut self,
94        thread_id: &OpTy<'tcx>,
95        attr: &OpTy<'tcx>,
96        start_routine: &OpTy<'tcx>,
97        arg: &OpTy<'tcx>,
98        dest: &MPlaceTy<'tcx>,
99    ) -> InterpResult<'tcx> {
100        let ecx = self.eval_context_mut();
101
102        let thread_id_place = ecx.deref_pointer(thread_id)?;
103
104        let start_routine = ecx.read_pointer(start_routine)?;
105
106        let func_arg = ecx.read_immediate(arg)?;
107
108        // A null `attr` means default attributes.
109        let stack_size = if ecx.ptr_is_null(ecx.read_pointer(attr)?)? {
110            None
111        } else {
112            attr_get_data(ecx, attr)?.stack_size
113        };
114        if let Some(stack_size) = stack_size
115            && !ecx.thread_stack_size_ok(stack_size)
116        {
117            // There are not enough resources for such a big stack.
118            return ecx.write_scalar(ecx.eval_libc("EAGAIN"), dest);
119        }
120
121        let thread_id = ecx.start_regular_thread(
122            start_routine,
123            ExternAbi::C { unwind: false },
124            func_arg,
125            ecx.machine.layouts.unit_ptr_mut,
126        )?;
127        ecx.write_int(thread_id.to_u32(), &thread_id_place)?; // pthread_t is just the Miri ThreadId
128        ecx.write_scalar(Scalar::from_i32(0), dest)
129    }
130
131    fn pthread_join(
132        &mut self,
133        thread: &OpTy<'tcx>,
134        retval: &OpTy<'tcx>,
135        return_dest: &MPlaceTy<'tcx>,
136    ) -> InterpResult<'tcx> {
137        let ecx = self.eval_context_mut();
138
139        if !ecx.ptr_is_null(ecx.read_pointer(retval)?)? {
140            // FIXME: implement reading the thread function's return place.
141            throw_unsup_format!("Miri supports pthread_join only with retval==NULL");
142        }
143
144        let thread = ecx.read_int::<i128>(thread)?;
145        // Joining a terminated thread is valid.
146        let thread = match ecx.thread_id_try_from(thread) {
147            Ok(id) | Err(ThreadLookupError::Terminated(id)) => id,
148            Err(ThreadLookupError::InvalidId) =>
149                throw_ub_format!("pthread_join: invalid pthread_t handle"),
150        };
151
152        ecx.join_thread_exclusive(
153            thread,
154            /* success_retval */ Scalar::from_u32(0),
155            return_dest,
156        )
157    }
158
159    fn pthread_detach(&mut self, thread: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
160        let ecx = self.eval_context_mut();
161
162        let thread = ecx.read_int::<i128>(thread)?;
163        // Detaching a terminated thread is valid.
164        let thread = match ecx.thread_id_try_from(thread) {
165            Ok(id) | Err(ThreadLookupError::Terminated(id)) => id,
166            Err(ThreadLookupError::InvalidId) =>
167                throw_ub_format!("pthread_detach: invalid pthread_t handle"),
168        };
169        ecx.detach_thread(thread, /*allow_terminated_joined*/ false)?;
170
171        interp_ok(Scalar::from_u32(0))
172    }
173
174    fn pthread_self(&mut self, dest: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
175        let ecx = self.eval_context_mut();
176
177        let thread_id = ecx.active_thread();
178        ecx.write_int(thread_id.to_u32(), dest) // pthread_t is just the Miri ThreadId
179    }
180
181    /// Set the name of the specified thread. `None` indicates the current thread.
182    /// If the name including the null terminator
183    /// is longer or equals to `name_max_len`, then if `truncate` is set the truncated name
184    /// is used as the thread name, otherwise [`ThreadNameResult::NameTooLong`] is returned.
185    /// If the specified thread wasn't found, UB is raised.
186    fn pthread_setname_np(
187        &mut self,
188        thread: Option<&OpTy<'tcx>>,
189        name: Pointer,
190        name_max_len: u64,
191        truncate: bool,
192    ) -> InterpResult<'tcx, ThreadNameResult> {
193        let ecx = self.eval_context_mut();
194
195        let thread = match thread {
196            None => ecx.active_thread(),
197            Some(thread) => {
198                let thread = ecx.read_int::<i128>(thread)?;
199                let Ok(thread) = ecx.thread_id_try_from(thread) else {
200                    // On Linux this has been observed to segfault. FreeBSD documents an error code
201                    // for this condition but it is not clear whether they *guarantee* that error.
202                    throw_ub_format!("pthread_setname_np: invalid pthread_t handle");
203                };
204                thread
205            }
206        };
207        let mut name = ecx.read_c_str(name)?.to_owned();
208
209        // Comparing with `>=` to account for null terminator.
210        if name.len().to_u64() >= name_max_len {
211            if truncate {
212                name.truncate(name_max_len.saturating_sub(1).try_into().unwrap());
213            } else {
214                return interp_ok(ThreadNameResult::NameTooLong);
215            }
216        }
217
218        ecx.set_thread_name(thread, name);
219
220        interp_ok(ThreadNameResult::Ok)
221    }
222
223    /// Get the name of the specified thread. If the thread name doesn't fit
224    /// the buffer, then if `truncate` is set the truncated name is written out,
225    /// otherwise [`ThreadNameResult::NameTooLong`] is returned. If the specified
226    /// thread wasn't found, UB is raised.
227    fn pthread_getname_np(
228        &mut self,
229        thread: Option<&OpTy<'tcx>>,
230        name_out: Pointer,
231        len: Scalar,
232        truncate: bool,
233    ) -> InterpResult<'tcx, ThreadNameResult> {
234        let ecx = self.eval_context_mut();
235
236        let thread = match thread {
237            None => ecx.active_thread(),
238            Some(thread) => {
239                let thread = ecx.read_int::<i128>(thread)?;
240                let Ok(thread) = ecx.thread_id_try_from(thread) else {
241                    // On Linux this has been observed to segfault. FreeBSD documents an error code
242                    // for this condition but it is not clear whether they *guarantee* that error.
243                    throw_ub_format!("pthread_getname_np: invalid pthread_t handle");
244                };
245                thread
246            }
247        };
248        let len = len.to_target_usize(ecx)?;
249
250        // FIXME: we should use the program name if the thread name is not set
251        let name = ecx.get_thread_name(thread).unwrap_or(b"<unnamed>").to_owned();
252        let name = match truncate {
253            true => &name[..name.len().min(len.try_into().unwrap_or(usize::MAX).saturating_sub(1))],
254            false => &name,
255        };
256
257        let (success, _written) = ecx.write_c_str(name, name_out, len)?;
258        let res = if success { ThreadNameResult::Ok } else { ThreadNameResult::NameTooLong };
259
260        interp_ok(res)
261    }
262
263    fn sched_yield(&mut self) -> InterpResult<'tcx, ()> {
264        let ecx = self.eval_context_mut();
265
266        ecx.yield_active_thread();
267
268        interp_ok(())
269    }
270}