Skip to main content

miri/shims/unix/
foreign_items.rs

1use std::ffi::OsStr;
2use std::str;
3
4use rustc_abi::{CanonAbi, Size};
5use rustc_middle::ty::Ty;
6use rustc_span::Symbol;
7use rustc_target::callconv::FnAbi;
8use rustc_target::spec::Os;
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::{shim_sig, *};
19
20pub fn is_dyn_sym(name: &str, target_os: &Os) -> 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                Os::Android => android::is_dyn_sym(name),
33                Os::FreeBsd => freebsd::is_dyn_sym(name),
34                Os::Linux => linux::is_dyn_sym(name),
35                Os::MacOs => macos::is_dyn_sym(name),
36                Os::Solaris | Os::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_sig(
116                    shim_sig!(extern "C" fn(*const _) -> *mut _),
117                    link_name,
118                    abi,
119                    args,
120                )?;
121                let result = this.getenv(name)?;
122                this.write_pointer(result, dest)?;
123            }
124            "unsetenv" => {
125                let [name] = this.check_shim_sig(
126                    shim_sig!(extern "C" fn(*const _) -> i32),
127                    link_name,
128                    abi,
129                    args,
130                )?;
131                let result = this.unsetenv(name)?;
132                this.write_scalar(result, dest)?;
133            }
134            "setenv" => {
135                let [name, value, overwrite] = this.check_shim_sig(
136                    shim_sig!(extern "C" fn(*const _, *const _, i32) -> i32),
137                    link_name,
138                    abi,
139                    args,
140                )?;
141                this.read_scalar(overwrite)?.to_i32()?;
142                let result = this.setenv(name, value)?;
143                this.write_scalar(result, dest)?;
144            }
145            "getcwd" => {
146                // FIXME: This does not have a direct test (#3179).
147                let [buf, size] = this.check_shim_sig(
148                    shim_sig!(extern "C" fn(*mut _, usize) -> *mut _),
149                    link_name,
150                    abi,
151                    args,
152                )?;
153                let result = this.getcwd(buf, size)?;
154                this.write_pointer(result, dest)?;
155            }
156            "chdir" => {
157                // FIXME: This does not have a direct test (#3179).
158                let [path] = this.check_shim_sig(
159                    shim_sig!(extern "C" fn(*const _) -> i32),
160                    link_name,
161                    abi,
162                    args,
163                )?;
164                let result = this.chdir(path)?;
165                this.write_scalar(result, dest)?;
166            }
167            "getpid" => {
168                let [] = this.check_shim_sig(
169                    shim_sig!(extern "C" fn() -> libc::pid_t),
170                    link_name,
171                    abi,
172                    args,
173                )?;
174                let result = this.getpid()?;
175                this.write_scalar(result, dest)?;
176            }
177            "uname" => {
178                // Not all Unixes have the `uname` symbol, e.g. FreeBSD does not.
179                this.check_target_os(
180                    &[Os::Linux, Os::Android, Os::MacOs, Os::Solaris, Os::Illumos],
181                    link_name,
182                )?;
183                let [uname] = this.check_shim_sig(
184                    shim_sig!(extern "C" fn(*mut _) -> i32),
185                    link_name,
186                    abi,
187                    args,
188                )?;
189                let result = this.uname(uname, None)?;
190                this.write_scalar(result, dest)?;
191            }
192            "sysconf" => {
193                let [val] = this.check_shim_sig(
194                    shim_sig!(extern "C" fn(i32) -> isize),
195                    link_name,
196                    abi,
197                    args,
198                )?;
199                let result = this.sysconf(val)?;
200                this.write_scalar(result, dest)?;
201            }
202            // File descriptors
203            "read" => {
204                let [fd, buf, count] = this.check_shim_sig(
205                    shim_sig!(extern "C" fn(i32, *mut _, usize) -> isize),
206                    link_name,
207                    abi,
208                    args,
209                )?;
210                let fd = this.read_scalar(fd)?.to_i32()?;
211                let buf = this.read_pointer(buf)?;
212                let count = this.read_target_usize(count)?;
213                this.read(fd, buf, count, None, dest)?;
214            }
215            "write" => {
216                let [fd, buf, n] = this.check_shim_sig(
217                    shim_sig!(extern "C" fn(i32, *const _, usize) -> isize),
218                    link_name,
219                    abi,
220                    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            "pread" => {
229                // FIXME: This does not have a direct test (#3179).
230                let [fd, buf, count, offset] = this.check_shim_sig(
231                    shim_sig!(extern "C" fn(i32, *mut _, usize, libc::off_t) -> isize),
232                    link_name,
233                    abi,
234                    args,
235                )?;
236                let fd = this.read_scalar(fd)?.to_i32()?;
237                let buf = this.read_pointer(buf)?;
238                let count = this.read_target_usize(count)?;
239                let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?;
240                this.read(fd, buf, count, Some(offset), dest)?;
241            }
242            "pwrite" => {
243                // FIXME: This does not have a direct test (#3179).
244                let [fd, buf, n, offset] = this.check_shim_sig(
245                    shim_sig!(extern "C" fn(i32, *const _, usize, libc::off_t) -> isize),
246                    link_name,
247                    abi,
248                    args,
249                )?;
250                let fd = this.read_scalar(fd)?.to_i32()?;
251                let buf = this.read_pointer(buf)?;
252                let count = this.read_target_usize(n)?;
253                let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?;
254                trace!("Called pwrite({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset);
255                this.write(fd, buf, count, Some(offset), dest)?;
256            }
257            "close" => {
258                let [fd] = this.check_shim_sig(
259                    shim_sig!(extern "C" fn(i32) -> i32),
260                    link_name,
261                    abi,
262                    args,
263                )?;
264                let result = this.close(fd)?;
265                this.write_scalar(result, dest)?;
266            }
267            "fcntl" => {
268                let ([fd_num, cmd], varargs) =
269                    this.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?;
270                let result = this.fcntl(fd_num, cmd, varargs)?;
271                this.write_scalar(result, dest)?;
272            }
273            "dup" => {
274                let [old_fd] = this.check_shim_sig(
275                    shim_sig!(extern "C" fn(i32) -> i32),
276                    link_name,
277                    abi,
278                    args,
279                )?;
280                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
281                let new_fd = this.dup(old_fd)?;
282                this.write_scalar(new_fd, dest)?;
283            }
284            "dup2" => {
285                let [old_fd, new_fd] = this.check_shim_sig(
286                    shim_sig!(extern "C" fn(i32, i32) -> i32),
287                    link_name,
288                    abi,
289                    args,
290                )?;
291                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
292                let new_fd = this.read_scalar(new_fd)?.to_i32()?;
293                let result = this.dup2(old_fd, new_fd)?;
294                this.write_scalar(result, dest)?;
295            }
296            "flock" => {
297                // Currently this function does not exist on all Unixes, e.g. on Solaris.
298                this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::MacOs, Os::Illumos], link_name)?;
299                let [fd, op] = this.check_shim_sig(
300                    shim_sig!(extern "C" fn(i32, i32) -> i32),
301                    link_name,
302                    abi,
303                    args,
304                )?;
305                let fd = this.read_scalar(fd)?.to_i32()?;
306                let op = this.read_scalar(op)?.to_i32()?;
307                let result = this.flock(fd, op)?;
308                this.write_scalar(result, dest)?;
309            }
310
311            // File and file system access
312            "open" => {
313                // `open` is variadic, the third argument is only present when the second argument
314                // has O_CREAT (or on linux O_TMPFILE, but miri doesn't support that) set
315                let ([path_raw, flag], varargs) =
316                    this.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?;
317                let result = this.open(path_raw, flag, varargs)?;
318                this.write_scalar(result, dest)?;
319            }
320            "unlink" => {
321                // FIXME: This does not have a direct test (#3179).
322                let [path] = this.check_shim_sig(
323                    shim_sig!(extern "C" fn(*const _) -> i32),
324                    link_name,
325                    abi,
326                    args,
327                )?;
328                let result = this.unlink(path)?;
329                this.write_scalar(result, dest)?;
330            }
331            "symlink" => {
332                // FIXME: This does not have a direct test (#3179).
333                let [target, linkpath] = this.check_shim_sig(
334                    shim_sig!(extern "C" fn(*const _, *const _) -> i32),
335                    link_name,
336                    abi,
337                    args,
338                )?;
339                let result = this.symlink(target, linkpath)?;
340                this.write_scalar(result, dest)?;
341            }
342            "fstat" => {
343                let [fd, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
344                let result = this.fstat(fd, buf)?;
345                this.write_scalar(result, dest)?;
346            }
347            "rename" => {
348                // FIXME: This does not have a direct test (#3179).
349                let [oldpath, newpath] = this.check_shim_sig(
350                    shim_sig!(extern "C" fn(*const _, *const _) -> i32),
351                    link_name,
352                    abi,
353                    args,
354                )?;
355                let result = this.rename(oldpath, newpath)?;
356                this.write_scalar(result, dest)?;
357            }
358            "mkdir" => {
359                // FIXME: This does not have a direct test (#3179).
360                let [path, mode] = this.check_shim_sig(
361                    shim_sig!(extern "C" fn(*const _, libc::mode_t) -> i32),
362                    link_name,
363                    abi,
364                    args,
365                )?;
366                let result = this.mkdir(path, mode)?;
367                this.write_scalar(result, dest)?;
368            }
369            "rmdir" => {
370                // FIXME: This does not have a direct test (#3179).
371                let [path] = this.check_shim_sig(
372                    shim_sig!(extern "C" fn(*const _) -> i32),
373                    link_name,
374                    abi,
375                    args,
376                )?;
377                let result = this.rmdir(path)?;
378                this.write_scalar(result, dest)?;
379            }
380            "opendir" => {
381                let [name] = this.check_shim_sig(
382                    shim_sig!(extern "C" fn(*const _) -> *mut _),
383                    link_name,
384                    abi,
385                    args,
386                )?;
387                let result = this.opendir(name)?;
388                this.write_scalar(result, dest)?;
389            }
390            "closedir" => {
391                let [dirp] = this.check_shim_sig(
392                    shim_sig!(extern "C" fn(*mut _) -> i32),
393                    link_name,
394                    abi,
395                    args,
396                )?;
397                let result = this.closedir(dirp)?;
398                this.write_scalar(result, dest)?;
399            }
400            "readdir" => {
401                let [dirp] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
402                this.readdir(dirp, dest)?;
403            }
404            "lseek" => {
405                // FIXME: This does not have a direct test (#3179).
406                let [fd, offset, whence] = this.check_shim_sig(
407                    shim_sig!(extern "C" fn(i32, libc::off_t, i32) -> libc::off_t),
408                    link_name,
409                    abi,
410                    args,
411                )?;
412                let fd = this.read_scalar(fd)?.to_i32()?;
413                let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?;
414                let whence = this.read_scalar(whence)?.to_i32()?;
415                this.lseek(fd, offset, whence, dest)?;
416            }
417            "ftruncate" => {
418                let [fd, length] = this.check_shim_sig(
419                    shim_sig!(extern "C" fn(i32, libc::off_t) -> i32),
420                    link_name,
421                    abi,
422                    args,
423                )?;
424                let fd = this.read_scalar(fd)?.to_i32()?;
425                let length = this.read_scalar(length)?.to_int(length.layout.size)?;
426                let result = this.ftruncate64(fd, length)?;
427                this.write_scalar(result, dest)?;
428            }
429            "fsync" => {
430                // FIXME: This does not have a direct test (#3179).
431                let [fd] = this.check_shim_sig(
432                    shim_sig!(extern "C" fn(i32) -> i32),
433                    link_name,
434                    abi,
435                    args,
436                )?;
437                let result = this.fsync(fd)?;
438                this.write_scalar(result, dest)?;
439            }
440            "fdatasync" => {
441                // FIXME: This does not have a direct test (#3179).
442                let [fd] = this.check_shim_sig(
443                    shim_sig!(extern "C" fn(i32) -> i32),
444                    link_name,
445                    abi,
446                    args,
447                )?;
448                let result = this.fdatasync(fd)?;
449                this.write_scalar(result, dest)?;
450            }
451            "readlink" => {
452                let [pathname, buf, bufsize] = this.check_shim_sig(
453                    shim_sig!(extern "C" fn(*const _, *mut _, usize) -> isize),
454                    link_name,
455                    abi,
456                    args,
457                )?;
458                let result = this.readlink(pathname, buf, bufsize)?;
459                this.write_scalar(Scalar::from_target_isize(result, this), dest)?;
460            }
461            "posix_fadvise" => {
462                let [fd, offset, len, advice] = this.check_shim_sig(
463                    shim_sig!(extern "C" fn(i32, libc::off_t, libc::off_t, i32) -> i32),
464                    link_name,
465                    abi,
466                    args,
467                )?;
468                this.read_scalar(fd)?.to_i32()?;
469                this.read_scalar(offset)?.to_int(offset.layout.size)?;
470                this.read_scalar(len)?.to_int(len.layout.size)?;
471                this.read_scalar(advice)?.to_i32()?;
472                // fadvise is only informational, we can ignore it.
473                this.write_null(dest)?;
474            }
475
476            "posix_fallocate" => {
477                // posix_fallocate is not supported by macos.
478                this.check_target_os(
479                    &[Os::Linux, Os::FreeBsd, Os::Solaris, Os::Illumos, Os::Android],
480                    link_name,
481                )?;
482                let [fd, offset, len] = this.check_shim_sig(
483                    shim_sig!(extern "C" fn(i32, libc::off_t, libc::off_t) -> i32),
484                    link_name,
485                    abi,
486                    args,
487                )?;
488
489                let fd = this.read_scalar(fd)?.to_i32()?;
490                // We don't support platforms which have libc::off_t bigger than 64 bits.
491                let offset =
492                    i64::try_from(this.read_scalar(offset)?.to_int(offset.layout.size)?).unwrap();
493                let len = i64::try_from(this.read_scalar(len)?.to_int(len.layout.size)?).unwrap();
494
495                let result = this.posix_fallocate(fd, offset, len)?;
496                this.write_scalar(result, dest)?;
497            }
498
499            "realpath" => {
500                let [path, resolved_path] = this.check_shim_sig(
501                    shim_sig!(extern "C" fn(*const _, *mut _) -> *mut _),
502                    link_name,
503                    abi,
504                    args,
505                )?;
506                let result = this.realpath(path, resolved_path)?;
507                this.write_scalar(result, dest)?;
508            }
509            "mkstemp" => {
510                let [template] = this.check_shim_sig(
511                    shim_sig!(extern "C" fn(*mut _) -> i32),
512                    link_name,
513                    abi,
514                    args,
515                )?;
516                let result = this.mkstemp(template)?;
517                this.write_scalar(result, dest)?;
518            }
519
520            // Unnamed sockets and pipes
521            "socketpair" => {
522                let [domain, type_, protocol, sv] = this.check_shim_sig(
523                    shim_sig!(extern "C" fn(i32, i32, i32, *mut _) -> i32),
524                    link_name,
525                    abi,
526                    args,
527                )?;
528                let result = this.socketpair(domain, type_, protocol, sv)?;
529                this.write_scalar(result, dest)?;
530            }
531            "pipe" => {
532                let [pipefd] = this.check_shim_sig(
533                    shim_sig!(extern "C" fn(*mut _) -> i32),
534                    link_name,
535                    abi,
536                    args,
537                )?;
538                let result = this.pipe2(pipefd, /*flags*/ None)?;
539                this.write_scalar(result, dest)?;
540            }
541            "pipe2" => {
542                // Currently this function does not exist on all Unixes, e.g. on macOS.
543                this.check_target_os(
544                    &[Os::Linux, Os::Android, Os::FreeBsd, Os::Solaris, Os::Illumos],
545                    link_name,
546                )?;
547                let [pipefd, flags] = this.check_shim_sig(
548                    shim_sig!(extern "C" fn(*mut _, i32) -> i32),
549                    link_name,
550                    abi,
551                    args,
552                )?;
553                let result = this.pipe2(pipefd, Some(flags))?;
554                this.write_scalar(result, dest)?;
555            }
556
557            // Network sockets
558            "socket" => {
559                let [domain, type_, protocol] = this.check_shim_sig(
560                    shim_sig!(extern "C" fn(i32, i32, i32) -> i32),
561                    link_name,
562                    abi,
563                    args,
564                )?;
565                let result = this.socket(domain, type_, protocol)?;
566                this.write_scalar(result, dest)?;
567            }
568            "bind" => {
569                let [socket, address, address_len] = this.check_shim_sig(
570                    shim_sig!(extern "C" fn(i32, *const _, libc::socklen_t) -> i32),
571                    link_name,
572                    abi,
573                    args,
574                )?;
575                let result = this.bind(socket, address, address_len)?;
576                this.write_scalar(result, dest)?;
577            }
578            "listen" => {
579                let [socket, backlog] = this.check_shim_sig(
580                    shim_sig!(extern "C" fn(i32, i32) -> i32),
581                    link_name,
582                    abi,
583                    args,
584                )?;
585                let result = this.listen(socket, backlog)?;
586                this.write_scalar(result, dest)?;
587            }
588            "accept" => {
589                let [socket, address, address_len] = this.check_shim_sig(
590                    shim_sig!(extern "C" fn(i32, *mut _, *mut _) -> i32),
591                    link_name,
592                    abi,
593                    args,
594                )?;
595                this.accept4(socket, address, address_len, /* flags */ None, dest)?;
596            }
597            "accept4" => {
598                let [socket, address, address_len, flags] = this.check_shim_sig(
599                    shim_sig!(extern "C" fn(i32, *mut _, *mut _, i32) -> i32),
600                    link_name,
601                    abi,
602                    args,
603                )?;
604                this.accept4(socket, address, address_len, Some(flags), dest)?;
605            }
606            "connect" => {
607                let [socket, address, address_len] = this.check_shim_sig(
608                    shim_sig!(extern "C" fn(i32, *const _, libc::socklen_t) -> i32),
609                    link_name,
610                    abi,
611                    args,
612                )?;
613                this.connect(socket, address, address_len, dest)?;
614            }
615            "setsockopt" => {
616                let [socket, level, option_name, option_value, option_len] = this.check_shim_sig(
617                    shim_sig!(extern "C" fn(i32, i32, i32, *const _, libc::socklen_t) -> i32),
618                    link_name,
619                    abi,
620                    args,
621                )?;
622                let result =
623                    this.setsockopt(socket, level, option_name, option_value, option_len)?;
624                this.write_scalar(result, dest)?;
625            }
626            "getsockname" => {
627                let [socket, address, address_len] = this.check_shim_sig(
628                    shim_sig!(extern "C" fn(i32, *mut _, *mut _) -> i32),
629                    link_name,
630                    abi,
631                    args,
632                )?;
633                let result = this.getsockname(socket, address, address_len)?;
634                this.write_scalar(result, dest)?;
635            }
636            "getpeername" => {
637                let [socket, address, address_len] = this.check_shim_sig(
638                    shim_sig!(extern "C" fn(i32, *mut _, *mut _) -> i32),
639                    link_name,
640                    abi,
641                    args,
642                )?;
643                let result = this.getpeername(socket, address, address_len)?;
644                this.write_scalar(result, dest)?;
645            }
646
647            // Time
648            "gettimeofday" => {
649                let [tv, tz] = this.check_shim_sig(
650                    shim_sig!(extern "C" fn(*mut _, *mut _) -> i32),
651                    link_name,
652                    abi,
653                    args,
654                )?;
655                let result = this.gettimeofday(tv, tz)?;
656                this.write_scalar(result, dest)?;
657            }
658            "localtime_r" => {
659                let [timep, result_op] = this.check_shim_sig(
660                    shim_sig!(extern "C" fn(*const _, *mut _) -> *mut _),
661                    link_name,
662                    abi,
663                    args,
664                )?;
665                let result = this.localtime_r(timep, result_op)?;
666                this.write_pointer(result, dest)?;
667            }
668            "clock_gettime" => {
669                let [clk_id, tp] = this.check_shim_sig(
670                    shim_sig!(extern "C" fn(libc::clockid_t, *mut _) -> i32),
671                    link_name,
672                    abi,
673                    args,
674                )?;
675                this.clock_gettime(clk_id, tp, dest)?;
676            }
677
678            // Allocation
679            "posix_memalign" => {
680                let [memptr, align, size] =
681                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
682                let result = this.posix_memalign(memptr, align, size)?;
683                this.write_scalar(result, dest)?;
684            }
685
686            "mmap" => {
687                let [addr, length, prot, flags, fd, offset] =
688                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
689                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
690                let ptr = this.mmap(addr, length, prot, flags, fd, offset)?;
691                this.write_scalar(ptr, dest)?;
692            }
693            "munmap" => {
694                let [addr, length] =
695                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
696                let result = this.munmap(addr, length)?;
697                this.write_scalar(result, dest)?;
698            }
699
700            "reallocarray" => {
701                // Currently this function does not exist on all Unixes, e.g. on macOS.
702                this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?;
703                let [ptr, nmemb, size] =
704                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
705                let ptr = this.read_pointer(ptr)?;
706                let nmemb = this.read_target_usize(nmemb)?;
707                let size = this.read_target_usize(size)?;
708                // reallocarray checks a possible overflow and returns ENOMEM
709                // if that happens.
710                //
711                // Linux: https://www.unix.com/man-page/linux/3/reallocarray/
712                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=reallocarray
713                match this.compute_size_in_bytes(Size::from_bytes(size), nmemb) {
714                    None => {
715                        this.set_last_error(LibcError("ENOMEM"))?;
716                        this.write_null(dest)?;
717                    }
718                    Some(len) => {
719                        let res = this.realloc(ptr, len.bytes())?;
720                        this.write_pointer(res, dest)?;
721                    }
722                }
723            }
724            "aligned_alloc" => {
725                // This is a C11 function, we assume all Unixes have it.
726                // (MSVC explicitly does not support this.)
727                let [align, size] =
728                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
729                let res = this.aligned_alloc(align, size)?;
730                this.write_pointer(res, dest)?;
731            }
732
733            // Dynamic symbol loading
734            "dlsym" => {
735                let [handle, symbol] =
736                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
737                this.read_target_usize(handle)?;
738                let symbol = this.read_pointer(symbol)?;
739                let name = this.read_c_str(symbol)?;
740                let Ok(name) = str::from_utf8(name) else {
741                    throw_unsup_format!("dlsym: non UTF-8 symbol name not supported")
742                };
743                if is_dyn_sym(name, &this.tcx.sess.target.os) {
744                    let ptr = this.fn_ptr(FnVal::Other(DynSym::from_str(name)));
745                    this.write_pointer(ptr, dest)?;
746                } else if let Some(&ptr) = this.machine.extern_statics.get(&Symbol::intern(name)) {
747                    this.write_pointer(ptr, dest)?;
748                } else {
749                    this.write_null(dest)?;
750                }
751            }
752
753            // Thread-local storage
754            "pthread_key_create" => {
755                let [key, dtor] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
756                let key_place = this.deref_pointer_as(key, this.libc_ty_layout("pthread_key_t"))?;
757                let dtor = this.read_pointer(dtor)?;
758
759                // Extract the function type out of the signature (that seems easier than constructing it ourselves).
760                let dtor = if !this.ptr_is_null(dtor)? {
761                    Some((
762                        this.get_ptr_fn(dtor)?.as_instance()?,
763                        this.machine.current_user_relevant_span(),
764                    ))
765                } else {
766                    None
767                };
768
769                // Figure out how large a pthread TLS key actually is.
770                // To this end, deref the argument type. This is `libc::pthread_key_t`.
771                let key_type = key.layout.ty
772                    .builtin_deref(true)
773                    .ok_or_else(|| err_ub_format!(
774                        "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
775                    ))?;
776                let key_layout = this.layout_of(key_type)?;
777
778                // Create key and write it into the memory where `key_ptr` wants it.
779                let key = this.machine.tls.create_tls_key(dtor, key_layout.size)?;
780                this.write_scalar(Scalar::from_uint(key, key_layout.size), &key_place)?;
781
782                // Return success (`0`).
783                this.write_null(dest)?;
784            }
785            "pthread_key_delete" => {
786                // FIXME: This does not have a direct test (#3179).
787                let [key] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
788                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
789                this.machine.tls.delete_tls_key(key)?;
790                // Return success (0)
791                this.write_null(dest)?;
792            }
793            "pthread_getspecific" => {
794                // FIXME: This does not have a direct test (#3179).
795                let [key] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
796                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
797                let active_thread = this.active_thread();
798                let ptr = this.machine.tls.load_tls(key, active_thread, this)?;
799                this.write_scalar(ptr, dest)?;
800            }
801            "pthread_setspecific" => {
802                // FIXME: This does not have a direct test (#3179).
803                let [key, new_ptr] =
804                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
805                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
806                let active_thread = this.active_thread();
807                let new_data = this.read_scalar(new_ptr)?;
808                this.machine.tls.store_tls(key, active_thread, new_data, &*this.tcx)?;
809
810                // Return success (`0`).
811                this.write_null(dest)?;
812            }
813
814            // Synchronization primitives
815            "pthread_mutexattr_init" => {
816                let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
817                this.pthread_mutexattr_init(attr)?;
818                this.write_null(dest)?;
819            }
820            "pthread_mutexattr_settype" => {
821                let [attr, kind] =
822                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
823                let result = this.pthread_mutexattr_settype(attr, kind)?;
824                this.write_scalar(result, dest)?;
825            }
826            "pthread_mutexattr_destroy" => {
827                let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
828                this.pthread_mutexattr_destroy(attr)?;
829                this.write_null(dest)?;
830            }
831            "pthread_mutex_init" => {
832                let [mutex, attr] =
833                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
834                this.pthread_mutex_init(mutex, attr)?;
835                this.write_null(dest)?;
836            }
837            "pthread_mutex_lock" => {
838                let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
839                this.pthread_mutex_lock(mutex, dest)?;
840            }
841            "pthread_mutex_trylock" => {
842                let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
843                let result = this.pthread_mutex_trylock(mutex)?;
844                this.write_scalar(result, dest)?;
845            }
846            "pthread_mutex_unlock" => {
847                let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
848                let result = this.pthread_mutex_unlock(mutex)?;
849                this.write_scalar(result, dest)?;
850            }
851            "pthread_mutex_destroy" => {
852                let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
853                this.pthread_mutex_destroy(mutex)?;
854                this.write_int(0, dest)?;
855            }
856            "pthread_rwlock_rdlock" => {
857                let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
858                this.pthread_rwlock_rdlock(rwlock, dest)?;
859            }
860            "pthread_rwlock_tryrdlock" => {
861                let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
862                let result = this.pthread_rwlock_tryrdlock(rwlock)?;
863                this.write_scalar(result, dest)?;
864            }
865            "pthread_rwlock_wrlock" => {
866                let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
867                this.pthread_rwlock_wrlock(rwlock, dest)?;
868            }
869            "pthread_rwlock_trywrlock" => {
870                let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
871                let result = this.pthread_rwlock_trywrlock(rwlock)?;
872                this.write_scalar(result, dest)?;
873            }
874            "pthread_rwlock_unlock" => {
875                let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
876                this.pthread_rwlock_unlock(rwlock)?;
877                this.write_null(dest)?;
878            }
879            "pthread_rwlock_destroy" => {
880                let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
881                this.pthread_rwlock_destroy(rwlock)?;
882                this.write_null(dest)?;
883            }
884            "pthread_condattr_init" => {
885                let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
886                this.pthread_condattr_init(attr)?;
887                this.write_null(dest)?;
888            }
889            "pthread_condattr_setclock" => {
890                let [attr, clock_id] =
891                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
892                let result = this.pthread_condattr_setclock(attr, clock_id)?;
893                this.write_scalar(result, dest)?;
894            }
895            "pthread_condattr_getclock" => {
896                let [attr, clock_id] =
897                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
898                this.pthread_condattr_getclock(attr, clock_id)?;
899                this.write_null(dest)?;
900            }
901            "pthread_condattr_destroy" => {
902                let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
903                this.pthread_condattr_destroy(attr)?;
904                this.write_null(dest)?;
905            }
906            "pthread_cond_init" => {
907                let [cond, attr] =
908                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
909                this.pthread_cond_init(cond, attr)?;
910                this.write_null(dest)?;
911            }
912            "pthread_cond_signal" => {
913                let [cond] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
914                this.pthread_cond_signal(cond)?;
915                this.write_null(dest)?;
916            }
917            "pthread_cond_broadcast" => {
918                let [cond] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
919                this.pthread_cond_broadcast(cond)?;
920                this.write_null(dest)?;
921            }
922            "pthread_cond_wait" => {
923                let [cond, mutex] =
924                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
925                this.pthread_cond_wait(cond, mutex, dest)?;
926            }
927            "pthread_cond_timedwait" => {
928                let [cond, mutex, abstime] =
929                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
930                this.pthread_cond_timedwait(
931                    cond, mutex, abstime, dest, /* macos_relative_np */ false,
932                )?;
933            }
934            "pthread_cond_destroy" => {
935                let [cond] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
936                this.pthread_cond_destroy(cond)?;
937                this.write_null(dest)?;
938            }
939
940            // Threading
941            "pthread_create" => {
942                let [thread, attr, start, arg] =
943                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
944                this.pthread_create(thread, attr, start, arg)?;
945                this.write_null(dest)?;
946            }
947            "pthread_join" => {
948                let [thread, retval] =
949                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
950                this.pthread_join(thread, retval, dest)?;
951            }
952            "pthread_detach" => {
953                let [thread] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
954                let res = this.pthread_detach(thread)?;
955                this.write_scalar(res, dest)?;
956            }
957            "pthread_self" => {
958                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
959                let res = this.pthread_self()?;
960                this.write_scalar(res, dest)?;
961            }
962            "sched_yield" => {
963                // FIXME: This does not have a direct test (#3179).
964                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
965                this.sched_yield()?;
966                this.write_null(dest)?;
967            }
968            "nanosleep" => {
969                let [duration, rem] =
970                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
971                let result = this.nanosleep(duration, rem)?;
972                this.write_scalar(result, dest)?;
973            }
974            "clock_nanosleep" => {
975                // Currently this function does not exist on all Unixes, e.g. on macOS.
976                this.check_target_os(
977                    &[Os::FreeBsd, Os::Linux, Os::Android, Os::Solaris, Os::Illumos],
978                    link_name,
979                )?;
980                let [clock_id, flags, req, rem] =
981                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
982                let result = this.clock_nanosleep(clock_id, flags, req, rem)?;
983                this.write_scalar(result, dest)?;
984            }
985            "sched_getaffinity" => {
986                // Currently this function does not exist on all Unixes, e.g. on macOS.
987                this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?;
988                let [pid, cpusetsize, mask] =
989                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
990                let pid = this.read_scalar(pid)?.to_u32()?;
991                let cpusetsize = this.read_target_usize(cpusetsize)?;
992                let mask = this.read_pointer(mask)?;
993
994                // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid
995                let thread_id = match pid {
996                    0 => this.active_thread(),
997                    _ =>
998                        throw_unsup_format!(
999                            "`sched_getaffinity` is only supported with a pid of 0 (indicating the current thread)"
1000                        ),
1001                };
1002
1003                // The mask is stored in chunks, and the size must be a whole number of chunks.
1004                let chunk_size = CpuAffinityMask::chunk_size(this);
1005
1006                if this.ptr_is_null(mask)? {
1007                    this.set_last_error_and_return(LibcError("EFAULT"), dest)?;
1008                } else if cpusetsize == 0 || cpusetsize.checked_rem(chunk_size).unwrap() != 0 {
1009                    // we only copy whole chunks of size_of::<c_ulong>()
1010                    this.set_last_error_and_return(LibcError("EINVAL"), dest)?;
1011                } else if let Some(cpuset) = this.machine.thread_cpu_affinity.get(&thread_id) {
1012                    let cpuset = cpuset.clone();
1013                    // we only copy whole chunks of size_of::<c_ulong>()
1014                    let byte_count =
1015                        Ord::min(cpuset.as_slice().len(), cpusetsize.try_into().unwrap());
1016                    this.write_bytes_ptr(mask, cpuset.as_slice()[..byte_count].iter().copied())?;
1017                    this.write_null(dest)?;
1018                } else {
1019                    // The thread whose ID is pid could not be found
1020                    this.set_last_error_and_return(LibcError("ESRCH"), dest)?;
1021                }
1022            }
1023            "sched_setaffinity" => {
1024                // Currently this function does not exist on all Unixes, e.g. on macOS.
1025                this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?;
1026                let [pid, cpusetsize, mask] =
1027                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1028                let pid = this.read_scalar(pid)?.to_u32()?;
1029                let cpusetsize = this.read_target_usize(cpusetsize)?;
1030                let mask = this.read_pointer(mask)?;
1031
1032                // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid
1033                let thread_id = match pid {
1034                    0 => this.active_thread(),
1035                    _ =>
1036                        throw_unsup_format!(
1037                            "`sched_setaffinity` is only supported with a pid of 0 (indicating the current thread)"
1038                        ),
1039                };
1040
1041                if this.ptr_is_null(mask)? {
1042                    this.set_last_error_and_return(LibcError("EFAULT"), dest)?;
1043                } else {
1044                    // NOTE: cpusetsize might be smaller than `CpuAffinityMask::CPU_MASK_BYTES`.
1045                    // Any unspecified bytes are treated as zero here (none of the CPUs are configured).
1046                    // This is not exactly documented, so we assume that this is the behavior in practice.
1047                    let bits_slice =
1048                        this.read_bytes_ptr_strip_provenance(mask, Size::from_bytes(cpusetsize))?;
1049                    // This ignores the bytes beyond `CpuAffinityMask::CPU_MASK_BYTES`
1050                    let bits_array: [u8; CpuAffinityMask::CPU_MASK_BYTES] =
1051                        std::array::from_fn(|i| bits_slice.get(i).copied().unwrap_or(0));
1052                    match CpuAffinityMask::from_array(this, this.machine.num_cpus, bits_array) {
1053                        Some(cpuset) => {
1054                            this.machine.thread_cpu_affinity.insert(thread_id, cpuset);
1055                            this.write_null(dest)?;
1056                        }
1057                        None => {
1058                            // The intersection between the mask and the available CPUs was empty.
1059                            this.set_last_error_and_return(LibcError("EINVAL"), dest)?;
1060                        }
1061                    }
1062                }
1063            }
1064
1065            // Miscellaneous
1066            "isatty" => {
1067                let [fd] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1068                let result = this.isatty(fd)?;
1069                this.write_scalar(result, dest)?;
1070            }
1071            "pthread_atfork" => {
1072                // FIXME: This does not have a direct test (#3179).
1073                let [prepare, parent, child] =
1074                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1075                this.read_pointer(prepare)?;
1076                this.read_pointer(parent)?;
1077                this.read_pointer(child)?;
1078                // We do not support forking, so there is nothing to do here.
1079                this.write_null(dest)?;
1080            }
1081            "getentropy" => {
1082                // This function is non-standard but exists with the same signature and behavior on
1083                // Linux, macOS, FreeBSD and Solaris/Illumos.
1084                this.check_target_os(
1085                    &[Os::Linux, Os::MacOs, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android],
1086                    link_name,
1087                )?;
1088                let [buf, bufsize] =
1089                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1090                let buf = this.read_pointer(buf)?;
1091                let bufsize = this.read_target_usize(bufsize)?;
1092
1093                // getentropy sets errno to EIO when the buffer size exceeds 256 bytes.
1094                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html
1095                // Linux: https://man7.org/linux/man-pages/man3/getentropy.3.html
1096                // macOS: https://keith.github.io/xcode-man-pages/getentropy.2.html
1097                // Solaris/Illumos: https://illumos.org/man/3C/getentropy
1098                if bufsize > 256 {
1099                    this.set_last_error_and_return(LibcError("EIO"), dest)?;
1100                } else {
1101                    this.gen_random(buf, bufsize)?;
1102                    this.write_null(dest)?;
1103                }
1104            }
1105
1106            "strerror_r" => {
1107                let [errnum, buf, buflen] =
1108                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1109                let result = this.strerror_r(errnum, buf, buflen)?;
1110                this.write_scalar(result, dest)?;
1111            }
1112
1113            "getrandom" => {
1114                // This function is non-standard but exists with the same signature and behavior on
1115                // Linux, FreeBSD and Solaris/Illumos.
1116                this.check_target_os(
1117                    &[Os::Linux, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android],
1118                    link_name,
1119                )?;
1120                let [ptr, len, flags] =
1121                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1122                let ptr = this.read_pointer(ptr)?;
1123                let len = this.read_target_usize(len)?;
1124                let _flags = this.read_scalar(flags)?.to_i32()?;
1125                // We ignore the flags, just always use the same PRNG / host RNG.
1126                this.gen_random(ptr, len)?;
1127                this.write_scalar(Scalar::from_target_usize(len, this), dest)?;
1128            }
1129            "arc4random_buf" => {
1130                // This function is non-standard but exists with the same signature and
1131                // same behavior (eg never fails) on FreeBSD and Solaris/Illumos.
1132                this.check_target_os(&[Os::FreeBsd, Os::Illumos, Os::Solaris], link_name)?;
1133                let [ptr, len] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1134                let ptr = this.read_pointer(ptr)?;
1135                let len = this.read_target_usize(len)?;
1136                this.gen_random(ptr, len)?;
1137            }
1138            "_Unwind_RaiseException" => {
1139                // This is not formally part of POSIX, but it is very wide-spread on POSIX systems.
1140                // It was originally specified as part of the Itanium C++ ABI:
1141                // https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html#base-throw.
1142                // On Linux it is
1143                // documented as part of the LSB:
1144                // https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/baselib--unwind-raiseexception.html
1145                // Basically every other UNIX uses the exact same api though. Arm also references
1146                // back to the Itanium C++ ABI for the definition of `_Unwind_RaiseException` for
1147                // arm64:
1148                // https://github.com/ARM-software/abi-aa/blob/main/cppabi64/cppabi64.rst#toc-entry-35
1149                // For arm32 they did something custom, but similar enough that the same
1150                // `_Unwind_RaiseException` impl in miri should work:
1151                // https://github.com/ARM-software/abi-aa/blob/main/ehabi32/ehabi32.rst
1152                this.check_target_os(
1153                    &[Os::Linux, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android, Os::MacOs],
1154                    link_name,
1155                )?;
1156                // This function looks and behaves exactly like miri_start_unwind.
1157                let [payload] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1158                this.handle_miri_start_unwind(payload)?;
1159                return interp_ok(EmulateItemResult::NeedsUnwind);
1160            }
1161            "getuid" | "geteuid" => {
1162                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1163                // For now, just pretend we always have this fixed UID.
1164                this.write_int(UID, dest)?;
1165            }
1166
1167            // Incomplete shims that we "stub out" just to get pre-main initialization code to work.
1168            // These shims are enabled only when the caller is in the standard library.
1169            "pthread_attr_getguardsize" if this.frame_in_std() => {
1170                let [_attr, guard_size] =
1171                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1172                let guard_size_layout = this.machine.layouts.usize;
1173                let guard_size = this.deref_pointer_as(guard_size, guard_size_layout)?;
1174                this.write_scalar(
1175                    Scalar::from_uint(this.machine.page_size, guard_size_layout.size),
1176                    &guard_size,
1177                )?;
1178
1179                // Return success (`0`).
1180                this.write_null(dest)?;
1181            }
1182
1183            "pthread_attr_init" | "pthread_attr_destroy" if this.frame_in_std() => {
1184                let [_] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1185                this.write_null(dest)?;
1186            }
1187            "pthread_attr_setstacksize" if this.frame_in_std() => {
1188                let [_, _] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1189                this.write_null(dest)?;
1190            }
1191
1192            "pthread_attr_getstack" if this.frame_in_std() => {
1193                // We don't support "pthread_attr_setstack", so we just pretend all stacks have the same values here.
1194                // Hence we can mostly ignore the input `attr_place`.
1195                let [attr_place, addr_place, size_place] =
1196                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1197                let _attr_place =
1198                    this.deref_pointer_as(attr_place, this.libc_ty_layout("pthread_attr_t"))?;
1199                let addr_place = this.deref_pointer_as(addr_place, this.machine.layouts.usize)?;
1200                let size_place = this.deref_pointer_as(size_place, this.machine.layouts.usize)?;
1201
1202                this.write_scalar(
1203                    Scalar::from_uint(this.machine.stack_addr, this.pointer_size()),
1204                    &addr_place,
1205                )?;
1206                this.write_scalar(
1207                    Scalar::from_uint(this.machine.stack_size, this.pointer_size()),
1208                    &size_place,
1209                )?;
1210
1211                // Return success (`0`).
1212                this.write_null(dest)?;
1213            }
1214
1215            "signal" | "sigaltstack" if this.frame_in_std() => {
1216                let [_, _] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1217                this.write_null(dest)?;
1218            }
1219            "sigaction" | "mprotect" if this.frame_in_std() => {
1220                let [_, _, _] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1221                this.write_null(dest)?;
1222            }
1223
1224            "getpwuid_r" | "__posix_getpwuid_r" if this.frame_in_std() => {
1225                // getpwuid_r is the standard name, __posix_getpwuid_r is used on solarish
1226                let [uid, pwd, buf, buflen, result] =
1227                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1228                this.check_no_isolation("`getpwuid_r`")?;
1229
1230                let uid = this.read_scalar(uid)?.to_u32()?;
1231                let pwd = this.deref_pointer_as(pwd, this.libc_ty_layout("passwd"))?;
1232                let buf = this.read_pointer(buf)?;
1233                let buflen = this.read_target_usize(buflen)?;
1234                let result = this.deref_pointer_as(result, this.machine.layouts.mut_raw_ptr)?;
1235
1236                // Must be for "us".
1237                if uid != UID {
1238                    throw_unsup_format!("`getpwuid_r` on other users is not supported");
1239                }
1240
1241                // Reset all fields to `uninit` to make sure nobody reads them.
1242                // (This is a std-only shim so we are okay with such hacks.)
1243                this.write_uninit(&pwd)?;
1244
1245                // We only set the home_dir field.
1246                #[allow(deprecated)]
1247                let home_dir = std::env::home_dir().unwrap();
1248                let (written, _) = this.write_path_to_c_str(&home_dir, buf, buflen)?;
1249                let pw_dir = this.project_field_named(&pwd, "pw_dir")?;
1250                this.write_pointer(buf, &pw_dir)?;
1251
1252                if written {
1253                    this.write_pointer(pwd.ptr(), &result)?;
1254                    this.write_null(dest)?;
1255                } else {
1256                    this.write_null(&result)?;
1257                    this.write_scalar(this.eval_libc("ERANGE"), dest)?;
1258                }
1259            }
1260
1261            // Platform-specific shims
1262            _ => {
1263                let target_os = &this.tcx.sess.target.os;
1264                return match target_os {
1265                    Os::Android =>
1266                        android::EvalContextExt::emulate_foreign_item_inner(
1267                            this, link_name, abi, args, dest,
1268                        ),
1269                    Os::FreeBsd =>
1270                        freebsd::EvalContextExt::emulate_foreign_item_inner(
1271                            this, link_name, abi, args, dest,
1272                        ),
1273                    Os::Linux =>
1274                        linux::EvalContextExt::emulate_foreign_item_inner(
1275                            this, link_name, abi, args, dest,
1276                        ),
1277                    Os::MacOs =>
1278                        macos::EvalContextExt::emulate_foreign_item_inner(
1279                            this, link_name, abi, args, dest,
1280                        ),
1281                    Os::Solaris | Os::Illumos =>
1282                        solarish::EvalContextExt::emulate_foreign_item_inner(
1283                            this, link_name, abi, args, dest,
1284                        ),
1285                    _ => interp_ok(EmulateItemResult::NotSupported),
1286                };
1287            }
1288        };
1289
1290        interp_ok(EmulateItemResult::NeedsReturn)
1291    }
1292}