Skip to main content

miri/shims/unix/macos/
foreign_items.rs

1use rustc_abi::CanonAbi;
2use rustc_middle::ty::Ty;
3use rustc_span::Symbol;
4use rustc_target::callconv::FnAbi;
5
6use super::sync::{EvalContextExt as _, MacOsFutexTimeout};
7use crate::shims::unix::*;
8use crate::*;
9
10pub fn is_dyn_sym(name: &str) -> bool {
11    match name {
12        // These only became available with macOS 11.0, so std looks them up dynamically.
13        "os_sync_wait_on_address"
14        | "os_sync_wait_on_address_with_deadline"
15        | "os_sync_wait_on_address_with_timeout"
16        | "os_sync_wake_by_address_any"
17        | "os_sync_wake_by_address_all" => true,
18        _ => false,
19    }
20}
21
22impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
23pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
24    fn emulate_foreign_item_inner(
25        &mut self,
26        link_name: Symbol,
27        abi: &FnAbi<'tcx, Ty<'tcx>>,
28        args: &[OpTy<'tcx>],
29        dest: &MPlaceTy<'tcx>,
30    ) -> InterpResult<'tcx, EmulateItemResult> {
31        let this = self.eval_context_mut();
32
33        // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern.
34
35        match link_name.as_str() {
36            // errno
37            "__error" => {
38                let [] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
39                let errno_place = this.last_error_place()?;
40                this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?;
41            }
42
43            // File related shims
44            "close$NOCANCEL" => {
45                let [fd] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
46                let fd = this.read_scalar(fd)?.to_i32()?;
47                let result = this.close(fd)?;
48                this.write_scalar(result, dest)?;
49            }
50            "stat$INODE64" => {
51                let [path, buf] =
52                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
53                let result = this.stat(path, buf)?;
54                this.write_scalar(result, dest)?;
55            }
56            "lstat$INODE64" => {
57                let [path, buf] =
58                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
59                let result = this.lstat(path, buf)?;
60                this.write_scalar(result, dest)?;
61            }
62            "fstat$INODE64" => {
63                let [fd, buf] =
64                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
65                let result = this.fstat(fd, buf)?;
66                this.write_scalar(result, dest)?;
67            }
68            "opendir$INODE64" => {
69                let [name] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
70                let result = this.opendir(name)?;
71                this.write_scalar(result, dest)?;
72            }
73            "readdir$INODE64" => {
74                let [dirp] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
75                this.readdir(dirp, dest)?;
76            }
77            "realpath$DARWIN_EXTSN" => {
78                let [path, resolved_path] =
79                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
80                let result = this.realpath(path, resolved_path)?;
81                this.write_scalar(result, dest)?;
82            }
83
84            // Environment related shims
85            "_NSGetEnviron" => {
86                // FIXME: This does not have a direct test (#3179).
87                let [] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
88                let environ = this.machine.env_vars.unix().environ();
89                this.write_pointer(environ, dest)?;
90            }
91
92            // Random data generation
93            "CCRandomGenerateBytes" => {
94                let [bytes, count] =
95                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
96                let bytes = this.read_pointer(bytes)?;
97                let count = this.read_target_usize(count)?;
98                let success = this.eval_libc_i32("kCCSuccess");
99                this.gen_random(bytes, count)?;
100                this.write_int(success, dest)?;
101            }
102
103            // Time related shims
104            "mach_absolute_time" => {
105                let [] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
106                let result = this.mach_absolute_time()?;
107                this.write_scalar(result, dest)?;
108            }
109
110            "mach_timebase_info" => {
111                // FIXME: This does not have a direct test (#3179).
112                let [info] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
113                let result = this.mach_timebase_info(info)?;
114                this.write_scalar(result, dest)?;
115            }
116
117            "mach_wait_until" => {
118                // FIXME: This does not have a direct test (#3179).
119                let [deadline] =
120                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
121                let result = this.mach_wait_until(deadline)?;
122                this.write_scalar(result, dest)?;
123            }
124
125            // Access to command-line arguments
126            "_NSGetArgc" => {
127                // FIXME: This does not have a direct test (#3179).
128                let [] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
129                this.write_pointer(this.machine.argc.expect("machine must be initialized"), dest)?;
130            }
131            "_NSGetArgv" => {
132                // FIXME: This does not have a direct test (#3179).
133                let [] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
134                this.write_pointer(this.machine.argv.expect("machine must be initialized"), dest)?;
135            }
136            "_NSGetExecutablePath" => {
137                // FIXME: This does not have a direct test (#3179).
138                let [buf, bufsize] =
139                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
140                this.check_no_isolation("`_NSGetExecutablePath`")?;
141
142                let buf_ptr = this.read_pointer(buf)?;
143                let bufsize = this.deref_pointer_as(bufsize, this.machine.layouts.u32)?;
144
145                // Using the host current_exe is a bit off, but consistent with Linux
146                // (where stdlib reads /proc/self/exe).
147                let path = std::env::current_exe().unwrap();
148                let (written, size_needed) = this.write_path_to_c_str(
149                    &path,
150                    buf_ptr,
151                    this.read_scalar(&bufsize)?.to_u32()?.into(),
152                )?;
153
154                if written {
155                    this.write_null(dest)?;
156                } else {
157                    this.write_scalar(Scalar::from_u32(size_needed.try_into().unwrap()), &bufsize)?;
158                    this.write_int(-1, dest)?;
159                }
160            }
161
162            // Thread-local storage
163            "_tlv_atexit" => {
164                let [dtor, data] =
165                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
166                let dtor = this.read_pointer(dtor)?;
167                let dtor = this.get_ptr_fn(dtor)?.as_instance()?;
168                let data = this.read_scalar(data)?;
169                let active_thread = this.active_thread();
170                this.machine.tls.add_macos_thread_dtor(
171                    active_thread,
172                    dtor,
173                    data,
174                    this.machine.current_user_relevant_span(),
175                )?;
176            }
177
178            // Querying system information
179            "pthread_get_stackaddr_np" => {
180                // FIXME: This does not have a direct test (#3179).
181                let [thread] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
182                this.read_target_usize(thread)?;
183                let stack_addr = Scalar::from_uint(this.machine.stack_addr, this.pointer_size());
184                this.write_scalar(stack_addr, dest)?;
185            }
186            "pthread_get_stacksize_np" => {
187                // FIXME: This does not have a direct test (#3179).
188                let [thread] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
189                this.read_target_usize(thread)?;
190                let stack_size = Scalar::from_uint(this.machine.stack_size, this.pointer_size());
191                this.write_scalar(stack_size, dest)?;
192            }
193
194            // Threading
195            "pthread_setname_np" => {
196                let [name] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
197
198                // The real implementation has logic in two places:
199                // * in userland at https://github.com/apple-oss-distributions/libpthread/blob/c032e0b076700a0a47db75528a282b8d3a06531a/src/pthread.c#L1178-L1200,
200                // * in kernel at https://github.com/apple-oss-distributions/xnu/blob/8d741a5de7ff4191bf97d57b9f54c2f6d4a15585/bsd/kern/proc_info.c#L3218-L3227.
201                //
202                // The function in libc calls the kernel to validate
203                // the security policies and the input. If all of the requirements
204                // are met, then the name is set and 0 is returned. Otherwise, if
205                // the specified name is lomnger than MAXTHREADNAMESIZE, then
206                // ENAMETOOLONG is returned.
207                let thread = this.pthread_self()?;
208                let res = match this.pthread_setname_np(
209                    thread,
210                    this.read_scalar(name)?,
211                    this.eval_libc("MAXTHREADNAMESIZE").to_target_usize(this)?,
212                    /* truncate */ false,
213                )? {
214                    ThreadNameResult::Ok => Scalar::from_i32(0),
215                    ThreadNameResult::NameTooLong => {
216                        // Testing on native systems indicates that the error is returned via errno.
217                        this.set_errno_and_return_neg1_i32(LibcError("ENAMETOOLONG"))?
218                    }
219                };
220                // Contrary to the manpage, `pthread_setname_np` on macOS still
221                // returns an integer indicating success.
222                this.write_scalar(res, dest)?;
223            }
224            "pthread_getname_np" => {
225                let [thread, name, len] =
226                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
227
228                // The function's behavior isn't portable between platforms.
229                // In case of macOS, a truncated name (due to a too small buffer)
230                // does not lead to an error.
231                //
232                // For details, see the implementation at
233                // https://github.com/apple-oss-distributions/libpthread/blob/c032e0b076700a0a47db75528a282b8d3a06531a/src/pthread.c#L1160-L1175.
234                // The key part is the strlcpy, which truncates the resulting value,
235                // but always null terminates (except for zero sized buffers).
236                let res = match this.pthread_getname_np(
237                    this.read_scalar(thread)?,
238                    this.read_scalar(name)?,
239                    this.read_scalar(len)?,
240                    /* truncate */ true,
241                )? {
242                    ThreadNameResult::Ok => Scalar::from_i32(0),
243                    // `NameTooLong` is possible when the buffer is zero sized,
244                    ThreadNameResult::NameTooLong => Scalar::from_i32(0),
245                };
246                this.write_scalar(res, dest)?;
247            }
248            "pthread_threadid_np" => {
249                let [thread, tid_ptr] =
250                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
251                let res = this.apple_pthread_threadid_np(thread, tid_ptr)?;
252                this.write_scalar(res, dest)?;
253            }
254
255            // Synchronization primitives
256            "os_sync_wait_on_address" => {
257                let [addr_op, value_op, size_op, flags_op] =
258                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
259                this.os_sync_wait_on_address(
260                    addr_op,
261                    value_op,
262                    size_op,
263                    flags_op,
264                    MacOsFutexTimeout::None,
265                    dest,
266                )?;
267            }
268            "os_sync_wait_on_address_with_deadline" => {
269                let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] =
270                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
271                this.os_sync_wait_on_address(
272                    addr_op,
273                    value_op,
274                    size_op,
275                    flags_op,
276                    MacOsFutexTimeout::Absolute { clock_op, timeout_op },
277                    dest,
278                )?;
279            }
280            "os_sync_wait_on_address_with_timeout" => {
281                let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] =
282                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
283                this.os_sync_wait_on_address(
284                    addr_op,
285                    value_op,
286                    size_op,
287                    flags_op,
288                    MacOsFutexTimeout::Relative { clock_op, timeout_op },
289                    dest,
290                )?;
291            }
292            "os_sync_wake_by_address_any" => {
293                let [addr_op, size_op, flags_op] =
294                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
295                this.os_sync_wake_by_address(
296                    addr_op, size_op, flags_op, /* all */ false, dest,
297                )?;
298            }
299            "os_sync_wake_by_address_all" => {
300                let [addr_op, size_op, flags_op] =
301                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
302                this.os_sync_wake_by_address(
303                    addr_op, size_op, flags_op, /* all */ true, dest,
304                )?;
305            }
306            "os_unfair_lock_lock" => {
307                let [lock_op] =
308                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
309                this.os_unfair_lock_lock(lock_op)?;
310            }
311            "os_unfair_lock_trylock" => {
312                let [lock_op] =
313                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
314                this.os_unfair_lock_trylock(lock_op, dest)?;
315            }
316            "os_unfair_lock_unlock" => {
317                let [lock_op] =
318                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
319                this.os_unfair_lock_unlock(lock_op)?;
320            }
321            "os_unfair_lock_assert_owner" => {
322                let [lock_op] =
323                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
324                this.os_unfair_lock_assert_owner(lock_op)?;
325            }
326            "os_unfair_lock_assert_not_owner" => {
327                let [lock_op] =
328                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
329                this.os_unfair_lock_assert_not_owner(lock_op)?;
330            }
331
332            "pthread_cond_timedwait_relative_np" => {
333                let [cond, mutex, reltime] =
334                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
335                this.pthread_cond_timedwait(
336                    cond, mutex, reltime, dest, /* macos_relative_np */ true,
337                )?;
338            }
339
340            // Incomplete shims that we "stub out" just to get pre-main initialization code to work.
341            // These shims are enabled only when the caller is in the standard library.
342            "confstr" => {
343                let [_key, _buf, _buflen] =
344                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
345                // We just pretend that no configuration key exists, and return EINVAL.
346                this.set_last_error(LibcError("EINVAL"))?;
347                this.write_null(dest)?;
348            }
349
350            _ => return interp_ok(EmulateItemResult::NotSupported),
351        };
352
353        interp_ok(EmulateItemResult::NeedsReturn)
354    }
355}