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