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