miri/shims/unix/
foreign_items.rs

1use std::ffi::OsStr;
2use std::str;
3
4use rustc_abi::Size;
5use rustc_middle::ty::Ty;
6use rustc_middle::ty::layout::LayoutOf;
7use rustc_span::Symbol;
8use rustc_target::callconv::{Conv, FnAbi};
9
10use self::shims::unix::android::foreign_items as android;
11use self::shims::unix::freebsd::foreign_items as freebsd;
12use self::shims::unix::linux::foreign_items as linux;
13use self::shims::unix::macos::foreign_items as macos;
14use self::shims::unix::solarish::foreign_items as solarish;
15use crate::concurrency::cpu_affinity::CpuAffinityMask;
16use crate::shims::alloc::EvalContextExt as _;
17use crate::shims::unix::*;
18use crate::*;
19
20pub fn is_dyn_sym(name: &str, target_os: &str) -> bool {
21    match name {
22        // Used for tests.
23        "isatty" => true,
24        // `signal` is set up as a weak symbol in `init_extern_statics` (on Android) so we might as
25        // well allow it in `dlsym`.
26        "signal" => true,
27        // needed at least on macOS to avoid file-based fallback in getrandom
28        "getentropy" | "getrandom" => true,
29        // Give specific OSes a chance to allow their symbols.
30        _ =>
31            match target_os {
32                "android" => android::is_dyn_sym(name),
33                "freebsd" => freebsd::is_dyn_sym(name),
34                "linux" => linux::is_dyn_sym(name),
35                "macos" => macos::is_dyn_sym(name),
36                "solaris" | "illumos" => solarish::is_dyn_sym(name),
37                _ => false,
38            },
39    }
40}
41
42impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
43pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
44    // Querying system information
45    fn sysconf(&mut self, val: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
46        let this = self.eval_context_mut();
47
48        let name = this.read_scalar(val)?.to_i32()?;
49        // FIXME: Which of these are POSIX, and which are GNU/Linux?
50        // At least the names seem to all also exist on macOS.
51        let sysconfs: &[(&str, fn(&MiriInterpCx<'_>) -> Scalar)] = &[
52            ("_SC_PAGESIZE", |this| Scalar::from_int(this.machine.page_size, this.pointer_size())),
53            ("_SC_PAGE_SIZE", |this| Scalar::from_int(this.machine.page_size, this.pointer_size())),
54            ("_SC_NPROCESSORS_CONF", |this| {
55                Scalar::from_int(this.machine.num_cpus, this.pointer_size())
56            }),
57            ("_SC_NPROCESSORS_ONLN", |this| {
58                Scalar::from_int(this.machine.num_cpus, this.pointer_size())
59            }),
60            // 512 seems to be a reasonable default. The value is not critical, in
61            // the sense that getpwuid_r takes and checks the buffer length.
62            ("_SC_GETPW_R_SIZE_MAX", |this| Scalar::from_int(512, this.pointer_size())),
63            // Miri doesn't have a fixed limit on FDs, but we may be limited in terms of how
64            // many *host* FDs we can open. Just use some arbitrary, pretty big value;
65            // this can be adjusted if it causes problems.
66            // The spec imposes a minimum of `_POSIX_OPEN_MAX` (20).
67            ("_SC_OPEN_MAX", |this| Scalar::from_int(2_i32.pow(16), this.pointer_size())),
68        ];
69        for &(sysconf_name, value) in sysconfs {
70            let sysconf_name = this.eval_libc_i32(sysconf_name);
71            if sysconf_name == name {
72                return interp_ok(value(this));
73            }
74        }
75        throw_unsup_format!("unimplemented sysconf name: {}", name)
76    }
77
78    fn strerror_r(
79        &mut self,
80        errnum: &OpTy<'tcx>,
81        buf: &OpTy<'tcx>,
82        buflen: &OpTy<'tcx>,
83    ) -> InterpResult<'tcx, Scalar> {
84        let this = self.eval_context_mut();
85
86        let errnum = this.read_scalar(errnum)?;
87        let buf = this.read_pointer(buf)?;
88        let buflen = this.read_target_usize(buflen)?;
89        let error = this.try_errnum_to_io_error(errnum)?;
90        let formatted = match error {
91            Some(err) => format!("{err}"),
92            None => format!("<unknown errnum in strerror_r: {errnum}>"),
93        };
94        let (complete, _) = this.write_os_str_to_c_str(OsStr::new(&formatted), buf, buflen)?;
95        if complete {
96            interp_ok(Scalar::from_i32(0))
97        } else {
98            interp_ok(Scalar::from_i32(this.eval_libc_i32("ERANGE")))
99        }
100    }
101
102    fn emulate_foreign_item_inner(
103        &mut self,
104        link_name: Symbol,
105        abi: &FnAbi<'tcx, Ty<'tcx>>,
106        args: &[OpTy<'tcx>],
107        dest: &MPlaceTy<'tcx>,
108    ) -> InterpResult<'tcx, EmulateItemResult> {
109        let this = self.eval_context_mut();
110
111        // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern.
112        match link_name.as_str() {
113            // Environment related shims
114            "getenv" => {
115                let [name] = this.check_shim(abi, Conv::C, link_name, args)?;
116                let result = this.getenv(name)?;
117                this.write_pointer(result, dest)?;
118            }
119            "unsetenv" => {
120                let [name] = this.check_shim(abi, Conv::C, link_name, args)?;
121                let result = this.unsetenv(name)?;
122                this.write_scalar(result, dest)?;
123            }
124            "setenv" => {
125                let [name, value, overwrite] = this.check_shim(abi, Conv::C, link_name, args)?;
126                this.read_scalar(overwrite)?.to_i32()?;
127                let result = this.setenv(name, value)?;
128                this.write_scalar(result, dest)?;
129            }
130            "getcwd" => {
131                let [buf, size] = this.check_shim(abi, Conv::C, link_name, args)?;
132                let result = this.getcwd(buf, size)?;
133                this.write_pointer(result, dest)?;
134            }
135            "chdir" => {
136                let [path] = this.check_shim(abi, Conv::C, link_name, args)?;
137                let result = this.chdir(path)?;
138                this.write_scalar(result, dest)?;
139            }
140            "getpid" => {
141                let [] = this.check_shim(abi, Conv::C, link_name, args)?;
142                let result = this.getpid()?;
143                this.write_scalar(result, dest)?;
144            }
145            "sysconf" => {
146                let [val] = this.check_shim(abi, Conv::C, link_name, args)?;
147                let result = this.sysconf(val)?;
148                this.write_scalar(result, dest)?;
149            }
150            // File descriptors
151            "read" => {
152                let [fd, buf, count] = this.check_shim(abi, Conv::C, link_name, args)?;
153                let fd = this.read_scalar(fd)?.to_i32()?;
154                let buf = this.read_pointer(buf)?;
155                let count = this.read_target_usize(count)?;
156                this.read(fd, buf, count, None, dest)?;
157            }
158            "write" => {
159                let [fd, buf, n] = this.check_shim(abi, Conv::C, link_name, args)?;
160                let fd = this.read_scalar(fd)?.to_i32()?;
161                let buf = this.read_pointer(buf)?;
162                let count = this.read_target_usize(n)?;
163                trace!("Called write({:?}, {:?}, {:?})", fd, buf, count);
164                this.write(fd, buf, count, None, dest)?;
165            }
166            "pread" => {
167                let [fd, buf, count, offset] = this.check_shim(abi, Conv::C, link_name, args)?;
168                let fd = this.read_scalar(fd)?.to_i32()?;
169                let buf = this.read_pointer(buf)?;
170                let count = this.read_target_usize(count)?;
171                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
172                this.read(fd, buf, count, Some(offset), dest)?;
173            }
174            "pwrite" => {
175                let [fd, buf, n, offset] = this.check_shim(abi, Conv::C, link_name, args)?;
176                let fd = this.read_scalar(fd)?.to_i32()?;
177                let buf = this.read_pointer(buf)?;
178                let count = this.read_target_usize(n)?;
179                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
180                trace!("Called pwrite({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset);
181                this.write(fd, buf, count, Some(offset), dest)?;
182            }
183            "pread64" => {
184                let [fd, buf, count, offset] = this.check_shim(abi, Conv::C, link_name, args)?;
185                let fd = this.read_scalar(fd)?.to_i32()?;
186                let buf = this.read_pointer(buf)?;
187                let count = this.read_target_usize(count)?;
188                let offset =
189                    this.read_scalar(offset)?.to_int(this.libc_ty_layout("off64_t").size)?;
190                this.read(fd, buf, count, Some(offset), dest)?;
191            }
192            "pwrite64" => {
193                let [fd, buf, n, offset] = this.check_shim(abi, Conv::C, link_name, args)?;
194                let fd = this.read_scalar(fd)?.to_i32()?;
195                let buf = this.read_pointer(buf)?;
196                let count = this.read_target_usize(n)?;
197                let offset =
198                    this.read_scalar(offset)?.to_int(this.libc_ty_layout("off64_t").size)?;
199                trace!("Called pwrite64({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset);
200                this.write(fd, buf, count, Some(offset), dest)?;
201            }
202            "close" => {
203                let [fd] = this.check_shim(abi, Conv::C, link_name, args)?;
204                let result = this.close(fd)?;
205                this.write_scalar(result, dest)?;
206            }
207            "fcntl" => {
208                let ([fd_num, cmd], varargs) =
209                    this.check_shim_variadic(abi, Conv::C, link_name, args)?;
210                let result = this.fcntl(fd_num, cmd, varargs)?;
211                this.write_scalar(result, dest)?;
212            }
213            "dup" => {
214                let [old_fd] = this.check_shim(abi, Conv::C, link_name, args)?;
215                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
216                let new_fd = this.dup(old_fd)?;
217                this.write_scalar(new_fd, dest)?;
218            }
219            "dup2" => {
220                let [old_fd, new_fd] = this.check_shim(abi, Conv::C, link_name, args)?;
221                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
222                let new_fd = this.read_scalar(new_fd)?.to_i32()?;
223                let result = this.dup2(old_fd, new_fd)?;
224                this.write_scalar(result, dest)?;
225            }
226            "flock" => {
227                let [fd, op] = this.check_shim(abi, Conv::C, link_name, args)?;
228                let fd = this.read_scalar(fd)?.to_i32()?;
229                let op = this.read_scalar(op)?.to_i32()?;
230                let result = this.flock(fd, op)?;
231                this.write_scalar(result, dest)?;
232            }
233
234            // File and file system access
235            "open" | "open64" => {
236                // `open` is variadic, the third argument is only present when the second argument
237                // has O_CREAT (or on linux O_TMPFILE, but miri doesn't support that) set
238                let ([path_raw, flag], varargs) =
239                    this.check_shim_variadic(abi, Conv::C, link_name, args)?;
240                let result = this.open(path_raw, flag, varargs)?;
241                this.write_scalar(result, dest)?;
242            }
243            "unlink" => {
244                let [path] = this.check_shim(abi, Conv::C, link_name, args)?;
245                let result = this.unlink(path)?;
246                this.write_scalar(result, dest)?;
247            }
248            "symlink" => {
249                let [target, linkpath] = this.check_shim(abi, Conv::C, link_name, args)?;
250                let result = this.symlink(target, linkpath)?;
251                this.write_scalar(result, dest)?;
252            }
253            "rename" => {
254                let [oldpath, newpath] = this.check_shim(abi, Conv::C, link_name, args)?;
255                let result = this.rename(oldpath, newpath)?;
256                this.write_scalar(result, dest)?;
257            }
258            "mkdir" => {
259                let [path, mode] = this.check_shim(abi, Conv::C, link_name, args)?;
260                let result = this.mkdir(path, mode)?;
261                this.write_scalar(result, dest)?;
262            }
263            "rmdir" => {
264                let [path] = this.check_shim(abi, Conv::C, link_name, args)?;
265                let result = this.rmdir(path)?;
266                this.write_scalar(result, dest)?;
267            }
268            "opendir" => {
269                let [name] = this.check_shim(abi, Conv::C, link_name, args)?;
270                let result = this.opendir(name)?;
271                this.write_scalar(result, dest)?;
272            }
273            "closedir" => {
274                let [dirp] = this.check_shim(abi, Conv::C, link_name, args)?;
275                let result = this.closedir(dirp)?;
276                this.write_scalar(result, dest)?;
277            }
278            "lseek64" => {
279                let [fd, offset, whence] = this.check_shim(abi, Conv::C, link_name, args)?;
280                let fd = this.read_scalar(fd)?.to_i32()?;
281                let offset = this.read_scalar(offset)?.to_i64()?;
282                let whence = this.read_scalar(whence)?.to_i32()?;
283                let result = this.lseek64(fd, offset.into(), whence)?;
284                this.write_scalar(result, dest)?;
285            }
286            "lseek" => {
287                let [fd, offset, whence] = this.check_shim(abi, Conv::C, link_name, args)?;
288                let fd = this.read_scalar(fd)?.to_i32()?;
289                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
290                let whence = this.read_scalar(whence)?.to_i32()?;
291                let result = this.lseek64(fd, offset, whence)?;
292                this.write_scalar(result, dest)?;
293            }
294            "ftruncate64" => {
295                let [fd, length] = this.check_shim(abi, Conv::C, link_name, args)?;
296                let fd = this.read_scalar(fd)?.to_i32()?;
297                let length = this.read_scalar(length)?.to_i64()?;
298                let result = this.ftruncate64(fd, length.into())?;
299                this.write_scalar(result, dest)?;
300            }
301            "ftruncate" => {
302                let [fd, length] = this.check_shim(abi, Conv::C, link_name, args)?;
303                let fd = this.read_scalar(fd)?.to_i32()?;
304                let length = this.read_scalar(length)?.to_int(this.libc_ty_layout("off_t").size)?;
305                let result = this.ftruncate64(fd, length)?;
306                this.write_scalar(result, dest)?;
307            }
308            "fsync" => {
309                let [fd] = this.check_shim(abi, Conv::C, link_name, args)?;
310                let result = this.fsync(fd)?;
311                this.write_scalar(result, dest)?;
312            }
313            "fdatasync" => {
314                let [fd] = this.check_shim(abi, Conv::C, link_name, args)?;
315                let result = this.fdatasync(fd)?;
316                this.write_scalar(result, dest)?;
317            }
318            "readlink" => {
319                let [pathname, buf, bufsize] = this.check_shim(abi, Conv::C, link_name, args)?;
320                let result = this.readlink(pathname, buf, bufsize)?;
321                this.write_scalar(Scalar::from_target_isize(result, this), dest)?;
322            }
323            "posix_fadvise" => {
324                let [fd, offset, len, advice] = this.check_shim(abi, Conv::C, link_name, args)?;
325                this.read_scalar(fd)?.to_i32()?;
326                this.read_target_isize(offset)?;
327                this.read_target_isize(len)?;
328                this.read_scalar(advice)?.to_i32()?;
329                // fadvise is only informational, we can ignore it.
330                this.write_null(dest)?;
331            }
332            "realpath" => {
333                let [path, resolved_path] = this.check_shim(abi, Conv::C, link_name, args)?;
334                let result = this.realpath(path, resolved_path)?;
335                this.write_scalar(result, dest)?;
336            }
337            "mkstemp" => {
338                let [template] = this.check_shim(abi, Conv::C, link_name, args)?;
339                let result = this.mkstemp(template)?;
340                this.write_scalar(result, dest)?;
341            }
342
343            // Unnamed sockets and pipes
344            "socketpair" => {
345                let [domain, type_, protocol, sv] =
346                    this.check_shim(abi, Conv::C, link_name, args)?;
347                let result = this.socketpair(domain, type_, protocol, sv)?;
348                this.write_scalar(result, dest)?;
349            }
350            "pipe" => {
351                let [pipefd] = this.check_shim(abi, Conv::C, link_name, args)?;
352                let result = this.pipe2(pipefd, /*flags*/ None)?;
353                this.write_scalar(result, dest)?;
354            }
355            "pipe2" => {
356                // Currently this function does not exist on all Unixes, e.g. on macOS.
357                this.check_target_os(&["linux", "freebsd", "solaris", "illumos"], link_name)?;
358                let [pipefd, flags] = this.check_shim(abi, Conv::C, link_name, args)?;
359                let result = this.pipe2(pipefd, Some(flags))?;
360                this.write_scalar(result, dest)?;
361            }
362
363            // Time
364            "gettimeofday" => {
365                let [tv, tz] = this.check_shim(abi, Conv::C, link_name, args)?;
366                let result = this.gettimeofday(tv, tz)?;
367                this.write_scalar(result, dest)?;
368            }
369            "localtime_r" => {
370                let [timep, result_op] = this.check_shim(abi, Conv::C, link_name, args)?;
371                let result = this.localtime_r(timep, result_op)?;
372                this.write_pointer(result, dest)?;
373            }
374            "clock_gettime" => {
375                let [clk_id, tp] = this.check_shim(abi, Conv::C, link_name, args)?;
376                let result = this.clock_gettime(clk_id, tp)?;
377                this.write_scalar(result, dest)?;
378            }
379
380            // Allocation
381            "posix_memalign" => {
382                let [memptr, align, size] = this.check_shim(abi, Conv::C, link_name, args)?;
383                let result = this.posix_memalign(memptr, align, size)?;
384                this.write_scalar(result, dest)?;
385            }
386
387            "mmap" => {
388                let [addr, length, prot, flags, fd, offset] =
389                    this.check_shim(abi, Conv::C, link_name, args)?;
390                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
391                let ptr = this.mmap(addr, length, prot, flags, fd, offset)?;
392                this.write_scalar(ptr, dest)?;
393            }
394            "munmap" => {
395                let [addr, length] = this.check_shim(abi, Conv::C, link_name, args)?;
396                let result = this.munmap(addr, length)?;
397                this.write_scalar(result, dest)?;
398            }
399
400            "reallocarray" => {
401                // Currently this function does not exist on all Unixes, e.g. on macOS.
402                this.check_target_os(&["linux", "freebsd", "android"], link_name)?;
403                let [ptr, nmemb, size] = this.check_shim(abi, Conv::C, link_name, args)?;
404                let ptr = this.read_pointer(ptr)?;
405                let nmemb = this.read_target_usize(nmemb)?;
406                let size = this.read_target_usize(size)?;
407                // reallocarray checks a possible overflow and returns ENOMEM
408                // if that happens.
409                //
410                // Linux: https://www.unix.com/man-page/linux/3/reallocarray/
411                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=reallocarray
412                match this.compute_size_in_bytes(Size::from_bytes(size), nmemb) {
413                    None => {
414                        this.set_last_error(LibcError("ENOMEM"))?;
415                        this.write_null(dest)?;
416                    }
417                    Some(len) => {
418                        let res = this.realloc(ptr, len.bytes())?;
419                        this.write_pointer(res, dest)?;
420                    }
421                }
422            }
423            "aligned_alloc" => {
424                // This is a C11 function, we assume all Unixes have it.
425                // (MSVC explicitly does not support this.)
426                let [align, size] = this.check_shim(abi, Conv::C, link_name, args)?;
427                let res = this.aligned_alloc(align, size)?;
428                this.write_pointer(res, dest)?;
429            }
430
431            // Dynamic symbol loading
432            "dlsym" => {
433                let [handle, symbol] = this.check_shim(abi, Conv::C, link_name, args)?;
434                this.read_target_usize(handle)?;
435                let symbol = this.read_pointer(symbol)?;
436                let name = this.read_c_str(symbol)?;
437                if let Ok(name) = str::from_utf8(name)
438                    && is_dyn_sym(name, &this.tcx.sess.target.os)
439                {
440                    let ptr = this.fn_ptr(FnVal::Other(DynSym::from_str(name)));
441                    this.write_pointer(ptr, dest)?;
442                } else {
443                    this.write_null(dest)?;
444                }
445            }
446
447            // Thread-local storage
448            "pthread_key_create" => {
449                let [key, dtor] = this.check_shim(abi, Conv::C, link_name, args)?;
450                let key_place = this.deref_pointer_as(key, this.libc_ty_layout("pthread_key_t"))?;
451                let dtor = this.read_pointer(dtor)?;
452
453                // Extract the function type out of the signature (that seems easier than constructing it ourselves).
454                let dtor = if !this.ptr_is_null(dtor)? {
455                    Some(this.get_ptr_fn(dtor)?.as_instance()?)
456                } else {
457                    None
458                };
459
460                // Figure out how large a pthread TLS key actually is.
461                // To this end, deref the argument type. This is `libc::pthread_key_t`.
462                let key_type = key.layout.ty
463                    .builtin_deref(true)
464                    .ok_or_else(|| err_ub_format!(
465                        "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
466                    ))?;
467                let key_layout = this.layout_of(key_type)?;
468
469                // Create key and write it into the memory where `key_ptr` wants it.
470                let key = this.machine.tls.create_tls_key(dtor, key_layout.size)?;
471                this.write_scalar(Scalar::from_uint(key, key_layout.size), &key_place)?;
472
473                // Return success (`0`).
474                this.write_null(dest)?;
475            }
476            "pthread_key_delete" => {
477                let [key] = this.check_shim(abi, Conv::C, link_name, args)?;
478                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
479                this.machine.tls.delete_tls_key(key)?;
480                // Return success (0)
481                this.write_null(dest)?;
482            }
483            "pthread_getspecific" => {
484                let [key] = this.check_shim(abi, Conv::C, link_name, args)?;
485                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
486                let active_thread = this.active_thread();
487                let ptr = this.machine.tls.load_tls(key, active_thread, this)?;
488                this.write_scalar(ptr, dest)?;
489            }
490            "pthread_setspecific" => {
491                let [key, new_ptr] = this.check_shim(abi, Conv::C, link_name, args)?;
492                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
493                let active_thread = this.active_thread();
494                let new_data = this.read_scalar(new_ptr)?;
495                this.machine.tls.store_tls(key, active_thread, new_data, &*this.tcx)?;
496
497                // Return success (`0`).
498                this.write_null(dest)?;
499            }
500
501            // Synchronization primitives
502            "pthread_mutexattr_init" => {
503                let [attr] = this.check_shim(abi, Conv::C, link_name, args)?;
504                this.pthread_mutexattr_init(attr)?;
505                this.write_null(dest)?;
506            }
507            "pthread_mutexattr_settype" => {
508                let [attr, kind] = this.check_shim(abi, Conv::C, link_name, args)?;
509                let result = this.pthread_mutexattr_settype(attr, kind)?;
510                this.write_scalar(result, dest)?;
511            }
512            "pthread_mutexattr_destroy" => {
513                let [attr] = this.check_shim(abi, Conv::C, link_name, args)?;
514                this.pthread_mutexattr_destroy(attr)?;
515                this.write_null(dest)?;
516            }
517            "pthread_mutex_init" => {
518                let [mutex, attr] = this.check_shim(abi, Conv::C, link_name, args)?;
519                this.pthread_mutex_init(mutex, attr)?;
520                this.write_null(dest)?;
521            }
522            "pthread_mutex_lock" => {
523                let [mutex] = this.check_shim(abi, Conv::C, link_name, args)?;
524                this.pthread_mutex_lock(mutex, dest)?;
525            }
526            "pthread_mutex_trylock" => {
527                let [mutex] = this.check_shim(abi, Conv::C, link_name, args)?;
528                let result = this.pthread_mutex_trylock(mutex)?;
529                this.write_scalar(result, dest)?;
530            }
531            "pthread_mutex_unlock" => {
532                let [mutex] = this.check_shim(abi, Conv::C, link_name, args)?;
533                let result = this.pthread_mutex_unlock(mutex)?;
534                this.write_scalar(result, dest)?;
535            }
536            "pthread_mutex_destroy" => {
537                let [mutex] = this.check_shim(abi, Conv::C, link_name, args)?;
538                this.pthread_mutex_destroy(mutex)?;
539                this.write_int(0, dest)?;
540            }
541            "pthread_rwlock_rdlock" => {
542                let [rwlock] = this.check_shim(abi, Conv::C, link_name, args)?;
543                this.pthread_rwlock_rdlock(rwlock, dest)?;
544            }
545            "pthread_rwlock_tryrdlock" => {
546                let [rwlock] = this.check_shim(abi, Conv::C, link_name, args)?;
547                let result = this.pthread_rwlock_tryrdlock(rwlock)?;
548                this.write_scalar(result, dest)?;
549            }
550            "pthread_rwlock_wrlock" => {
551                let [rwlock] = this.check_shim(abi, Conv::C, link_name, args)?;
552                this.pthread_rwlock_wrlock(rwlock, dest)?;
553            }
554            "pthread_rwlock_trywrlock" => {
555                let [rwlock] = this.check_shim(abi, Conv::C, link_name, args)?;
556                let result = this.pthread_rwlock_trywrlock(rwlock)?;
557                this.write_scalar(result, dest)?;
558            }
559            "pthread_rwlock_unlock" => {
560                let [rwlock] = this.check_shim(abi, Conv::C, link_name, args)?;
561                this.pthread_rwlock_unlock(rwlock)?;
562                this.write_null(dest)?;
563            }
564            "pthread_rwlock_destroy" => {
565                let [rwlock] = this.check_shim(abi, Conv::C, link_name, args)?;
566                this.pthread_rwlock_destroy(rwlock)?;
567                this.write_null(dest)?;
568            }
569            "pthread_condattr_init" => {
570                let [attr] = this.check_shim(abi, Conv::C, link_name, args)?;
571                this.pthread_condattr_init(attr)?;
572                this.write_null(dest)?;
573            }
574            "pthread_condattr_setclock" => {
575                let [attr, clock_id] = this.check_shim(abi, Conv::C, link_name, args)?;
576                let result = this.pthread_condattr_setclock(attr, clock_id)?;
577                this.write_scalar(result, dest)?;
578            }
579            "pthread_condattr_getclock" => {
580                let [attr, clock_id] = this.check_shim(abi, Conv::C, link_name, args)?;
581                this.pthread_condattr_getclock(attr, clock_id)?;
582                this.write_null(dest)?;
583            }
584            "pthread_condattr_destroy" => {
585                let [attr] = this.check_shim(abi, Conv::C, link_name, args)?;
586                this.pthread_condattr_destroy(attr)?;
587                this.write_null(dest)?;
588            }
589            "pthread_cond_init" => {
590                let [cond, attr] = this.check_shim(abi, Conv::C, link_name, args)?;
591                this.pthread_cond_init(cond, attr)?;
592                this.write_null(dest)?;
593            }
594            "pthread_cond_signal" => {
595                let [cond] = this.check_shim(abi, Conv::C, link_name, args)?;
596                this.pthread_cond_signal(cond)?;
597                this.write_null(dest)?;
598            }
599            "pthread_cond_broadcast" => {
600                let [cond] = this.check_shim(abi, Conv::C, link_name, args)?;
601                this.pthread_cond_broadcast(cond)?;
602                this.write_null(dest)?;
603            }
604            "pthread_cond_wait" => {
605                let [cond, mutex] = this.check_shim(abi, Conv::C, link_name, args)?;
606                this.pthread_cond_wait(cond, mutex, dest)?;
607            }
608            "pthread_cond_timedwait" => {
609                let [cond, mutex, abstime] = this.check_shim(abi, Conv::C, link_name, args)?;
610                this.pthread_cond_timedwait(cond, mutex, abstime, dest)?;
611            }
612            "pthread_cond_destroy" => {
613                let [cond] = this.check_shim(abi, Conv::C, link_name, args)?;
614                this.pthread_cond_destroy(cond)?;
615                this.write_null(dest)?;
616            }
617
618            // Threading
619            "pthread_create" => {
620                let [thread, attr, start, arg] = this.check_shim(abi, Conv::C, link_name, args)?;
621                this.pthread_create(thread, attr, start, arg)?;
622                this.write_null(dest)?;
623            }
624            "pthread_join" => {
625                let [thread, retval] = this.check_shim(abi, Conv::C, link_name, args)?;
626                let res = this.pthread_join(thread, retval)?;
627                this.write_scalar(res, dest)?;
628            }
629            "pthread_detach" => {
630                let [thread] = this.check_shim(abi, Conv::C, link_name, args)?;
631                let res = this.pthread_detach(thread)?;
632                this.write_scalar(res, dest)?;
633            }
634            "pthread_self" => {
635                let [] = this.check_shim(abi, Conv::C, link_name, args)?;
636                let res = this.pthread_self()?;
637                this.write_scalar(res, dest)?;
638            }
639            "sched_yield" => {
640                let [] = this.check_shim(abi, Conv::C, link_name, args)?;
641                this.sched_yield()?;
642                this.write_null(dest)?;
643            }
644            "nanosleep" => {
645                let [req, rem] = this.check_shim(abi, Conv::C, link_name, args)?;
646                let result = this.nanosleep(req, rem)?;
647                this.write_scalar(result, dest)?;
648            }
649            "sched_getaffinity" => {
650                // Currently this function does not exist on all Unixes, e.g. on macOS.
651                this.check_target_os(&["linux", "freebsd", "android"], link_name)?;
652                let [pid, cpusetsize, mask] = this.check_shim(abi, Conv::C, link_name, args)?;
653                let pid = this.read_scalar(pid)?.to_u32()?;
654                let cpusetsize = this.read_target_usize(cpusetsize)?;
655                let mask = this.read_pointer(mask)?;
656
657                // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid
658                let thread_id = match pid {
659                    0 => this.active_thread(),
660                    _ =>
661                        throw_unsup_format!(
662                            "`sched_getaffinity` is only supported with a pid of 0 (indicating the current thread)"
663                        ),
664                };
665
666                // The mask is stored in chunks, and the size must be a whole number of chunks.
667                let chunk_size = CpuAffinityMask::chunk_size(this);
668
669                if this.ptr_is_null(mask)? {
670                    this.set_last_error_and_return(LibcError("EFAULT"), dest)?;
671                } else if cpusetsize == 0 || cpusetsize.checked_rem(chunk_size).unwrap() != 0 {
672                    // we only copy whole chunks of size_of::<c_ulong>()
673                    this.set_last_error_and_return(LibcError("EINVAL"), dest)?;
674                } else if let Some(cpuset) = this.machine.thread_cpu_affinity.get(&thread_id) {
675                    let cpuset = cpuset.clone();
676                    // we only copy whole chunks of size_of::<c_ulong>()
677                    let byte_count =
678                        Ord::min(cpuset.as_slice().len(), cpusetsize.try_into().unwrap());
679                    this.write_bytes_ptr(mask, cpuset.as_slice()[..byte_count].iter().copied())?;
680                    this.write_null(dest)?;
681                } else {
682                    // The thread whose ID is pid could not be found
683                    this.set_last_error_and_return(LibcError("ESRCH"), dest)?;
684                }
685            }
686            "sched_setaffinity" => {
687                // Currently this function does not exist on all Unixes, e.g. on macOS.
688                this.check_target_os(&["linux", "freebsd", "android"], link_name)?;
689                let [pid, cpusetsize, mask] = this.check_shim(abi, Conv::C, link_name, args)?;
690                let pid = this.read_scalar(pid)?.to_u32()?;
691                let cpusetsize = this.read_target_usize(cpusetsize)?;
692                let mask = this.read_pointer(mask)?;
693
694                // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid
695                let thread_id = match pid {
696                    0 => this.active_thread(),
697                    _ =>
698                        throw_unsup_format!(
699                            "`sched_setaffinity` is only supported with a pid of 0 (indicating the current thread)"
700                        ),
701                };
702
703                if this.ptr_is_null(mask)? {
704                    this.set_last_error_and_return(LibcError("EFAULT"), dest)?;
705                } else {
706                    // NOTE: cpusetsize might be smaller than `CpuAffinityMask::CPU_MASK_BYTES`.
707                    // Any unspecified bytes are treated as zero here (none of the CPUs are configured).
708                    // This is not exactly documented, so we assume that this is the behavior in practice.
709                    let bits_slice =
710                        this.read_bytes_ptr_strip_provenance(mask, Size::from_bytes(cpusetsize))?;
711                    // This ignores the bytes beyond `CpuAffinityMask::CPU_MASK_BYTES`
712                    let bits_array: [u8; CpuAffinityMask::CPU_MASK_BYTES] =
713                        std::array::from_fn(|i| bits_slice.get(i).copied().unwrap_or(0));
714                    match CpuAffinityMask::from_array(this, this.machine.num_cpus, bits_array) {
715                        Some(cpuset) => {
716                            this.machine.thread_cpu_affinity.insert(thread_id, cpuset);
717                            this.write_null(dest)?;
718                        }
719                        None => {
720                            // The intersection between the mask and the available CPUs was empty.
721                            this.set_last_error_and_return(LibcError("EINVAL"), dest)?;
722                        }
723                    }
724                }
725            }
726
727            // Miscellaneous
728            "isatty" => {
729                let [fd] = this.check_shim(abi, Conv::C, link_name, args)?;
730                let result = this.isatty(fd)?;
731                this.write_scalar(result, dest)?;
732            }
733            "pthread_atfork" => {
734                let [prepare, parent, child] = this.check_shim(abi, Conv::C, link_name, args)?;
735                this.read_pointer(prepare)?;
736                this.read_pointer(parent)?;
737                this.read_pointer(child)?;
738                // We do not support forking, so there is nothing to do here.
739                this.write_null(dest)?;
740            }
741            "getentropy" => {
742                // This function is non-standard but exists with the same signature and behavior on
743                // Linux, macOS, FreeBSD and Solaris/Illumos.
744                this.check_target_os(
745                    &["linux", "macos", "freebsd", "illumos", "solaris", "android"],
746                    link_name,
747                )?;
748                let [buf, bufsize] = this.check_shim(abi, Conv::C, link_name, args)?;
749                let buf = this.read_pointer(buf)?;
750                let bufsize = this.read_target_usize(bufsize)?;
751
752                // getentropy sets errno to EIO when the buffer size exceeds 256 bytes.
753                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html
754                // Linux: https://man7.org/linux/man-pages/man3/getentropy.3.html
755                // macOS: https://keith.github.io/xcode-man-pages/getentropy.2.html
756                // Solaris/Illumos: https://illumos.org/man/3C/getentropy
757                if bufsize > 256 {
758                    this.set_last_error_and_return(LibcError("EIO"), dest)?;
759                } else {
760                    this.gen_random(buf, bufsize)?;
761                    this.write_null(dest)?;
762                }
763            }
764
765            "strerror_r" => {
766                let [errnum, buf, buflen] = this.check_shim(abi, Conv::C, link_name, args)?;
767                let result = this.strerror_r(errnum, buf, buflen)?;
768                this.write_scalar(result, dest)?;
769            }
770
771            "getrandom" => {
772                // This function is non-standard but exists with the same signature and behavior on
773                // Linux, FreeBSD and Solaris/Illumos.
774                this.check_target_os(
775                    &["linux", "freebsd", "illumos", "solaris", "android"],
776                    link_name,
777                )?;
778                let [ptr, len, flags] = this.check_shim(abi, Conv::C, link_name, args)?;
779                let ptr = this.read_pointer(ptr)?;
780                let len = this.read_target_usize(len)?;
781                let _flags = this.read_scalar(flags)?.to_i32()?;
782                // We ignore the flags, just always use the same PRNG / host RNG.
783                this.gen_random(ptr, len)?;
784                this.write_scalar(Scalar::from_target_usize(len, this), dest)?;
785            }
786            "arc4random_buf" => {
787                // This function is non-standard but exists with the same signature and
788                // same behavior (eg never fails) on FreeBSD and Solaris/Illumos.
789                this.check_target_os(&["freebsd", "illumos", "solaris"], link_name)?;
790                let [ptr, len] = this.check_shim(abi, Conv::C, link_name, args)?;
791                let ptr = this.read_pointer(ptr)?;
792                let len = this.read_target_usize(len)?;
793                this.gen_random(ptr, len)?;
794            }
795            "_Unwind_RaiseException" => {
796                // This is not formally part of POSIX, but it is very wide-spread on POSIX systems.
797                // It was originally specified as part of the Itanium C++ ABI:
798                // https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html#base-throw.
799                // On Linux it is
800                // documented as part of the LSB:
801                // https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/baselib--unwind-raiseexception.html
802                // Basically every other UNIX uses the exact same api though. Arm also references
803                // back to the Itanium C++ ABI for the definition of `_Unwind_RaiseException` for
804                // arm64:
805                // https://github.com/ARM-software/abi-aa/blob/main/cppabi64/cppabi64.rst#toc-entry-35
806                // For arm32 they did something custom, but similar enough that the same
807                // `_Unwind_RaiseException` impl in miri should work:
808                // https://github.com/ARM-software/abi-aa/blob/main/ehabi32/ehabi32.rst
809                this.check_target_os(
810                    &["linux", "freebsd", "illumos", "solaris", "android", "macos"],
811                    link_name,
812                )?;
813                // This function looks and behaves excatly like miri_start_unwind.
814                let [payload] = this.check_shim(abi, Conv::C, link_name, args)?;
815                this.handle_miri_start_unwind(payload)?;
816                return interp_ok(EmulateItemResult::NeedsUnwind);
817            }
818            "getuid" => {
819                let [] = this.check_shim(abi, Conv::C, link_name, args)?;
820                // For now, just pretend we always have this fixed UID.
821                this.write_int(UID, dest)?;
822            }
823
824            // Incomplete shims that we "stub out" just to get pre-main initialization code to work.
825            // These shims are enabled only when the caller is in the standard library.
826            "pthread_attr_getguardsize" if this.frame_in_std() => {
827                let [_attr, guard_size] = this.check_shim(abi, Conv::C, link_name, args)?;
828                let guard_size_layout = this.libc_ty_layout("size_t");
829                let guard_size = this.deref_pointer_as(guard_size, guard_size_layout)?;
830                this.write_scalar(
831                    Scalar::from_uint(this.machine.page_size, guard_size_layout.size),
832                    &guard_size,
833                )?;
834
835                // Return success (`0`).
836                this.write_null(dest)?;
837            }
838
839            "pthread_attr_init" | "pthread_attr_destroy" if this.frame_in_std() => {
840                let [_] = this.check_shim(abi, Conv::C, link_name, args)?;
841                this.write_null(dest)?;
842            }
843            "pthread_attr_setstacksize" if this.frame_in_std() => {
844                let [_, _] = this.check_shim(abi, Conv::C, link_name, args)?;
845                this.write_null(dest)?;
846            }
847
848            "pthread_attr_getstack" if this.frame_in_std() => {
849                // We don't support "pthread_attr_setstack", so we just pretend all stacks have the same values here.
850                // Hence we can mostly ignore the input `attr_place`.
851                let [attr_place, addr_place, size_place] =
852                    this.check_shim(abi, Conv::C, link_name, args)?;
853                let _attr_place =
854                    this.deref_pointer_as(attr_place, this.libc_ty_layout("pthread_attr_t"))?;
855                let addr_place = this.deref_pointer_as(addr_place, this.machine.layouts.usize)?;
856                let size_place = this.deref_pointer_as(size_place, this.machine.layouts.usize)?;
857
858                this.write_scalar(
859                    Scalar::from_uint(this.machine.stack_addr, this.pointer_size()),
860                    &addr_place,
861                )?;
862                this.write_scalar(
863                    Scalar::from_uint(this.machine.stack_size, this.pointer_size()),
864                    &size_place,
865                )?;
866
867                // Return success (`0`).
868                this.write_null(dest)?;
869            }
870
871            "signal" | "sigaltstack" if this.frame_in_std() => {
872                let [_, _] = this.check_shim(abi, Conv::C, link_name, args)?;
873                this.write_null(dest)?;
874            }
875            "sigaction" | "mprotect" if this.frame_in_std() => {
876                let [_, _, _] = this.check_shim(abi, Conv::C, link_name, args)?;
877                this.write_null(dest)?;
878            }
879
880            "getpwuid_r" | "__posix_getpwuid_r" if this.frame_in_std() => {
881                // getpwuid_r is the standard name, __posix_getpwuid_r is used on solarish
882                let [uid, pwd, buf, buflen, result] =
883                    this.check_shim(abi, Conv::C, link_name, args)?;
884                this.check_no_isolation("`getpwuid_r`")?;
885
886                let uid = this.read_scalar(uid)?.to_u32()?;
887                let pwd = this.deref_pointer_as(pwd, this.libc_ty_layout("passwd"))?;
888                let buf = this.read_pointer(buf)?;
889                let buflen = this.read_target_usize(buflen)?;
890                let result = this.deref_pointer_as(result, this.machine.layouts.mut_raw_ptr)?;
891
892                // Must be for "us".
893                if uid != UID {
894                    throw_unsup_format!("`getpwuid_r` on other users is not supported");
895                }
896
897                // Reset all fields to `uninit` to make sure nobody reads them.
898                // (This is a std-only shim so we are okay with such hacks.)
899                this.write_uninit(&pwd)?;
900
901                // We only set the home_dir field.
902                #[allow(deprecated)]
903                let home_dir = std::env::home_dir().unwrap();
904                let (written, _) = this.write_path_to_c_str(&home_dir, buf, buflen)?;
905                let pw_dir = this.project_field_named(&pwd, "pw_dir")?;
906                this.write_pointer(buf, &pw_dir)?;
907
908                if written {
909                    this.write_pointer(pwd.ptr(), &result)?;
910                    this.write_null(dest)?;
911                } else {
912                    this.write_null(&result)?;
913                    this.write_scalar(this.eval_libc("ERANGE"), dest)?;
914                }
915            }
916
917            // Platform-specific shims
918            _ => {
919                let target_os = &*this.tcx.sess.target.os;
920                return match target_os {
921                    "android" =>
922                        android::EvalContextExt::emulate_foreign_item_inner(
923                            this, link_name, abi, args, dest,
924                        ),
925                    "freebsd" =>
926                        freebsd::EvalContextExt::emulate_foreign_item_inner(
927                            this, link_name, abi, args, dest,
928                        ),
929                    "linux" =>
930                        linux::EvalContextExt::emulate_foreign_item_inner(
931                            this, link_name, abi, args, dest,
932                        ),
933                    "macos" =>
934                        macos::EvalContextExt::emulate_foreign_item_inner(
935                            this, link_name, abi, args, dest,
936                        ),
937                    "solaris" | "illumos" =>
938                        solarish::EvalContextExt::emulate_foreign_item_inner(
939                            this, link_name, abi, args, dest,
940                        ),
941                    _ => interp_ok(EmulateItemResult::NotSupported),
942                };
943            }
944        };
945
946        interp_ok(EmulateItemResult::NeedsReturn)
947    }
948}