Skip to main content

miri/shims/unix/
foreign_items.rs

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