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