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_lenient(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 [result] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
46                let result = this.close(result)?;
47                this.write_scalar(result, dest)?;
48            }
49            "stat" | "stat64" | "stat$INODE64" => {
50                let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
51                let result = this.macos_fbsd_solarish_stat(path, buf)?;
52                this.write_scalar(result, dest)?;
53            }
54            "lstat" | "lstat64" | "lstat$INODE64" => {
55                let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
56                let result = this.macos_fbsd_solarish_lstat(path, buf)?;
57                this.write_scalar(result, dest)?;
58            }
59            "fstat" | "fstat64" | "fstat$INODE64" => {
60                let [fd, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
61                let result = this.macos_fbsd_solarish_fstat(fd, buf)?;
62                this.write_scalar(result, dest)?;
63            }
64            "opendir$INODE64" => {
65                let [name] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
66                let result = this.opendir(name)?;
67                this.write_scalar(result, dest)?;
68            }
69            "readdir_r" | "readdir_r$INODE64" => {
70                let [dirp, entry, result] =
71                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
72                let result = this.macos_fbsd_readdir_r(dirp, entry, result)?;
73                this.write_scalar(result, dest)?;
74            }
75            "realpath$DARWIN_EXTSN" => {
76                let [path, resolved_path] =
77                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
78                let result = this.realpath(path, resolved_path)?;
79                this.write_scalar(result, dest)?;
80            }
81            "ioctl" => {
82                let ([fd_num, cmd], varargs) =
83                    this.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?;
84                let result = this.ioctl(fd_num, cmd, varargs)?;
85                this.write_scalar(result, dest)?;
86            }
87
88            // Environment related shims
89            "_NSGetEnviron" => {
90                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
91                let environ = this.machine.env_vars.unix().environ();
92                this.write_pointer(environ, dest)?;
93            }
94
95            // Random data generation
96            "CCRandomGenerateBytes" => {
97                let [bytes, count] =
98                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
99                let bytes = this.read_pointer(bytes)?;
100                let count = this.read_target_usize(count)?;
101                let success = this.eval_libc_i32("kCCSuccess");
102                this.gen_random(bytes, count)?;
103                this.write_int(success, dest)?;
104            }
105
106            // Time related shims
107            "mach_absolute_time" => {
108                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
109                let result = this.mach_absolute_time()?;
110                this.write_scalar(result, dest)?;
111            }
112
113            "mach_timebase_info" => {
114                let [info] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
115                let result = this.mach_timebase_info(info)?;
116                this.write_scalar(result, dest)?;
117            }
118
119            // Access to command-line arguments
120            "_NSGetArgc" => {
121                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
122                this.write_pointer(this.machine.argc.expect("machine must be initialized"), dest)?;
123            }
124            "_NSGetArgv" => {
125                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
126                this.write_pointer(this.machine.argv.expect("machine must be initialized"), dest)?;
127            }
128            "_NSGetExecutablePath" => {
129                let [buf, bufsize] =
130                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
131                this.check_no_isolation("`_NSGetExecutablePath`")?;
132
133                let buf_ptr = this.read_pointer(buf)?;
134                let bufsize = this.deref_pointer_as(bufsize, this.machine.layouts.u32)?;
135
136                // Using the host current_exe is a bit off, but consistent with Linux
137                // (where stdlib reads /proc/self/exe).
138                let path = std::env::current_exe().unwrap();
139                let (written, size_needed) = this.write_path_to_c_str(
140                    &path,
141                    buf_ptr,
142                    this.read_scalar(&bufsize)?.to_u32()?.into(),
143                )?;
144
145                if written {
146                    this.write_null(dest)?;
147                } else {
148                    this.write_scalar(Scalar::from_u32(size_needed.try_into().unwrap()), &bufsize)?;
149                    this.write_int(-1, dest)?;
150                }
151            }
152
153            // Thread-local storage
154            "_tlv_atexit" => {
155                let [dtor, data] =
156                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
157                let dtor = this.read_pointer(dtor)?;
158                let dtor = this.get_ptr_fn(dtor)?.as_instance()?;
159                let data = this.read_scalar(data)?;
160                let active_thread = this.active_thread();
161                this.machine.tls.add_macos_thread_dtor(active_thread, dtor, data)?;
162            }
163
164            // Querying system information
165            "pthread_get_stackaddr_np" => {
166                let [thread] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
167                this.read_target_usize(thread)?;
168                let stack_addr = Scalar::from_uint(this.machine.stack_addr, this.pointer_size());
169                this.write_scalar(stack_addr, dest)?;
170            }
171            "pthread_get_stacksize_np" => {
172                let [thread] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
173                this.read_target_usize(thread)?;
174                let stack_size = Scalar::from_uint(this.machine.stack_size, this.pointer_size());
175                this.write_scalar(stack_size, dest)?;
176            }
177
178            // Threading
179            "pthread_setname_np" => {
180                let [name] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
181
182                // The real implementation has logic in two places:
183                // * in userland at https://github.com/apple-oss-distributions/libpthread/blob/c032e0b076700a0a47db75528a282b8d3a06531a/src/pthread.c#L1178-L1200,
184                // * in kernel at https://github.com/apple-oss-distributions/xnu/blob/8d741a5de7ff4191bf97d57b9f54c2f6d4a15585/bsd/kern/proc_info.c#L3218-L3227.
185                //
186                // The function in libc calls the kernel to validate
187                // the security policies and the input. If all of the requirements
188                // are met, then the name is set and 0 is returned. Otherwise, if
189                // the specified name is lomnger than MAXTHREADNAMESIZE, then
190                // ENAMETOOLONG is returned.
191                let thread = this.pthread_self()?;
192                let res = match this.pthread_setname_np(
193                    thread,
194                    this.read_scalar(name)?,
195                    this.eval_libc("MAXTHREADNAMESIZE").to_target_usize(this)?,
196                    /* truncate */ false,
197                )? {
198                    ThreadNameResult::Ok => Scalar::from_u32(0),
199                    ThreadNameResult::NameTooLong => this.eval_libc("ENAMETOOLONG"),
200                    ThreadNameResult::ThreadNotFound => unreachable!(),
201                };
202                // Contrary to the manpage, `pthread_setname_np` on macOS still
203                // returns an integer indicating success.
204                this.write_scalar(res, dest)?;
205            }
206            "pthread_getname_np" => {
207                let [thread, name, len] =
208                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
209
210                // The function's behavior isn't portable between platforms.
211                // In case of macOS, a truncated name (due to a too small buffer)
212                // does not lead to an error.
213                //
214                // For details, see the implementation at
215                // https://github.com/apple-oss-distributions/libpthread/blob/c032e0b076700a0a47db75528a282b8d3a06531a/src/pthread.c#L1160-L1175.
216                // The key part is the strlcpy, which truncates the resulting value,
217                // but always null terminates (except for zero sized buffers).
218                let res = match this.pthread_getname_np(
219                    this.read_scalar(thread)?,
220                    this.read_scalar(name)?,
221                    this.read_scalar(len)?,
222                    /* truncate */ true,
223                )? {
224                    ThreadNameResult::Ok => Scalar::from_u32(0),
225                    // `NameTooLong` is possible when the buffer is zero sized,
226                    ThreadNameResult::NameTooLong => Scalar::from_u32(0),
227                    ThreadNameResult::ThreadNotFound => this.eval_libc("ESRCH"),
228                };
229                this.write_scalar(res, dest)?;
230            }
231            "pthread_threadid_np" => {
232                let [thread, tid_ptr] =
233                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
234                let res = this.apple_pthread_threadip_np(thread, tid_ptr)?;
235                this.write_scalar(res, dest)?;
236            }
237
238            // Synchronization primitives
239            "os_sync_wait_on_address" => {
240                let [addr_op, value_op, size_op, flags_op] =
241                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
242                this.os_sync_wait_on_address(
243                    addr_op,
244                    value_op,
245                    size_op,
246                    flags_op,
247                    MacOsFutexTimeout::None,
248                    dest,
249                )?;
250            }
251            "os_sync_wait_on_address_with_deadline" => {
252                let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] =
253                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
254                this.os_sync_wait_on_address(
255                    addr_op,
256                    value_op,
257                    size_op,
258                    flags_op,
259                    MacOsFutexTimeout::Absolute { clock_op, timeout_op },
260                    dest,
261                )?;
262            }
263            "os_sync_wait_on_address_with_timeout" => {
264                let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] =
265                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
266                this.os_sync_wait_on_address(
267                    addr_op,
268                    value_op,
269                    size_op,
270                    flags_op,
271                    MacOsFutexTimeout::Relative { clock_op, timeout_op },
272                    dest,
273                )?;
274            }
275            "os_sync_wake_by_address_any" => {
276                let [addr_op, size_op, flags_op] =
277                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
278                this.os_sync_wake_by_address(
279                    addr_op, size_op, flags_op, /* all */ false, dest,
280                )?;
281            }
282            "os_sync_wake_by_address_all" => {
283                let [addr_op, size_op, flags_op] =
284                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
285                this.os_sync_wake_by_address(
286                    addr_op, size_op, flags_op, /* all */ true, dest,
287                )?;
288            }
289            "os_unfair_lock_lock" => {
290                let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
291                this.os_unfair_lock_lock(lock_op)?;
292            }
293            "os_unfair_lock_trylock" => {
294                let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
295                this.os_unfair_lock_trylock(lock_op, dest)?;
296            }
297            "os_unfair_lock_unlock" => {
298                let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
299                this.os_unfair_lock_unlock(lock_op)?;
300            }
301            "os_unfair_lock_assert_owner" => {
302                let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
303                this.os_unfair_lock_assert_owner(lock_op)?;
304            }
305            "os_unfair_lock_assert_not_owner" => {
306                let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
307                this.os_unfair_lock_assert_not_owner(lock_op)?;
308            }
309
310            _ => return interp_ok(EmulateItemResult::NotSupported),
311        };
312
313        interp_ok(EmulateItemResult::NeedsReturn)
314    }
315
316    fn ioctl(
317        &mut self,
318        fd_num: &OpTy<'tcx>,
319        cmd: &OpTy<'tcx>,
320        _varargs: &[OpTy<'tcx>],
321    ) -> InterpResult<'tcx, Scalar> {
322        let this = self.eval_context_mut();
323
324        let fioclex = this.eval_libc_u64("FIOCLEX");
325
326        let fd_num = this.read_scalar(fd_num)?.to_i32()?;
327        let cmd = this.read_scalar(cmd)?.to_u64()?;
328
329        if cmd == fioclex {
330            // Since we don't support `exec`, this is a NOP. However, we want to
331            // return EBADF if the FD is invalid.
332            if this.machine.fds.is_fd_num(fd_num) {
333                interp_ok(Scalar::from_i32(0))
334            } else {
335                this.set_last_error_and_return_i32(LibcError("EBADF"))
336            }
337        } else {
338            throw_unsup_format!("ioctl: unsupported command {cmd:#x}");
339        }
340    }
341}