Skip to main content

miri/shims/unix/
foreign_items.rs

1use std::ffi::OsStr;
2use std::str;
3use std::time::Duration;
4
5use rustc_abi::{CanonAbi, Size};
6use rustc_middle::ty::Ty;
7use rustc_span::Symbol;
8use rustc_target::callconv::FnAbi;
9use rustc_target::spec::{Env, Os};
10
11use self::shims::unix::android::foreign_items as android;
12use self::shims::unix::freebsd::foreign_items as freebsd;
13use self::shims::unix::linux::foreign_items as linux;
14use self::shims::unix::macos::foreign_items as macos;
15use self::shims::unix::netbsd::foreign_items as netbsd;
16use self::shims::unix::solarish::foreign_items as solarish;
17use crate::shims::alloc::EvalContextExt as _;
18use crate::shims::cpu_affinity::EvalContextExt as _;
19use crate::shims::unix::*;
20use crate::{shim_sig, *};
21
22pub fn is_dyn_sym(name: &str, target_os: &Os) -> bool {
23    match name {
24        // Used for (std and Miri) tests.
25        "strlen" => true,
26        // `signal` is set up as a weak symbol in `init_extern_statics` (on Android) so we might as
27        // well allow it in `dlsym`.
28        "signal" => true,
29        // needed at least on macOS to avoid file-based fallback in getrandom
30        "getentropy" | "getrandom" => true,
31        // `futimens` is set up as a weak symbol in `init_extern_statics` (on Android), so we
32        // allow it here too (it exists on all our Unix targets).
33        "futimens" => true,
34        // `preadv`/`pwritev` are set up as weak symbols in `init_extern_statics` (on Android,
35        // where std uses them via `weak!` since bionic only gained them in API level 24), so
36        // we allow them here too. They do not exist on Solaris.
37        "preadv" | "pwritev" if !matches!(*target_os, Os::Solaris) => true,
38        // Give specific OSes a chance to allow their symbols.
39        _ =>
40            match *target_os {
41                Os::Android => android::is_dyn_sym(name),
42                Os::FreeBsd => freebsd::is_dyn_sym(name),
43                Os::Linux => linux::is_dyn_sym(name),
44                Os::MacOs => macos::is_dyn_sym(name),
45                Os::Solaris | Os::Illumos => solarish::is_dyn_sym(name),
46                Os::NetBsd => netbsd::is_dyn_sym(name),
47                _ => false,
48            },
49    }
50}
51
52impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
53pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
54    // Querying system information
55    fn sysconf(&mut self, val: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
56        let this = self.eval_context_mut();
57
58        let name = this.read_scalar(val)?.to_i32()?;
59        // FIXME: Which of these are POSIX, and which are GNU/Linux?
60        // At least the names seem to all also exist on macOS.
61        static SYSCONFS: &[(&str, fn(&MiriInterpCx<'_>) -> i64)] = &[
62            ("_SC_PAGESIZE", |this| this.machine.page_size.try_into().unwrap()),
63            ("_SC_PAGE_SIZE", |this| this.machine.page_size.try_into().unwrap()),
64            ("_SC_NPROCESSORS_CONF", |this| this.machine.num_cpus.into()),
65            ("_SC_NPROCESSORS_ONLN", |this| this.machine.num_cpus.into()),
66            // 512 seems to be a reasonable default. The value is not critical, in
67            // the sense that getpwuid_r takes and checks the buffer length.
68            ("_SC_GETPW_R_SIZE_MAX", |_this| 512),
69            // Miri doesn't have a fixed limit on FDs, but we may be limited in terms of how
70            // many *host* FDs we can open. Just use some arbitrary, pretty big value;
71            // this can be adjusted if it causes problems.
72            // The spec imposes a minimum of `_POSIX_OPEN_MAX` (20).
73            ("_SC_OPEN_MAX", |_this| 2_i32.pow(16).into()),
74            // Our hard-coded hostname is just 4 bytes so we don't need anything big here.
75            ("_SC_HOST_NAME_MAX", |_this| 255),
76        ];
77        for &(sysconf_name, value) in SYSCONFS {
78            let sysconf_name = this.eval_libc_i32(sysconf_name);
79            if sysconf_name == name {
80                let value = Scalar::from_target_isize(value(this), this);
81                return interp_ok(value);
82            }
83        }
84        throw_unsup_format!("unimplemented sysconf name: {}", name)
85    }
86
87    fn strerror_r(
88        &mut self,
89        errnum: &OpTy<'tcx>,
90        buf: &OpTy<'tcx>,
91        buflen: &OpTy<'tcx>,
92    ) -> InterpResult<'tcx, Scalar> {
93        let this = self.eval_context_mut();
94
95        let errnum = this.read_scalar(errnum)?;
96        let buf = this.read_pointer(buf)?;
97        let buflen = this.read_target_usize(buflen)?;
98        let error = this.try_errnum_to_io_error(errnum)?;
99        let formatted = match error {
100            Some(err) => format!("{err}"),
101            None => format!("<unknown errnum in strerror_r: {errnum}>"),
102        };
103        let (complete, _) = this.write_os_str_to_c_str(OsStr::new(&formatted), buf, buflen)?;
104        if complete {
105            interp_ok(Scalar::from_i32(0))
106        } else {
107            interp_ok(Scalar::from_i32(this.eval_libc_i32("ERANGE")))
108        }
109    }
110
111    fn emulate_foreign_item_inner(
112        &mut self,
113        link_name: Symbol,
114        abi: &FnAbi<'tcx, Ty<'tcx>>,
115        args: &[OpTy<'tcx>],
116        dest: &MPlaceTy<'tcx>,
117    ) -> InterpResult<'tcx, EmulateItemResult> {
118        let this = self.eval_context_mut();
119
120        if this.machine.communicate() {
121            // When isolation is disabled we need to check for new host I/O events before
122            // running any shimmed function. This is needed to ensure that the shim we
123            // execute has up-to-date information about host readiness (as reflected
124            // e.g. by epoll) even if the current thread never yields.
125
126            // Perform a non-blocking poll for newly available I/O events from the OS.
127            this.poll_and_unblock(Some(Duration::ZERO))?;
128        }
129
130        // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern.
131        match link_name.as_str() {
132            // Environment related shims
133            "getenv" => {
134                let [name] = this
135                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?;
136                let result = this.getenv(name)?;
137                this.write_pointer(result, dest)?;
138            }
139            "unsetenv" => {
140                let [name] = this
141                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
142                let result = this.unsetenv(name)?;
143                this.write_scalar(result, dest)?;
144            }
145            "setenv" => {
146                let [name, value, overwrite] = this.check_shim_sig(
147                    shim_sig!(extern "C" fn(*_, *_, i32) -> i32),
148                    (link_name, abi, args),
149                )?;
150                this.read_scalar(overwrite)?.to_i32()?;
151                let result = this.setenv(name, value)?;
152                this.write_scalar(result, dest)?;
153            }
154            "getcwd" => {
155                // FIXME: This does not have a direct test (#3179).
156                let [buf, size] = this.check_shim_sig(
157                    shim_sig!(extern "C" fn(*_, usize) -> *_),
158                    (link_name, abi, args),
159                )?;
160                let result = this.getcwd(buf, size)?;
161                this.write_pointer(result, dest)?;
162            }
163            "gethostname" => {
164                let [name, len] = this.check_shim_sig(
165                    shim_sig!(extern "C" fn(*_, usize) -> i32),
166                    (link_name, abi, args),
167                )?;
168                let result = this.gethostname(name, len)?;
169                this.write_scalar(result, dest)?;
170            }
171            "chdir" => {
172                // FIXME: This does not have a direct test (#3179).
173                let [path] = this
174                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
175                let result = this.chdir(path)?;
176                this.write_scalar(result, dest)?;
177            }
178            "getpid" => {
179                let [] = this.check_shim_sig(
180                    shim_sig!(extern "C" fn() -> libc::pid_t),
181                    (link_name, abi, args),
182                )?;
183                let result = this.getpid()?;
184                this.write_scalar(result, dest)?;
185            }
186            "uname" => {
187                // Not all Unixes have the `uname` symbol, e.g. FreeBSD does not.
188                this.check_target_os(
189                    &[Os::Linux, Os::Android, Os::MacOs, Os::Solaris, Os::Illumos],
190                    link_name,
191                )?;
192
193                let [uname] = this
194                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
195                let result = this.uname(uname, None)?;
196                this.write_scalar(result, dest)?;
197            }
198            "sysconf" => {
199                let [val] = this.check_shim_sig(
200                    shim_sig!(extern "C" fn(i32) -> isize),
201                    (link_name, abi, args),
202                )?;
203                let result = this.sysconf(val)?;
204                this.write_scalar(result, dest)?;
205            }
206            // File descriptors
207            "read" => {
208                let [fd, buf, count] = this.check_shim_sig(
209                    shim_sig!(extern "C" fn(i32, *_, usize) -> isize),
210                    (link_name, abi, args),
211                )?;
212                let fd = this.read_scalar(fd)?.to_i32()?;
213                let buf = this.read_pointer(buf)?;
214                let count = this.read_target_usize(count)?;
215                this.read(fd, buf, count, None, dest)?;
216            }
217            "write" => {
218                let [fd, buf, n] = this.check_shim_sig(
219                    shim_sig!(extern "C" fn(i32, *_, usize) -> isize),
220                    (link_name, abi, args),
221                )?;
222                let fd = this.read_scalar(fd)?.to_i32()?;
223                let buf = this.read_pointer(buf)?;
224                let count = this.read_target_usize(n)?;
225                trace!("Called write({:?}, {:?}, {:?})", fd, buf, count);
226                this.write(fd, buf, count, None, dest)?;
227            }
228            "readv" => {
229                let [fd, iov, iovcnt] = this.check_shim_sig(
230                    shim_sig!(extern "C" fn(i32, *_, i32) -> isize),
231                    (link_name, abi, args),
232                )?;
233                this.readv(fd, iov, iovcnt, None, dest)?;
234            }
235            "writev" => {
236                let [fd, iov, iovcnt] = this.check_shim_sig(
237                    shim_sig!(extern "C" fn(i32, *_, i32) -> isize),
238                    (link_name, abi, args),
239                )?;
240                this.writev(fd, iov, iovcnt, None, dest)?;
241            }
242            "pread" => {
243                let [fd, buf, count, offset] = this.check_shim_sig(
244                    shim_sig!(extern "C" fn(i32, *_, usize, libc::off_t) -> isize),
245                    (link_name, abi, args),
246                )?;
247                let fd = this.read_scalar(fd)?.to_i32()?;
248                let buf = this.read_pointer(buf)?;
249                let count = this.read_target_usize(count)?;
250                let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?;
251                this.read(fd, buf, count, Some(offset), dest)?;
252            }
253            "pwrite" => {
254                let [fd, buf, n, offset] = this.check_shim_sig(
255                    shim_sig!(extern "C" fn(i32, *_, usize, libc::off_t) -> isize),
256                    (link_name, abi, args),
257                )?;
258                let fd = this.read_scalar(fd)?.to_i32()?;
259                let buf = this.read_pointer(buf)?;
260                let count = this.read_target_usize(n)?;
261                let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?;
262                trace!("Called pwrite({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset);
263                this.write(fd, buf, count, Some(offset), dest)?;
264            }
265            "preadv" => {
266                let [fd, iov, iovcnt, offset] = this.check_shim_sig(
267                    shim_sig!(extern "C" fn(i32, *_, i32, libc::off_t) -> isize),
268                    (link_name, abi, args),
269                )?;
270                this.readv(fd, iov, iovcnt, Some(offset), dest)?;
271            }
272            "pwritev" => {
273                let [fd, iov, iovcnt, offset] = this.check_shim_sig(
274                    shim_sig!(extern "C" fn(i32, *_, i32, libc::off_t) -> isize),
275                    (link_name, abi, args),
276                )?;
277                this.writev(fd, iov, iovcnt, Some(offset), dest)?;
278            }
279
280            "close" => {
281                let [fd] = this
282                    .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?;
283                let fd = this.read_scalar(fd)?.to_i32()?;
284                let result = this.close(fd)?;
285                this.write_scalar(result, dest)?;
286            }
287            "fcntl" => {
288                let ([fd_num, cmd], varargs) = this.check_shim_sig_variadic(
289                    shim_sig!(extern "C" fn(i32, i32, ...) -> i32),
290                    (link_name, abi, args),
291                )?;
292                let result = this.fcntl(fd_num, cmd, varargs)?;
293                this.write_scalar(result, dest)?;
294            }
295            "dup" => {
296                let [old_fd] = this
297                    .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?;
298                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
299                let new_fd = this.dup(old_fd)?;
300                this.write_scalar(new_fd, dest)?;
301            }
302            "dup2" => {
303                let [old_fd, new_fd] = this.check_shim_sig(
304                    shim_sig!(extern "C" fn(i32, i32) -> i32),
305                    (link_name, abi, args),
306                )?;
307                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
308                let new_fd = this.read_scalar(new_fd)?.to_i32()?;
309                let result = this.dup2(old_fd, new_fd)?;
310                this.write_scalar(result, dest)?;
311            }
312            "flock" => {
313                // Currently this function does not exist on all Unixes, e.g. on Solaris.
314                this.check_target_os(
315                    &[Os::Linux, Os::Android, Os::FreeBsd, Os::MacOs, Os::Illumos],
316                    link_name,
317                )?;
318
319                let [fd, op] = this.check_shim_sig(
320                    shim_sig!(extern "C" fn(i32, i32) -> i32),
321                    (link_name, abi, args),
322                )?;
323                let fd = this.read_scalar(fd)?.to_i32()?;
324                let op = this.read_scalar(op)?.to_i32()?;
325                let result = this.flock(fd, op)?;
326                this.write_scalar(result, dest)?;
327            }
328            "ioctl" => {
329                // The type of `op` depends on the libc. :(
330                // glibc, BSD use `unsigned long`, the rest uses `int`.
331                let op_is_ulong = match this.tcx.sess.target.os {
332                    Os::FreeBsd | Os::NetBsd | Os::MacOs => true,
333                    Os::Linux if this.tcx.sess.target.env == Env::Gnu => true,
334                    _ => false,
335                };
336                let ([fd, op], varargs) = this.check_shim_sig_variadic(
337                    if op_is_ulong {
338                        shim_sig!(extern "C" fn(i32, usize, ...) -> i32)
339                    } else {
340                        shim_sig!(extern "C" fn(i32, i32, ...) -> i32)
341                    },
342                    (link_name, abi, args),
343                )?;
344                let result = this.ioctl(fd, op, varargs)?;
345                this.write_scalar(result, dest)?;
346            }
347
348            // File and file system access
349            "open" => {
350                // `open` is variadic, the third argument is only present when the second argument
351                // has O_CREAT (or on linux O_TMPFILE, but miri doesn't support that) set
352                let ([path_raw, flag], varargs) = this.check_shim_sig_variadic(
353                    shim_sig!(extern "C" fn(*_, i32, ...) -> i32),
354                    (link_name, abi, args),
355                )?;
356                let result = this.open(path_raw, flag, varargs)?;
357                this.write_scalar(result, dest)?;
358            }
359            "unlink" => {
360                // FIXME: This does not have a direct test (#3179).
361                let [path] = this
362                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
363                let result = this.unlink(path)?;
364                this.write_scalar(result, dest)?;
365            }
366            "symlink" => {
367                // FIXME: This does not have a direct test (#3179).
368                let [target, linkpath] = this.check_shim_sig(
369                    shim_sig!(extern "C" fn(*_, *_) -> i32),
370                    (link_name, abi, args),
371                )?;
372                let result = this.symlink(target, linkpath)?;
373                this.write_scalar(result, dest)?;
374            }
375            "linkat" => {
376                let [oldfd, oldpath, newfd, newpath, flags] = this.check_shim_sig(
377                    shim_sig!(extern "C" fn(i32, *_, i32, *_, i32) -> i32),
378                    (link_name, abi, args),
379                )?;
380                let result = this.linkat(oldfd, oldpath, newfd, newpath, flags)?;
381                this.write_scalar(result, dest)?;
382            }
383            "fstat" => {
384                let [fd, buf] = this.check_shim_sig(
385                    shim_sig!(extern "C" fn(i32, *_) -> i32),
386                    (link_name, abi, args),
387                )?;
388                let result = this.fstat(fd, buf)?;
389                this.write_scalar(result, dest)?;
390            }
391            "lstat" => {
392                let [path, buf] = this.check_shim_sig(
393                    shim_sig!(extern "C" fn(*_, *_) -> i32),
394                    (link_name, abi, args),
395                )?;
396                let result = this.lstat(path, buf)?;
397                this.write_scalar(result, dest)?;
398            }
399            "stat" => {
400                let [path, buf] = this.check_shim_sig(
401                    shim_sig!(extern "C" fn(*_, *_) -> i32),
402                    (link_name, abi, args),
403                )?;
404                let result = this.stat(path, buf)?;
405                this.write_scalar(result, dest)?;
406            }
407            "chmod" => {
408                let [path, mode] = this.check_shim_sig(
409                    shim_sig!(extern "C" fn(*_, libc::mode_t) -> i32),
410                    (link_name, abi, args),
411                )?;
412                let result = this.chmod(path, mode)?;
413                this.write_scalar(result, dest)?;
414            }
415            "fchmod" => {
416                let [fd, mode] = this.check_shim_sig(
417                    shim_sig!(extern "C" fn(i32, libc::mode_t) -> i32),
418                    (link_name, abi, args),
419                )?;
420                let result = this.fchmod(fd, mode)?;
421                this.write_scalar(result, dest)?;
422            }
423            "rename" => {
424                // FIXME: This does not have a direct test (#3179).
425                let [oldpath, newpath] = this.check_shim_sig(
426                    shim_sig!(extern "C" fn(*_, *_) -> i32),
427                    (link_name, abi, args),
428                )?;
429                let result = this.rename(oldpath, newpath)?;
430                this.write_scalar(result, dest)?;
431            }
432            "mkdir" => {
433                // FIXME: This does not have a direct test (#3179).
434                let [path, mode] = this.check_shim_sig(
435                    shim_sig!(extern "C" fn(*_, libc::mode_t) -> i32),
436                    (link_name, abi, args),
437                )?;
438                let result = this.mkdir(path, mode)?;
439                this.write_scalar(result, dest)?;
440            }
441            "rmdir" => {
442                // FIXME: This does not have a direct test (#3179).
443                let [path] = this
444                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
445                let result = this.rmdir(path)?;
446                this.write_scalar(result, dest)?;
447            }
448            "opendir" => {
449                let [name] = this
450                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?;
451                let result = this.opendir(name)?;
452                this.write_scalar(result, dest)?;
453            }
454            "closedir" => {
455                let [dirp] = this
456                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
457                let result = this.closedir(dirp)?;
458                this.write_scalar(result, dest)?;
459            }
460            "readdir" => {
461                let [dirp] = this
462                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?;
463                this.readdir(dirp, dest)?;
464            }
465            "dirfd" => {
466                let [dirp] = this
467                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
468                this.dirfd(dirp, dest)?;
469            }
470            "lseek" => {
471                // FIXME: This does not have a direct test (#3179).
472                let [fd, offset, whence] = this.check_shim_sig(
473                    shim_sig!(extern "C" fn(i32, libc::off_t, i32) -> libc::off_t),
474                    (link_name, abi, args),
475                )?;
476                let fd = this.read_scalar(fd)?.to_i32()?;
477                let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?;
478                let whence = this.read_scalar(whence)?.to_i32()?;
479                this.lseek(fd, offset, whence, dest)?;
480            }
481            "ftruncate" => {
482                let [fd, length] = this.check_shim_sig(
483                    shim_sig!(extern "C" fn(i32, libc::off_t) -> i32),
484                    (link_name, abi, args),
485                )?;
486                let fd = this.read_scalar(fd)?.to_i32()?;
487                let length = this.read_scalar(length)?.to_int(length.layout.size)?;
488                let result = this.ftruncate64(fd, length)?;
489                this.write_scalar(result, dest)?;
490            }
491            "fsync" => {
492                // FIXME: This does not have a direct test (#3179).
493                let [fd] = this
494                    .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?;
495                let result = this.fsync(fd)?;
496                this.write_scalar(result, dest)?;
497            }
498            "fdatasync" => {
499                // FIXME: This does not have a direct test (#3179).
500                let [fd] = this
501                    .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?;
502                let result = this.fdatasync(fd)?;
503                this.write_scalar(result, dest)?;
504            }
505            "futimens" => {
506                let [fd, times] = this.check_shim_sig(
507                    shim_sig!(extern "C" fn(i32, *_) -> i32),
508                    (link_name, abi, args),
509                )?;
510                let result = this.futimens(fd, times)?;
511                this.write_scalar(result, dest)?;
512            }
513            "readlink" => {
514                let [pathname, buf, bufsize] = this.check_shim_sig(
515                    shim_sig!(extern "C" fn(*_, *_, usize) -> isize),
516                    (link_name, abi, args),
517                )?;
518                let result = this.readlink(pathname, buf, bufsize)?;
519                this.write_scalar(Scalar::from_target_isize(result, this), dest)?;
520            }
521            "posix_fadvise" => {
522                let [fd, offset, len, advice] = this.check_shim_sig(
523                    shim_sig!(extern "C" fn(i32, libc::off_t, libc::off_t, i32) -> i32),
524                    (link_name, abi, args),
525                )?;
526                this.read_scalar(fd)?.to_i32()?;
527                this.read_scalar(offset)?.to_int(offset.layout.size)?;
528                this.read_scalar(len)?.to_int(len.layout.size)?;
529                this.read_scalar(advice)?.to_i32()?;
530                // fadvise is only informational, we can ignore it.
531                this.write_null(dest)?;
532            }
533
534            "posix_fallocate" => {
535                // posix_fallocate is not supported by macos.
536                this.check_target_os(
537                    &[Os::Linux, Os::FreeBsd, Os::Solaris, Os::Illumos, Os::Android],
538                    link_name,
539                )?;
540
541                let [fd, offset, len] = this.check_shim_sig(
542                    shim_sig!(extern "C" fn(i32, libc::off_t, libc::off_t) -> i32),
543                    (link_name, abi, args),
544                )?;
545
546                let fd = this.read_scalar(fd)?.to_i32()?;
547                // We don't support platforms which have libc::off_t bigger than 64 bits.
548                let offset =
549                    i64::try_from(this.read_scalar(offset)?.to_int(offset.layout.size)?).unwrap();
550                let len = i64::try_from(this.read_scalar(len)?.to_int(len.layout.size)?).unwrap();
551
552                let result = this.posix_fallocate(fd, offset, len)?;
553                this.write_scalar(result, dest)?;
554            }
555
556            "realpath" => {
557                let [path, resolved_path] = this.check_shim_sig(
558                    shim_sig!(extern "C" fn(*_, *_) -> *_),
559                    (link_name, abi, args),
560                )?;
561                let result = this.realpath(path, resolved_path)?;
562                this.write_scalar(result, dest)?;
563            }
564            "mkstemp" => {
565                let [template] = this
566                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
567                let result = this.mkstemp(template)?;
568                this.write_scalar(result, dest)?;
569            }
570
571            // Poll
572            "poll" => {
573                let [fds, nfds, timeout] = this.check_shim_sig(
574                    shim_sig!(extern "C" fn(*_, libc::nfds_t, i32) -> i32),
575                    (link_name, abi, args),
576                )?;
577                this.poll(fds, nfds, timeout, dest)?;
578            }
579
580            // Sockets and pipes
581            "socketpair" => {
582                let [domain, type_, protocol, sv] = this.check_shim_sig(
583                    shim_sig!(extern "C" fn(i32, i32, i32, *_) -> i32),
584                    (link_name, abi, args),
585                )?;
586                let result = this.socketpair(domain, type_, protocol, sv)?;
587                this.write_scalar(result, dest)?;
588            }
589            "pipe" => {
590                let [pipefd] = this
591                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
592                let result = this.pipe2(pipefd, /*flags*/ None)?;
593                this.write_scalar(result, dest)?;
594            }
595            "pipe2" => {
596                // Currently this function does not exist on all Unixes, e.g. on macOS.
597                this.check_target_os(
598                    &[Os::Linux, Os::Android, Os::FreeBsd, Os::Solaris, Os::Illumos],
599                    link_name,
600                )?;
601
602                let [pipefd, flags] = this.check_shim_sig(
603                    shim_sig!(extern "C" fn(*_, i32) -> i32),
604                    (link_name, abi, args),
605                )?;
606                let result = this.pipe2(pipefd, Some(flags))?;
607                this.write_scalar(result, dest)?;
608            }
609
610            // Network sockets
611            "socket" => {
612                let [domain, type_, protocol] = this.check_shim_sig(
613                    shim_sig!(extern "C" fn(i32, i32, i32) -> i32),
614                    (link_name, abi, args),
615                )?;
616                let result = this.socket(domain, type_, protocol)?;
617                this.write_scalar(result, dest)?;
618            }
619            "bind" => {
620                let [socket, address, address_len] = this.check_shim_sig(
621                    shim_sig!(extern "C" fn(i32, *_, libc::socklen_t) -> i32),
622                    (link_name, abi, args),
623                )?;
624                let result = this.bind(socket, address, address_len)?;
625                this.write_scalar(result, dest)?;
626            }
627            "listen" => {
628                let [socket, backlog] = this.check_shim_sig(
629                    shim_sig!(extern "C" fn(i32, i32) -> i32),
630                    (link_name, abi, args),
631                )?;
632                let result = this.listen(socket, backlog)?;
633                this.write_scalar(result, dest)?;
634            }
635            "accept" => {
636                let [socket, address, address_len] = this.check_shim_sig(
637                    shim_sig!(extern "C" fn(i32, *_, *_) -> i32),
638                    (link_name, abi, args),
639                )?;
640                this.accept4(socket, address, address_len, /* flags */ None, dest)?;
641            }
642            "accept4" => {
643                let [socket, address, address_len, flags] = this.check_shim_sig(
644                    shim_sig!(extern "C" fn(i32, *_, *_, i32) -> i32),
645                    (link_name, abi, args),
646                )?;
647                this.accept4(socket, address, address_len, Some(flags), dest)?;
648            }
649            "connect" => {
650                let [socket, address, address_len] = this.check_shim_sig(
651                    shim_sig!(extern "C" fn(i32, *_, libc::socklen_t) -> i32),
652                    (link_name, abi, args),
653                )?;
654                this.connect(socket, address, address_len, dest)?;
655            }
656            "send" => {
657                let [socket, buffer, length, flags] = this.check_shim_sig(
658                    shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32) -> libc::ssize_t),
659                    (link_name, abi, args),
660                )?;
661                this.send(socket, buffer, length, flags, dest)?;
662            }
663            "recv" => {
664                let [socket, buffer, length, flags] = this.check_shim_sig(
665                    shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32) -> libc::ssize_t),
666                    (link_name, abi, args),
667                )?;
668                this.recv(socket, buffer, length, flags, dest)?;
669            }
670            "setsockopt" => {
671                let [socket, level, option_name, option_value, option_len] = this.check_shim_sig(
672                    shim_sig!(extern "C" fn(i32, i32, i32, *_, libc::socklen_t) -> i32),
673                    (link_name, abi, args),
674                )?;
675                let result =
676                    this.setsockopt(socket, level, option_name, option_value, option_len)?;
677                this.write_scalar(result, dest)?;
678            }
679            "getsockopt" => {
680                let [socket, level, option_name, option_value, option_len] = this.check_shim_sig(
681                    shim_sig!(extern "C" fn(i32, i32, i32, *_, *_) -> i32),
682                    (link_name, abi, args),
683                )?;
684                let result =
685                    this.getsockopt(socket, level, option_name, option_value, option_len)?;
686                this.write_scalar(result, dest)?;
687            }
688            "getsockname" => {
689                let [socket, address, address_len] = this.check_shim_sig(
690                    shim_sig!(extern "C" fn(i32, *_, *_) -> i32),
691                    (link_name, abi, args),
692                )?;
693                let result = this.getsockname(socket, address, address_len)?;
694                this.write_scalar(result, dest)?;
695            }
696            "getpeername" => {
697                let [socket, address, address_len] = this.check_shim_sig(
698                    shim_sig!(extern "C" fn(i32, *_, *_) -> i32),
699                    (link_name, abi, args),
700                )?;
701                this.getpeername(socket, address, address_len, dest)?;
702            }
703            "shutdown" => {
704                let [sockfd, how] = this.check_shim_sig(
705                    shim_sig!(extern "C" fn(i32, i32) -> i32),
706                    (link_name, abi, args),
707                )?;
708                let result = this.shutdown(sockfd, how)?;
709                this.write_scalar(result, dest)?;
710            }
711            "getaddrinfo" => {
712                let [node, service, hints, res] = this.check_shim_sig(
713                    shim_sig!(extern "C" fn(*_, *_, *_, *_) -> i32),
714                    (link_name, abi, args),
715                )?;
716                let result = this.getaddrinfo(node, service, hints, res)?;
717                this.write_scalar(result, dest)?;
718            }
719            "freeaddrinfo" => {
720                let [res] = this
721                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> ()), (link_name, abi, args))?;
722                this.freeaddrinfo(res)?;
723            }
724
725            // Time
726            "gettimeofday" => {
727                let [tv, tz] = this.check_shim_sig(
728                    shim_sig!(extern "C" fn(*_, *_) -> i32),
729                    (link_name, abi, args),
730                )?;
731                let result = this.gettimeofday(tv, tz)?;
732                this.write_scalar(result, dest)?;
733            }
734            "localtime_r" => {
735                let [timep, result_op] = this.check_shim_sig(
736                    shim_sig!(extern "C" fn(*_, *_) -> *_),
737                    (link_name, abi, args),
738                )?;
739                let result = this.localtime_r(timep, result_op)?;
740                this.write_pointer(result, dest)?;
741            }
742            "clock_gettime" => {
743                let [clk_id, tp] = this.check_shim_sig(
744                    shim_sig!(extern "C" fn(libc::clockid_t, *_) -> i32),
745                    (link_name, abi, args),
746                )?;
747                this.clock_gettime(clk_id, tp, dest)?;
748            }
749
750            // Allocation
751            "posix_memalign" => {
752                let [memptr, align, size] = this.check_shim_sig(
753                    shim_sig!(extern "C" fn(*_, usize, usize) -> i32),
754                    (link_name, abi, args),
755                )?;
756                let result = this.posix_memalign(memptr, align, size)?;
757                this.write_scalar(result, dest)?;
758            }
759
760            "mmap" => {
761                let [addr, length, prot, flags, fd, offset] = this.check_shim_sig(
762                    shim_sig!(extern "C" fn(*_, usize, i32, i32, i32, libc::off_t) -> *_),
763                    (link_name, abi, args),
764                )?;
765                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
766                let ptr = this.mmap(addr, length, prot, flags, fd, offset)?;
767                this.write_scalar(ptr, dest)?;
768            }
769            "munmap" => {
770                let [addr, length] = this.check_shim_sig(
771                    shim_sig!(extern "C" fn(*_, usize) -> i32),
772                    (link_name, abi, args),
773                )?;
774                let result = this.munmap(addr, length)?;
775                this.write_scalar(result, dest)?;
776            }
777            "mprotect" => {
778                let [addr, length, prot] = this.check_shim_sig(
779                    shim_sig!(extern "C" fn(*_, usize, i32) -> i32),
780                    (link_name, abi, args),
781                )?;
782                let result = this.mprotect(addr, length, prot)?;
783                this.write_scalar(result, dest)?;
784            }
785            "madvise" => {
786                let [addr, length, advice] = this.check_shim_sig(
787                    shim_sig!(extern "C" fn(*_, usize, i32) -> i32),
788                    (link_name, abi, args),
789                )?;
790                let result = this.madvise(addr, length, advice)?;
791                this.write_scalar(result, dest)?;
792            }
793
794            "reallocarray" => {
795                // Currently this function does not exist on all Unixes, e.g. on macOS.
796                this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?;
797
798                let [ptr, nmemb, size] = this.check_shim_sig(
799                    shim_sig!(extern "C" fn(*_, usize, usize) -> *_),
800                    (link_name, abi, args),
801                )?;
802                let ptr = this.read_pointer(ptr)?;
803                let nmemb = this.read_target_usize(nmemb)?;
804                let size = this.read_target_usize(size)?;
805                // reallocarray checks a possible overflow and returns ENOMEM
806                // if that happens.
807                //
808                // Linux: https://www.unix.com/man-page/linux/3/reallocarray/
809                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=reallocarray
810                match this.compute_size_in_bytes(Size::from_bytes(size), nmemb) {
811                    None => {
812                        this.set_last_error(LibcError("ENOMEM"))?;
813                        this.write_null(dest)?;
814                    }
815                    Some(len) => {
816                        let res = this.realloc(ptr, len.bytes())?;
817                        this.write_pointer(res, dest)?;
818                    }
819                }
820            }
821            "aligned_alloc" => {
822                // This is a C11 function, we assume all Unixes have it.
823                // (MSVC explicitly does not support this.)
824                let [align, size] = this.check_shim_sig(
825                    shim_sig!(extern "C" fn(usize, usize) -> *_),
826                    (link_name, abi, args),
827                )?;
828                let res = this.aligned_alloc(align, size)?;
829                this.write_pointer(res, dest)?;
830            }
831
832            // Dynamic symbol loading
833            "dlsym" => {
834                let [handle, symbol] = this.check_shim_sig(
835                    shim_sig!(extern "C" fn(*_, *_) -> *_),
836                    (link_name, abi, args),
837                )?;
838                this.read_target_usize(handle)?;
839                let symbol = this.read_pointer(symbol)?;
840                let name = this.read_c_str(symbol)?;
841                let Ok(name) = str::from_utf8(name) else {
842                    throw_unsup_format!("dlsym: non UTF-8 symbol name not supported")
843                };
844                if is_dyn_sym(name, &this.tcx.sess.target.os) {
845                    let ptr = this.fn_ptr(FnVal::Other(DynSym::from_str(name)));
846                    this.write_pointer(ptr, dest)?;
847                } else if let Some(&ptr) = this.machine.extern_statics.get(&Symbol::intern(name)) {
848                    this.write_pointer(ptr, dest)?;
849                } else {
850                    this.write_null(dest)?;
851                }
852            }
853
854            // Thread-local storage
855            "pthread_key_create" => {
856                let [key, dtor] = this.check_shim_sig(
857                    shim_sig!(extern "C" fn(*_, fn(..) -> _) -> i32),
858                    (link_name, abi, args),
859                )?;
860                let key_place = this.deref_pointer_as(key, this.libc_ty_layout("pthread_key_t"))?;
861                let dtor = this.read_pointer(dtor)?;
862
863                // Extract the function type out of the signature (that seems easier than constructing it ourselves).
864                let dtor = if !this.ptr_is_null(dtor)? {
865                    Some((
866                        this.get_ptr_fn(dtor)?.as_instance()?,
867                        this.machine.current_user_relevant_span(),
868                    ))
869                } else {
870                    None
871                };
872
873                // Figure out how large a pthread TLS key actually is.
874                // To this end, deref the argument type. This is `libc::pthread_key_t`.
875                let key_type = key.layout.ty
876                    .builtin_deref(true)
877                    .ok_or_else(|| err_ub_format!(
878                        "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
879                    ))?;
880                let key_layout = this.layout_of(key_type)?;
881
882                // Create key and write it into the memory where `key_ptr` wants it.
883                let key = this.machine.tls.create_tls_key(dtor, key_layout.size)?;
884                this.write_scalar(Scalar::from_uint(key, key_layout.size), &key_place)?;
885
886                // Return success (`0`).
887                this.write_null(dest)?;
888            }
889            "pthread_key_delete" => {
890                // FIXME: This does not have a direct test (#3179).
891                let [key] = this.check_shim_sig(
892                    shim_sig!(extern "C" fn(libc::pthread_key_t) -> i32),
893                    (link_name, abi, args),
894                )?;
895                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
896                this.machine.tls.delete_tls_key(key)?;
897                // Return success (0)
898                this.write_null(dest)?;
899            }
900            "pthread_getspecific" => {
901                // FIXME: This does not have a direct test (#3179).
902                let [key] = this.check_shim_sig(
903                    shim_sig!(extern "C" fn(libc::pthread_key_t) -> *_),
904                    (link_name, abi, args),
905                )?;
906                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
907                let active_thread = this.active_thread();
908                let ptr = this.machine.tls.load_tls(key, active_thread, this)?;
909                this.write_scalar(ptr, dest)?;
910            }
911            "pthread_setspecific" => {
912                let [key, new_ptr] = this.check_shim_sig(
913                    shim_sig!(extern "C" fn(libc::pthread_key_t, *_) -> i32),
914                    (link_name, abi, args),
915                )?;
916                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
917                let active_thread = this.active_thread();
918                let new_data = this.read_scalar(new_ptr)?;
919                this.machine.tls.store_tls(key, active_thread, new_data, &*this.tcx)?;
920
921                // Return success (`0`).
922                this.write_null(dest)?;
923            }
924
925            // Synchronization primitives
926            "pthread_mutexattr_init" => {
927                let [attr] = this
928                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
929                this.pthread_mutexattr_init(attr)?;
930                this.write_null(dest)?;
931            }
932            "pthread_mutexattr_settype" => {
933                let [attr, kind] = this.check_shim_sig(
934                    shim_sig!(extern "C" fn(*_, i32) -> i32),
935                    (link_name, abi, args),
936                )?;
937                let result = this.pthread_mutexattr_settype(attr, kind)?;
938                this.write_scalar(result, dest)?;
939            }
940            "pthread_mutexattr_destroy" => {
941                let [attr] = this
942                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
943                this.pthread_mutexattr_destroy(attr)?;
944                this.write_null(dest)?;
945            }
946            "pthread_mutex_init" => {
947                let [mutex, attr] = this.check_shim_sig(
948                    shim_sig!(extern "C" fn(*_, *_) -> i32),
949                    (link_name, abi, args),
950                )?;
951                this.pthread_mutex_init(mutex, attr)?;
952                this.write_null(dest)?;
953            }
954            "pthread_mutex_lock" => {
955                let [mutex] = this
956                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
957                this.pthread_mutex_lock(mutex, dest)?;
958            }
959            "pthread_mutex_trylock" => {
960                let [mutex] = this
961                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
962                let result = this.pthread_mutex_trylock(mutex)?;
963                this.write_scalar(result, dest)?;
964            }
965            "pthread_mutex_unlock" => {
966                let [mutex] = this
967                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
968                let result = this.pthread_mutex_unlock(mutex)?;
969                this.write_scalar(result, dest)?;
970            }
971            "pthread_mutex_destroy" => {
972                let [mutex] = this
973                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
974                this.pthread_mutex_destroy(mutex)?;
975                this.write_int(0, dest)?;
976            }
977            "pthread_rwlock_rdlock" => {
978                let [rwlock] = this
979                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
980                this.pthread_rwlock_rdlock(rwlock, dest)?;
981            }
982            "pthread_rwlock_tryrdlock" => {
983                let [rwlock] = this
984                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
985                let result = this.pthread_rwlock_tryrdlock(rwlock)?;
986                this.write_scalar(result, dest)?;
987            }
988            "pthread_rwlock_wrlock" => {
989                let [rwlock] = this
990                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
991                this.pthread_rwlock_wrlock(rwlock, dest)?;
992            }
993            "pthread_rwlock_trywrlock" => {
994                let [rwlock] = this
995                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
996                let result = this.pthread_rwlock_trywrlock(rwlock)?;
997                this.write_scalar(result, dest)?;
998            }
999            "pthread_rwlock_unlock" => {
1000                let [rwlock] = this
1001                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
1002                this.pthread_rwlock_unlock(rwlock)?;
1003                this.write_null(dest)?;
1004            }
1005            "pthread_rwlock_destroy" => {
1006                let [rwlock] = this
1007                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
1008                this.pthread_rwlock_destroy(rwlock)?;
1009                this.write_null(dest)?;
1010            }
1011            "pthread_condattr_init" => {
1012                let [attr] = this
1013                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
1014                this.pthread_condattr_init(attr)?;
1015                this.write_null(dest)?;
1016            }
1017            "pthread_condattr_setclock" => {
1018                let [attr, clock_id] = this.check_shim_sig(
1019                    shim_sig!(extern "C" fn(*_, i32) -> i32),
1020                    (link_name, abi, args),
1021                )?;
1022                let result = this.pthread_condattr_setclock(attr, clock_id)?;
1023                this.write_scalar(result, dest)?;
1024            }
1025            "pthread_condattr_getclock" => {
1026                let [attr, clock_id] = this.check_shim_sig(
1027                    shim_sig!(extern "C" fn(*_, *_) -> i32),
1028                    (link_name, abi, args),
1029                )?;
1030                this.pthread_condattr_getclock(attr, clock_id)?;
1031                this.write_null(dest)?;
1032            }
1033            "pthread_condattr_destroy" => {
1034                let [attr] = this
1035                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
1036                this.pthread_condattr_destroy(attr)?;
1037                this.write_null(dest)?;
1038            }
1039            "pthread_cond_init" => {
1040                let [cond, attr] = this.check_shim_sig(
1041                    shim_sig!(extern "C" fn(*_, *_) -> i32),
1042                    (link_name, abi, args),
1043                )?;
1044                this.pthread_cond_init(cond, attr)?;
1045                this.write_null(dest)?;
1046            }
1047            "pthread_cond_signal" => {
1048                let [cond] = this
1049                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
1050                this.pthread_cond_signal(cond)?;
1051                this.write_null(dest)?;
1052            }
1053            "pthread_cond_broadcast" => {
1054                let [cond] = this
1055                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
1056                this.pthread_cond_broadcast(cond)?;
1057                this.write_null(dest)?;
1058            }
1059            "pthread_cond_wait" => {
1060                let [cond, mutex] = this.check_shim_sig(
1061                    shim_sig!(extern "C" fn(*_, *_) -> i32),
1062                    (link_name, abi, args),
1063                )?;
1064                this.pthread_cond_wait(cond, mutex, dest)?;
1065            }
1066            "pthread_cond_timedwait" => {
1067                let [cond, mutex, abstime] = this.check_shim_sig(
1068                    shim_sig!(extern "C" fn(*_, *_, *_) -> i32),
1069                    (link_name, abi, args),
1070                )?;
1071                this.pthread_cond_timedwait(
1072                    cond, mutex, abstime, dest, /* macos_relative_np */ false,
1073                )?;
1074            }
1075            "pthread_cond_destroy" => {
1076                let [cond] = this
1077                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?;
1078                this.pthread_cond_destroy(cond)?;
1079                this.write_null(dest)?;
1080            }
1081
1082            // Threading
1083            "pthread_create" => {
1084                let [thread, attr, start, arg] = this.check_shim_sig(
1085                    shim_sig!(extern "C" fn(*_, *_, fn(..) -> _, *_) -> i32),
1086                    (link_name, abi, args),
1087                )?;
1088                this.pthread_create(thread, attr, start, arg)?;
1089                this.write_null(dest)?;
1090            }
1091            "pthread_join" => {
1092                let [thread, retval] = this.check_shim_sig(
1093                    shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32),
1094                    (link_name, abi, args),
1095                )?;
1096                this.pthread_join(thread, retval, dest)?;
1097            }
1098            "pthread_detach" => {
1099                let [thread] = this.check_shim_sig(
1100                    shim_sig!(extern "C" fn(libc::pthread_t) -> i32),
1101                    (link_name, abi, args),
1102                )?;
1103                let res = this.pthread_detach(thread)?;
1104                this.write_scalar(res, dest)?;
1105            }
1106            "pthread_self" => {
1107                let [] = this.check_shim_sig(
1108                    shim_sig!(extern "C" fn() -> libc::pthread_t),
1109                    (link_name, abi, args),
1110                )?;
1111                let res = this.pthread_self()?;
1112                this.write_scalar(res, dest)?;
1113            }
1114            "sched_yield" => {
1115                // FIXME: This does not have a direct test (#3179).
1116                let [] =
1117                    this.check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?;
1118                this.sched_yield()?;
1119                this.write_null(dest)?;
1120            }
1121            "nanosleep" => {
1122                let [duration, rem] = this.check_shim_sig(
1123                    shim_sig!(extern "C" fn(*_, *_) -> i32),
1124                    (link_name, abi, args),
1125                )?;
1126                let result = this.nanosleep(duration, rem)?;
1127                this.write_scalar(result, dest)?;
1128            }
1129            "clock_nanosleep" => {
1130                // Currently this function does not exist on all Unixes, e.g. on macOS.
1131                this.check_target_os(
1132                    &[Os::FreeBsd, Os::Linux, Os::Android, Os::Solaris, Os::Illumos],
1133                    link_name,
1134                )?;
1135
1136                let [clock_id, flags, req, rem] = this.check_shim_sig(
1137                    shim_sig!(extern "C" fn(libc::clockid_t, i32, *_, *_) -> i32),
1138                    (link_name, abi, args),
1139                )?;
1140                let result = this.clock_nanosleep(clock_id, flags, req, rem)?;
1141                this.write_scalar(result, dest)?;
1142            }
1143            "sched_getaffinity" => {
1144                // Currently this function does not exist on all Unixes, e.g. on macOS.
1145                this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?;
1146
1147                let [pid, cpusetsize, mask] = this.check_shim_sig(
1148                    shim_sig!(extern "C" fn(libc::pid_t, usize, *_) -> i32),
1149                    (link_name, abi, args),
1150                )?;
1151                this.sched_getaffinity(pid, cpusetsize, mask, dest)?;
1152            }
1153            "sched_setaffinity" => {
1154                // Currently this function does not exist on all Unixes, e.g. on macOS.
1155                this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?;
1156
1157                let [pid, cpusetsize, mask] = this.check_shim_sig(
1158                    shim_sig!(extern "C" fn(libc::pid_t, usize, *_) -> i32),
1159                    (link_name, abi, args),
1160                )?;
1161                this.sched_setaffinity(pid, cpusetsize, mask, dest)?;
1162            }
1163
1164            // Miscellaneous
1165            "isatty" => {
1166                let [fd] = this
1167                    .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?;
1168                let result = this.isatty(fd)?;
1169                this.write_scalar(result, dest)?;
1170            }
1171            "pthread_atfork" => {
1172                // FIXME: This does not have a direct test (#3179).
1173                let [prepare, parent, child] = this.check_shim_sig(
1174                    shim_sig!(extern "C" fn(fn(..) -> _, fn(..) -> _, fn(..) -> _) -> i32),
1175                    (link_name, abi, args),
1176                )?;
1177                this.read_pointer(prepare)?;
1178                this.read_pointer(parent)?;
1179                this.read_pointer(child)?;
1180                // We do not support forking, so there is nothing to do here.
1181                this.write_null(dest)?;
1182            }
1183            "strerror_r" => {
1184                let [errnum, buf, buflen] = this.check_shim_sig(
1185                    shim_sig!(extern "C" fn(i32, *_, usize) -> i32),
1186                    (link_name, abi, args),
1187                )?;
1188                let result = this.strerror_r(errnum, buf, buflen)?;
1189                this.write_scalar(result, dest)?;
1190            }
1191            "getentropy" => {
1192                // This function is non-standard but exists with the same signature and behavior on
1193                // Linux, macOS, FreeBSD and Solaris/Illumos.
1194                this.check_target_os(
1195                    &[Os::Linux, Os::MacOs, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android],
1196                    link_name,
1197                )?;
1198
1199                let [buf, bufsize] = this.check_shim_sig(
1200                    shim_sig!(extern "C" fn(*_, usize) -> i32),
1201                    (link_name, abi, args),
1202                )?;
1203                let buf = this.read_pointer(buf)?;
1204                let bufsize = this.read_target_usize(bufsize)?;
1205
1206                // getentropy sets errno to EIO when the buffer size exceeds 256 bytes.
1207                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html
1208                // Linux: https://man7.org/linux/man-pages/man3/getentropy.3.html
1209                // macOS: https://keith.github.io/xcode-man-pages/getentropy.2.html
1210                // Solaris/Illumos: https://illumos.org/man/3C/getentropy
1211                if bufsize > 256 {
1212                    this.set_errno_and_return_neg1(LibcError("EIO"), dest)?;
1213                } else {
1214                    this.gen_random(buf, bufsize)?;
1215                    this.write_null(dest)?;
1216                }
1217            }
1218            "getrandom" => {
1219                // This function is non-standard but exists with the same signature and behavior on
1220                // Linux, FreeBSD and Solaris/Illumos.
1221                this.check_target_os(
1222                    &[Os::Linux, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android],
1223                    link_name,
1224                )?;
1225
1226                let [ptr, len, flags] = this.check_shim_sig(
1227                    shim_sig!(extern "C" fn(*_, usize, u32) -> isize),
1228                    (link_name, abi, args),
1229                )?;
1230                let ptr = this.read_pointer(ptr)?;
1231                let len = this.read_target_usize(len)?;
1232                let _flags = this.read_scalar(flags)?.to_i32()?;
1233                // We ignore the flags, just always use the same PRNG / host RNG.
1234                this.gen_random(ptr, len)?;
1235                this.write_scalar(Scalar::from_target_usize(len, this), dest)?;
1236            }
1237            "arc4random_buf" => {
1238                // This function is non-standard but exists with the same signature and
1239                // same behavior (eg never fails) on FreeBSD and Solaris/Illumos.
1240                this.check_target_os(&[Os::FreeBsd, Os::Illumos, Os::Solaris], link_name)?;
1241
1242                let [ptr, len] = this.check_shim_sig(
1243                    shim_sig!(extern "C" fn(*_, usize) -> ()),
1244                    (link_name, abi, args),
1245                )?;
1246                let ptr = this.read_pointer(ptr)?;
1247                let len = this.read_target_usize(len)?;
1248                this.gen_random(ptr, len)?;
1249            }
1250            "_Unwind_RaiseException" => {
1251                // This is not formally part of POSIX, but it is very wide-spread on POSIX systems.
1252                // It was originally specified as part of the Itanium C++ ABI:
1253                // https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html#base-throw.
1254                // On Linux it is
1255                // documented as part of the LSB:
1256                // https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/baselib--unwind-raiseexception.html
1257                // Basically every other UNIX uses the exact same api though. Arm also references
1258                // back to the Itanium C++ ABI for the definition of `_Unwind_RaiseException` for
1259                // arm64:
1260                // https://github.com/ARM-software/abi-aa/blob/main/cppabi64/cppabi64.rst#toc-entry-35
1261                // For arm32 they did something custom, but similar enough that the same
1262                // `_Unwind_RaiseException` impl in miri should work:
1263                // https://github.com/ARM-software/abi-aa/blob/main/ehabi32/ehabi32.rst
1264                this.check_target_os(
1265                    &[Os::Linux, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android, Os::MacOs],
1266                    link_name,
1267                )?;
1268
1269                // This function looks and behaves exactly like miri_start_unwind.
1270                let [payload] = this.check_shim_sig(
1271                    // Look up the return type via `panic_unwind::`, not via `unwind::`, as
1272                    // the latter it not always unique.
1273                    shim_sig!(extern "C" fn(*_) -> panic_unwind::imp::uw::_Unwind_Reason_Code),
1274                    (link_name, abi, args),
1275                )?;
1276                this.handle_miri_start_unwind(payload)?;
1277                return interp_ok(EmulateItemResult::NeedsUnwind);
1278            }
1279            "getuid" | "geteuid" => {
1280                let [] = this.check_shim_sig(
1281                    shim_sig!(extern "C" fn() -> libc::uid_t),
1282                    (link_name, abi, args),
1283                )?;
1284                // For now, just pretend we always have this fixed UID.
1285                this.write_int(UID, dest)?;
1286            }
1287
1288            // Incomplete shims that we "stub out" just to get pre-main initialization code to work.
1289            // These shims are enabled only when the caller is in the standard library.
1290            "pthread_attr_getguardsize" if this.frame_in_std() => {
1291                let [_attr, guard_size] =
1292                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
1293                let guard_size_layout = this.machine.layouts.usize;
1294                let guard_size = this.deref_pointer_as(guard_size, guard_size_layout)?;
1295                this.write_scalar(
1296                    Scalar::from_uint(this.machine.page_size, guard_size_layout.size),
1297                    &guard_size,
1298                )?;
1299
1300                // Return success (`0`).
1301                this.write_null(dest)?;
1302            }
1303
1304            "pthread_attr_init" | "pthread_attr_destroy" if this.frame_in_std() => {
1305                let [_] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
1306                this.write_null(dest)?;
1307            }
1308            "pthread_attr_setstacksize" if this.frame_in_std() => {
1309                let [_, _] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
1310                this.write_null(dest)?;
1311            }
1312
1313            "pthread_attr_getstack" if this.frame_in_std() => {
1314                // We don't support "pthread_attr_setstack", so we just pretend all stacks have the same values here.
1315                // Hence we can mostly ignore the input `attr_place`.
1316                let [attr_place, addr_place, size_place] =
1317                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
1318                let _attr_place =
1319                    this.deref_pointer_as(attr_place, this.libc_ty_layout("pthread_attr_t"))?;
1320                let addr_place = this.deref_pointer_as(addr_place, this.machine.layouts.usize)?;
1321                let size_place = this.deref_pointer_as(size_place, this.machine.layouts.usize)?;
1322
1323                this.write_scalar(
1324                    Scalar::from_uint(this.machine.stack_addr, this.pointer_size()),
1325                    &addr_place,
1326                )?;
1327                this.write_scalar(
1328                    Scalar::from_uint(this.machine.stack_size, this.pointer_size()),
1329                    &size_place,
1330                )?;
1331
1332                // Return success (`0`).
1333                this.write_null(dest)?;
1334            }
1335
1336            "signal" | "sigaltstack" if this.frame_in_std() => {
1337                let [_, _] = this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
1338                this.write_null(dest)?;
1339            }
1340            "sigaction" if this.frame_in_std() => {
1341                let [_, _, _] =
1342                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
1343                this.write_null(dest)?;
1344            }
1345
1346            "getpwuid_r" | "__posix_getpwuid_r" if this.frame_in_std() => {
1347                // getpwuid_r is the standard name, __posix_getpwuid_r is used on solarish
1348                let [uid, pwd, buf, buflen, result] =
1349                    this.check_shim_sig_deprecated(abi, CanonAbi::C, link_name, args)?;
1350                this.check_no_isolation("`getpwuid_r`")?;
1351
1352                let uid = this.read_scalar(uid)?.to_u32()?;
1353                let pwd = this.deref_pointer_as(pwd, this.libc_ty_layout("passwd"))?;
1354                let buf = this.read_pointer(buf)?;
1355                let buflen = this.read_target_usize(buflen)?;
1356                let result = this.deref_pointer_as(result, this.machine.layouts.unit_ptr_mut)?;
1357
1358                // Must be for "us".
1359                if uid != UID {
1360                    throw_unsup_format!("`getpwuid_r` on other users is not supported");
1361                }
1362
1363                // Reset all fields to `uninit` to make sure nobody reads them.
1364                // (This is a std-only shim so we are okay with such hacks.)
1365                this.write_uninit(&pwd)?;
1366
1367                // We only set the home_dir field.
1368                #[allow(deprecated)]
1369                let home_dir = std::env::home_dir().unwrap();
1370                let (written, _) = this.write_path_to_c_str(&home_dir, buf, buflen)?;
1371                let pw_dir = this.project_field_named(&pwd, "pw_dir")?;
1372                this.write_pointer(buf, &pw_dir)?;
1373
1374                if written {
1375                    this.write_pointer(pwd.ptr(), &result)?;
1376                    this.write_null(dest)?;
1377                } else {
1378                    this.write_null(&result)?;
1379                    this.write_scalar(this.eval_libc("ERANGE"), dest)?;
1380                }
1381            }
1382
1383            // Platform-specific shims
1384            _ => {
1385                let target_os = &this.tcx.sess.target.os;
1386                return match target_os {
1387                    Os::Android =>
1388                        android::EvalContextExt::emulate_foreign_item_inner(
1389                            this, link_name, abi, args, dest,
1390                        ),
1391                    Os::FreeBsd =>
1392                        freebsd::EvalContextExt::emulate_foreign_item_inner(
1393                            this, link_name, abi, args, dest,
1394                        ),
1395                    Os::Linux =>
1396                        linux::EvalContextExt::emulate_foreign_item_inner(
1397                            this, link_name, abi, args, dest,
1398                        ),
1399                    Os::MacOs =>
1400                        macos::EvalContextExt::emulate_foreign_item_inner(
1401                            this, link_name, abi, args, dest,
1402                        ),
1403                    Os::Solaris | Os::Illumos =>
1404                        solarish::EvalContextExt::emulate_foreign_item_inner(
1405                            this, link_name, abi, args, dest,
1406                        ),
1407                    Os::NetBsd =>
1408                        netbsd::EvalContextExt::emulate_foreign_item_inner(
1409                            this, link_name, abi, args, dest,
1410                        ),
1411                    _ => interp_ok(EmulateItemResult::NotSupported),
1412                };
1413            }
1414        };
1415
1416        interp_ok(EmulateItemResult::NeedsReturn)
1417    }
1418}